"""services/integration_connector/engine.py 用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→按步 map-params→call→classify→audit。 依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 逻辑:域入参先经能力 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 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, 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 from app.services.integration_connector.security import resolve_credential, sanitize from app.services.integration_connector.transports.base import ( RESULT_FAILURE_STATUSES, IntegrationCallResult, Transport, classify_transport_response, ) 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。""" request_spec = request_spec or {} spec_path = str(request_spec.get('path') or '') try: path = spec_path.format(**params) except (KeyError, IndexError, ValueError): path = spec_path headers = dict(config.get('headers') or {}) spec_params = list(request_spec.get('params') or []) selected = {k: params[k] for k in spec_params if k in params} or params template = request_spec.get('template') if isinstance(template, dict): body = _fill_template(template, params) else: body = selected return {'path': path, 'params': selected, 'body': body, 'headers': headers} def _fill_template(template: dict, params: dict) -> dict: """填充模板 dict 中的 {placeholder} 占位符。""" filled: dict = {} for key, value in template.items(): if isinstance(value, str) and '{' in value: try: filled[key] = value.format(**params) except (KeyError, IndexError, ValueError): filled[key] = value else: filled[key] = value return filled def _environment() -> str: """从 Flask 配置推导环境(dev/test/prod),缺省 prod。""" try: from flask import current_app, has_app_context if has_app_context(): value = str(current_app.config.get('ENV_NAME') or '').strip().lower() if value in {'dev', 'test', 'prod'}: return value except Exception: pass return 'prod' class CapabilityGateway: """能力调用引擎;transports 为 {connector_type: Transport} 可注入。""" def __init__(self, transports: dict[str, Transport] | None = None) -> None: self.transports = dict(transports or {}) def call( self, *, capability: str, context: dict, params: dict, operation_id: str, 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: # InputInvalidError 只带 message 不带明细,降级进 result_message 后只剩 # "input invalid";不落日志则字段级原因(required missing/类型不符)永久丢失。 logger.warning( "connector input invalid: capability=%s errors=%s", capability, input_errors, ) raise InputInvalidError(details={'errors': input_errors}) 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(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}'}) # 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。 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': 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, 0, params, None, result, start_ms, trace_id, business_ref) return result 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(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, 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(每步一条;同 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': 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': 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_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, ) db.session.add(call) db.session.commit()