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:
hugo committed 2026-09-27 18:05:08 +08:00
1 parent 8a814e7152
commit e750fa8602
47 files changed
+7441 -353

No files matched your search

+360 -47
View File
@@ -1,13 +1,18 @@
"""api/integration_connector.py
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点、
连接测试与集成调用日志查询(列表 + 详情 + 同 operation 步骤时间线)。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto、
models.integration_connector.CONNECTOR_TYPES / DB_KINDS(白名单同源)。
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
客户端实例 connector_type ∈ rest/soap/database;database 时 db_kind 必填且 ∈
mysql/oracle/sqlserver/postgresql,非 database 强制置 NULL。
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
转移(绑定发布附加就绪门禁:每步接口须已发布且每步客户端启用);绑定以
steps_json 有序数组表达一对多配方(每步 interface_code + param_mapping_json),
客户端由各步接口归属自带;旧单步字段可合成单元素 steps(兼容窗)。
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
@@ -28,10 +33,12 @@ from app.core.errors import AppError, NotFoundError, ValidationError
from app.core.response import ok
from app.models import (
IntegrationBinding,
IntegrationCall,
IntegrationClientInstance,
IntegrationCredentialReference,
IntegrationInterfaceDefinition,
)
from app.models.integration_connector import CONNECTOR_TYPES, DB_KINDS
from app.services.integration_connector.capability import list_capabilities
from app.services.integration_connector.credential_types import (
build_secret_dict,
@@ -40,12 +47,18 @@ from app.services.integration_connector.credential_types import (
visible_fields,
)
from app.services.integration_connector.gateway import get_capability_gateway
from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
from app.services.integration_connector.security import (
CREDENTIAL_KEY_CONFIG_NAME,
_DB_SECRET_CODES,
resolve_credential,
)
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
integration_connector_bp = Blueprint('integration_connector', __name__)
VALID_CONNECTOR_TYPES = ('rest', 'soap')
# 与模型 CONNECTOR_TYPES / DB_KINDS 同源,禁止本地另维护一份白名单。
VALID_CONNECTOR_TYPES = CONNECTOR_TYPES
VALID_DB_KINDS = DB_KINDS
VALID_STATUSES = ('draft', 'published', 'retired')
VALID_SECRET_PROVIDERS = ('db', 'env')
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
@@ -70,6 +83,32 @@ def _require(value, field: str) -> None:
raise ValidationError(f'{field} is required', details={'field': field})
def _resolve_db_kind(connector_type: str, raw_db_kind) -> str | None:
"""按连接器类型解析 db_kind:database 必填且 ∈ VALID_DB_KINDS;其余强制 NULL。
Args:
connector_type: 已校验的连接器类型。
raw_db_kind: 请求体中的 db_kind(可为 None/空串)。
Returns:
合法库种字符串,或非 database 时的 None。
Raises:
ValidationError: database 缺省或未知库种(fail-closed,含历史别名 mssql)。
"""
if connector_type != 'database':
return None
kind = str(raw_db_kind or '').strip()
if not kind:
raise ValidationError('db_kind is required for database connector', details={'field': 'db_kind'})
if kind not in VALID_DB_KINDS:
raise ValidationError(
'invalid db_kind',
details={'field': 'db_kind', 'allowed': list(VALID_DB_KINDS)},
)
return kind
def _require_client(code: str) -> IntegrationClientInstance:
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
@@ -112,7 +151,8 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
400(fail-fast),不留给调用期 fail-closed。
400(fail-fast),不留给调用期 fail-closed。多步绑定时仅用于可选的绑定级
client_instance_code 与首步接口的一致性检查。
"""
client = _require_client(str(client_code).strip())
iface = _require_interface(str(interface_code).strip())
@@ -129,16 +169,101 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
return client, iface
def _normalize_binding_steps(body: dict) -> list[dict]:
"""校验并归一化绑定 steps_json(非空数组;每步 interface 存在且客户端可用)。
核心逻辑:优先读 steps_json;缺省时用旧单步字段合成一元素数组(兼容窗)。
每步 interface_code 必须存在,其归属客户端必须存在(绑定的客户端实例族);
param_mapping_json 须为 dict。返回供落库的 [{interface_code, param_mapping_json}, ...]。
Args:
body: 创建/更新请求体。
Returns:
归一化后的步骤列表(至少一元素)。
Raises:
ValidationError: 空数组、步形状非法、接口不存在、映射非 dict。
"""
raw = body.get('steps_json')
if raw is None:
# 兼容窗:旧单步 API 字段 → 单元素 steps
iface_code = body.get('interface_definition_code')
if not iface_code:
raise ValidationError(
'steps_json is required',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json'},
)
raw = [{
'interface_code': iface_code,
'param_mapping_json': body.get('param_mapping_json') or {},
}]
if not isinstance(raw, list) or len(raw) == 0:
raise ValidationError(
'steps_json must be a non-empty array',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json'},
)
normalized: list[dict] = []
for idx, step in enumerate(raw):
if not isinstance(step, dict):
raise ValidationError(
'each step must be an object',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json', 'index': idx},
)
iface_code = step.get('interface_code') or step.get('interface_definition_code')
_require(iface_code, f'steps_json[{idx}].interface_code')
mapping = step.get('param_mapping_json', step.get('param_mapping', {}))
if mapping is None:
mapping = {}
if not isinstance(mapping, dict):
raise ValidationError(
'step param_mapping_json must be an object',
code='INTEGRATION.BINDING_STEPS_INVALID',
details={'field': 'steps_json', 'index': idx, 'key': 'param_mapping_json'},
)
iface = _require_interface(str(iface_code).strip())
# 客户端实例族:接口归属客户端必须存在(跨步可不同客户端,如 database+soap)。
_require_client(iface.client_instance_code)
normalized.append({
'interface_code': iface.code,
'param_mapping_json': mapping,
})
# 若请求仍带绑定级 client_instance_code,与首步接口做成对校验(防错配镜像列)。
binding_client = body.get('client_instance_code')
if binding_client is not None and str(binding_client).strip():
_validate_binding_pair(binding_client, normalized[0]['interface_code'])
return normalized
def _mirror_legacy_binding_columns(steps: list[dict]) -> tuple[str, str, dict]:
"""由归一化 steps 镜像旧 NOT NULL 列(首步);P2 删列前保持可写。
Returns:
(client_instance_code, interface_definition_code, param_mapping_json)
"""
first = steps[0]
iface = _require_interface(first['interface_code'])
return iface.client_instance_code, iface.code, dict(first.get('param_mapping_json') or {})
def _interface_transition(iface, action: str) -> None:
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
_apply_status_transition(iface, action, kind='interface')
def _serialize_client(client) -> dict:
"""客户端实例序列化(含 database 专列 db_kind;非 database 为 null)。"""
return {
'id': client.id, 'code': client.code, 'name': client.name,
'connector_type': client.connector_type, 'environment': client.environment,
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
'db_kind': client.db_kind,
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
'enabled': client.enabled,
}
@@ -156,9 +281,11 @@ def _serialize_interface(iface) -> dict:
def _serialize_binding(binding) -> dict:
"""绑定序列化:含 steps_json;旧单步列仍回显(P2 删前列镜像)。"""
return {
'id': binding.id, 'capability': binding.capability,
'context_selector_json': binding.context_selector_json or {},
'steps_json': binding.steps_json or [],
'param_mapping_json': binding.param_mapping_json or {},
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
@@ -276,6 +403,7 @@ def list_client_instances():
@integration_connector_bp.route('/client-instances', methods=['POST'])
@require_admin
def create_client_instance():
"""创建客户端实例;database 类型强制校验 db_kind 四库枚举,非 database 置 NULL。"""
body = request.get_json(silent=True) or {}
connector_type = str(body.get('connector_type') or '').strip()
_require(body.get('code'), 'code')
@@ -284,11 +412,13 @@ def create_client_instance():
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
db_kind = _resolve_db_kind(connector_type, body.get('db_kind'))
client = IntegrationClientInstance(
code=str(body['code']).strip(), name=str(body['name']).strip(),
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
endpoint=(str(body.get('endpoint') or '').strip() or None),
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
db_kind=db_kind,
config_json=body.get('config_json') or {},
credential_ref_code=body.get('credential_ref_code'),
enabled=bool(body.get('enabled', True)),
@@ -323,7 +453,10 @@ def delete_client_instance(code):
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
@require_admin
def update_client_instance(code):
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停/db_kind)。
database 类型必填合法 db_kind;切离 database 时强制清空 db_kind。
"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
@@ -348,6 +481,9 @@ def update_client_instance(code):
client.credential_ref_code = body.get('credential_ref_code')
if 'enabled' in body:
client.enabled = bool(body.get('enabled', True))
# 最终类型决定 db_kind:database 必填合法值;rest/soap 强制 NULL。
raw_kind = body['db_kind'] if 'db_kind' in body else client.db_kind
client.db_kind = _resolve_db_kind(connector_type, raw_kind)
from app import db
db.session.commit()
return ok(_serialize_client(client))
@@ -482,18 +618,22 @@ def list_bindings():
@integration_connector_bp.route('/bindings', methods=['POST'])
@require_admin
def create_binding():
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
"""创建绑定:校验 steps_json 后落库;新建固定落 draft,发布走 /publish 动作端点。
核心逻辑:归一化 steps → 镜像首步到旧列(NOT NULL)→ 落 draft。
仍接受旧单步字段(无 steps_json 时合成一元素数组)。
"""
body = request.get_json(silent=True) or {}
_require(body.get('capability'), 'capability')
_require(body.get('client_instance_code'), 'client_instance_code')
_require(body.get('interface_definition_code'), 'interface_definition_code')
client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
steps = _normalize_binding_steps(body)
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
binding = IntegrationBinding(
capability=body['capability'],
context_selector_json=body.get('context_selector_json') or {},
param_mapping_json=body.get('param_mapping_json') or {},
client_instance_code=client.code,
interface_definition_code=iface.code,
steps_json=steps,
param_mapping_json=param_mapping,
client_instance_code=client_code,
interface_definition_code=iface_code,
mapping_version=int(body.get('mapping_version') or 1),
priority=int(body.get('priority') or 0),
environment=str(body.get('environment') or 'prod').strip(),
@@ -508,10 +648,14 @@ def create_binding():
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
@require_admin
def update_binding(binding_id):
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
"""更新绑定(可改 context / steps_json / 映射版本 / 优先级 / 环境 / 生效区间)。
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
状态不在此改写(须经动作端点按转移表流转)。规则(评审修正轮收紧后):
[1] steps_json 与旧单步字段(interface_definition_code/param_mapping_json)同 PUT
属矛盾载荷 → 400(旧键会被静默忽略、部分生效无提示);
[2] 三把旧钥匙(interface_definition_code/param_mapping_json/client_instance_code)
任一出现在多步绑定 PUT → 400(兼容窗会合成单元素 steps 回写、静默销毁第 2..n 步);
[3] 单步绑定的旧字段 PUT 走兼容窗(换绑接口 / 仅更新首步映射);纯 steps_json PUT 不受限。
"""
from app import db
binding = db.session.get(IntegrationBinding, binding_id)
@@ -523,23 +667,83 @@ def update_binding(binding_id):
binding.capability = body['capability']
if 'context_selector_json' in body:
binding.context_selector_json = body.get('context_selector_json') or {}
if 'param_mapping_json' in body:
binding.param_mapping_json = body.get('param_mapping_json') or {}
new_client_code = body.get('client_instance_code')
new_iface_code = body.get('interface_definition_code')
if new_client_code is not None:
_require(new_client_code, 'client_instance_code')
if new_iface_code is not None:
_require(new_iface_code, 'interface_definition_code')
if new_client_code is not None or new_iface_code is not None:
_validate_binding_pair(
new_client_code if new_client_code is not None else binding.client_instance_code,
new_iface_code if new_iface_code is not None else binding.interface_definition_code,
if 'steps_json' in body:
# 评审 P2-2:矛盾载荷 fail-fast——steps_json 分支本会静默忽略旧单步键(部分生效无提示)。
# client_instance_code 不在矛盾集:它在 steps_json 分支仍被消费(首步成对校验)。
conflicts = sorted(
key for key in ('interface_definition_code', 'param_mapping_json') if key in body
)
if new_client_code is not None:
binding.client_instance_code = str(new_client_code).strip()
if new_iface_code is not None:
binding.interface_definition_code = str(new_iface_code).strip()
if conflicts:
raise ValidationError(
'steps_json PUT cannot carry legacy single-step fields; they would be silently ignored',
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
details={
'fields': conflicts,
'conflicting_with': 'steps_json',
'hint': 'submit the full ordered recipe via steps_json only',
},
)
merge_body = {
'steps_json': body['steps_json'],
'client_instance_code': body.get('client_instance_code'),
}
steps = _normalize_binding_steps(merge_body)
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
binding.steps_json = steps
binding.client_instance_code = client_code
binding.interface_definition_code = iface_code
binding.param_mapping_json = param_mapping
elif 'interface_definition_code' in body or 'client_instance_code' in body or 'param_mapping_json' in body:
# 评审 P1 守卫:三把旧钥匙(含 client_instance_code)任一出现在多步绑定 PUT,
# 都会经兼容窗用旧单步列合成单元素 steps 回写、静默销毁第 2..n 步 → fail-fast 400。
legacy_keys = sorted(
key for key in ('interface_definition_code', 'param_mapping_json', 'client_instance_code')
if key in body
)
if binding.steps_json and len(binding.steps_json) > 1:
raise ValidationError(
'legacy single-step fields cannot update a multi-step binding; use steps_json',
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
details={
'fields': legacy_keys,
'steps_count': len(binding.steps_json),
'hint': 'submit the full ordered recipe via steps_json',
},
)
# 兼容窗:旧单步字段 → 重写/局部更新 steps
if (
'param_mapping_json' in body
and 'interface_definition_code' not in body
and 'client_instance_code' not in body
and binding.steps_json
):
steps = [dict(s) if isinstance(s, dict) else s for s in binding.steps_json]
first = dict(steps[0])
first['param_mapping_json'] = body.get('param_mapping_json') or {}
steps[0] = first
steps = _normalize_binding_steps({
'steps_json': steps,
'client_instance_code': binding.client_instance_code,
})
else:
steps = _normalize_binding_steps({
'interface_definition_code': body.get(
'interface_definition_code', binding.interface_definition_code,
),
'client_instance_code': body.get(
'client_instance_code', binding.client_instance_code,
),
'param_mapping_json': body.get(
'param_mapping_json', binding.param_mapping_json or {},
),
})
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
binding.steps_json = steps
binding.client_instance_code = client_code
binding.interface_definition_code = iface_code
binding.param_mapping_json = param_mapping
if body.get('mapping_version') is not None:
binding.mapping_version = int(body.get('mapping_version') or 1)
if body.get('priority') is not None:
@@ -550,7 +754,6 @@ def update_binding(binding_id):
binding.effective_from = body['effective_from'] or None
if body.get('effective_to') is not None:
binding.effective_to = body['effective_to'] or None
from app import db
db.session.commit()
return ok(_serialize_binding(binding))
@@ -560,7 +763,7 @@ def update_binding(binding_id):
def _do_binding_lifecycle(binding_id: int, action: str):
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
发布(publish)附加就绪门禁:steps_json 每步接口须已发布、每步客户端须启用,
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
(与 binding.resolve_binding 的调用期门禁同一语义)。
"""
@@ -569,17 +772,44 @@ def _do_binding_lifecycle(binding_id: int, action: str):
if binding is None:
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
if action == 'publish':
client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first()
iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first()
if client is None or iface is None or iface.status != 'published' or not client.enabled:
raw_steps = list(binding.steps_json or [])
if not raw_steps and binding.interface_definition_code:
raw_steps = [{
'interface_code': binding.interface_definition_code,
'param_mapping_json': binding.param_mapping_json or {},
}]
if not raw_steps:
raise ValidationError(
'binding target not ready: interface must be published and client instance enabled',
'binding target not ready: steps_json is empty',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
},
details={'steps_json': []},
)
for idx, step in enumerate(raw_steps):
if not isinstance(step, dict):
raise ValidationError(
'binding target not ready: invalid step',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={'index': idx},
)
iface_code = str(step.get('interface_code') or '').strip()
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
client = (
IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
if iface is not None else None
)
if client is None or iface is None or iface.status != 'published' or not client.enabled:
raise ValidationError(
'binding target not ready: each step interface must be published '
'and client instance enabled',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={
'index': idx,
'interface_code': iface_code,
'client_instance_code': getattr(iface, 'client_instance_code', None),
'iface_status': getattr(iface, 'status', None),
'client_enabled': getattr(client, 'enabled', None),
},
)
_apply_status_transition(binding, action, kind='binding')
db.session.commit()
return ok(_serialize_binding(binding))
@@ -718,8 +948,8 @@ def update_credential_reference(code):
def test_connection(code):
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds/db_kind
独立列拼回 config_json 后再交给 transport,否则存独立列的地址/库种会被误判为未冻结。
"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
@@ -735,8 +965,12 @@ def test_connection(code):
'config_json': client.config_json or {},
'endpoint': client.endpoint,
'timeout_seconds': client.timeout_seconds,
'db_kind': client.db_kind,
}),
'credential': {},
# 连接测试按设计须证明「网络与认证」可用(数据库直连无凭据无法建连):
# 有凭据引用时解析真实凭据(db 解密 / env 注入,与 engine 调用链同源),
# 无引用(匿名)为空 dict;解析失败 fail-closed 抛 CredentialUnresolvedError。
'credential': resolve_credential(client.credential_ref_code) if client.credential_ref_code else {},
}
probe = getattr(transport, 'probe', None)
if probe is not None:
@@ -747,3 +981,82 @@ def test_connection(code):
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
# ---- 集成调用日志查询 ----
@integration_connector_bp.route('/calls', methods=['GET'])
@require_admin
def list_integration_calls_api():
"""集成调用日志分页查询(能力无关通用口径)。
筛选:capability/interface_code/client_code/connector_type/status/
operation_id/trace_id/business_ref 精确;keyword 对请求摘要 JSON 文本模糊;
date_from/date_to=YYYY-MM-DD(按 created_at 闭区间,date_to 补全天)。
"""
from sqlalchemy import cast, String
args = request.args
query = IntegrationCall.query
for field in ('capability', 'status', 'operation_id', 'trace_id', 'business_ref'):
value = (args.get(field) or '').strip()
if value:
query = query.filter(getattr(IntegrationCall, field) == value)
for json_field in ('interface_code', 'client_code', 'connector_type'):
value = (args.get(json_field) or '').strip()
if value:
query = query.filter(
IntegrationCall.binding_snapshot_json[json_field].as_string() == value)
keyword = (args.get('keyword') or '').strip()
if keyword:
query = query.filter(
cast(IntegrationCall.request_summary_json, String).ilike(f'%{keyword}%'))
date_from = (args.get('date_from') or '').strip()
if date_from:
query = query.filter(IntegrationCall.created_at >= f'{date_from} 00:00:00')
date_to = (args.get('date_to') or '').strip()
if date_to:
query = query.filter(IntegrationCall.created_at <= f'{date_to} 23:59:59.999999')
page = max(int(args.get('page') or 1), 1)
page_size = min(max(int(args.get('page_size') or 20), 1), 100)
total = query.count()
rows = (query.order_by(IntegrationCall.id.desc())
.offset((page - 1) * page_size).limit(page_size).all())
def _row(c: IntegrationCall) -> dict:
snap = c.binding_snapshot_json or {}
return {'id': c.id, 'created_at': c.created_at.isoformat() if c.created_at else None,
'capability': c.capability, 'operation_id': c.operation_id,
'trace_id': c.trace_id, 'status': c.status, 'elapsed_ms': c.elapsed_ms,
'business_ref': c.business_ref,
'client_code': snap.get('client_code'), 'interface_code': snap.get('interface_code'),
'connector_type': snap.get('connector_type'),
'step_index': snap.get('step_index'), 'step_count': snap.get('step_count')}
return ok({'total': total, 'page': page, 'page_size': page_size,
'items': [_row(c) for c in rows]})
@integration_connector_bp.route('/calls/<int:call_id>', methods=['GET'])
@require_admin
def get_integration_call_api(call_id: int):
"""单条全量(含 wire_json/request/response/绑定快照)+ 同 operation_id 步骤时间线。"""
call = IntegrationCall.query.get(call_id)
if call is None:
raise NotFoundError('integration call not found', code='INTEGRATION.CALL_NOT_FOUND')
full = {'id': call.id, 'created_at': call.created_at.isoformat() if call.created_at else None,
'capability': call.capability, 'operation_id': call.operation_id,
'trace_id': call.trace_id, 'status': call.status, 'elapsed_ms': call.elapsed_ms,
'business_ref': call.business_ref,
'binding_snapshot_json': call.binding_snapshot_json or {},
'request_summary_json': call.request_summary_json or {},
'response_summary_json': call.response_summary_json or {},
'wire_json': call.wire_json}
siblings = (IntegrationCall.query.filter_by(operation_id=call.operation_id)
.order_by(IntegrationCall.id.asc()).all())
timeline = [{'id': c.id, 'step_index': (c.binding_snapshot_json or {}).get('step_index'),
'step_count': (c.binding_snapshot_json or {}).get('step_count'),
'interface_code': (c.binding_snapshot_json or {}).get('interface_code'),
'status': c.status, 'elapsed_ms': c.elapsed_ms} for c in siblings]
return ok({'call': full, 'timeline': timeline})
+2
View File
@@ -739,6 +739,8 @@ class ProductionConfig(Config):
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
# 钉住测试 TTL 语义(陈旧行门禁用例按 600s 书写),不随开发者 .env.shared 漂移。
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = 600
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
SCHEDULE_WORKER_ENABLED = False
+37 -10
View File
@@ -1,11 +1,13 @@
"""models/integration_connector.py
用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型:
用途:Integration Connector(外部系统连接器框架)配置与运行时模型:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。
连接器类型(rest/soap/database)与状态均用 CheckConstraint 兜底;database 客户端
另有 db_kind 专列(mysql/oracle/sqlserver/postgresql),fail-closed 语义在服务层。
Binding.steps_json 表达一对多有序接口配方(D10);旧单步列保留至 P2。
"""
from __future__ import annotations
@@ -31,8 +33,10 @@ from sqlalchemy.dialects.postgresql import JSONB
from app.models.base import Base
# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。
CONNECTOR_TYPES = ('rest', 'soap')
# 连接器类型白名单;模型 CHECK 由本常量动态生成,扩枚举须配套 Alembic 迁移重建 CHECK。
CONNECTOR_TYPES = ('rest', 'soap', 'database')
# database 专属库种(D16):专列 db_kind,非 config_json;API/transport 同源 fail-closed。
DB_KINDS = ('mysql', 'oracle', 'sqlserver', 'postgresql')
CONFIG_STATUSES = ('draft', 'published', 'retired')
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
@@ -89,9 +93,12 @@ class IntegrationClientInstance(Base):
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点);
# database 为 host:port[/database|service_name]。
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# database 专属库种(仅 connector_type='database' 有值;rest/soap 为 NULL)。
db_kind: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
credential_ref_code: Mapped[Optional[str]] = mapped_column(
ForeignKey('integration_credential_references.code'), nullable=True,
@@ -144,7 +151,12 @@ class IntegrationInterfaceDefinition(Base):
class IntegrationBinding(Base):
"""绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。"""
"""绑定:(Capability, context_selector) → 有序接口步骤配方;版本化、可发布、可退役。
一对多有序(D10/D13):steps_json = [{interface_code, param_mapping_json}, ...];
每步客户端由接口归属自带。旧列 interface_definition_code / param_mapping_json /
client_instance_code 迁移后保留镜像首步,解析不再读取,P2 删除。
"""
__tablename__ = 'integration_bindings'
__table_args__ = (
@@ -165,8 +177,11 @@ class IntegrationBinding(Base):
capability: Mapped[str] = mapped_column(String(128), nullable=False)
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
# 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}});
# 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。
# 有序步骤配方:每步 {interface_code, param_mapping_json};客户端由接口归属推导。
steps_json: Mapped[list[dict[str, Any]]] = mapped_column(
CONTEXT_SELECTOR_JSON, nullable=False, default=list,
)
# 域参数 → 接口参数的声明式映射(旧单步列,P2 删;迁移后镜像 steps_json[0])。
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
client_instance_code: Mapped[str] = mapped_column(
@@ -188,13 +203,20 @@ class IntegrationBinding(Base):
class IntegrationCall(Base):
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。"""
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。
多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id
(一票一次执行 = N 条,按 operation_id 串联 + binding_snapshot_json.step_index
定位),故 operation_id 无唯一约束;原唯一约束兼作的索引由普通索引
ix_integration_calls_operation_id 补回(迁移 tt5b6c7d8e9f)。
"""
__tablename__ = 'integration_calls'
__table_args__ = (
UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
Index('ix_integration_calls_operation_id', 'operation_id'),
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
Index('ix_integration_calls_trace_id', 'trace_id'),
Index('ix_integration_calls_business_ref', 'business_ref'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -206,4 +228,9 @@ class IntegrationCall(Base):
status: Mapped[str] = mapped_column(String(32), nullable=False)
elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
# 线级事实(database 最终 SQL/绑定/行数;soap endpoint+XML;rest HTTP 往返)。
# 可空:历史行与未捕获场景为 NULL,前台如实展示。
wire_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
# 通用业务锚点:调用方透传的业务单号/任务号(能力无关;不传为 NULL)。
business_ref: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -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,只证明网络与服务可达。