"""services/integration_connector/engine.py 用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。 依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout; 入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。 """ from __future__ import annotations import time import uuid from dataclasses import replace from app import db from app.services.integration_connector.binding import BindingSnapshot, resolve_binding from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, 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 sanitize from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response from app.models import IntegrationCall 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, ) -> IntegrationCallResult: ensure_capabilities_loaded() spec = get_capability(capability) input_errors = schema_errors(params, spec.input_schema) if input_errors: raise InputInvalidError(details={'errors': input_errors}) env = environment or _environment() snapshot = resolve_binding(capability, context, env) transport = (transports or self.transports).get(snapshot.connector_type) if transport is None: raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'}) request = build_request(snapshot.request_spec, snapshot.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': {}}, interface={'request_spec_json': snapshot.request_spec}, request=request, ) except TimeoutError: result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id) _record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id) return result result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success') if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'): data = map_response(snapshot.response_mapping, raw, snapshot.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) return result def _record_call( operation_id: str, capability: str, snapshot: BindingSnapshot, params: dict, raw: dict | None, result: IntegrationCallResult, start_ms: int, trace_id: str, ) -> None: """落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。""" elapsed_ms = int(time.time() * 1000) - start_ms 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, 'mapping_version': snapshot.mapping_version, 'credential_ref_code': snapshot.credential_ref_code, }, request_summary_json=sanitize(params), response_summary_json=sanitize(raw or {}), status=result.status, elapsed_ms=elapsed_ms, trace_id=trace_id, ) db.session.add(call) db.session.commit()