feat(integration-connector): database 传输类型、两步绑定编排与调用日志捕获查询
- 新增 database 传输:直连 MySQL/Oracle/SQLServer/PostgreSQL 执行绑定 SQL(新增 pymysql/pymssql 驱动依赖) - 绑定支持 steps_json 多步编排:每步独立传输调用与审计,无 steps 的既有绑定走单步兼容路径 - 客户端实例校验 connector_type ∈ rest/soap/database,database 强制 db_kind 白名单,非 database 置空 - 三个传输层捕获线级事实(最终 SQL/渲染后 XML/原始响应)随调用记录落库,引擎可选透传 business_ref 业务锚点 - 新增调用日志查询 API(列表/详情/同 operation 步骤时间线,仅管理员)与管理端「调用日志」tab:筛选、双栏对照、外部工具复现命令 - 迁移 tt7a/tta9/tt5b:连接器类型枚举、绑定 steps_json、放开 calls 操作唯一约束 - 说明:wire_json 列迁移挂链尾(依赖域表迁移),随后续批次单独落地
This commit is contained in:
1 parent
8a814e7152
commit
e750fa8602
47 files changed
+7441
-353
No files matched your search
@@ -1,11 +1,13 @@
|
||||
"""services/integration_connector/binding.py
|
||||
|
||||
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
|
||||
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
|
||||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
|
||||
有序 BindingStep 快照(一对多配方),并冻结调用期配置。
|
||||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、
|
||||
errors.py、transports.base.merge_client_config。
|
||||
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
|
||||
且接口定义须为 published、客户端实例须 enabled(管理端「发布/退役」「启停」的总开关);
|
||||
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
|
||||
每步接口须 published、每步客户端须 enabled(fail-closed);同 context 下 priority
|
||||
高者优先;无命中或任一步门禁失败抛 BindingNotFoundError。
|
||||
存量空 steps_json 时由旧列合成单步(迁移兜底);读能力=单步,形状与多步统一。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,24 +24,35 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BindingSnapshot:
|
||||
"""一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。"""
|
||||
class BindingStep:
|
||||
"""绑定中的单步冻结快照:接口 + 归属客户端配置 + 该步参数映射。"""
|
||||
|
||||
capability: str
|
||||
context_selector: dict
|
||||
client_code: str
|
||||
interface_code: str
|
||||
connector_type: str
|
||||
interface_version: int
|
||||
mapping_version: int
|
||||
credential_ref_code: str | None
|
||||
client_code: str
|
||||
config: dict
|
||||
request_spec: dict
|
||||
response_mapping: dict
|
||||
output_schema: dict
|
||||
# 域参数→接口参数映射(空 = 同名直通)与接口入参 Schema(映射结果校验)。
|
||||
param_mapping: dict
|
||||
input_schema: dict
|
||||
param_mapping: dict
|
||||
output_schema: dict
|
||||
interface_version: int
|
||||
credential_ref_code: str | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BindingSnapshot:
|
||||
"""一次调用冻结的绑定快照:有序步骤 + 映射版本(非活表引用)。
|
||||
|
||||
读能力为单元素 steps;写能力可为多步。credential_ref_code 兼容字段取自首步
|
||||
(真实凭据在逐步 client 上,顺序引擎按步解析)。
|
||||
"""
|
||||
|
||||
capability: str
|
||||
context_selector: dict
|
||||
steps: tuple[BindingStep, ...]
|
||||
mapping_version: int
|
||||
credential_ref_code: str | None
|
||||
|
||||
|
||||
def _to_naive(dt: datetime | None) -> datetime | None:
|
||||
@@ -65,19 +78,140 @@ def _is_subset(selector: dict, context: dict) -> bool:
|
||||
return all(context.get(k) == v for k, v in selector.items())
|
||||
|
||||
|
||||
def _raw_steps_from_binding(row: IntegrationBinding) -> list[dict]:
|
||||
"""取出绑定步骤原料:优先 steps_json;空则由旧单步列合成(存量迁移兜底)。"""
|
||||
raw = list(row.steps_json or [])
|
||||
if raw:
|
||||
return raw
|
||||
# 兼容窗:迁移前/未回填行 → 单元素数组
|
||||
if row.interface_definition_code:
|
||||
return [{
|
||||
'interface_code': row.interface_definition_code,
|
||||
'param_mapping_json': row.param_mapping_json or {},
|
||||
}]
|
||||
return []
|
||||
|
||||
|
||||
def _freeze_step(
|
||||
*,
|
||||
capability: str,
|
||||
binding_id: int,
|
||||
step_index: int,
|
||||
step_raw: dict,
|
||||
) -> BindingStep:
|
||||
"""将一步配置冻结为 BindingStep;门禁失败抛 BindingNotFoundError。
|
||||
|
||||
Args:
|
||||
capability: 能力名(日志/异常)。
|
||||
binding_id: 绑定主键。
|
||||
step_index: 步骤下标(0-based,日志区分哪一步)。
|
||||
step_raw: {interface_code, param_mapping_json|param_mapping}。
|
||||
|
||||
Returns:
|
||||
BindingStep。
|
||||
|
||||
Raises:
|
||||
BindingNotFoundError: 接口/客户端缺失、未发布或停用。
|
||||
"""
|
||||
if not isinstance(step_raw, dict):
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=not_dict",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
iface_code = str(
|
||||
step_raw.get('interface_code') or step_raw.get('interface_definition_code') or ''
|
||||
).strip()
|
||||
if not iface_code:
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=missing_interface_code",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
mapping = step_raw.get('param_mapping_json', step_raw.get('param_mapping', {}))
|
||||
if mapping is None:
|
||||
mapping = {}
|
||||
if not isinstance(mapping, dict):
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=param_mapping_not_dict",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
|
||||
if iface is None:
|
||||
logger.warning(
|
||||
"connector binding step target missing: capability=%s binding_id=%s step=%s iface=%s",
|
||||
capability, binding_id, step_index, iface_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
client = IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
|
||||
if client is None:
|
||||
logger.warning(
|
||||
"connector binding step client missing: capability=%s binding_id=%s step=%s client=%s iface=%s",
|
||||
capability, binding_id, step_index, iface.client_instance_code, iface_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# fail-closed:该步接口未发布或客户端停用 → 视同无可用绑定(日志标明步号与原因)。
|
||||
if iface.status != 'published':
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s step=%s iface=%s reason=iface_status=%s",
|
||||
capability, binding_id, step_index, iface_code, iface.status,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
if not client.enabled:
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s step=%s client=%s reason=client_disabled",
|
||||
capability, binding_id, step_index, client.code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
config = merge_client_config({
|
||||
'config_json': client.config_json,
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
'db_kind': client.db_kind,
|
||||
})
|
||||
request_spec = dict(iface.request_spec_json or {})
|
||||
if iface.http_method is not None:
|
||||
request_spec['method'] = iface.http_method
|
||||
if iface.request_path is not None:
|
||||
request_spec['path'] = iface.request_path
|
||||
|
||||
return BindingStep(
|
||||
interface_code=iface.code,
|
||||
connector_type=client.connector_type,
|
||||
client_code=client.code,
|
||||
config=config,
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
input_schema=iface.input_schema_json or {},
|
||||
param_mapping=dict(mapping),
|
||||
output_schema=iface.output_schema_json or {},
|
||||
interface_version=int(iface.version or 1),
|
||||
credential_ref_code=client.credential_ref_code,
|
||||
)
|
||||
|
||||
|
||||
def resolve_binding(capability: str, context: dict, environment: str, *, now: datetime | None = None) -> BindingSnapshot:
|
||||
"""解析最佳绑定并冻结调用期快照。
|
||||
"""解析最佳绑定并冻结有序步骤快照。
|
||||
|
||||
Args:
|
||||
capability: 能力名(如 in_transit_transfer.query_inventory)。
|
||||
context: 路由上下文(来源/组织/租户等),如 {"source_code": "DBS-AWSBI"}。
|
||||
environment: 环境(prod/test/dev)。
|
||||
now: 可选时钟(测试注入);缺省用 utcnow。
|
||||
|
||||
Returns:
|
||||
BindingSnapshot。
|
||||
BindingSnapshot(steps 至少一元素;读能力通常单步)。
|
||||
|
||||
Raises:
|
||||
BindingNotFoundError: 无可用绑定(fail-closed);接口未发布或客户端已停用同样按
|
||||
无可用绑定处理(与列表「发布/退役」「启停」按钮语义闭环,且不向调用方泄露配置细节)。
|
||||
BindingNotFoundError: 无可用绑定,或任一步接口未发布/客户端停用/目标缺失
|
||||
(与列表「发布/退役」「启停」语义闭环;不向调用方泄露配置细节)。
|
||||
"""
|
||||
base_now = now or datetime.utcnow()
|
||||
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
|
||||
@@ -90,63 +224,37 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
continue
|
||||
candidates.append((row, selector))
|
||||
if not candidates:
|
||||
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」,
|
||||
# 否则调用方只看到 no binding for capability(2026-09 排障实测痛点)。
|
||||
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」。
|
||||
logger.warning(
|
||||
"connector binding miss: capability=%s env=%s published_rows=%s context_keys=%s",
|
||||
capability, environment, len(rows), sorted((context or {}).keys()),
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
|
||||
row, selector = candidates[0]
|
||||
|
||||
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
|
||||
if client is None or iface is None:
|
||||
raw_steps = _raw_steps_from_binding(row)
|
||||
if not raw_steps:
|
||||
logger.warning(
|
||||
"connector binding target missing: capability=%s binding_id=%s client=%s iface=%s",
|
||||
capability, row.id, row.client_instance_code, row.interface_definition_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
# fail-closed 门禁:接口未发布(draft/retired)或客户端已停用视同无可用绑定——
|
||||
# 管理端「发布/退役」「启停」按钮因此具备真实的调用期语义;错误类型与无命中一致。
|
||||
if iface.status != 'published' or not client.enabled:
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s iface_status=%s client_enabled=%s",
|
||||
capability, row.id, iface.status, client.enabled,
|
||||
"connector binding empty steps: capability=%s binding_id=%s",
|
||||
capability, row.id,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费
|
||||
# (与 transports.base.merge_client_config 同一实现)。
|
||||
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
|
||||
config = merge_client_config({
|
||||
'config_json': client.config_json,
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
})
|
||||
|
||||
request_spec = dict(iface.request_spec_json or {})
|
||||
if iface.http_method is not None:
|
||||
request_spec['method'] = iface.http_method
|
||||
if iface.request_path is not None:
|
||||
request_spec['path'] = iface.request_path
|
||||
|
||||
selector = dict(row.context_selector_json or {})
|
||||
steps: list[BindingStep] = []
|
||||
for idx, step_raw in enumerate(raw_steps):
|
||||
steps.append(_freeze_step(
|
||||
capability=capability,
|
||||
binding_id=row.id,
|
||||
step_index=idx,
|
||||
step_raw=step_raw,
|
||||
))
|
||||
|
||||
return BindingSnapshot(
|
||||
capability=row.capability,
|
||||
context_selector=selector,
|
||||
client_code=client.code,
|
||||
interface_code=iface.code,
|
||||
connector_type=client.connector_type,
|
||||
interface_version=iface.version,
|
||||
context_selector=dict(row.context_selector_json or {}),
|
||||
steps=tuple(steps),
|
||||
mapping_version=row.mapping_version,
|
||||
credential_ref_code=client.credential_ref_code,
|
||||
config=config,
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
output_schema=iface.output_schema_json or {},
|
||||
param_mapping=row.param_mapping_json or {},
|
||||
input_schema=iface.input_schema_json or {},
|
||||
credential_ref_code=steps[0].credential_ref_code,
|
||||
)
|
||||
@@ -1,11 +1,30 @@
|
||||
"""services/integration_connector/engine.py
|
||||
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→map-params→call→classify→audit。
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→按步 map-params→call→classify→audit。
|
||||
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
|
||||
逻辑:域入参先经能力 Schema 校验,再按绑定 param_mapping 翻译为接口参数(对照接口
|
||||
入参 Schema 校验);凭据按引用解析后以 credential_* 注入传输层;读能力返回
|
||||
带 status 的失败 dict 时原样分类,其余映射校验通过即 success;
|
||||
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
|
||||
逻辑:域入参先经能力 Schema 校验,再按绑定步骤 param_mapping 翻译为接口参数(对照该步
|
||||
接口入参 Schema 校验);凭据按引用逐步解析后以 credential_* 注入传输层。
|
||||
读能力(write=False)保持单步语义:首步执行 + 成功态做输出映射(行为与历史一致)。
|
||||
写能力(write=True)按 BindingSnapshot.steps 顺序执行四条统一规则(唯一编排语义,
|
||||
禁止扩展成 DSL):①resume=True 跳过全部非末步(不建连、不审计);
|
||||
②非末步失败/超时 → 中止=技术失败(后续步零调用):普通失败原样返回该步分类结果;
|
||||
超时的审计行保留 status='timeout' 技术真相,引擎对外返回 technical_failed
|
||||
(error_code=EXTERNAL_TIMEOUT_ABORTED,与末步超时区分)——stage 超时=WS 未触发、
|
||||
ERP 不可能建单,恢复路径是全量重跑(stage SQL 自带 DELETE 同时间戳幂等),
|
||||
不得落入 result_unknown 红线态;
|
||||
③末步响应经该步 response_mapping 映射 → 六态分类,result.data 恒带映射结果
|
||||
(含失败态);④末步超时 → status=timeout(上层落 result_unknown)。
|
||||
非末步成功放行后支持可选同步回调 on_nonfinal_success(通用步进机制,非业务 DSL):
|
||||
供域调用方在「中间表写成功」与「触发末步」之间落库断点标记(如 stage_confirmed_at
|
||||
先落库再触发);回调异常按该步失败处理(中止=technical_failed,追加异常审计行);
|
||||
读能力单步路径不回调。
|
||||
每步落一条 IntegrationCall:同 operation_id(一票一次执行 = N 条,按 operation_id 串联,
|
||||
步骤定位靠 binding_snapshot_json 的 step_index;模型已解除该列唯一约束并补普通索引,
|
||||
迁移 tt5b6c7d8e9f);传输层返回的保留键 `_wire`(线级事实,database/soap/rest)在落库前
|
||||
剥离为 wire_json 独立成列(经 _clamp_wire 统一尺寸收口,防超大响应撑爆审计行),
|
||||
禁止混入 response_summary_json;调用方可透传 business_ref(业务单号锚点)落库供检索;
|
||||
禁止跨步传参;入参非法/无绑定/映射失败/无 transport
|
||||
均 fail-closed;result_unknown 不自动重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,9 +33,10 @@ import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import replace
|
||||
from typing import Callable
|
||||
|
||||
from app import db
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
from app.services.integration_connector.binding import BindingSnapshot, BindingStep, resolve_binding
|
||||
from app.services.integration_connector.capability import CapabilitySpec, get_capability
|
||||
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
|
||||
from app.services.integration_connector.mapping import map_response, schema_errors
|
||||
@@ -31,6 +51,38 @@ from app.models import IntegrationCall
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 非末步"允许继续"的终态:仅成功族。其余(失败态/timeout/result_unknown)一律中止——
|
||||
# 非末步未确认成功时继续执行后续步会破坏"先落表后触发"的顺序不变量。
|
||||
_NON_FINAL_PROCEED_STATUSES = ('success', 'duplicate_success', 'duplicate_unverified')
|
||||
|
||||
# wire_json 内单字符串尺寸收口上限(控制器裁定:引擎侧统一截断,不在三传输层散补)。
|
||||
_WIRE_MAX_STRING_LEN = 20000
|
||||
# 超长截断尾缀:排障时可辨识"此处曾被收口",非原文。
|
||||
_WIRE_TRUNCATED_SUFFIX = '...[truncated]'
|
||||
|
||||
|
||||
def _clamp_wire(wire):
|
||||
"""递归收口 wire_json 内所有字符串字段到 _WIRE_MAX_STRING_LEN(纯函数,不改入参)。
|
||||
|
||||
用途:传输层 `_wire` 可能携带超大线级事实(SQL 全文/statements[].sql、请求体/
|
||||
响应体等),落 IntegrationCall.wire_json 前统一截断,防审计行与 JSON 列被撑爆。
|
||||
|
||||
Args:
|
||||
wire: `_wire` 原始结构(dict/嵌套 dict/list/标量任意组合)。
|
||||
Returns:
|
||||
收口后的新结构:超长字符串截为前 _WIRE_MAX_STRING_LEN 字符并追加
|
||||
_WIRE_TRUNCATED_SUFFIX 尾缀;未超长字符串与其余类型原样保留。
|
||||
"""
|
||||
if isinstance(wire, str):
|
||||
if len(wire) > _WIRE_MAX_STRING_LEN:
|
||||
return wire[:_WIRE_MAX_STRING_LEN] + _WIRE_TRUNCATED_SUFFIX
|
||||
return wire
|
||||
if isinstance(wire, dict):
|
||||
return {key: _clamp_wire(value) for key, value in wire.items()}
|
||||
if isinstance(wire, (list, tuple)):
|
||||
return [_clamp_wire(item) for item in wire]
|
||||
return wire
|
||||
|
||||
|
||||
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
|
||||
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
|
||||
@@ -94,7 +146,43 @@ class CapabilityGateway:
|
||||
idempotency_key: str | None = None,
|
||||
environment: str | None = None,
|
||||
transports: dict[str, Transport] | None = None,
|
||||
resume: bool = False,
|
||||
on_nonfinal_success: Callable[[BindingStep, int], None] | None = None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""执行一次能力调用:读能力单步(既有行为);写能力按绑定步骤顺序执行。
|
||||
|
||||
Args:
|
||||
capability: 已注册能力名。
|
||||
context: 绑定路由上下文(来源/组织等键值对)。
|
||||
params: 域入参(先经能力 input_schema 校验,再逐步经 param_mapping 翻译)。
|
||||
operation_id: 审计串联键(一次调用 N 步共享,按 step_index 定位)。
|
||||
idempotency_key: 预留幂等键(引擎当前不消费)。
|
||||
environment: 显式环境;缺省从 Flask 配置推导。
|
||||
transports: 临时覆盖的 {connector_type: Transport}。
|
||||
resume: True 时跳过全部非末步(断点续跑:该票可能已建成单,禁止重插,
|
||||
只重新触发末步);被跳过的步骤不建连、不落审计、不回调。
|
||||
on_nonfinal_success: 通用步进回调(仅写能力多步路径):每个非末步成功放行
|
||||
(该步审计落库后、进入下一步前)同步调用一次,入参 (该步 BindingStep, 步号)。
|
||||
用途:域调用方在「中间表写成功」与「触发末步」之间落库断点标记
|
||||
(如 stage_confirmed_at 先落库再触发,D7③)。约束:回调同步执行并阻塞
|
||||
后续步,须保持短小——长事务/外部 IO 的副作用与耗时由调用方自律;
|
||||
回调异常按该步失败处理(中止=technical_failed,追加异常审计行,
|
||||
原成功审计行保留不篡改)。读能力单步路径不回调。
|
||||
business_ref: 通用业务锚点(可空):调用方透传的业务单号/任务号,落
|
||||
IntegrationCall.business_ref 供调用日志按业务单号检索/关联(能力无关,
|
||||
不传为 NULL,现有消费者零改动)。
|
||||
|
||||
Returns:
|
||||
IntegrationCallResult(六态之一;写能力末步 data 恒带映射结果)。
|
||||
|
||||
Raises:
|
||||
CapabilityNotFoundError: 能力未注册。
|
||||
InputInvalidError: 域入参不合能力输入 Schema。
|
||||
BindingNotFoundError: 无可用绑定或任一步接口/客户端门禁失败。
|
||||
CallFailedError: 某步无可用 transport。
|
||||
MappingInvalidError: 参数翻译或末步输出映射不合 Schema。
|
||||
"""
|
||||
spec = get_capability(capability)
|
||||
input_errors = schema_errors(params, spec.input_schema)
|
||||
if input_errors:
|
||||
@@ -108,70 +196,297 @@ class CapabilityGateway:
|
||||
|
||||
env = environment or _environment()
|
||||
snapshot = resolve_binding(capability, context, env)
|
||||
if not spec.write:
|
||||
return self._call_read(spec, snapshot, params, operation_id, transports, business_ref)
|
||||
return self._call_write(
|
||||
spec, snapshot, params, operation_id, transports, resume, on_nonfinal_success,
|
||||
business_ref,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 读能力:单步(既有行为,勿改语义)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _call_read(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""读能力单步执行:首步翻译参数 → 调用 → 失败态直通分类 / 成功态输出映射。"""
|
||||
step = snapshot.steps[0]
|
||||
# 域参数 → 接口参数翻译:绑定配置了 param_mapping 时按映射引擎执行,
|
||||
# 结果对照接口入参 Schema 校验;未配置时同名直通(能力入参原样下传)。
|
||||
params = map_response(snapshot.param_mapping, params, snapshot.input_schema) \
|
||||
if snapshot.param_mapping else params
|
||||
transport = (transports or self.transports).get(snapshot.connector_type)
|
||||
params = map_response(step.param_mapping, params, step.input_schema) \
|
||||
if step.param_mapping else params
|
||||
transport = (transports or self.transports).get(step.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={step.connector_type}'})
|
||||
|
||||
# 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。
|
||||
credential = resolve_credential(snapshot.credential_ref_code) if snapshot.credential_ref_code else {}
|
||||
request = build_request(snapshot.request_spec, snapshot.config, params)
|
||||
credential = resolve_credential(step.credential_ref_code) if step.credential_ref_code else {}
|
||||
request = build_request(step.request_spec, step.config, params)
|
||||
trace_id = f'ic-{uuid.uuid4().hex}'
|
||||
start_ms = int(time.time() * 1000)
|
||||
try:
|
||||
raw = transport.call(
|
||||
client={'config_json': snapshot.config, 'credential': credential},
|
||||
interface={'request_spec_json': snapshot.request_spec},
|
||||
client={'config_json': step.config, 'credential': credential},
|
||||
interface={'request_spec_json': step.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, 0, params, None, result, start_ms, trace_id, business_ref)
|
||||
return result
|
||||
|
||||
if spec.write:
|
||||
result = classify_transport_response(raw)
|
||||
elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||||
if isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||||
# 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML)→ 原样分类,不做输出映射。
|
||||
result = classify_transport_response(raw)
|
||||
else:
|
||||
result = IntegrationCallResult(status='success')
|
||||
if result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
|
||||
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
|
||||
data = map_response(step.response_mapping, raw, step.output_schema or spec.output_schema)
|
||||
result = replace(result, data=data)
|
||||
result = replace(result, trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, raw, result, start_ms, trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, 0, params, raw, result, start_ms, trace_id, business_ref)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 写能力:多步顺序执行(四条统一规则)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _call_write(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
resume: bool,
|
||||
on_nonfinal_success: Callable[[BindingStep, int], None] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""写能力按绑定步骤顺序执行;规则②非末步失败/超时中止、规则④末步超时返回 timeout。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(write=True)。
|
||||
snapshot: 冻结的有序步骤快照(≥1 步)。
|
||||
params: 域入参(已过能力 Schema 校验)。
|
||||
operation_id: 审计串联键。
|
||||
transports: 临时覆盖的传输层字典。
|
||||
resume: 规则①——True 跳过全部非末步(不建连、不审计、不回调)。
|
||||
on_nonfinal_success: 非末步成功放行后的同步回调((该步 BindingStep, 步号));
|
||||
None 表示不回调。
|
||||
business_ref: 业务锚点(可空):透传各步审计行 business_ref 列落库。
|
||||
|
||||
Returns:
|
||||
末步分类结果;或中止步(非末步)结果——普通失败原样返回该步分类结果,
|
||||
超时中止对外返回 technical_failed(EXTERNAL_TIMEOUT_ABORTED,与末步超时区分),
|
||||
回调异常中止返回 technical_failed(STEP_CALLBACK_FAILED)。
|
||||
"""
|
||||
steps = snapshot.steps
|
||||
last_index = len(steps) - 1
|
||||
result: IntegrationCallResult | None = None
|
||||
for index, step in enumerate(steps):
|
||||
is_final = index == last_index
|
||||
if resume and not is_final:
|
||||
# 规则①:续跑只执行末步——非末步可能已落表,禁止重插;不建连、不审计、不回调。
|
||||
continue
|
||||
result, step_params, trace_id, start_ms = self._execute_step(
|
||||
spec, snapshot, index, step, params, operation_id, transports, business_ref,
|
||||
)
|
||||
if not is_final and result.status not in _NON_FINAL_PROCEED_STATUSES:
|
||||
if result.status == 'timeout':
|
||||
# 规则②:非末步超时 → 中止=技术失败。审计行已按 'timeout' 落库(技术
|
||||
# 真相),对外改判 technical_failed:stage 超时=WS 未触发、ERP 不可能
|
||||
# 建单,正确恢复路径是全量重跑(stage SQL 自带 DELETE 同时间戳幂等),
|
||||
# 不得落入 result_unknown 红线态(组锁+人工 retrigger)。
|
||||
result = replace(result, status='technical_failed', error_code='EXTERNAL_TIMEOUT_ABORTED')
|
||||
return result
|
||||
if not is_final and on_nonfinal_success is not None:
|
||||
# 通用步进机制(非业务 DSL):非末步成功放行且审计已落库后、进入下一步前
|
||||
# 同步回调一次——域调用方借此在「中间表写成功」与「触发末步」之间落库
|
||||
# 断点标记(如 stage_confirmed_at 先落库再触发,D7③)。
|
||||
callback_started_ms = int(time.time() * 1000)
|
||||
try:
|
||||
on_nonfinal_success(step, index)
|
||||
except Exception as exc:
|
||||
# 回调异常按该步失败处理:中止=technical_failed,并追加一条异常审计行
|
||||
# (原成功审计行保留不篡改,append-only,同 operation_id 同 step_index)。
|
||||
logger.warning(
|
||||
"connector nonfinal callback failed: capability=%s operation_id=%s step=%s",
|
||||
spec.name, operation_id, index, exc_info=True,
|
||||
)
|
||||
cb_result = IntegrationCallResult(
|
||||
status='technical_failed',
|
||||
error_code='STEP_CALLBACK_FAILED',
|
||||
error_message=str(exc)[:500],
|
||||
trace_id=trace_id,
|
||||
)
|
||||
_record_call(
|
||||
operation_id, spec.name, snapshot, index, step_params,
|
||||
None, cb_result, callback_started_ms, trace_id, business_ref,
|
||||
)
|
||||
return cb_result
|
||||
assert result is not None # steps ≥ 1(resolve_binding 保证),末步必产出结果
|
||||
return result
|
||||
|
||||
def _execute_step(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
index: int,
|
||||
step: BindingStep,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> tuple[IntegrationCallResult, dict, str, int]:
|
||||
"""执行单步:参数翻译 → transport → 分类;末步追加映射 + 六态分类(规则③)。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(write=True)。
|
||||
snapshot: 冻结的有序步骤快照。
|
||||
index: 当前步下标(0-based)。
|
||||
step: 当前步快照。
|
||||
params: 域入参(已过能力 Schema 校验)。
|
||||
operation_id: 审计串联键(所有步骤共用同一裸值)。
|
||||
transports: 临时覆盖的传输层字典。
|
||||
business_ref: 业务锚点(可空):本步审计行 business_ref 列落库值。
|
||||
|
||||
Returns:
|
||||
(该步结果, 该步翻译后的接口参数, trace_id, 起始毫秒)——后三项供调用方在
|
||||
回调异常等场景补落审计行时复用。
|
||||
"""
|
||||
# 域参数 → 该步接口参数翻译(沿用既有 map_response 路径,结果对照该步入参 Schema)。
|
||||
step_params = map_response(step.param_mapping, params, step.input_schema) \
|
||||
if step.param_mapping else params
|
||||
transport = (transports or self.transports).get(step.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={step.connector_type}'})
|
||||
credential = resolve_credential(step.credential_ref_code) if step.credential_ref_code else {}
|
||||
request = build_request(step.request_spec, step.config, step_params)
|
||||
trace_id = f'ic-{uuid.uuid4().hex}' # 每步独立链路 ID(与单步时代一致;串联由 operation_id 承担)
|
||||
start_ms = int(time.time() * 1000)
|
||||
try:
|
||||
raw = transport.call(
|
||||
client={'config_json': step.config, 'credential': credential},
|
||||
interface={'request_spec_json': step.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, index, step_params, None, result, start_ms, trace_id, business_ref)
|
||||
return result, step_params, trace_id, start_ms
|
||||
|
||||
if index == len(snapshot.steps) - 1:
|
||||
result = _finalize_step(spec, step, raw, trace_id)
|
||||
else:
|
||||
# 非末步不产出末步判定:仅按传输层分类,供"是否继续"判定。
|
||||
classified = classify_transport_response(raw if isinstance(raw, dict) else {})
|
||||
result = replace(classified, trace_id=trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, index, step_params, raw, result, start_ms, trace_id, business_ref)
|
||||
return result, step_params, trace_id, start_ms
|
||||
|
||||
|
||||
def _finalize_step(
|
||||
spec: CapabilitySpec,
|
||||
step: BindingStep,
|
||||
raw: dict | None,
|
||||
trace_id: str,
|
||||
) -> IntegrationCallResult:
|
||||
"""末步判定链(规则③):response_mapping 映射 → 六态分类。
|
||||
|
||||
分类输入 = 原始响应 ∪ 映射结果(映射优先):映射未覆盖 status 时保留传输层
|
||||
规范六态(存量单步写绑定兼容),覆盖后以映射为准(如 TIPTOP code→status)。
|
||||
result.data 恒带 mapped(含失败态),供上层消费业务字段;ERP 业务拒单
|
||||
(code≠0)即 classify 归 technical_failed、code/message 透传(用户口径:
|
||||
失败+原因,恢复动作与关票口径对失败态本就一致)。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(output_schema 兜底来源)。
|
||||
step: 末步快照(response_mapping/output_schema)。
|
||||
raw: 末步原始响应。
|
||||
trace_id: 链路追踪 ID。
|
||||
|
||||
Returns:
|
||||
分类后的 IntegrationCallResult。
|
||||
|
||||
Raises:
|
||||
MappingInvalidError: 映射结果不合该步/能力输出 Schema(fail-closed)。
|
||||
"""
|
||||
mapped = map_response(step.response_mapping, raw, step.output_schema or spec.output_schema)
|
||||
base = dict(raw) if isinstance(raw, dict) else {}
|
||||
result = classify_transport_response({**base, **mapped})
|
||||
return replace(result, data=mapped, trace_id=trace_id)
|
||||
|
||||
|
||||
def _record_call(
|
||||
operation_id: str,
|
||||
capability: str,
|
||||
snapshot: BindingSnapshot,
|
||||
step_index: int,
|
||||
params: dict,
|
||||
raw: dict | None,
|
||||
result: IntegrationCallResult,
|
||||
start_ms: int,
|
||||
trace_id: str,
|
||||
business_ref: str | None = None,
|
||||
) -> None:
|
||||
"""落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。"""
|
||||
"""落 IntegrationCall(每步一条;同 operation_id 串联 + step_index 定位 + 脱敏请求/响应摘要)。
|
||||
|
||||
多步顺序引擎一次调用落 N 条、共享同一裸 operation_id(模型唯一约束已由迁移
|
||||
tt5b6c7d8e9f 解除并补普通索引);步骤定位靠 binding_snapshot_json.step_index/step_count。
|
||||
传输层保留键 `_wire`(线级事实)在本函数剥离:经 _clamp_wire 尺寸收口后落
|
||||
wire_json 独立成列,不混入 response_summary_json。
|
||||
|
||||
Args:
|
||||
operation_id: 审计串联键(所有步骤共用同一裸值)。
|
||||
capability: 能力名。
|
||||
snapshot: 冻结的有序步骤快照。
|
||||
step_index: 当前步下标(0-based)。
|
||||
params: 该步翻译后的接口参数(sanitize 脱敏后入审计)。
|
||||
raw: 该步原始响应(超时为 None;可含保留键 `_wire`)。
|
||||
result: 该步结果。
|
||||
start_ms: 该步起始毫秒时间戳。
|
||||
trace_id: 该步链路 ID(每步独立生成)。
|
||||
business_ref: 业务锚点(可空):调用方透传的业务单号/任务号,不传为 NULL。
|
||||
"""
|
||||
elapsed_ms = int(time.time() * 1000) - start_ms
|
||||
step = snapshot.steps[step_index]
|
||||
# 剥离保留键 `_wire`:副本上 pop(不污染传输层原返回对象);非 dict(可缺/异形)
|
||||
# 视为无 wire;dict 则尺寸收口后落 wire_json 独立列。余下内容才是响应摘要。
|
||||
raw_dict = dict(raw) if isinstance(raw, dict) else {}
|
||||
wire = raw_dict.pop('_wire', None)
|
||||
call = IntegrationCall(
|
||||
operation_id=operation_id,
|
||||
capability=capability,
|
||||
binding_snapshot_json={
|
||||
'client_code': snapshot.client_code,
|
||||
'interface_code': snapshot.interface_code,
|
||||
'connector_type': snapshot.connector_type,
|
||||
'interface_version': snapshot.interface_version,
|
||||
'client_code': step.client_code,
|
||||
'interface_code': step.interface_code,
|
||||
'connector_type': step.connector_type,
|
||||
'interface_version': step.interface_version,
|
||||
'mapping_version': snapshot.mapping_version,
|
||||
'credential_ref_code': snapshot.credential_ref_code,
|
||||
'credential_ref_code': step.credential_ref_code,
|
||||
# 步骤定位:本条审计对应的步号与总步数(一票一次执行 = N 条同 operation_id)。
|
||||
'step_index': step_index,
|
||||
'step_count': len(snapshot.steps),
|
||||
'steps': [
|
||||
{
|
||||
'interface_code': s.interface_code,
|
||||
'client_code': s.client_code,
|
||||
'connector_type': s.connector_type,
|
||||
}
|
||||
for s in snapshot.steps
|
||||
],
|
||||
},
|
||||
request_summary_json=sanitize(params),
|
||||
response_summary_json=sanitize(raw or {}),
|
||||
response_summary_json=sanitize(raw_dict or {}),
|
||||
wire_json=_clamp_wire(wire) if isinstance(wire, dict) else None,
|
||||
business_ref=business_ref,
|
||||
status=result.status,
|
||||
elapsed_ms=elapsed_ms,
|
||||
trace_id=trace_id,
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"""services/integration_connector/gateway.py
|
||||
|
||||
用途:模块级 CapabilityGateway 装配与测试注入点。
|
||||
依赖:engine.CapabilityGateway、transports.rest/soap。
|
||||
逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。
|
||||
依赖:engine.CapabilityGateway、transports.rest/soap/database。
|
||||
逻辑:生产用 REST/SOAP/Database 传输;测试通过 set_capability_gateway 注入替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.engine import CapabilityGateway
|
||||
from app.services.integration_connector.transports.database import DatabaseTransport
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
@@ -21,7 +22,11 @@ def set_capability_gateway(gateway: CapabilityGateway | None) -> None:
|
||||
|
||||
|
||||
def get_capability_gateway() -> CapabilityGateway:
|
||||
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。"""
|
||||
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP/Database)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()})
|
||||
return CapabilityGateway(transports={
|
||||
'rest': RestTransport(),
|
||||
'soap': SoapTransport(),
|
||||
'database': DatabaseTransport(),
|
||||
})
|
||||
@@ -168,6 +168,11 @@ def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
|
||||
return MISSING
|
||||
if key_field is None or key_value is None:
|
||||
raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"})
|
||||
# [形态归一] XML 归一化后重复子节点"单条=dict、多条=list"二态并存(如单条
|
||||
# Field);单 dict 等价单元素列表,直接按列表语义 pick(回归:ERP 返回单条
|
||||
# doc_no Field 时 pick_target_not_list → 单号丢失,单被误判 technical_failed)。
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "pick_target_not_list"})
|
||||
for item in value:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""services/integration_connector/transports/__init__.py
|
||||
|
||||
集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。
|
||||
集成连接器传输层:base(契约+分类)、rest、soap、database。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
|
||||
from app.services.integration_connector.transports.database import DatabaseTransport
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
@@ -15,4 +16,5 @@ __all__ = [
|
||||
'classify_transport_response',
|
||||
'RestTransport',
|
||||
'SoapTransport',
|
||||
'DatabaseTransport',
|
||||
]
|
||||
@@ -5,6 +5,7 @@
|
||||
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
|
||||
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
|
||||
probe 为可选实现的连接测试探针(只证明网络可达,不做业务调用)。
|
||||
merge_client_config 将 endpoint/timeout_seconds/db_kind 专列拼回 config_json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -52,16 +53,19 @@ class Transport(Protocol):
|
||||
|
||||
|
||||
def merge_client_config(client: dict) -> dict:
|
||||
"""把客户端实例独立列(endpoint/timeout_seconds)拼回 config_json 的兼容层。
|
||||
"""把客户端实例独立列(endpoint/timeout_seconds/db_kind)拼回 config_json 的兼容层。
|
||||
|
||||
与 binding.resolve_binding 的列拼回逻辑同源(单一实现),供连接测试等
|
||||
不经绑定解析、直接消费客户端实例的调用方复用;返回副本,不改入参。
|
||||
database 类型的 db_kind 专列在此拼入,供 DatabaseTransport 查驱动注册表。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
if client.get('endpoint') is not None:
|
||||
config['endpoint'] = client['endpoint']
|
||||
if client.get('timeout_seconds') is not None:
|
||||
config['timeout_seconds'] = client['timeout_seconds']
|
||||
if client.get('db_kind') is not None:
|
||||
config['db_kind'] = client['db_kind']
|
||||
return config
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
"""services/integration_connector/transports/database.py
|
||||
|
||||
用途:Database SQL 传输层——按 db_kind 四库驱动注册表连接并执行/查询 SQL。
|
||||
依赖:oracledb / pymysql / psycopg2 / pymssql;errors、transports.base.mask_secrets。
|
||||
逻辑:gateway 按 connector_type=database 分发至此;request_spec.sql 支持 execute
|
||||
(pre→bulk→post 单事务 commit)与 query(返回 rows 不 commit);D17 标识符
|
||||
白名单 `{key}` 替换(替换后残留任何 `{...}` 形状即 fail-closed,封堵畸形
|
||||
占位符静默直通缺口);四库 connect 工厂消费 config.timeout_seconds 接入驱动
|
||||
超时参数(缺失/非法用驱动默认);异常 rollback + 凭据脱敏;probe 按库种 probe_sql。
|
||||
标识符替换后须从 bind dict 剔除白名单键(oracledb 不容多余键);pre/bulk/post/query
|
||||
再按各语句实际引用的 :bind(跳过字符串字面量与注释)逐语句过滤(oracledb 对
|
||||
语句未引用的键同样报 ORA-01036)。
|
||||
本模块禁止出现具体业务表/单据字面量(D12)。
|
||||
调用日志:execute/query 成功返回 dict 附带保留键 `_wire`(语句、最终 SQL、
|
||||
实际绑定、行数/行快照等线级事实),由引擎(Task 4)剥离落库 wire_json,
|
||||
禁止上游业务消费该键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.integration_connector.errors import InputInvalidError, TransportNotFrozenError
|
||||
from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
# D17:标识符(schema/表名)安全正则——字母开头,允许字母数字与 _ $ #
|
||||
_IDENTIFIER_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_$#]{0,127}$')
|
||||
# 语句中出现的 {placeholder}
|
||||
_PLACEHOLDER_RE = re.compile(r'\{([A-Za-z_][A-Za-z0-9_]*)\}')
|
||||
# 语句中出现的 :bind(配合字面量/注释扫描使用)
|
||||
_PLACEHOLDER_BIND_RE = re.compile(r':([A-Za-z_][A-Za-z0-9_]*)')
|
||||
# 任意 `{...}` 残留形状(含畸形占位符如 {schema.} / {1abc} / {})——替换后不容残留
|
||||
_RESIDUAL_PLACEHOLDER_RE = re.compile(r'\{[^}]*\}')
|
||||
# endpoint 统一 host:port[/database](oracle 段为 service_name)
|
||||
_ENDPOINT_RE = re.compile(r'^([^:]+):(\d+)(?:/(.+))?$')
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
ConnectFn = Callable[..., Any]
|
||||
|
||||
|
||||
def _timeout_seconds(config: dict) -> int | None:
|
||||
"""从 config.timeout_seconds 解析整数秒;缺失/非法/非正数 → None(用驱动默认,不报错)。
|
||||
|
||||
Args:
|
||||
config: 客户端 config(merge_client_config 已拼入 timeout_seconds 专列值)。
|
||||
|
||||
Returns:
|
||||
正整数秒;不可解析或 ≤0 返回 None(调用方据此省略驱动超时参数)。
|
||||
"""
|
||||
raw = config.get('timeout_seconds')
|
||||
if raw is None or isinstance(raw, bool):
|
||||
return None
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return value if value > 0 else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DriverSpec:
|
||||
"""单库驱动规格:connect 工厂 + probe SQL。"""
|
||||
|
||||
connect: ConnectFn
|
||||
probe_sql: str
|
||||
|
||||
|
||||
def _parse_endpoint(endpoint: str) -> tuple[str, int, str | None]:
|
||||
"""解析统一 endpoint 为 (host, port, database_or_service)。
|
||||
|
||||
Args:
|
||||
endpoint: `host:port` 或 `host:port/database`(oracle 为 service_name)。
|
||||
|
||||
Returns:
|
||||
(host, port, database_or_service);无路径段时第三项为 None。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 格式不合法。
|
||||
"""
|
||||
text = str(endpoint or '').strip()
|
||||
match = _ENDPOINT_RE.match(text)
|
||||
if not match:
|
||||
raise TransportNotFrozenError(f'invalid database endpoint: {endpoint!r}')
|
||||
host, port_s, db = match.group(1), match.group(2), match.group(3)
|
||||
return host, int(port_s), db or None
|
||||
|
||||
|
||||
def _connect_oracle(*, config: dict, credential: dict) -> Any:
|
||||
"""Oracle:oracledb EZConnect dsn=host:port/service;可选 thick(11g 等老服务端必须)。
|
||||
|
||||
thick 目录取值优先级:按客户端 config_json.oracle_lib_dir → 全局环境变量
|
||||
ORACLE_CLIENT_LIB_DIR(.env.* 由 settings 载入 os.environ;容器/系统环境同样生效,
|
||||
与 text2sql 同源)。初始化失败(路径无效/版本过老/已初始化)静默回退 thin——
|
||||
真实连接失败在 connect 处暴露(thick-only 的老版本服务端会报 DPY-3010)。
|
||||
超时:tcp_connect_timeout(秒,建连超时)为安装版本(oracledb 4.0.2)connect()
|
||||
实际支持的参数;call_timeout(毫秒,单次 round-trip 超时)不是 connect 参数,
|
||||
建连后按连接属性设置(thin/thick 均支持,异常安装版本静默跳过用驱动默认)。
|
||||
"""
|
||||
import oracledb
|
||||
|
||||
# [STEP 1] 可选 thick 模式(config_json.oracle_lib_dir → 全局环境兜底)
|
||||
lib_dir = str(config.get('oracle_lib_dir') or '').strip() or (os.getenv('ORACLE_CLIENT_LIB_DIR') or '').strip()
|
||||
if lib_dir:
|
||||
try:
|
||||
oracledb.init_oracle_client(lib_dir=lib_dir)
|
||||
except Exception:
|
||||
# 已初始化或 thin 可用时忽略;真实连接失败再暴露
|
||||
pass
|
||||
|
||||
host, port, service = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
if not service:
|
||||
raise TransportNotFrozenError('oracle endpoint requires service_name: host:port/service')
|
||||
dsn = f'{host}:{port}/{service}'
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs['tcp_connect_timeout'] = timeout
|
||||
conn = oracledb.connect(
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
dsn=dsn,
|
||||
**kwargs,
|
||||
)
|
||||
if timeout is not None:
|
||||
try:
|
||||
conn.call_timeout = timeout * 1000 # 毫秒
|
||||
except Exception:
|
||||
# 个别安装模式不支持 call_timeout 属性时跳过(建连超时已生效),不阻断调用
|
||||
pass
|
||||
return conn
|
||||
|
||||
|
||||
def _connect_mysql(*, config: dict, credential: dict) -> Any:
|
||||
"""MySQL:pymysql,charset=utf8mb4;超时=connect/read/write_timeout(秒)。"""
|
||||
import pymysql
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs.update(connect_timeout=timeout, read_timeout=timeout, write_timeout=timeout)
|
||||
return pymysql.connect(
|
||||
host=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
database=database or '',
|
||||
charset='utf8mb4',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _connect_postgresql(*, config: dict, credential: dict) -> Any:
|
||||
"""PostgreSQL:psycopg2,dbname 对应 endpoint 路径段;超时=connect_timeout(秒)。"""
|
||||
import psycopg2
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs['connect_timeout'] = timeout
|
||||
return psycopg2.connect(
|
||||
host=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
dbname=database or '',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _connect_sqlserver(*, config: dict, credential: dict) -> Any:
|
||||
"""SQL Server:pymssql(注册表键为 sqlserver,非 mssql);超时=login/timeout(秒)。"""
|
||||
import pymssql
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs.update(login_timeout=timeout, timeout=timeout)
|
||||
return pymssql.connect(
|
||||
server=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
database=database or '',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
# D16 四库驱动注册表;键必须与 models.DB_KINDS 一致(sqlserver 非 mssql)。
|
||||
_DRIVERS: dict[str, DriverSpec] = {
|
||||
'oracle': DriverSpec(connect=_connect_oracle, probe_sql='SELECT 1 FROM DUAL'),
|
||||
'mysql': DriverSpec(connect=_connect_mysql, probe_sql='SELECT 1'),
|
||||
'postgresql': DriverSpec(connect=_connect_postgresql, probe_sql='SELECT 1'),
|
||||
'sqlserver': DriverSpec(connect=_connect_sqlserver, probe_sql='SELECT 1'),
|
||||
}
|
||||
|
||||
|
||||
def _apply_identifiers(sql: str, *, identifiers: list[str], params: dict) -> str:
|
||||
"""对单条 SQL 做 D17 标识符 `{key}` 白名单替换。
|
||||
|
||||
标识符值字面量写入 SQL,不走 :bind。调用方在 execute/executemany 前须用
|
||||
`_strip_identifier_keys` 剔除白名单键,否则 oracledb 等对多余 bind 键报错。
|
||||
|
||||
Args:
|
||||
sql: 原始语句。
|
||||
identifiers: 允许替换的键名白名单。
|
||||
params: 绑定参数(标识符值取自此,不走 :bind)。
|
||||
|
||||
Returns:
|
||||
替换后的 SQL(保证无任何 `{...}` 残留形状)。
|
||||
|
||||
Raises:
|
||||
InputInvalidError: 未声明占位符、缺值、值未过安全正则,或替换后仍残留
|
||||
`{...}` 形状(畸形占位符如 `{schema.}`/`{1abc}` 不匹配替换正则,
|
||||
若不拦截会原样进入 SQL——fail-closed 封堵该静默直通缺口)。
|
||||
"""
|
||||
allowed = set(identifiers or [])
|
||||
|
||||
def _repl(match: re.Match[str]) -> str:
|
||||
key = match.group(1)
|
||||
if key not in allowed:
|
||||
raise InputInvalidError(
|
||||
f'undeclared SQL identifier placeholder: {{{key}}}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
if key not in params:
|
||||
raise InputInvalidError(
|
||||
f'missing identifier value: {key}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
value = str(params[key])
|
||||
if not _IDENTIFIER_RE.match(value):
|
||||
raise InputInvalidError(
|
||||
f'illegal SQL identifier value for {key}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
return value
|
||||
|
||||
result = _PLACEHOLDER_RE.sub(_repl, sql)
|
||||
# 替换完成后断言无残留:任何 `{...}` 形状(含畸形占位符)都视为未消化的模板,
|
||||
# 静默下传会让数据库收到字面 `{...}` 或被利用的畸形标识符。
|
||||
residual = _RESIDUAL_PLACEHOLDER_RE.search(result)
|
||||
if residual:
|
||||
raise InputInvalidError(
|
||||
f'unresolved SQL placeholder after substitution: {residual.group(0)}',
|
||||
details={'placeholder': residual.group(0)},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _strip_identifier_keys(params: dict, identifiers: list[str]) -> dict:
|
||||
"""从 bind 参数字典中剔除 identifiers 白名单键。
|
||||
|
||||
用途:`{schema}` 等已做字面量替换后,不得再作为 :bind 传入驱动。
|
||||
核心逻辑:按白名单集合过滤,返回新 dict(不修改入参)。
|
||||
|
||||
Args:
|
||||
params: 待传给 execute/executemany 的绑定参数。
|
||||
identifiers: `sql.identifiers` 白名单键列表。
|
||||
|
||||
Returns:
|
||||
已剔除标识符键的新字典。
|
||||
"""
|
||||
if not identifiers:
|
||||
return dict(params)
|
||||
drop = set(identifiers)
|
||||
return {k: v for k, v in params.items() if k not in drop}
|
||||
|
||||
|
||||
def _referenced_bind_names(sql: str) -> set[str]:
|
||||
"""提取语句实际引用的 :bind 名(跳过字符串字面量与注释)。
|
||||
|
||||
【为什么】oracledb 不容许多余 bind 键(ORA-01036 unrecognized bind variable);
|
||||
pre/bulk/post/query 共享同一份参数字典,而各语句通常只引用其中一部分——
|
||||
必须按语句真实引用过滤,映射方可只写自己需要的绑定。
|
||||
|
||||
Args:
|
||||
sql: 标识符替换后的最终 SQL 文本。
|
||||
|
||||
Returns:
|
||||
语句中出现的 :name 集合(不含字符串字面量与 `--` / `/* */` 注释内的冒号)。
|
||||
"""
|
||||
names: set[str] = set()
|
||||
in_string = False
|
||||
i = 0
|
||||
n = len(sql)
|
||||
while i < n:
|
||||
ch = sql[i]
|
||||
if in_string:
|
||||
if ch == "'":
|
||||
in_string = False
|
||||
i += 1
|
||||
continue
|
||||
if ch == "'":
|
||||
in_string = True
|
||||
i += 1
|
||||
continue
|
||||
if ch == '-' and sql[i:i + 2] == '--':
|
||||
i = sql.find('\n', i)
|
||||
i = n if i == -1 else i + 1
|
||||
continue
|
||||
if ch == '/' and sql[i:i + 2] == '/*':
|
||||
end = sql.find('*/', i + 2)
|
||||
i = n if end == -1 else end + 2
|
||||
continue
|
||||
if ch == ':':
|
||||
match = _PLACEHOLDER_BIND_RE.match(sql, i)
|
||||
if match:
|
||||
names.add(match.group(1))
|
||||
i = match.end()
|
||||
continue
|
||||
i += 1
|
||||
return names
|
||||
|
||||
|
||||
def _filter_statement_binds(params: dict, sql: str) -> dict:
|
||||
"""按语句引用的 :bind 过滤参数字典(保持原键序,不改入参)。
|
||||
|
||||
Args:
|
||||
params: 待传给 execute/executemany 的绑定参数。
|
||||
sql: 该语句替换标识符后的最终文本。
|
||||
|
||||
Returns:
|
||||
仅含语句实际引用键的新字典。
|
||||
"""
|
||||
allowed = _referenced_bind_names(sql)
|
||||
return {k: v for k, v in params.items() if k in allowed}
|
||||
|
||||
|
||||
def _rows_as_dicts(cursor: Any) -> list[dict[str, Any]]:
|
||||
"""将游标结果按 description 列名(别名)转为 dict 列表。"""
|
||||
description = getattr(cursor, 'description', None) or ()
|
||||
columns = [col[0] for col in description]
|
||||
return [dict(zip(columns, row)) for row in (cursor.fetchall() or [])]
|
||||
|
||||
|
||||
class DatabaseTransport:
|
||||
"""数据库 SQL 传输;按 config.db_kind 查 `_DRIVERS`,未知值 fail-closed。"""
|
||||
|
||||
connector_type = 'database'
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""执行 request_spec.sql(execute 单事务 / query 返回 rows)。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(须已拼入 endpoint/db_kind)与 credential。
|
||||
interface: 含 request_spec_json.sql 节点。
|
||||
request: 引擎构造的请求,参数取自 request['params']。
|
||||
|
||||
Returns:
|
||||
成功 dict(execute: status=success;query: 另含 rows),均附带保留键
|
||||
`_wire`(线级事实,由引擎剥离落库,业务侧不得消费);
|
||||
驱动异常时 technical_failed(message 已脱敏,无 `_wire`)。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint/db_kind 或未知库种。
|
||||
InputInvalidError: 标识符白名单/安全正则失败或 sql 规格非法。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
credential = dict(client.get('credential') or {})
|
||||
params = dict(request.get('params') or {})
|
||||
sql_spec = (interface.get('request_spec_json') or {}).get('sql') or {}
|
||||
if not isinstance(sql_spec, dict) or not sql_spec:
|
||||
raise InputInvalidError('request_spec.sql is required for database transport')
|
||||
|
||||
driver = self._resolve_driver(config)
|
||||
identifiers = list(sql_spec.get('identifiers') or [])
|
||||
mode = str(sql_spec.get('mode') or '').strip().lower()
|
||||
|
||||
conn = None
|
||||
try:
|
||||
# [STEP 1] 建连
|
||||
conn = driver.connect(config=config, credential=credential)
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
if mode == 'execute':
|
||||
return self._run_execute(conn, cursor, sql_spec, params, identifiers)
|
||||
if mode == 'query':
|
||||
return self._run_query(cursor, sql_spec, params, identifiers)
|
||||
raise InputInvalidError(
|
||||
f'unsupported sql.mode: {mode!r}',
|
||||
details={'mode': mode},
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
except Exception:
|
||||
pass
|
||||
except (TransportNotFrozenError, InputInvalidError):
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except Exception as exc:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'DB_ERROR',
|
||||
'message': mask_secrets(str(exc)[:2000], credential)[:500],
|
||||
}
|
||||
finally:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试:执行各库 probe_sql,成功即 ok(不做业务调用)。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/db_kind)与 credential。
|
||||
|
||||
Returns:
|
||||
{'ok': True/False, 'code': ..., 'message': ...};异常 message 已脱敏。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint/db_kind 或未知库种。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
credential = dict(client.get('credential') or {})
|
||||
driver = self._resolve_driver(config)
|
||||
conn = None
|
||||
try:
|
||||
conn = driver.connect(config=config, credential=credential)
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute(driver.probe_sql)
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
except Exception:
|
||||
pass
|
||||
return {'ok': True, 'code': 'DB_PROBE_OK', 'message': 'ok'}
|
||||
except TransportNotFrozenError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
return {
|
||||
'ok': False,
|
||||
'code': 'CONNECTION_FAILED',
|
||||
'message': mask_secrets(str(exc)[:500], credential),
|
||||
}
|
||||
finally:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _resolve_driver(self, config: dict) -> DriverSpec:
|
||||
"""校验 endpoint/db_kind 并返回驱动规格;未知库种 fail-closed。"""
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('database endpoint not frozen (missing endpoint)')
|
||||
db_kind = str(config.get('db_kind') or '').strip().lower()
|
||||
if not db_kind:
|
||||
raise TransportNotFrozenError('database db_kind not frozen (missing db_kind)')
|
||||
driver = _DRIVERS.get(db_kind)
|
||||
if driver is None:
|
||||
raise TransportNotFrozenError(f'unknown database db_kind: {db_kind!r}')
|
||||
return driver
|
||||
|
||||
def _run_execute(
|
||||
self,
|
||||
conn: Any,
|
||||
cursor: Any,
|
||||
sql_spec: dict,
|
||||
params: dict,
|
||||
identifiers: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""execute:pre → bulk(executemany) → post,单事务 commit。
|
||||
|
||||
标识符 `{key}` 替换后,bind 参数(含 bulk 行合并)须剔除 identifiers 键。
|
||||
返回 dict 附带保留键 `_wire`:逐语句记录 phase/最终 SQL/实际绑定/行数
|
||||
(bulk 另记 row_count),顶层 rowcount 为各语句之和,供调用日志落库。
|
||||
"""
|
||||
bulk = sql_spec.get('bulk') or {}
|
||||
rows_param = str(bulk.get('rows_param') or '').strip() if bulk else ''
|
||||
# 基础参数不含行列表,避免 pre/post 绑定把整表塞进驱动参数。
|
||||
base_raw = (
|
||||
{k: v for k, v in params.items() if k != rows_param}
|
||||
if rows_param
|
||||
else dict(params)
|
||||
)
|
||||
# [STEP 1.5] 剔除已字面量替换的标识符键,避免 oracledb 多余 bind 键报错
|
||||
base = _strip_identifier_keys(base_raw, identifiers)
|
||||
|
||||
statements: list[dict] = []
|
||||
# [STEP 2] pre 语句(按语句引用过滤后的基础参数)
|
||||
for stmt in list(sql_spec.get('pre') or []):
|
||||
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
|
||||
cursor.execute(sql, _filter_statement_binds(base, sql))
|
||||
statements.append({'phase': 'pre', 'sql': sql,
|
||||
'binds': _filter_statement_binds(base, sql),
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
|
||||
|
||||
# [STEP 3] bulk:行与基础参数合并,行内键覆盖;合并后再剔标识符键
|
||||
if bulk:
|
||||
bulk_sql = _apply_identifiers(
|
||||
str(bulk.get('sql') or ''), identifiers=identifiers, params=params,
|
||||
)
|
||||
raw_rows = params.get(rows_param) if rows_param else None
|
||||
if not isinstance(raw_rows, list):
|
||||
raise InputInvalidError(
|
||||
f'bulk.rows_param must resolve to a list: {rows_param!r}',
|
||||
details={'rows_param': rows_param},
|
||||
)
|
||||
merged_rows = [
|
||||
_strip_identifier_keys({**base_raw, **dict(row or {})}, identifiers)
|
||||
for row in raw_rows
|
||||
]
|
||||
cursor.executemany(
|
||||
bulk_sql,
|
||||
[_filter_statement_binds(row, bulk_sql) for row in merged_rows],
|
||||
)
|
||||
statements.append({'phase': 'bulk', 'sql': bulk_sql,
|
||||
'binds': merged_rows[0] if merged_rows else {},
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0),
|
||||
'row_count': len(merged_rows)})
|
||||
|
||||
# [STEP 4] post 语句
|
||||
for stmt in list(sql_spec.get('post') or []):
|
||||
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
|
||||
cursor.execute(sql, _filter_statement_binds(base, sql))
|
||||
statements.append({'phase': 'post', 'sql': sql,
|
||||
'binds': _filter_statement_binds(base, sql),
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
|
||||
|
||||
conn.commit()
|
||||
return {'status': 'success',
|
||||
'_wire': {'kind': 'database', 'statements': statements,
|
||||
'rowcount': sum(s.get('rowcount', 0) for s in statements)}}
|
||||
|
||||
def _run_query(
|
||||
self,
|
||||
cursor: Any,
|
||||
sql_spec: dict,
|
||||
params: dict,
|
||||
identifiers: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""query:执行 SELECT,按列别名返回 rows,不 commit。
|
||||
|
||||
标识符替换后 bind 参数剔除 identifiers 键。
|
||||
返回 dict 附带保留键 `_wire`:单语句记录 phase=query 与最终 SQL/实际绑定,
|
||||
rows 截断至 _WIRE_TEXT_LIMIT 行作快照,供调用日志落库。
|
||||
"""
|
||||
raw_sql = str(sql_spec.get('sql') or '').strip()
|
||||
if not raw_sql:
|
||||
raise InputInvalidError('query mode requires sql.sql')
|
||||
sql = _apply_identifiers(raw_sql, identifiers=identifiers, params=params)
|
||||
binds = _filter_statement_binds(
|
||||
_strip_identifier_keys(params, identifiers), sql)
|
||||
cursor.execute(sql, binds)
|
||||
rows = _rows_as_dicts(cursor)
|
||||
return {'status': 'success', 'rows': rows,
|
||||
'_wire': {'kind': 'database',
|
||||
'statements': [{'phase': 'query', 'sql': sql, 'binds': binds}],
|
||||
'rows': rows[:_WIRE_TEXT_LIMIT]}}
|
||||
@@ -4,11 +4,15 @@
|
||||
依赖:requests(默认注入),可注入 http_request 供测试替身。
|
||||
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
|
||||
business_failed dict;非 JSON 响应映射为 technical_failed。
|
||||
调用日志:call 各返回分支(JSON 成功/HTTP≥400/NON_JSON)附带保留键 `_wire`
|
||||
(method/url/脱敏请求头/请求体/状态码/脱敏响应体等线级事实),由引擎
|
||||
(Task 4)剥离落库 wire_json,禁止上游业务消费该键。
|
||||
probe 连接测试探针:GET endpoint,任意 HTTP 响应即算可达(连接异常才算不通)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Callable
|
||||
|
||||
import requests
|
||||
@@ -18,6 +22,9 @@ from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
HttpRequest = Callable[..., Any]
|
||||
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
|
||||
class RestTransport:
|
||||
"""REST 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
|
||||
@@ -28,6 +35,24 @@ class RestTransport:
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""构造 HTTP 请求并返回原始响应 dict;各返回分支附带保留键 `_wire`。
|
||||
|
||||
用途与触发时机:引擎按 connector_type=rest 分发至此完成一次真实调用;
|
||||
`_wire` 记录线级事实(method/url/脱敏请求头/请求体/状态码/脱敏响应体),
|
||||
仅由调用日志引擎剥离落库,业务侧禁止消费。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/timeout_seconds/headers)与 credential。
|
||||
interface: 含 request_spec_json(method/path)。
|
||||
request: 引擎构造的请求(params/body/headers)。
|
||||
|
||||
Returns:
|
||||
JSON 成功 dict / business_failed(HTTP≥400)/ technical_failed(NON_JSON),
|
||||
各分支均附 `_wire`(JSON 解析结果非 dict 时无法附加键,按原样返回)。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint(fail-closed)。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
@@ -48,21 +73,37 @@ class RestTransport:
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
)
|
||||
if int(getattr(response, 'status_code', 0)) >= 400:
|
||||
http_status = int(getattr(response, 'status_code', 0))
|
||||
response_text = str(getattr(response, 'text', '') or '')
|
||||
request_body = json.dumps(request.get('body'), ensure_ascii=False, default=str) \
|
||||
if request.get('body') is not None else ''
|
||||
wire = {'kind': 'rest', 'method': method, 'url': url,
|
||||
'headers': mask_secrets(json.dumps(headers, ensure_ascii=False, default=str),
|
||||
client.get('credential')),
|
||||
'request_body': request_body,
|
||||
'http_status': http_status,
|
||||
'response_body': mask_secrets(response_text, client.get('credential'))[:_WIRE_TEXT_LIMIT]}
|
||||
if http_status >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
'code': f"HTTP_{http_status}",
|
||||
# 错误回显可能包含请求内容(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
try:
|
||||
return response.json()
|
||||
parsed = response.json()
|
||||
except Exception:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_JSON',
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
# JSON 解析结果为 dict 时附 `_wire`;list/标量无法携带键,按原样返回。
|
||||
if isinstance(parsed, dict):
|
||||
parsed['_wire'] = wire
|
||||
return parsed
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET endpoint,任意 HTTP 响应(含 4xx/5xx)都证明网络可达。
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
非 XML → technical_failed。
|
||||
probe 连接测试探针:GET WSDL 地址并校验返回 XML(definitions/Envelope 任一即通);
|
||||
裸服务端点自动补 ?wsdl(SOAP 端点对裸 GET 常返回 404/405/501)。
|
||||
调用日志:call 各返回分支(成功/HTTP≥400/NON_XML)附带保留键 `_wire`
|
||||
(method/url/soap_action/脱敏请求体/状态码/脱敏响应体等线级事实),
|
||||
由引擎(Task 4)剥离落库 wire_json,禁止上游业务消费该键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -31,6 +34,8 @@ HttpRequest = Callable[..., Any]
|
||||
|
||||
# 内嵌转义 XML 的最大递归展开深度(防深嵌套/构造报文拖垮解析)。
|
||||
MAX_EMBED_DEPTH = 3
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
|
||||
def _localname(tag: Any) -> str:
|
||||
@@ -137,6 +142,25 @@ class SoapTransport:
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""按契约生成 SOAP 报文并解析响应;各返回分支附带保留键 `_wire`。
|
||||
|
||||
用途与触发时机:引擎按 connector_type=soap 分发至此完成一次真实调用;
|
||||
`_wire` 记录线级事实(method/url/soap_action/脱敏请求体/状态码/脱敏响应体),
|
||||
仅由调用日志引擎剥离落库,业务侧禁止消费。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/timeout_seconds)与 credential。
|
||||
interface: 含 request_spec_json(method + soap.action/body_template)。
|
||||
request: 引擎构造的请求,参数取自 request['params']。
|
||||
|
||||
Returns:
|
||||
解析后的业务 dict / business_failed(HTTP≥400、SOAP Fault)/
|
||||
technical_failed(NON_XML),各分支均附 `_wire`。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint 或 soap.body_template(fail-closed)。
|
||||
InputInvalidError: 模板占位符缺值/非法(fail-closed)。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
@@ -165,22 +189,29 @@ class SoapTransport:
|
||||
headers=headers,
|
||||
timeout=int(config.get('timeout_seconds') or 60),
|
||||
)
|
||||
if int(getattr(response, 'status_code', 0)) >= 400:
|
||||
http_status = int(getattr(response, 'status_code', 0))
|
||||
# 响应文本与请求体在进入任何分支前先脱敏:错误回显/成功报文都可能含凭据。
|
||||
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
|
||||
wire = {'kind': 'soap', 'method': method, 'url': url,
|
||||
'soap_action': headers['SOAPAction'],
|
||||
'request_body': mask_secrets(body, client.get('credential')),
|
||||
'http_status': http_status,
|
||||
'response_body': response_text[:_WIRE_TEXT_LIMIT]}
|
||||
if http_status >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
'code': f"HTTP_{http_status}",
|
||||
# 错误回显可能包含请求体(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
|
||||
try:
|
||||
return _parse_soap_payload(response_text)
|
||||
parsed = _parse_soap_payload(response_text)
|
||||
except ET.ParseError:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_XML',
|
||||
'message': response_text[:500],
|
||||
}
|
||||
return {'status': 'technical_failed', 'code': 'NON_XML',
|
||||
'message': response_text[:500], '_wire': wire}
|
||||
parsed['_wire'] = wire
|
||||
return parsed
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET WSDL 地址并校验返回 XML,只证明网络与服务可达。
|
||||
|
||||
Reference in new issue
Block a user