diff --git a/backend/app/api/integration_connector.py b/backend/app/api/integration_connector.py index 7597db6c..ad117c6f 100644 --- a/backend/app/api/integration_connector.py +++ b/backend/app/api/integration_connector.py @@ -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/', 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/', 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/', 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}) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 1f0e835c..47067904 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -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 diff --git a/backend/app/models/integration_connector.py b/backend/app/models/integration_connector.py index 843c675f..263f3049 100644 --- a/backend/app/models/integration_connector.py +++ b/backend/app/models/integration_connector.py @@ -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) diff --git a/backend/app/services/integration_connector/binding.py b/backend/app/services/integration_connector/binding.py index 68f22a21..58bfe8eb 100644 --- a/backend/app/services/integration_connector/binding.py +++ b/backend/app/services/integration_connector/binding.py @@ -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, ) diff --git a/backend/app/services/integration_connector/engine.py b/backend/app/services/integration_connector/engine.py index a0efaca2..4823bbbb 100644 --- a/backend/app/services/integration_connector/engine.py +++ b/backend/app/services/integration_connector/engine.py @@ -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, diff --git a/backend/app/services/integration_connector/gateway.py b/backend/app/services/integration_connector/gateway.py index 3785c80d..a544bbc5 100644 --- a/backend/app/services/integration_connector/gateway.py +++ b/backend/app/services/integration_connector/gateway.py @@ -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(), + }) diff --git a/backend/app/services/integration_connector/mapping.py b/backend/app/services/integration_connector/mapping.py index 30929df6..2c9c7343 100644 --- a/backend/app/services/integration_connector/mapping.py +++ b/backend/app/services/integration_connector/mapping.py @@ -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: diff --git a/backend/app/services/integration_connector/transports/__init__.py b/backend/app/services/integration_connector/transports/__init__.py index be8b4ce2..39f706a9 100644 --- a/backend/app/services/integration_connector/transports/__init__.py +++ b/backend/app/services/integration_connector/transports/__init__.py @@ -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', ] diff --git a/backend/app/services/integration_connector/transports/base.py b/backend/app/services/integration_connector/transports/base.py index 6a552b4a..07e0c2bf 100644 --- a/backend/app/services/integration_connector/transports/base.py +++ b/backend/app/services/integration_connector/transports/base.py @@ -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 diff --git a/backend/app/services/integration_connector/transports/database.py b/backend/app/services/integration_connector/transports/database.py new file mode 100644 index 00000000..4110a95f --- /dev/null +++ b/backend/app/services/integration_connector/transports/database.py @@ -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]}} diff --git a/backend/app/services/integration_connector/transports/rest.py b/backend/app/services/integration_connector/transports/rest.py index a6ae2f9b..0c3ec531 100644 --- a/backend/app/services/integration_connector/transports/rest.py +++ b/backend/app/services/integration_connector/transports/rest.py @@ -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)都证明网络可达。 diff --git a/backend/app/services/integration_connector/transports/soap.py b/backend/app/services/integration_connector/transports/soap.py index 12e3bb00..382767da 100644 --- a/backend/app/services/integration_connector/transports/soap.py +++ b/backend/app/services/integration_connector/transports/soap.py @@ -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,只证明网络与服务可达。 diff --git a/backend/migrations/versions/tt5b6c7d8e9f_drop_integration_calls_operation_unique.py b/backend/migrations/versions/tt5b6c7d8e9f_drop_integration_calls_operation_unique.py new file mode 100644 index 00000000..36149427 --- /dev/null +++ b/backend/migrations/versions/tt5b6c7d8e9f_drop_integration_calls_operation_unique.py @@ -0,0 +1,51 @@ +""" +backend/migrations/versions/tt5b6c7d8e9f_drop_integration_calls_operation_unique.py + +用途:integration_calls.operation_id 唯一约束 → 普通索引(多步顺序引擎审计 N 行同 operation_id)。 +依赖:Alembic head tta9b0c1d2e3;IntegrationCall 模型已同步删除 + UniqueConstraint('operation_id') 并新增 Index('ix_integration_calls_operation_id')。 +逻辑:多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id + (计划 D13/全局约束:一票一次执行 = N 条,按 operation_id 串联);原唯一约束 + uq_integration_calls_operation_id 兼作的索引由普通索引 + ix_integration_calls_operation_id 补回(无任何代码按 operation_id 查询单行, + 删约束无消费方风险)。downgrade 精确反向(重建唯一约束);若库中已存在 + 同 operation_id 多行,downgrade 会因唯一约束失败——这是预期: + 多步审计本身就不兼容旧约束(必要时应先人工清理多步行)。 + +Revision ID: tt5b6c7d8e9f +Revises: tta9b0c1d2e3 +Create Date: 2026-09-24 03:00:00.000000 +""" + +from __future__ import annotations + +from alembic import op + +revision = 'tt5b6c7d8e9f' +down_revision = 'tta9b0c1d2e3' +branch_labels = None +depends_on = None + +# 与模型 IntegrationCall.__table_args__ 同源的约束/索引命名(ic1a2b3c4d5f 创建时的原名)。 +_UQ_NAME = 'uq_integration_calls_operation_id' +_IX_NAME = 'ix_integration_calls_operation_id' + + +def upgrade() -> None: + """删 operation_id 唯一约束,补回同名普通索引(查询性能不回退)。""" + # batch_alter_table:SQLite 不支持 DROP CONSTRAINT,须经批处理模式重建表; + # PostgreSQL 等方言按普通 ALTER 执行。 + with op.batch_alter_table('integration_calls') as batch: + batch.drop_constraint(_UQ_NAME, type_='unique') + op.create_index(_IX_NAME, 'integration_calls', ['operation_id']) + + +def downgrade() -> None: + """回滚:删普通索引并重建唯一约束。 + + 注意:若已存在同 operation_id 多行(多步审计的正常数据形态),重建唯一约束 + 将失败——这是预期,多步审计与旧约束不兼容;必要时应先人工归并/清理多步行。 + """ + op.drop_index(_IX_NAME, table_name='integration_calls') + with op.batch_alter_table('integration_calls') as batch: + batch.create_unique_constraint(_UQ_NAME, ['operation_id']) diff --git a/backend/migrations/versions/tt7a8b9c0d1e_add_database_connector_type.py b/backend/migrations/versions/tt7a8b9c0d1e_add_database_connector_type.py new file mode 100644 index 00000000..2146f539 --- /dev/null +++ b/backend/migrations/versions/tt7a8b9c0d1e_add_database_connector_type.py @@ -0,0 +1,54 @@ +"""add database connector type and db_kind column + +Revision ID: tt7a8b9c0d1e +Revises: rn1a2b3c4d5e6 +Create Date: 2026-09-24 00:30:00.000000 + +用途:Integration Connector 扩枚举 database;客户端实例新增 db_kind 专列 + (mysql/oracle/sqlserver/postgresql);重建 client/interface 两表 connector_type CHECK。 +依赖:当前 alembic head rn1a2b3c4d5e6;integration_client_instances / + integration_interface_definitions 已存在。 +逻辑:先删后建两表 CHECK(含 database);client_instances 加可空 db_kind 列 + (存量 rest/soap 为 NULL);downgrade 反向(删列 + CHECK 回 rest/soap)。 + 采用与 if1b2c3d4e5i 相同的直连 drop/create(生产 PostgreSQL);不走 SQLite + batch 表重建,避免同批改 CHECK+加列时的临时表约束冲突。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'tt7a8b9c0d1e' +down_revision = 'rn1a2b3c4d5e6' +branch_labels = None +depends_on = None + +_CLIENT_CK = 'ck_integration_client_instances_connector_type' +_IFACE_CK = 'ck_integration_interface_definitions_connector_type' +_TYPES_WITH_DATABASE = "connector_type IN ('rest', 'soap', 'database')" +_TYPES_LEGACY = "connector_type IN ('rest', 'soap')" + + +def upgrade() -> None: + """扩 connector_type CHECK 含 database,并为客户端实例加 db_kind 列。""" + # [STEP 1] 客户端实例:先删后建 CHECK,再加 db_kind 列。 + op.drop_constraint(_CLIENT_CK, 'integration_client_instances', type_='check') + op.create_check_constraint(_CLIENT_CK, 'integration_client_instances', _TYPES_WITH_DATABASE) + op.add_column( + 'integration_client_instances', + sa.Column('db_kind', sa.String(length=32), nullable=True), + ) + + # [STEP 2] 接口定义:同步扩 CHECK(接口类型跟随客户端)。 + op.drop_constraint(_IFACE_CK, 'integration_interface_definitions', type_='check') + op.create_check_constraint(_IFACE_CK, 'integration_interface_definitions', _TYPES_WITH_DATABASE) + + +def downgrade() -> None: + """回滚:删 db_kind,两表 CHECK 恢复为 rest/soap(须无 database 存量行)。""" + op.drop_constraint(_IFACE_CK, 'integration_interface_definitions', type_='check') + op.create_check_constraint(_IFACE_CK, 'integration_interface_definitions', _TYPES_LEGACY) + + op.drop_column('integration_client_instances', 'db_kind') + op.drop_constraint(_CLIENT_CK, 'integration_client_instances', type_='check') + op.create_check_constraint(_CLIENT_CK, 'integration_client_instances', _TYPES_LEGACY) diff --git a/backend/migrations/versions/tta9b0c1d2e3_add_binding_steps_json.py b/backend/migrations/versions/tta9b0c1d2e3_add_binding_steps_json.py new file mode 100644 index 00000000..3e84b473 --- /dev/null +++ b/backend/migrations/versions/tta9b0c1d2e3_add_binding_steps_json.py @@ -0,0 +1,83 @@ +""" +backend/migrations/versions/tta9b0c1d2e3_add_binding_steps_json.py + +用途:IntegrationBinding 增加 steps_json(一对多有序绑定步骤);存量行回填为单元素数组。 +依赖:Alembic head tt7a8b9c0d1e;integration_bindings 已有 interface_definition_code / + param_mapping_json(旧单步列保留至 P2)。 +逻辑:加列(默认 [])→ 按旧列回填 [{"interface_code", "param_mapping_json"}]; + downgrade 仅删列。旧列不删、不改 NOT NULL(解析层优先读 steps_json)。 + +Revision ID: tta9b0c1d2e3 +Revises: tt7a8b9c0d1e +Create Date: 2026-09-24 01:10:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision = 'tta9b0c1d2e3' +down_revision = 'tt7a8b9c0d1e' +branch_labels = None +depends_on = None + +# 与 context_selector_json / param_mapping_json 同类型约定:PostgreSQL JSONB,其余 JSON。 +STEPS_JSON = sa.JSON().with_variant(postgresql.JSONB(), 'postgresql') + + +def upgrade() -> None: + """加 steps_json 并将存量单步绑定回填为一元素数组。""" + # [STEP 1] 加列(server_default 便于存量 NOT NULL 加列;回填后业务不再依赖默认空数组)。 + op.add_column( + 'integration_bindings', + sa.Column('steps_json', STEPS_JSON, nullable=False, server_default=sa.text("'[]'")), + ) + + # [STEP 2] 存量回填:旧 interface_definition_code + param_mapping_json → 单元素 steps。 + # PostgreSQL:jsonb_build_*;其他方言(如 SQLite 迁移单测)用 JSON 文本拼接兜底。 + bind = op.get_bind() + if bind.dialect.name == 'postgresql': + op.execute( + sa.text( + """ + UPDATE integration_bindings + SET steps_json = jsonb_build_array( + jsonb_build_object( + 'interface_code', interface_definition_code, + 'param_mapping_json', COALESCE(param_mapping_json, '{}'::jsonb) + ) + ) + """ + ) + ) + else: + # SQLite / 其他:用 Python 侧逐行回填,避免方言 JSON 函数差异。 + rows = bind.execute( + sa.text( + 'SELECT id, interface_definition_code, param_mapping_json ' + 'FROM integration_bindings' + ) + ).fetchall() + import json + + for row_id, iface_code, mapping in rows: + # 原生 SELECT 绕过 ORM 类型层:JSON 列读回是 JSON 文本,须先还原为 + # dict 再回填,否则 steps 里 param_mapping_json 是字符串, + # 解析层会按 param_mapping_not_dict fail-closed(存量绑定全灭)。 + if isinstance(mapping, str): + try: + mapping = json.loads(mapping) + except (TypeError, ValueError): + mapping = {} + steps = [{'interface_code': iface_code, 'param_mapping_json': mapping or {}}] + bind.execute( + sa.text('UPDATE integration_bindings SET steps_json = :steps WHERE id = :id'), + {'steps': json.dumps(steps), 'id': row_id}, + ) + + +def downgrade() -> None: + """回滚:删除 steps_json(旧单步列仍在,可继续服务)。""" + op.drop_column('integration_bindings', 'steps_json') diff --git a/backend/requirements.txt b/backend/requirements.txt index e62f110a..8615e1f3 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -41,3 +41,8 @@ tzdata pyyaml minio==7.2.20 google-re2>=1.1.20240702 + +# Integration Connector database transport(D16 四库;仅 connector_type=database 使用) +# oracledb / psycopg2-binary 已在上方;此处补齐 mysql / sqlserver 驱动。 +pymysql>=1.1.0 +pymssql>=2.2.0 diff --git a/backend/tests/api/test_integration_connector_api.py b/backend/tests/api/test_integration_connector_api.py index 76417fb9..f46ca70f 100644 --- a/backend/tests/api/test_integration_connector_api.py +++ b/backend/tests/api/test_integration_connector_api.py @@ -1,7 +1,8 @@ """tests/api/test_integration_connector_api.py 用途:Integration Connector Admin API 契约测试——能力清单、客户端 CRUD、能力调用、 - interface_id 拒绝、连接测试、鉴权(401/403)。依赖 Fake 网关注入。 + interface_id 拒绝、连接测试、集成调用日志查询(列表筛选/keyword/详情时间线)、 + 鉴权(401/403)。依赖 Fake 网关注入。 依赖:app fixture、client、issue_local_access_token、gateway 覆盖注入。 逻辑:Admin API 全部 require_admin;能力调用只暴露 Capability,拒绝传 interface_id。 """ @@ -12,7 +13,7 @@ import pytest from app import db from app.core.auth.jwt import issue_local_access_token -from app.models import User +from app.models import IntegrationCall, User from app.services.integration_connector.transports.base import IntegrationCallResult from app.services.integration_connector.gateway import set_capability_gateway @@ -75,11 +76,11 @@ def _params(): def test_list_capabilities(app, client, admin_headers): - """GET /capabilities → 200,含 3 个在途调拨能力。""" + """GET /capabilities → 200,含 2 个在途调拨能力(D13 收缩:读+写)。""" response = client.get(f"{API_PREFIX}/capabilities", headers=admin_headers) assert response.status_code == 200 names = {item["name"] for item in response.get_json()["data"]} - assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names) + assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer"}.issubset(names) def test_create_and_list_client_instance(app, client, admin_headers): @@ -187,6 +188,44 @@ def test_client_instance_test_connection_merges_endpoint_column(app, client, adm assert spy.seen["config_json"]["timeout_seconds"] == 45 +def test_client_instance_test_connection_resolves_credential_ref(app, client, admin_headers, fake_gateway): + """连接测试回归:有凭据引用时必须解析真实凭据传给 transport(与 engine 调用链同源)。 + + 曾因测试端点恒传空 credential,数据库直连探针必然认证失败—— + 连接测试按设计须证明「网络与认证」可用,无凭据无法建连。 + """ + # env 模式凭据:secret_ref 指向 app config 键,避免解密依赖(db 模式解密另有专门测试)。 + client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ + "code": "CRED-ENV", "secret_provider": "env", "secret_ref": "PROBE_TEST_CREDENTIAL", + }) + created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-DB", "name": "db client", "connector_type": "database", "environment": "prod", + "endpoint": "192.168.8.24:1521/topprod", "db_kind": "oracle", + "credential_ref_code": "CRED-ENV", + }) + assert created.status_code == 201 + + seen = {} + + class DbSpyTransport: + connector_type = "database" + + def probe(self, *, client): + seen.update(client) + return {"ok": True, "code": "DB_PROBE_OK", "message": "ok"} + + fake_gateway.transports["database"] = DbSpyTransport() + with app.app_context(): + app.config["PROBE_TEST_CREDENTIAL"] = {"username": "erp_u", "password": "erp_p"} + response = client.post(f"{API_PREFIX}/client-instances/CLI-DB/test", headers=admin_headers) + + assert response.status_code == 200 + assert response.get_json()["data"]["ok"] is True + # 凭据引用必须解析成真实凭据注入 transport(关键断言);db_kind 专列拼回 config_json。 + assert seen["credential"] == {"username": "erp_u", "password": "erp_p"} + assert seen["config_json"]["db_kind"] == "oracle" + + def test_client_instance_test_connection_reports_unreachable(app, client, admin_headers, fake_gateway): """probe 探测不通 → 仍 200 但 ok=False(探测结果是业务结果,不是请求错误)。""" client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ @@ -534,7 +573,7 @@ def test_interface_definition_split_columns(app, client, admin_headers): # ---- 绑定参数映射 / 凭据 db 模式 ---- def test_binding_param_mapping_round_trip(app, client, admin_headers): - """POST/PUT /bindings 透传 param_mapping_json,序列化原样返回。""" + """POST/PUT /bindings:steps_json 携带 param_mapping;旧字段镜像首步。""" client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ "code": "CLI-PM", "name": "cli", "connector_type": "rest", "environment": "prod", "endpoint": "https://erp.invalid", @@ -544,20 +583,238 @@ def test_binding_param_mapping_round_trip(app, client, admin_headers): }) created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ "capability": "in_transit_transfer.query_inventory", - "client_instance_code": "CLI-PM", "interface_definition_code": "IFACE-PM", - "param_mapping_json": {"organization": {"expr": "external_org"}, - "condition": {"template": "img04 = '{invoice_no}'"}}, + "steps_json": [{ + "interface_code": "IFACE-PM", + "param_mapping_json": { + "organization": {"expr": "external_org"}, + "condition": {"template": "img04 = '{invoice_no}'"}, + }, + }], }) assert created.status_code == 201 data = created.get_json()["data"] + assert data["steps_json"][0]["param_mapping_json"]["organization"] == {"expr": "external_org"} assert data["param_mapping_json"]["organization"] == {"expr": "external_org"} + assert data["interface_definition_code"] == "IFACE-PM" + assert data["client_instance_code"] == "CLI-PM" - updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, - json={"param_mapping_json": {"condition": {"template": "img02 = '{warehouse}'"}}}) + updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={ + "param_mapping_json": {"condition": {"template": "img02 = '{warehouse}'"}}, + }) assert updated.status_code == 200 - assert updated.get_json()["data"]["param_mapping_json"] == { + body = updated.get_json()["data"] + assert body["param_mapping_json"] == { "condition": {"template": "img02 = '{warehouse}'"}, } + assert body["steps_json"][0]["param_mapping_json"] == { + "condition": {"template": "img02 = '{warehouse}'"}, + } + + +def test_binding_steps_json_multi_step_and_validation(app, client, admin_headers): + """POST steps_json 多步落库;空数组/非法映射/缺失接口 → 400。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-S1", "name": "db", "connector_type": "database", "environment": "prod", + "endpoint": "127.0.0.1:1521/ORCL", "db_kind": "oracle", + }) + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-S2", "name": "ws", "connector_type": "soap", "environment": "prod", + "endpoint": "https://ws.invalid", + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-S1", "name": "stage", "client_instance_code": "CLI-S1", + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-S2", "name": "submit", "client_instance_code": "CLI-S2", + }) + + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.create_transfer", + "steps_json": [ + {"interface_code": "IF-S1", "param_mapping_json": {"maker": {"expr": "external_org"}}}, + {"interface_code": "IF-S2", "param_mapping_json": {}}, + ], + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert len(data["steps_json"]) == 2 + assert data["steps_json"][0]["interface_code"] == "IF-S1" + assert data["steps_json"][1]["interface_code"] == "IF-S2" + # 旧列镜像首步(跨客户端绑定:首步 database) + assert data["client_instance_code"] == "CLI-S1" + assert data["interface_definition_code"] == "IF-S1" + + empty = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.create_transfer", + "steps_json": [], + }) + assert empty.status_code == 400 + assert empty.get_json()["error"]["code"] == "INTEGRATION.BINDING_STEPS_INVALID" + + bad_mapping = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.create_transfer", + "steps_json": [{"interface_code": "IF-S1", "param_mapping_json": ["not", "dict"]}], + }) + assert bad_mapping.status_code == 400 + assert bad_mapping.get_json()["error"]["code"] == "INTEGRATION.BINDING_STEPS_INVALID" + + missing = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.create_transfer", + "steps_json": [{"interface_code": "IF-NOPE", "param_mapping_json": {}}], + }) + assert missing.status_code == 400 + assert missing.get_json()["error"]["code"] == "INTEGRATION.INTERFACE_NOT_FOUND" + + # 发布门禁:两步接口均须 published + binding_id = data["id"] + not_ready = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers) + assert not_ready.status_code == 400 + assert not_ready.get_json()["error"]["code"] == "INTEGRATION.BINDING_TARGET_NOT_READY" + client.post(f"{API_PREFIX}/interface-definitions/IF-S1/publish", headers=admin_headers) + still = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers) + assert still.status_code == 400 + client.post(f"{API_PREFIX}/interface-definitions/IF-S2/publish", headers=admin_headers) + ok_pub = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers) + assert ok_pub.status_code == 200 + assert ok_pub.get_json()["data"]["status"] == "published" + + +def test_binding_legacy_single_step_fields_still_accepted(app, client, admin_headers): + """兼容窗:无 steps_json 时旧 client+interface+param_mapping 合成单元素 steps。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-LEG", "name": "cli", "connector_type": "rest", "environment": "prod", + "endpoint": "https://erp.invalid", + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-LEG", "name": "iface", "client_instance_code": "CLI-LEG", + }) + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "client_instance_code": "CLI-LEG", + "interface_definition_code": "IF-LEG", + "param_mapping_json": {"org": {"expr": "external_org"}}, + }) + assert created.status_code == 201 + data = created.get_json()["data"] + assert data["steps_json"] == [{ + "interface_code": "IF-LEG", + "param_mapping_json": {"org": {"expr": "external_org"}}, + }] + + +def _seed_two_step_binding(client, admin_headers): + """公共夹具:两客户端两接口 + 一个两步绑定(database 中间表 → soap 触发 WS)。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-P1", "name": "db", "connector_type": "database", "environment": "prod", + "endpoint": "127.0.0.1:1521/ORCL", "db_kind": "oracle", + }) + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-P2", "name": "ws", "connector_type": "soap", "environment": "prod", + "endpoint": "https://ws.invalid", + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-P1", "name": "stage", "client_instance_code": "CLI-P1", + }) + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": "IF-P2", "name": "submit", "client_instance_code": "CLI-P2", + }) + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.create_transfer", + "steps_json": [ + {"interface_code": "IF-P1", "param_mapping_json": {"maker": {"expr": "external_org"}}}, + {"interface_code": "IF-P2", "param_mapping_json": {}}, + ], + }) + assert created.status_code == 201 + return created.get_json()["data"]["id"] + + +def test_binding_legacy_put_rejected_on_multi_step(app, client, admin_headers): + """多步绑定 PUT 携带旧单步字段 → 400 BINDING_LEGACY_PUT_REJECTED(防截断多步配方)。""" + binding_id = _seed_two_step_binding(client, admin_headers) + + # 三把旧钥匙(interface_definition_code / param_mapping_json / client_instance_code) + # 任一出现在多步绑定 PUT 均拒绝:都会经兼容窗合成单元素 steps 回写、静默销毁第 2..n 步 + for legacy_body in ( + {"interface_definition_code": "IF-P1"}, + {"param_mapping_json": {"org": {"expr": "external_org"}}}, + {"client_instance_code": "CLI-P2"}, + ): + rejected = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json=legacy_body) + assert rejected.status_code == 400 + assert rejected.get_json()["error"]["code"] == "INTEGRATION.BINDING_LEGACY_PUT_REJECTED" + + # 多步配方未被截断 + listed = client.get(f"{API_PREFIX}/bindings", headers=admin_headers) + row = next(item for item in listed.get_json()["data"] if item["id"] == binding_id) + assert len(row["steps_json"]) == 2 + + # 纯 steps_json PUT 不受影响:整表替换且可重排 + reordered = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ + "steps_json": [ + {"interface_code": "IF-P2", "param_mapping_json": {}}, + {"interface_code": "IF-P1", "param_mapping_json": {"maker": {"expr": "external_org"}}}, + ], + }) + assert reordered.status_code == 200 + assert [s["interface_code"] for s in reordered.get_json()["data"]["steps_json"]] == ["IF-P2", "IF-P1"] + + +def test_binding_steps_json_with_legacy_keys_rejected(app, client, admin_headers): + """矛盾载荷:steps_json 与旧单步字段同 PUT → 400(防旧键被静默忽略、部分生效无提示)。""" + binding_id = _seed_two_step_binding(client, admin_headers) + + for conflicting_key in ("param_mapping_json", "interface_definition_code"): + contradictory = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ + "steps_json": [{"interface_code": "IF-P1", "param_mapping_json": {}}], + conflicting_key: "IF-P1" if conflicting_key == "interface_definition_code" else {"x": {"expr": "y"}}, + }) + assert contradictory.status_code == 400 + assert contradictory.get_json()["error"]["code"] == "INTEGRATION.BINDING_LEGACY_PUT_REJECTED" + + # 矛盾载荷未被部分应用:配方保持原两步(IF-P1 → IF-P2) + listed = client.get(f"{API_PREFIX}/bindings", headers=admin_headers) + row = next(item for item in listed.get_json()["data"] if item["id"] == binding_id) + assert [s["interface_code"] for s in row["steps_json"]] == ["IF-P1", "IF-P2"] + + # 对照:去掉旧键后同一 steps_json PUT 正常生效 + ok_put = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ + "steps_json": [{"interface_code": "IF-P1", "param_mapping_json": {}}], + }) + assert ok_put.status_code == 200 + + +def test_binding_legacy_put_compat_single_step(app, client, admin_headers): + """兼容窗:单步绑定旧字段 PUT 仍通(换绑接口 / 更新首步映射)。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-C1", "name": "cli", "connector_type": "rest", "environment": "prod", + "endpoint": "https://erp.invalid", + }) + for code in ("IF-C1", "IF-C2"): + client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ + "code": code, "name": "iface", "client_instance_code": "CLI-C1", + }) + created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ + "capability": "in_transit_transfer.query_inventory", + "steps_json": [{"interface_code": "IF-C1", "param_mapping_json": {}}], + }) + binding_id = created.get_json()["data"]["id"] + + # 单步绑定换绑接口仍走兼容窗 + rebinding = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ + "interface_definition_code": "IF-C2", + }) + assert rebinding.status_code == 200 + assert rebinding.get_json()["data"]["interface_definition_code"] == "IF-C2" + assert rebinding.get_json()["data"]["steps_json"][0]["interface_code"] == "IF-C2" + + # 单步绑定仅更新映射仍走兼容窗(只更新首步映射) + mapping = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ + "param_mapping_json": {"a": {"expr": "x"}}, + }) + assert mapping.status_code == 200 + assert mapping.get_json()["data"]["steps_json"][0]["param_mapping_json"] == {"a": {"expr": "x"}} + def test_credential_db_mode_round_trip(app, client, admin_headers): @@ -629,3 +886,100 @@ def test_credential_db_mode_requires_username_and_password(app, client, admin_he "code": "CRED-DB2", "secret_provider": "db", "username": "only-user", }) assert response.status_code == 400 + + +# ---- 集成调用日志查询(Task 5)---- + +def _seed_integration_calls(): + """集成调用日志查询造数:1 条无关能力 + 同一 operation_id 的两步(stage 成功 + ws 失败)。 + + 与 engine._record_call 落库口径同构:binding_snapshot_json 含 client_code/ + interface_code/connector_type/step_index/step_count/steps;单号 + TGHX1-OR-26092600002 写入 request_summary_json 供 keyword 模糊命中。 + 插入顺序:无关行最先、ws 步最后 → 详情用例取 id 最大行即 ws 步, + timeline 覆盖同 operation 两步、wire_json 命中 dict 分支。 + + Returns: + 落库后的 [无关行, stage 步, ws 步] 三条 IntegrationCall。 + """ + def _snap(interface_code, connector_type, step_index, step_count): + return { + 'client_code': 'CLI-ERP', + 'interface_code': interface_code, + 'connector_type': connector_type, + 'step_index': step_index, + 'step_count': step_count, + 'steps': [ + {'interface_code': 'erp-db-stage-transfer', + 'client_code': 'CLI-ERP', 'connector_type': 'database'}, + {'interface_code': 'erp-ws-submit-transfer', + 'client_code': 'CLI-ERP', 'connector_type': 'soap'}, + ][:step_count], + } + + rows = [ + # 无关能力行:不应被 interface_code=erp-ws-submit-transfer / operation 筛选命中 + IntegrationCall( + operation_id='OP-OTHER', capability='in_transit_transfer.query_inventory', + binding_snapshot_json=_snap('erp-db-query-stock', 'database', 0, 1), + request_summary_json={'invoice_no': 'INV-OTHER-001'}, + response_summary_json={'found': True}, + status='success', elapsed_ms=12, trace_id='TRC-OTHER', + ), + # 同一 operation_id 的第 1 步(database 中间表,成功) + IntegrationCall( + operation_id='OP-TGHX-26092600002', capability='in_transit_transfer.create_transfer', + binding_snapshot_json=_snap('erp-db-stage-transfer', 'database', 0, 2), + request_summary_json={'document_no': 'TGHX1-OR-26092600002', 'maker': 'HW'}, + response_summary_json={'inserted': 1}, + status='success', elapsed_ms=88, trace_id='TRC-STAGE', + ), + # 同一 operation_id 的第 2 步(soap 触发 WS,失败;带线级事实 wire_json) + IntegrationCall( + operation_id='OP-TGHX-26092600002', capability='in_transit_transfer.create_transfer', + binding_snapshot_json=_snap('erp-ws-submit-transfer', 'soap', 1, 2), + request_summary_json={'document_no': 'TGHX1-OR-26092600002'}, + response_summary_json={'code': '504', 'message': 'ws timeout'}, + wire_json={'endpoint': 'https://ws.invalid/Service', + 'request_xml': '', 'http_status': 504}, + status='technical_failed', elapsed_ms=5021, trace_id='TRC-WS', + business_ref='TGHX1-OR-26092600002', + ), + ] + db.session.add_all(rows) + db.session.commit() + return rows + + +def test_list_calls_filters_by_interface_and_keyword(client, admin_headers): + """GET /calls?interface_code=… → 只命中快照含该接口的那一条(能力无关通用口径)。""" + _seed_integration_calls() + resp = client.get('/api/integration-connector/calls?interface_code=erp-ws-submit-transfer', + headers=admin_headers) + body = resp.get_json()['data'] + # 关键断言:interface_code 精确筛选走 binding_snapshot_json JSON 路径, + # 三行里只有 ws 步快照带该接口 → total 恰为 1 + assert body['total'] == 1 + assert body['items'][0]['interface_code'] == 'erp-ws-submit-transfer' + + +def test_list_calls_keyword_searches_request_summary(client, admin_headers): + """GET /calls?keyword=… → keyword 对 request_summary_json 文本化后模糊匹配。""" + _seed_integration_calls() + resp = client.get('/api/integration-connector/calls?keyword=TGHX1-OR-26092600002', + headers=admin_headers) + # 关键断言:单号只出现在两步的 request_summary_json 里 → 至少命中 1 条 + assert resp.get_json()['data']['total'] >= 1 + + +def test_call_detail_returns_wire_and_timeline(client, admin_headers): + """GET /calls/ → 单条全量(wire_json 透传)+ 同 operation_id 各步时间线。""" + _seed_integration_calls() + call = IntegrationCall.query.order_by(IntegrationCall.id.desc()).first() + resp = client.get(f'/api/integration-connector/calls/{call.id}', headers=admin_headers) + data = resp.get_json()['data'] + # 关键断言:详情返回所取行本身;wire_json 为 NULL 或 dict(JSON 列可空透传); + # timeline 按 operation_id 串联——种子最大 id 是两步 operation 的末步 → 至少 1 步 + assert data['call']['id'] == call.id + assert data['call']['wire_json'] is None or isinstance(data['call']['wire_json'], dict) + assert len(data['timeline']) >= 1 diff --git a/backend/tests/services/integration_connector/test_binding.py b/backend/tests/services/integration_connector/test_binding.py index f8159a72..16118e31 100644 --- a/backend/tests/services/integration_connector/test_binding.py +++ b/backend/tests/services/integration_connector/test_binding.py @@ -3,8 +3,8 @@ 用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。 依赖:IntegrationBinding 等模型、binding.py、errors.py。 逻辑:只匹配 published + environment + 生效区间 + context_selector 子集; - 接口定义须 published、客户端须 enabled,否则同样 fail-closed; - 无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。 + 每步接口须 published、客户端须 enabled,否则同样 fail-closed; + 无命中抛 BindingNotFoundError;快照冻结 steps 与配置(调用期冻结,非活表)。 """ from __future__ import annotations @@ -16,7 +16,7 @@ import pytest from app import db from app.core.errors import AppError from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition -from app.services.integration_connector.binding import BindingSnapshot, resolve_binding +from app.services.integration_connector.binding import resolve_binding def _client(code="CLI-A", **overrides): @@ -37,9 +37,26 @@ def _interface(code="IFACE-Q", **overrides): def _binding(capability="in_transit_transfer.query_inventory", **overrides): - values = {"capability": capability, "context_selector_json": {}, - "client_instance_code": "CLI-A", "interface_definition_code": "IFACE-Q", - "mapping_version": 2, "priority": 0, "environment": "prod", "status": "published"} + """构造单步绑定(steps_json 一元素);旧列镜像首步。""" + iface_code = overrides.pop("interface_definition_code", "IFACE-Q") + client_code = overrides.pop("client_instance_code", "CLI-A") + param_mapping = overrides.pop("param_mapping_json", {}) + steps = overrides.pop( + "steps_json", + [{"interface_code": iface_code, "param_mapping_json": param_mapping}], + ) + values = { + "capability": capability, + "context_selector_json": {}, + "steps_json": steps, + "client_instance_code": client_code, + "interface_definition_code": iface_code, + "param_mapping_json": param_mapping, + "mapping_version": 2, + "priority": 0, + "environment": "prod", + "status": "published", + } values.update(overrides) return IntegrationBinding(**values) @@ -53,8 +70,9 @@ def test_default_binding_matches_any_context(app): """空 context_selector 的默认绑定命中(context 含额外键也可命中)。""" _seed_default(app) snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "DBS-AWSBI"}, "prod") - assert snap.client_code == "CLI-A" - assert snap.interface_code == "IFACE-Q" + assert len(snap.steps) == 1 + assert snap.steps[0].client_code == "CLI-A" + assert snap.steps[0].interface_code == "IFACE-Q" assert snap.mapping_version == 2 @@ -117,10 +135,11 @@ def test_freeze_versions_in_snapshot(app): """快照冻结 interface 版本与调用期配置(非活表)。""" _seed_default(app) snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod") - assert snap.interface_version == 3 - assert snap.credential_ref_code is None - assert snap.request_spec.get("path") == "/stock" - assert snap.config.get("endpoint") == "https://erp.invalid" + step = snap.steps[0] + assert step.interface_version == 3 + assert step.credential_ref_code is None + assert step.request_spec.get("path") == "/stock" + assert step.config.get("endpoint") == "https://erp.invalid" def test_snapshot_carries_param_mapping_and_input_schema(app): @@ -132,8 +151,8 @@ def test_snapshot_carries_param_mapping_and_input_schema(app): ]) db.session.commit() snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod") - assert snap.param_mapping == {"condition": {"template": "img04 = '{invoice_no}'"}} - assert snap.input_schema == {"type": "object", "required": ["condition"]} + assert snap.steps[0].param_mapping == {"condition": {"template": "img04 = '{invoice_no}'"}} + assert snap.steps[0].input_schema == {"type": "object", "required": ["condition"]} def test_draft_interface_not_matched(app): diff --git a/backend/tests/services/integration_connector/test_binding_steps.py b/backend/tests/services/integration_connector/test_binding_steps.py new file mode 100644 index 00000000..73e55ff8 --- /dev/null +++ b/backend/tests/services/integration_connector/test_binding_steps.py @@ -0,0 +1,324 @@ +"""tests/services/integration_connector/test_binding_steps.py + +用途:验证绑定一对多有序步骤(steps_json)——多步快照解析、逐项发布门禁、 + 存量单步迁移形态、读能力单步兼容、空/非法步骤 fail-closed。 +依赖:IntegrationBinding 等模型、binding.BindingStep/BindingSnapshot/resolve_binding。 +逻辑:steps_json 为有序数组;每步自带 interface_code + param_mapping; + 客户端由接口归属推导;任一步接口未发布或客户端停用 → BindingNotFoundError。 +""" + +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +from app import db +from app.core.errors import AppError +from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.integration_connector.binding import BindingStep, resolve_binding + + +def _client(code="CLI-A", **overrides): + values = { + "name": f"client {code}", + "connector_type": "soap", + "environment": "prod", + "config_json": {"endpoint": "https://erp.invalid"}, + "enabled": True, + } + values.update(overrides) + return IntegrationClientInstance(code=code, **values) + + +def _interface(code="IFACE-Q", client_code="CLI-A", **overrides): + values = { + "name": f"iface {code}", + "client_instance_code": client_code, + "connector_type": "soap", + "request_spec_json": {"method": "GET", "path": f"/{code}"}, + "input_schema_json": {}, + "response_mapping_json": {}, + "output_schema_json": {}, + "version": 1, + "status": "published", + } + values.update(overrides) + return IntegrationInterfaceDefinition(code=code, **values) + + +def _binding(capability="in_transit_transfer.create_transfer", **overrides): + """构造绑定:默认两步 steps_json;旧列仍填首步以满足 NOT NULL(P2 删列前)。""" + steps = overrides.pop( + "steps_json", + [ + {"interface_code": "IFACE-STAGE", "param_mapping_json": {"maker": {"expr": "external_org"}}}, + {"interface_code": "IFACE-SUBMIT", "param_mapping_json": {"source_ip": {"template": "0.0.0.0"}}}, + ], + ) + first = steps[0] if steps else {} + first_iface = first.get("interface_code") or "IFACE-STAGE" + first_mapping = first.get("param_mapping_json") or first.get("param_mapping") or {} + if not isinstance(first_mapping, dict): + first_mapping = {} + values = { + "capability": capability, + "context_selector_json": {}, + "steps_json": steps, + "client_instance_code": "CLI-DB", + "interface_definition_code": first_iface, + "param_mapping_json": first_mapping, + "mapping_version": 1, + "priority": 0, + "environment": "prod", + "status": "published", + } + values.update(overrides) + values["steps_json"] = steps + return IntegrationBinding(**values) + + +def _seed_two_step(app): + """造两客户端 + 两接口 + 有序两步绑定(create_transfer 形态)。""" + db.session.add_all([ + _client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL", + config_json={}, db_kind="oracle"), + _client("CLI-WS", connector_type="soap", config_json={"endpoint": "https://ws.invalid"}), + _interface("IFACE-STAGE", "CLI-DB", connector_type="database", + request_spec_json={"sql": {"mode": "execute", "pre": [], "bulk": None, "post": []}}), + _interface("IFACE-SUBMIT", "CLI-WS", connector_type="soap", + request_spec_json={"method": "POST", "path": "/submit"}, version=5), + _binding(), + ]) + db.session.commit() + + +def test_multi_step_snapshot_preserves_order_and_per_step_fields(app): + """多步绑定解析为 BindingStep 有序元组;每步独立 client/config/mapping。""" + _seed_two_step(app) + snap = resolve_binding("in_transit_transfer.create_transfer", {}, "prod") + assert len(snap.steps) == 2 + assert all(isinstance(step, BindingStep) for step in snap.steps) + # 顺序锁定:写中间表 → 触发 WS + assert [s.interface_code for s in snap.steps] == ["IFACE-STAGE", "IFACE-SUBMIT"] + assert snap.steps[0].connector_type == "database" + assert snap.steps[0].client_code == "CLI-DB" + assert snap.steps[0].param_mapping == {"maker": {"expr": "external_org"}} + assert snap.steps[1].connector_type == "soap" + assert snap.steps[1].client_code == "CLI-WS" + assert snap.steps[1].param_mapping == {"source_ip": {"template": "0.0.0.0"}} + assert snap.steps[1].request_spec.get("path") == "/submit" + assert snap.mapping_version == 1 + + +def test_read_capability_single_step_shape(app): + """读能力单步绑定:steps 恰一元素,形状与多步统一(无扁平遗留字段依赖)。""" + db.session.add_all([ + _client(), + _interface(code="IFACE-Q", version=3, + response_mapping_json={"qty": {"expr": "quantity"}}, + request_spec_json={"method": "GET", "path": "/stock"}), + IntegrationBinding( + capability="in_transit_transfer.query_inventory", + context_selector_json={}, + steps_json=[{"interface_code": "IFACE-Q", "param_mapping_json": {"condition": {"expr": "invoice_no"}}}], + client_instance_code="CLI-A", + interface_definition_code="IFACE-Q", + param_mapping_json={"condition": {"expr": "invoice_no"}}, + mapping_version=2, + priority=0, + environment="prod", + status="published", + ), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X"}, "prod") + assert len(snap.steps) == 1 + step = snap.steps[0] + assert step.interface_code == "IFACE-Q" + assert step.client_code == "CLI-A" + assert step.param_mapping == {"condition": {"expr": "invoice_no"}} + assert step.request_spec.get("path") == "/stock" + assert snap.capability == "in_transit_transfer.query_inventory" + + +def test_legacy_columns_fallback_to_one_element_steps(app): + """存量单步:steps_json 空时由旧列合成单元素步骤(迁移兜底 / 兼容窗)。""" + db.session.add_all([ + _client(), + _interface(code="IFACE-LEGACY"), + IntegrationBinding( + capability="in_transit_transfer.query_inventory", + context_selector_json={}, + steps_json=[], # 空:模拟迁移前或未回填 + client_instance_code="CLI-A", + interface_definition_code="IFACE-LEGACY", + param_mapping_json={"org": {"expr": "external_org"}}, + mapping_version=1, + priority=0, + environment="prod", + status="published", + ), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert len(snap.steps) == 1 + assert snap.steps[0].interface_code == "IFACE-LEGACY" + assert snap.steps[0].param_mapping == {"org": {"expr": "external_org"}} + + +def test_gate_rejects_when_any_step_interface_not_published(app): + """门禁:第二步接口 draft → 整绑定 fail-closed(BindingNotFoundError)。""" + db.session.add_all([ + _client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL", + config_json={}, db_kind="oracle"), + _client("CLI-WS", connector_type="soap", config_json={"endpoint": "https://ws.invalid"}), + _interface("IFACE-STAGE", "CLI-DB", connector_type="database"), + _interface("IFACE-SUBMIT", "CLI-WS", status="draft"), # 末步未发布 + _binding(), + ]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.create_transfer", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_gate_rejects_when_any_step_client_disabled(app): + """门禁:任一步客户端 enabled=False → BindingNotFoundError。""" + db.session.add_all([ + _client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL", + config_json={}, db_kind="oracle"), + _client("CLI-WS", connector_type="soap", config_json={"endpoint": "https://ws.invalid"}, + enabled=False), + _interface("IFACE-STAGE", "CLI-DB", connector_type="database"), + _interface("IFACE-SUBMIT", "CLI-WS"), + _binding(), + ]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.create_transfer", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_gate_rejects_missing_step_interface(app): + """门禁:步骤引用的接口不存在 → BindingNotFoundError。""" + db.session.add_all([ + _client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL", + config_json={}, db_kind="oracle"), + _interface("IFACE-STAGE", "CLI-DB", connector_type="database"), + _binding(steps_json=[ + {"interface_code": "IFACE-STAGE", "param_mapping_json": {}}, + {"interface_code": "IFACE-MISSING", "param_mapping_json": {}}, + ]), + ]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.create_transfer", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_empty_steps_without_legacy_columns_raises(app): + """无步骤且旧列也无法兜底时 fail-closed(禁止静默空配方)。""" + db.session.add_all([ + _client(), + _interface(), + IntegrationBinding( + capability="in_transit_transfer.query_inventory", + context_selector_json={}, + steps_json=[], + client_instance_code="CLI-A", + interface_definition_code="IFACE-Q", + param_mapping_json={}, + mapping_version=1, + priority=0, + environment="prod", + status="published", + ), + ]) + # 故意把旧列指向不存在的接口,阻断兜底 + row = IntegrationBinding.query.filter_by(capability="in_transit_transfer.query_inventory").first() + row.interface_definition_code = "IFACE-GONE" + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +# ---- 迁移契约(tta9b0c1d2e3):加列 + 存量行回填单步数组 ---- + +VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions' +STEPS_MIGRATION_FILE = 'tta9b0c1d2e3_add_binding_steps_json.py' + + +def _load_steps_migration(): + """加载 binding steps_json 迁移模块(数据迁移须可脱离 Alembic 运行环境独立验证)。""" + path = VERSIONS_DIR / STEPS_MIGRATION_FILE + spec = importlib.util.spec_from_file_location('tta9b0c1d2e3_migration', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_steps_migration_chain_contract(): + """迁移链契约:revision=tta9b0c1d2e3,down_revision=tt7a8b9c0d1e(Task 1 之后单线)。""" + migration = _load_steps_migration() + assert migration.revision == 'tta9b0c1d2e3' + assert migration.down_revision == 'tt7a8b9c0d1e' + assert callable(migration.upgrade) and callable(migration.downgrade) + + +def test_steps_migration_backfills_legacy_rows_as_single_step_array(): + """存量行回填契约:旧列 → [{"interface_code", "param_mapping_json"}],mapping 须为 dict。 + + 在内存 SQLite 真实执行 upgrade/downgrade(非仅源码断言):原生 SELECT 绕过 ORM + 类型层,JSON 列读回是文本,若不还原为 dict 直接回填,解析层会按 + param_mapping_not_dict fail-closed(存量绑定全部失效);NULL mapping 回填 {}; + downgrade 仅删 steps_json,旧单步列保留。 + """ + migration = _load_steps_migration() + engine = sa.create_engine('sqlite://') + with engine.connect() as conn: + conn.execute(sa.text( + "CREATE TABLE integration_bindings (" + " id INTEGER PRIMARY KEY, capability VARCHAR(128) NOT NULL," + " client_instance_code VARCHAR(64) NOT NULL," + " interface_definition_code VARCHAR(64) NOT NULL," + " param_mapping_json TEXT)" + )) + # 行 1 模拟 ORM(JSON 列) 已写入的存量映射;行 2 模拟 NULL 映射 + conn.execute(sa.text( + "INSERT INTO integration_bindings (id, capability, client_instance_code," + " interface_definition_code, param_mapping_json) VALUES" + " (1,'cap.a','CLI-A','IFACE-Q','{\"org\": \"HX-CN01\"}')," + " (2,'cap.b','CLI-B','IFACE-R',NULL)" + )) + conn.commit() + mc = MigrationContext.configure(conn) + with Operations.context(mc) as op: + migration.upgrade() + conn.commit() + rows = conn.execute( + sa.text('SELECT id, steps_json FROM integration_bindings ORDER BY id') + ).fetchall() + # 断言 1:存量行回填为单元素数组,形状 {interface_code, param_mapping_json} 且映射为 dict + assert json.loads(rows[0][1]) == [ + {"interface_code": "IFACE-Q", "param_mapping_json": {"org": "HX-CN01"}}, + ] + # 断言 2:NULL 映射回填为空对象(同样必须是 dict 而非 JSON 文本) + assert json.loads(rows[1][1]) == [ + {"interface_code": "IFACE-R", "param_mapping_json": {}}, + ] + with Operations.context(mc) as op: + migration.downgrade() + conn.commit() + # 断言 3:downgrade 删 steps_json,旧单步列仍在(P2 前保持可服务) + cols = [r[1] for r in conn.execute( + sa.text('PRAGMA table_info(integration_bindings)')).fetchall()] + assert 'steps_json' not in cols + assert 'interface_definition_code' in cols and 'param_mapping_json' in cols diff --git a/backend/tests/services/integration_connector/test_database_connector_type.py b/backend/tests/services/integration_connector/test_database_connector_type.py new file mode 100644 index 00000000..ca7fc0e0 --- /dev/null +++ b/backend/tests/services/integration_connector/test_database_connector_type.py @@ -0,0 +1,211 @@ +"""tests/services/integration_connector/test_database_connector_type.py + +用途:Task 1——database 连接器类型注册回归:模型常量、db_kind 专列、API 必填/枚举、 + 迁移链与 CHECK 重建。 +依赖:app fixture、IntegrationClientInstance、API Blueprint 常量、Alembic 迁移模块。 +逻辑:先断言 CONNECTOR_TYPES / VALID_CONNECTOR_TYPES 含 database 且同源;再断言 + db_kind 列可落库;API create/update 对 database 必填且四库枚举 fail-closed, + 非 database 强制置 NULL;迁移挂接当前 head 并加列+重建两表 CHECK。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +from app import db +from app.api.integration_connector import VALID_CONNECTOR_TYPES, VALID_DB_KINDS +from app.core.auth.jwt import issue_local_access_token +from app.models import IntegrationClientInstance, User +from app.models.integration_connector import CONNECTOR_TYPES, DB_KINDS + +API_PREFIX = '/api/integration-connector' +VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions' +MIGRATION_FILE = 'tt7a8b9c0d1e_add_database_connector_type.py' + + +def _load_migration(): + """加载 database 连接器类型迁移模块。""" + path = VERSIONS_DIR / MIGRATION_FILE + spec = importlib.util.spec_from_file_location('tt7a8b9c0d1e_migration', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture +def admin_headers(app): + """发放 admin Bearer,供客户端实例 API 用例复用。""" + with app.app_context(): + user = db.session.query(User).filter_by(username='admin').first() + if not user: + user = User(username='admin', email='admin@example.com', role='admin', status='active') + user.set_password('admin') + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'} + + +def test_connector_types_include_database(): + """模型 CONNECTOR_TYPES 必须含 database,且与 API 白名单同源。""" + assert 'database' in CONNECTOR_TYPES + assert CONNECTOR_TYPES == ('rest', 'soap', 'database') + assert VALID_CONNECTOR_TYPES == CONNECTOR_TYPES + + +def test_db_kinds_enum_four_values(): + """db_kind 四库枚举为 mysql/oracle/sqlserver/postgresql(非 mssql),模型与 API 同源。""" + assert DB_KINDS == ('mysql', 'oracle', 'sqlserver', 'postgresql') + assert VALID_DB_KINDS == DB_KINDS + assert 'mssql' not in DB_KINDS + + +def test_client_instance_accepts_database_type_with_db_kind(app): + """connector_type=database + 合法 db_kind 可落库;响应可回读。""" + client = IntegrationClientInstance( + code='ERP-ORA-01', + name='Oracle ERP', + connector_type='database', + environment='prod', + endpoint='erp.invalid:1521/ORCL', + db_kind='oracle', + config_json={}, + ) + db.session.add(client) + db.session.commit() + loaded = IntegrationClientInstance.query.filter_by(code='ERP-ORA-01').one() + assert loaded.connector_type == 'database' + assert loaded.db_kind == 'oracle' + + +def test_api_create_database_requires_db_kind(app, client, admin_headers): + """POST database 缺 db_kind → 400 ValidationError。""" + response = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={ + 'code': 'DB-NO-KIND', 'name': 'no kind', 'connector_type': 'database', + 'endpoint': 'host:3306/db', + }) + assert response.status_code == 400 + body = response.get_json() + assert body['success'] is False + + +def test_api_create_database_rejects_unknown_db_kind(app, client, admin_headers): + """POST database + 未知 db_kind(含历史别名 mssql)→ 400 fail-closed。""" + for bad in ('mssql', 'sqlite', 'mongo', ''): + response = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={ + 'code': f'DB-BAD-{bad or "empty"}', 'name': 'bad', 'connector_type': 'database', + 'endpoint': 'host:1433/db', 'db_kind': bad, + }) + assert response.status_code == 400, bad + + +@pytest.mark.parametrize('db_kind', list(DB_KINDS)) +def test_api_create_database_accepts_four_kinds(app, client, admin_headers, db_kind): + """POST database + 四库之一 → 201,序列化含 db_kind。""" + response = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={ + 'code': f'DB-OK-{db_kind}', 'name': f'{db_kind} client', + 'connector_type': 'database', 'environment': 'dev', + 'endpoint': 'host:5432/app', 'db_kind': db_kind, + }) + assert response.status_code == 201 + data = response.get_json()['data'] + assert data['connector_type'] == 'database' + assert data['db_kind'] == db_kind + + +def test_api_non_database_forces_db_kind_null(app, client, admin_headers): + """rest/soap 创建时即使传 db_kind 也强制置 NULL(不进库、不回显有效值)。""" + created = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={ + 'code': 'REST-FORCE-NULL', 'name': 'rest', 'connector_type': 'rest', + 'endpoint': 'https://api.invalid', 'db_kind': 'oracle', + }) + assert created.status_code == 201 + assert created.get_json()['data']['db_kind'] is None + + row = IntegrationClientInstance.query.filter_by(code='REST-FORCE-NULL').one() + assert row.db_kind is None + + +def test_api_update_database_requires_valid_db_kind(app, client, admin_headers): + """PUT 切到 database 缺/非法 db_kind → 400;合法则落库。""" + client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={ + 'code': 'CLI-UPD', 'name': 'upd', 'connector_type': 'rest', + 'endpoint': 'https://api.invalid', + }) + missing = client.put(f'{API_PREFIX}/client-instances/CLI-UPD', headers=admin_headers, json={ + 'connector_type': 'database', 'endpoint': 'host:1521/ORCL', + }) + assert missing.status_code == 400 + + bad = client.put(f'{API_PREFIX}/client-instances/CLI-UPD', headers=admin_headers, json={ + 'connector_type': 'database', 'endpoint': 'host:1521/ORCL', 'db_kind': 'mssql', + }) + assert bad.status_code == 400 + + ok = client.put(f'{API_PREFIX}/client-instances/CLI-UPD', headers=admin_headers, json={ + 'connector_type': 'database', 'endpoint': 'host:1521/ORCL', 'db_kind': 'oracle', + }) + assert ok.status_code == 200 + assert ok.get_json()['data']['db_kind'] == 'oracle' + + +def test_api_update_away_from_database_clears_db_kind(app, client, admin_headers): + """从 database 改回 rest 时强制清空 db_kind。""" + client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={ + 'code': 'CLI-CLR', 'name': 'clr', 'connector_type': 'database', + 'endpoint': 'host:3306/db', 'db_kind': 'mysql', + }) + updated = client.put(f'{API_PREFIX}/client-instances/CLI-CLR', headers=admin_headers, json={ + 'connector_type': 'rest', 'endpoint': 'https://api.invalid', + }) + assert updated.status_code == 200 + assert updated.get_json()['data']['db_kind'] is None + + +def test_migration_chains_after_current_head(): + """迁移 revision=tt7a8b9c0d1e,down_revision 指向 flask db heads 当前 head。""" + migration = _load_migration() + assert migration.revision == 'tt7a8b9c0d1e' + assert migration.down_revision == 'rn1a2b3c4d5e6' + + +def test_migration_rebuilds_checks_and_adds_db_kind_contract(): + """迁移源码契约:两表 CHECK 含 database、加 db_kind;SQLite 验证列往返。 + + 生产目标为 PostgreSQL(drop/create CHECK);SQLite 不支持 DROP CHECK, + 故不对整段 upgrade 做内存库执行,仅断言源码步骤 + 加列/删列往返。 + """ + migration = _load_migration() + source = (VERSIONS_DIR / MIGRATION_FILE).read_text(encoding='utf-8') + assert "connector_type IN ('rest', 'soap', 'database')" in source + assert "connector_type IN ('rest', 'soap')" in source + assert 'ck_integration_client_instances_connector_type' in source + assert 'ck_integration_interface_definitions_connector_type' in source + assert 'op.add_column' in source and 'db_kind' in source + assert 'op.drop_constraint' in source and 'op.create_check_constraint' in source + assert callable(migration.upgrade) and callable(migration.downgrade) + + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + connection.execute(sa.text( + 'CREATE TABLE integration_client_instances (' + 'id INTEGER PRIMARY KEY, code VARCHAR(64) NOT NULL)' + )) + context = MigrationContext.configure(connection) + operations = Operations(context) + operations.add_column( + 'integration_client_instances', + sa.Column('db_kind', sa.String(length=32), nullable=True), + ) + cols = {c['name'] for c in sa.inspect(connection).get_columns('integration_client_instances')} + assert 'db_kind' in cols + operations.drop_column('integration_client_instances', 'db_kind') + cols_after = {c['name'] for c in sa.inspect(connection).get_columns('integration_client_instances')} + assert 'db_kind' not in cols_after diff --git a/backend/tests/services/integration_connector/test_database_transport.py b/backend/tests/services/integration_connector/test_database_transport.py new file mode 100644 index 00000000..2adbb132 --- /dev/null +++ b/backend/tests/services/integration_connector/test_database_transport.py @@ -0,0 +1,834 @@ +"""tests/services/integration_connector/test_database_transport.py + +用途:Task 2——DatabaseTransport 四库驱动注册表、execute/query/probe、D17 标识符替换、 + D12 业务无关回归锁;并覆盖 merge_client_config 拼入 db_kind。 +依赖:transports.database、transports.base、errors、unittest.mock / monkeypatch。 +逻辑:连接工厂一律替身(monkeypatch `_DRIVERS` 或底层驱动 connect);断言执行顺序、 + 事务 commit/不 commit、脱敏、endpoint 拆解、标识符 fail-closed 与源码无业务词; + StrictFakeCursor 断言 bind 键 ⊆ SQL 占位符(标识符键须剔除)。 +""" + +from __future__ import annotations + +import inspect +import re +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from app.services.integration_connector.errors import InputInvalidError, TransportNotFrozenError +from app.services.integration_connector.transports import database as database_mod +from app.services.integration_connector.transports.base import merge_client_config +from app.services.integration_connector.transports.database import DatabaseTransport, _DRIVERS + +# 与驱动 :name 风格一致,用于严格游标校验 bind 键 ⊆ SQL 占位符 +_BIND_PLACEHOLDER_RE = re.compile(r':([A-Za-z_][A-Za-z0-9_]*)') + + +# --------------------------------------------------------------------------- +# 连接/游标替身 +# --------------------------------------------------------------------------- + + +class FakeCursor: + """记录 execute/executemany,供断言 SQL 顺序与参数合并。""" + + def __init__(self, rows: list[tuple] | None = None, description: list | None = None): + self.calls: list[tuple[str, Any, Any]] = [] + self._rows = list(rows or []) + self.description = description + self.closed = False + + def execute(self, sql, params=None): + self.calls.append(('execute', sql, params)) + + def executemany(self, sql, seq_of_params): + self.calls.append(('executemany', sql, list(seq_of_params))) + + def fetchall(self): + return list(self._rows) + + def close(self): + self.closed = True + + +class StrictFakeCursor(FakeCursor): + """严格游标:断言每次 bind dict 的键 ⊆ SQL 中 `:name` 占位符(模拟 oracledb)。""" + + @staticmethod + def _assert_bind_keys_subset(sql: str, params: dict | None) -> None: + """校验 params 键均出现在 SQL `:bind` 中,禁止残留 `schema` 等标识符键。""" + if params is None: + return + allowed = set(_BIND_PLACEHOLDER_RE.findall(sql)) + extras = set(params) - allowed + assert not extras, ( + f'extra bind keys {sorted(extras)!r} not in SQL placeholders ' + f'{sorted(allowed)!r}; sql={sql!r}' + ) + + def execute(self, sql, params=None): + self._assert_bind_keys_subset(sql, params if isinstance(params, dict) else None) + super().execute(sql, params) + + def executemany(self, sql, seq_of_params): + for row in list(seq_of_params or []): + if isinstance(row, dict): + self._assert_bind_keys_subset(sql, row) + super().executemany(sql, seq_of_params) + + +class FakeConn: + """单事务替身:记录 commit/rollback/close。""" + + def __init__(self, cursor: FakeCursor | None = None): + self._cursor = cursor or FakeCursor() + self.committed = False + self.rolled_back = False + self.closed = False + + def cursor(self): + return self._cursor + + def commit(self): + self.committed = True + + def rollback(self): + self.rolled_back = True + + def close(self): + self.closed = True + + +def _client( + *, + endpoint: str = 'db.invalid:3306/appdb', + db_kind: str = 'mysql', + username: str = 'u1', + password: str = 'secret-pass', + extra_config: dict | None = None, +) -> dict: + """构造已拼回 config 的客户端 payload(模拟 merge_client_config 之后)。""" + cfg = {'endpoint': endpoint, 'db_kind': db_kind, 'timeout_seconds': 30} + if extra_config: + cfg.update(extra_config) + return {'config_json': cfg, 'credential': {'username': username, 'password': password}} + + +def _iface_execute(**sql_overrides) -> dict: + """执行型 request_spec:pre → bulk → post。""" + sql = { + 'mode': 'execute', + 'pre': ['DELETE FROM t WHERE batch=:batch'], + 'bulk': {'sql': 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)', 'rows_param': 'lines'}, + 'post': ['UPDATE t SET done=1 WHERE batch=:batch'], + 'identifiers': [], + } + sql.update(sql_overrides) + return {'request_spec_json': {'sql': sql}} + + +def _iface_query(sql: str = 'SELECT sku AS sku, qty AS qty FROM t', identifiers=None) -> dict: + """查询型 request_spec。""" + node = {'mode': 'query', 'sql': sql} + if identifiers is not None: + node['identifiers'] = identifiers + return {'request_spec_json': {'sql': node}} + + +def _patch_driver(monkeypatch, db_kind: str, connect_fn, probe_sql: str | None = None): + """用替身 connect 覆盖指定库的 DriverSpec,保留/覆盖 probe_sql。""" + original = _DRIVERS[db_kind] + spec = database_mod.DriverSpec( + connect=connect_fn, + probe_sql=probe_sql if probe_sql is not None else original.probe_sql, + ) + monkeypatch.setitem(database_mod._DRIVERS, db_kind, spec) + return spec + + +# --------------------------------------------------------------------------- +# ① execute:pre→bulk→post + commit + bulk 行合并基础参数 +# --------------------------------------------------------------------------- + + +def test_execute_pre_bulk_post_commit_and_merge_base_params(monkeypatch): + """execute 按 pre→bulk→post 顺序执行,bulk 行与基础参数合并(行内覆盖),最终 commit。""" + conn = FakeConn() + + def fake_connect(**kwargs): + return conn + + _patch_driver(monkeypatch, 'mysql', fake_connect) + transport = DatabaseTransport() + result = transport.call( + client=_client(db_kind='mysql'), + interface=_iface_execute(), + request={ + 'params': { + 'batch': 'B1', + 'lines': [ + {'sku': 'S1'}, + {'sku': 'S2', 'batch': 'OVERRIDE'}, + ], + }, + }, + ) + + assert result['status'] == 'success' + assert conn.committed is True + assert conn.rolled_back is False + assert conn.closed is True + + calls = conn._cursor.calls + assert len(calls) == 3 + assert calls[0][0] == 'execute' + assert 'DELETE FROM t' in calls[0][1] + assert calls[0][2] == {'batch': 'B1'} + + assert calls[1][0] == 'executemany' + assert 'INSERT INTO t' in calls[1][1] + # 行与基础参数合并;第二行 batch 被行内覆盖 + assert calls[1][2] == [ + {'batch': 'B1', 'sku': 'S1'}, + {'batch': 'OVERRIDE', 'sku': 'S2'}, + ] + + assert calls[2][0] == 'execute' + assert 'UPDATE t SET done=1' in calls[2][1] + assert calls[2][2] == {'batch': 'B1'} + + +# --------------------------------------------------------------------------- +# ② query:返回行 dict 且不 commit +# --------------------------------------------------------------------------- + + +def test_query_returns_row_dicts_without_commit(monkeypatch): + """query 将列别名映射为 dict 键,成功返回 rows,且不 commit。""" + cursor = FakeCursor( + rows=[('S1', 10), ('S2', 20)], + description=[('sku',), ('qty',)], + ) + conn = FakeConn(cursor) + + _patch_driver(monkeypatch, 'postgresql', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(endpoint='pg.invalid:5432/inv', db_kind='postgresql'), + interface=_iface_query('SELECT sku AS sku, qty AS qty FROM stock WHERE wh=:wh'), + request={'params': {'wh': 'HUB'}}, + ) + + # `_wire` 为 Task 2 起新增的保留键(线级事实,供引擎剥离落库), + # 全等断言排除该键,其余键保持全等。 + assert {k: v for k, v in result.items() if k != '_wire'} == { + 'status': 'success', + 'rows': [{'sku': 'S1', 'qty': 10}, {'sku': 'S2', 'qty': 20}], + } + assert conn.committed is False + assert conn.closed is True + assert cursor.calls[0][0] == 'execute' + assert cursor.calls[0][2] == {'wh': 'HUB'} + + +# --------------------------------------------------------------------------- +# ③ DB 异常 → technical_failed + 凭据脱敏 +# --------------------------------------------------------------------------- + + +def test_db_exception_maps_to_technical_failed_and_masks_secret(monkeypatch): + """驱动抛错时返回 technical_failed,message 中密码替换为 ***,并 rollback。""" + + class BoomConn(FakeConn): + def cursor(self): + raise RuntimeError('login failed for secret-pass at host') + + conn = BoomConn() + _patch_driver(monkeypatch, 'mysql', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(password='secret-pass'), + interface=_iface_execute(), + request={'params': {'batch': 'B1', 'lines': []}}, + ) + + assert result['status'] == 'technical_failed' + assert 'secret-pass' not in result['message'] + assert '***' in result['message'] + assert conn.rolled_back is True + assert conn.closed is True + + +# --------------------------------------------------------------------------- +# ④ probe:oracle FROM DUAL / 其余 SELECT 1 +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + 'db_kind,endpoint,expected_probe', + [ + ('oracle', 'ora.invalid:1521/ORCL', 'SELECT 1 FROM DUAL'), + ('mysql', 'my.invalid:3306/db', 'SELECT 1'), + ('postgresql', 'pg.invalid:5432/db', 'SELECT 1'), + ('sqlserver', 'ms.invalid:1433/db', 'SELECT 1'), + ], +) +def test_probe_uses_driver_sql(monkeypatch, db_kind, endpoint, expected_probe): + """probe 按库种执行注册表 probe_sql,成功返回 ok。""" + cursor = FakeCursor() + conn = FakeConn(cursor) + # 用真实注册表的 probe_sql,只替换 connect + _patch_driver(monkeypatch, db_kind, lambda **kw: conn) + + transport = DatabaseTransport() + result = transport.probe(client=_client(endpoint=endpoint, db_kind=db_kind)) + + assert result['ok'] is True + assert cursor.calls[0][0] == 'execute' + assert cursor.calls[0][1] == expected_probe + assert conn.closed is True + # probe 不做业务写入,不应依赖 commit + assert _DRIVERS[db_kind].probe_sql == expected_probe + + +# --------------------------------------------------------------------------- +# ⑤ 缺 endpoint / 未知 db_kind → fail-closed +# --------------------------------------------------------------------------- + + +def test_fail_closed_missing_endpoint(): + """缺 endpoint 时 fail-closed 抛 TransportNotFrozenError。""" + transport = DatabaseTransport() + with pytest.raises(TransportNotFrozenError): + transport.call( + client={'config_json': {'db_kind': 'mysql'}, 'credential': {}}, + interface=_iface_query(), + request={'params': {}}, + ) + + +def test_fail_closed_unknown_db_kind(): + """未知 db_kind(含历史别名 mssql)fail-closed。""" + transport = DatabaseTransport() + with pytest.raises(TransportNotFrozenError): + transport.call( + client=_client(db_kind='mssql'), + interface=_iface_query(), + request={'params': {}}, + ) + with pytest.raises(TransportNotFrozenError): + transport.call( + client=_client(db_kind='sqlite'), + interface=_iface_query(), + request={'params': {}}, + ) + + +def test_fail_closed_missing_db_kind(): + """缺 db_kind 时 fail-closed。""" + transport = DatabaseTransport() + with pytest.raises(TransportNotFrozenError): + transport.call( + client={'config_json': {'endpoint': 'h:1/db'}, 'credential': {}}, + interface=_iface_query(), + request={'params': {}}, + ) + + +# --------------------------------------------------------------------------- +# ⑥ 四库 connect 工厂收到正确拆解的驱动参数 +# --------------------------------------------------------------------------- + + +def test_connect_factories_receive_parsed_endpoint_params(monkeypatch): + """四库真实 connect 工厂:endpoint 拆为 host/port/database,凭据传入对应驱动关键字。""" + import sys + + captured: dict[str, dict] = {} + + def _install(mod_name: str, kind: str): + fake = MagicMock() + + def _connect(**kw): + captured[kind] = kw + return FakeConn() + + fake.connect.side_effect = _connect + monkeypatch.setitem(sys.modules, mod_name, fake) + return fake + + _install('oracledb', 'oracle') + _install('pymysql', 'mysql') + _install('psycopg2', 'postgresql') + _install('pymssql', 'sqlserver') + + cred = {'username': 'alice', 'password': 'pw'} + _DRIVERS['oracle'].connect(config={'endpoint': 'ora.host:1521/ORCLPDB'}, credential=cred) + assert captured['oracle']['user'] == 'alice' + assert captured['oracle']['password'] == 'pw' + assert captured['oracle']['dsn'] == 'ora.host:1521/ORCLPDB' + + _DRIVERS['mysql'].connect(config={'endpoint': 'my.host:3306/appdb'}, credential=cred) + assert captured['mysql']['host'] == 'my.host' + assert captured['mysql']['port'] == 3306 + assert captured['mysql']['database'] == 'appdb' + assert captured['mysql']['user'] == 'alice' + assert captured['mysql']['password'] == 'pw' + assert captured['mysql']['charset'] == 'utf8mb4' + + _DRIVERS['postgresql'].connect(config={'endpoint': 'pg.host:5432/inv'}, credential=cred) + assert captured['postgresql']['host'] == 'pg.host' + assert captured['postgresql']['port'] == 5432 + assert captured['postgresql']['dbname'] == 'inv' + assert captured['postgresql']['user'] == 'alice' + + _DRIVERS['sqlserver'].connect(config={'endpoint': 'ms.host:1433/erp'}, credential=cred) + assert captured['sqlserver']['server'] == 'ms.host' + assert captured['sqlserver']['port'] == 1433 + assert captured['sqlserver']['database'] == 'erp' + assert captured['sqlserver']['user'] == 'alice' + + # 注册表键必须是 sqlserver(D16),不是 mssql + assert 'sqlserver' in _DRIVERS + assert 'mssql' not in _DRIVERS + + +# --------------------------------------------------------------------------- +# ⑦ schema 标识符替换进表名 +# --------------------------------------------------------------------------- + + +def test_identifier_schema_substituted_into_sql(monkeypatch): + """白名单 identifiers 将 {schema} 替换为安全标识符值后再执行。""" + conn = FakeConn() + _patch_driver(monkeypatch, 'oracle', lambda **kw: conn) + transport = DatabaseTransport() + transport.call( + client=_client(endpoint='ora:1521/X', db_kind='oracle'), + interface=_iface_execute( + pre=['DELETE FROM {schema}.stage WHERE id=:id'], + bulk={'sql': 'INSERT INTO {schema}.stage (id) VALUES (:id)', 'rows_param': 'lines'}, + post=[], + identifiers=['schema'], + ), + request={'params': {'schema': 'HTT01', 'id': 1, 'lines': [{'id': 1}]}}, + ) + + pre_sql = conn._cursor.calls[0][1] + bulk_sql = conn._cursor.calls[1][1] + assert '{schema}' not in pre_sql + assert 'HTT01.stage' in pre_sql + assert 'HTT01.stage' in bulk_sql + + +def test_identifier_keys_stripped_from_bind_params(monkeypatch): + """标识符替换后 bind dict 不得残留 schema 等键(StrictFakeCursor 模拟 oracledb)。 + + 断言:每次 execute/executemany 的 bind 键 ⊆ SQL `:name` 占位符;无 leftover `schema`。 + """ + cursor = StrictFakeCursor() + conn = FakeConn(cursor) + _patch_driver(monkeypatch, 'oracle', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(endpoint='ora:1521/X', db_kind='oracle'), + interface=_iface_execute( + pre=['DELETE FROM {schema}.stage WHERE id=:id'], + bulk={ + 'sql': 'INSERT INTO {schema}.stage (id, sku) VALUES (:id, :sku)', + 'rows_param': 'lines', + }, + post=['UPDATE {schema}.stage SET done=1 WHERE id=:id'], + identifiers=['schema'], + ), + request={ + 'params': { + 'schema': 'HTT01', + 'id': 1, + 'lines': [{'sku': 'S1'}, {'sku': 'S2', 'schema': 'SHOULD_STRIP'}], + }, + }, + ) + + assert result['status'] == 'success' + # StrictFakeCursor 已在调用时断言 keys ⊆ placeholders;再显式确认无 schema 残留 + pre_params = cursor.calls[0][2] + bulk_rows = cursor.calls[1][2] + post_params = cursor.calls[2][2] + assert 'schema' not in pre_params + assert pre_params == {'id': 1} + assert all('schema' not in row for row in bulk_rows) + assert bulk_rows == [{'id': 1, 'sku': 'S1'}, {'id': 1, 'sku': 'S2'}] + assert 'schema' not in post_params + assert post_params == {'id': 1} + + +# --------------------------------------------------------------------------- +# ⑧ 非法标识符 / 未声明 {xxx} → fail-closed +# --------------------------------------------------------------------------- + + +def test_illegal_identifier_value_fail_closed(monkeypatch): + """标识符含引号/空格等非法字符 → InputInvalidError。""" + conn = FakeConn() + _patch_driver(monkeypatch, 'mysql', lambda **kw: conn) + transport = DatabaseTransport() + with pytest.raises(InputInvalidError): + transport.call( + client=_client(), + interface=_iface_query( + 'SELECT 1 FROM {schema}.t', + identifiers=['schema'], + ), + request={'params': {'schema': 'bad schema'}}, + ) + with pytest.raises(InputInvalidError): + transport.call( + client=_client(), + interface=_iface_query( + 'SELECT 1 FROM {schema}.t', + identifiers=['schema'], + ), + request={'params': {'schema': 'x"; DROP'}}, + ) + + +def test_undeclared_placeholder_fail_closed(monkeypatch): + """语句出现未在 identifiers 白名单声明的 {xxx} → InputInvalidError。""" + conn = FakeConn() + _patch_driver(monkeypatch, 'mysql', lambda **kw: conn) + transport = DatabaseTransport() + with pytest.raises(InputInvalidError): + transport.call( + client=_client(), + interface=_iface_query('SELECT 1 FROM {schema}.t', identifiers=[]), + request={'params': {'schema': 'HTT'}}, + ) + + +# --------------------------------------------------------------------------- +# ⑨ D12 业务无关回归锁 +# --------------------------------------------------------------------------- + + +def test_database_transport_has_no_business_sql_literals(): + """inspect.getsource 断言 database.py 无 gls_cm / 调拨 / C0089(D12 代码级锁)。""" + source = inspect.getsource(database_mod) + for forbidden in ('gls_cm', '调拨', 'C0089'): + assert forbidden not in source, f'D12 violation: found {forbidden!r} in database.py' + + +# --------------------------------------------------------------------------- +# merge_client_config 拼入 db_kind(Task 1 延期项) +# --------------------------------------------------------------------------- + + +def test_merge_client_config_includes_db_kind(): + """merge_client_config 将专列 db_kind 拼入 config,与 endpoint/timeout 同模式。""" + merged = merge_client_config({ + 'config_json': {'headers': {'X': '1'}}, + 'endpoint': 'h:1521/ORCL', + 'timeout_seconds': 45, + 'db_kind': 'oracle', + }) + assert merged['endpoint'] == 'h:1521/ORCL' + assert merged['timeout_seconds'] == 45 + assert merged['db_kind'] == 'oracle' + assert merged['headers'] == {'X': '1'} + + +def test_gateway_registers_database_transport(): + """CapabilityGateway 默认装配含 database → DatabaseTransport。""" + from app.services.integration_connector.gateway import get_capability_gateway + from app.services.integration_connector.gateway import set_capability_gateway + + set_capability_gateway(None) + gw = get_capability_gateway() + assert 'database' in gw.transports + assert isinstance(gw.transports['database'], DatabaseTransport) + assert gw.transports['database'].connector_type == 'database' + + +def test_drivers_registry_keys_match_d16(): + """_DRIVERS 键 = D16 四库:mysql/oracle/sqlserver/postgresql。""" + assert set(_DRIVERS.keys()) == {'mysql', 'oracle', 'sqlserver', 'postgresql'} + assert _DRIVERS['oracle'].probe_sql == 'SELECT 1 FROM DUAL' + for kind in ('mysql', 'postgresql', 'sqlserver'): + assert _DRIVERS[kind].probe_sql == 'SELECT 1' + + +# --------------------------------------------------------------------------- +# P2-1 四库 connect 工厂消费 timeout_seconds(T1-T3 评审遗留) +# --------------------------------------------------------------------------- + + +def _capture_driver_connects(monkeypatch) -> dict[str, dict]: + """伪造四个驱动模块并捕获各库 connect 工厂收到的关键字参数。""" + import sys + + captured: dict[str, dict] = {} + + def _install(mod_name: str, kind: str): + fake = MagicMock() + + def _connect(**kw): + captured[kind] = kw + return FakeConn() + + fake.connect.side_effect = _connect + monkeypatch.setitem(sys.modules, mod_name, fake) + + _install('oracledb', 'oracle') + _install('pymysql', 'mysql') + _install('psycopg2', 'postgresql') + _install('pymssql', 'sqlserver') + return captured + + +def test_connect_factories_receive_timeout_params(monkeypatch): + """timeout_seconds=30 → 四库工厂收到各自驱动的超时参数(单位秒)。 + + 断言意图:pymysql=connect/read/write 三参、pymssql=login/timeout 两参、 + psycopg2=connect_timeout、oracledb=tcp_connect_timeout 且建连后设 call_timeout(毫秒)。 + """ + captured = _capture_driver_connects(monkeypatch) + cred = {'username': 'u', 'password': 'p'} + cfg = {'timeout_seconds': 30} + + conn_oracle = _DRIVERS['oracle'].connect(config={'endpoint': 'ora:1521/X', **cfg}, credential=cred) + assert captured['oracle']['tcp_connect_timeout'] == 30 + # 断言意图:call_timeout(毫秒,单次 round-trip 超时)在建连后按连接属性设置 + assert conn_oracle.call_timeout == 30000 + + _DRIVERS['mysql'].connect(config={'endpoint': 'my:3306/db', **cfg}, credential=cred) + assert captured['mysql']['connect_timeout'] == 30 + assert captured['mysql']['read_timeout'] == 30 + assert captured['mysql']['write_timeout'] == 30 + + _DRIVERS['postgresql'].connect(config={'endpoint': 'pg:5432/db', **cfg}, credential=cred) + assert captured['postgresql']['connect_timeout'] == 30 + + _DRIVERS['sqlserver'].connect(config={'endpoint': 'ms:1433/db', **cfg}, credential=cred) + assert captured['sqlserver']['login_timeout'] == 30 + assert captured['sqlserver']['timeout'] == 30 + + +def test_connect_factories_without_timeout_use_driver_defaults(monkeypatch): + """timeout_seconds 缺失/非法 → 工厂不传任何超时参数(用驱动默认,不报错)。""" + captured = _capture_driver_connects(monkeypatch) + cred = {'username': 'u', 'password': 'p'} + + _DRIVERS['oracle'].connect(config={'endpoint': 'ora:1521/X'}, credential=cred) + _DRIVERS['mysql'].connect(config={'endpoint': 'my:3306/db', 'timeout_seconds': 'abc'}, credential=cred) + _DRIVERS['postgresql'].connect(config={'endpoint': 'pg:5432/db'}, credential=cred) + _DRIVERS['sqlserver'].connect(config={'endpoint': 'ms:1433/db'}, credential=cred) + + # 断言意图:无超时配置时键必须整体缺席(而非传 None 破坏驱动默认值) + assert 'tcp_connect_timeout' not in captured['oracle'] + assert 'connect_timeout' not in captured['mysql'] + assert 'read_timeout' not in captured['mysql'] + assert 'connect_timeout' not in captured['postgresql'] + assert 'login_timeout' not in captured['sqlserver'] + assert 'timeout' not in captured['sqlserver'] + + +# --------------------------------------------------------------------------- +# P2-2 标识符替换后残留占位符 → fail-closed(T1-T3 评审遗留) +# --------------------------------------------------------------------------- + + +def test_malformed_placeholder_with_dot_fail_closed(monkeypatch): + """畸形占位符 {schema.}(不匹配白名单替换正则)替换后残留 → InputInvalidError,禁止静默直通。""" + conn = FakeConn() + _patch_driver(monkeypatch, 'mysql', lambda **kw: conn) + transport = DatabaseTransport() + with pytest.raises(InputInvalidError): + transport.call( + client=_client(), + interface=_iface_query('SELECT 1 FROM {schema.}t', identifiers=['schema']), + request={'params': {'schema': 'HTT'}}, + ) + + +def test_malformed_placeholder_starts_with_digit_fail_closed(monkeypatch): + """畸形占位符 {1abc}(数字开头不匹配白名单正则)替换后残留 → InputInvalidError。""" + conn = FakeConn() + _patch_driver(monkeypatch, 'mysql', lambda **kw: conn) + transport = DatabaseTransport() + with pytest.raises(InputInvalidError): + transport.call( + client=_client(), + interface=_iface_query('SELECT 1 FROM {1abc}.t', identifiers=['schema']), + request={'params': {'schema': 'HTT'}}, + ) + + +# --------------------------------------------------------------------------- +# ⑨ 逐语句绑定过滤:pre/bulk/post/query 只传各语句实际引用的 :bind +# (回归:oracledb 不容多余 bind 键,生产 submit-stage-table 的 pre 仅引用 +# :submit_timestamp,全量 base 直传触发 ORA-01036 unrecognized bind doc_no) +# --------------------------------------------------------------------------- + + +def test_pre_statement_filters_unused_binds(monkeypatch): + """pre 语句只引用 :submit_timestamp 时,多余的 doc_no 等键不得传入驱动(StrictFakeCursor 模拟 oracledb)。""" + cursor = StrictFakeCursor() + conn = FakeConn(cursor) + _patch_driver(monkeypatch, 'oracle', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(endpoint='ora:1521/X', db_kind='oracle'), + interface=_iface_execute( + pre=["DELETE FROM t WHERE ts=:submit_timestamp AND flag='10'"], + bulk={ + 'sql': 'INSERT INTO t (ts, doc) VALUES (:submit_timestamp, :doc_no)', + 'rows_param': 'lines', + }, + post=[], + identifiers=[], + ), + request={ + 'params': { + 'doc_no': 'D1', + 'doc_date': '2026-09-26', + 'external_org': 'TGHX1', + 'posting_date': '2026-09-26', + 'maker_account': 'admin', + 'submit_timestamp': 'TS1', + 'lines': [{'doc_no': 'D1'}], + }, + }, + ) + + # 关键断言:StrictFakeCursor 已断言键 ⊆ 占位符(旧实现此处即抛 ORA-01036 同款失败) + assert result['status'] == 'success' + pre_params = cursor.calls[0][2] + assert pre_params == {'submit_timestamp': 'TS1'} + bulk_rows = cursor.calls[1][2] + assert bulk_rows == [{'submit_timestamp': 'TS1', 'doc_no': 'D1'}] + + +def test_bulk_row_extra_keys_filtered(monkeypatch): + """行键含 bulk SQL 未引用的 invoice_no 时不得传入 executemany(生产已潜伏的第二个多余键)。""" + cursor = StrictFakeCursor() + conn = FakeConn(cursor) + _patch_driver(monkeypatch, 'oracle', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(endpoint='ora:1521/X', db_kind='oracle'), + interface=_iface_execute( + pre=[], + bulk={ + 'sql': 'INSERT INTO t (doc, sku) VALUES (:doc_no, :sku)', + 'rows_param': 'lines', + }, + post=[], + identifiers=[], + ), + request={ + 'params': { + 'doc_no': 'D1', + 'lines': [{'sku': 'S1', 'invoice_no': 'INV1'}], + }, + }, + ) + + assert result['status'] == 'success' + assert cursor.calls[0][2] == [{'doc_no': 'D1', 'sku': 'S1'}] + + +def test_bind_extraction_ignores_colons_in_literals_and_comments(monkeypatch): + """字符串字面量与注释中的 ':name' 不算占位符:语句未真实引用的键必须被过滤。""" + cursor = StrictFakeCursor() + conn = FakeConn(cursor) + _patch_driver(monkeypatch, 'oracle', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(endpoint='ora:1521/X', db_kind='oracle'), + interface=_iface_execute( + pre=[ + # 字面量含 :doc_no、行注释含 :doc_no,均非真实绑定 + "DELETE FROM t WHERE ts=:submit_timestamp -- :doc_no\nAND url='http://x/:doc_no'", + ], + bulk={'sql': 'INSERT INTO t (ts) VALUES (:submit_timestamp)', 'rows_param': 'lines'}, + post=[], + identifiers=[], + ), + request={ + 'params': { + 'doc_no': 'D1', + 'submit_timestamp': 'TS1', + 'lines': [], + }, + }, + ) + + assert result['status'] == 'success' + assert cursor.calls[0][2] == {'submit_timestamp': 'TS1'} + + +def test_query_filters_unused_binds(monkeypatch): + """query 同口径:SQL 未引用的参数键不得传入 execute。""" + cursor = StrictFakeCursor() + conn = FakeConn(cursor) + _patch_driver(monkeypatch, 'postgresql', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(endpoint='pg.invalid:5432/inv', db_kind='postgresql'), + interface=_iface_query('SELECT sku AS sku FROM t WHERE wh=:wh'), + request={'params': {'wh': 'HUB', 'unused_key': 'X'}}, + ) + + assert result['status'] == 'success' + assert cursor.calls[0][2] == {'wh': 'HUB'} + + +# --------------------------------------------------------------------------- +# Task 2 wire 捕获:execute/query 返回 dict 附带保留键 `_wire`(线级事实, +# 供调用日志引擎(Task 4)剥离落库 IntegrationCall.wire_json) +# --------------------------------------------------------------------------- + + +def test_execute_attaches_wire_with_final_sql_and_binds(monkeypatch): + """execute 返回的 _wire 必须带标识符替换后的最终 SQL、逐语句绑定与行数。""" + conn = FakeConn() + _patch_driver(monkeypatch, 'mysql', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(), + interface=_iface_execute( + pre=['DELETE FROM t WHERE batch=:batch'], + bulk={'sql': 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)', 'rows_param': 'lines'}, + post=[], + ), + request={'params': {'batch': 'B1', 'lines': [{'sku': 'S1'}]}}, + ) + wire = result['_wire'] + # 关键断言:kind 固定 database、语句相位按 pre→bulk 顺序、SQL 为标识符替换后 + # 的最终文本、binds 为逐语句过滤后的实际绑定、顶层 rowcount 为各语句之和 + assert wire['kind'] == 'database' + assert [s['phase'] for s in wire['statements']] == ['pre', 'bulk'] + assert wire['statements'][0]['sql'] == 'DELETE FROM t WHERE batch=:batch' + assert wire['statements'][0]['binds'] == {'batch': 'B1'} + assert wire['statements'][1]['sql'] == 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)' + assert wire['statements'][1]['binds'] == {'batch': 'B1', 'sku': 'S1'} + assert 'rowcount' in wire + + +def test_query_attaches_wire_with_sql_and_rows(monkeypatch): + """query 返回的 _wire 记录最终 SQL、实际绑定与行快照(与返回 rows 同源)。""" + cursor = FakeCursor(rows=[('S1', 10)], description=[('sku',), ('qty',)]) + conn = FakeConn(cursor) + _patch_driver(monkeypatch, 'postgresql', lambda **kw: conn) + transport = DatabaseTransport() + result = transport.call( + client=_client(endpoint='pg.invalid:5432/inv', db_kind='postgresql'), + interface=_iface_query('SELECT sku AS sku, qty AS qty FROM t WHERE wh=:wh'), + request={'params': {'wh': 'HUB'}}, + ) + # 关键断言:query 相位单语句、SQL 为替换后最终文本、rows 与返回值同源 + assert result['_wire']['kind'] == 'database' + assert result['_wire']['statements'][0]['sql'] == 'SELECT sku AS sku, qty AS qty FROM t WHERE wh=:wh' + assert result['_wire']['rows'] == [{'sku': 'S1', 'qty': 10}] diff --git a/backend/tests/services/integration_connector/test_engine.py b/backend/tests/services/integration_connector/test_engine.py index ae6c8a7c..78301950 100644 --- a/backend/tests/services/integration_connector/test_engine.py +++ b/backend/tests/services/integration_connector/test_engine.py @@ -63,6 +63,8 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc capability=capability, context_selector_json={}, client_instance_code="CLI-A", interface_definition_code="IFACE-Q", mapping_version=2, priority=0, environment="prod", status="published", + steps_json=[{"interface_code": "IFACE-Q", "param_mapping_json": {}}], + param_mapping_json={}, ) db.session.add(binding) db.session.commit() @@ -72,7 +74,25 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc def _params(**overrides): values = { "external_org": "HX-CN01", - "targets": [{"material_no": "M-1", "from_warehouse": "W1", "lot_no": "L-1"}], + "targets": [{"material_no": "M-1", "warehouse_code": "W1", "lot_no": "L-1"}], + } + values.update(overrides) + return values + + +def _order_params(**overrides): + """create_transfer 单据级入参(能力收缩后契约):七必填 = 六域参数 + 制单人。""" + values = { + "external_org": "HX-CN01", + "doc_no": "HX-CN01-OR-26092400001", + "submit_timestamp": "b4f9c2d1a7e307260924101010123", + "doc_date": "2026-09-24", + "posting_date": "2026-09-24", + "maker_account": "15070211", + "lines": [{ + "line_no": 1, "material_no": "M-1", "from_warehouse": "W1", + "to_warehouse": "W2", "lot_no": "L-1", "quantity": 10, "unit": "EA", + }], } values.update(overrides) return values @@ -115,12 +135,12 @@ def test_call_no_binding_raises(app): def test_call_write_business_failed(app): - """写能力按原始 status 分类 → business_failed。""" + """写能力按原始 status 分类 → business_failed(入参为单据级契约)。""" _seed("in_transit_transfer.create_transfer") fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"}) result = CapabilityGateway(transports={"rest": fake}).call( capability="in_transit_transfer.create_transfer", context={}, - params=_params(), operation_id="OP-4", environment="prod", + params=_order_params(), operation_id="OP-4", environment="prod", ) assert result.status == "business_failed" assert result.error_code == "E1" @@ -162,7 +182,7 @@ def test_call_result_unknown_no_auto_retry(app): result = CapabilityGateway(transports={"rest": _OneShot(None)}).call( capability="in_transit_transfer.create_transfer", context={}, - params=_params(), operation_id="OP-7", environment="prod", + params=_order_params(), operation_id="OP-7", environment="prod", ) assert result.status == "result_unknown" assert len(calls) == 1 @@ -190,6 +210,10 @@ def _seed_full_params(*, param_mapping=None, input_schema=None, credential_ref=N param_mapping_json=param_mapping or {}, client_instance_code="CLI-P", interface_definition_code="IFACE-P", mapping_version=1, priority=0, environment="prod", status="published", + steps_json=[{ + "interface_code": "IFACE-P", + "param_mapping_json": param_mapping or {}, + }], ) db.session.add(binding) db.session.commit() @@ -213,7 +237,7 @@ def test_call_applies_binding_param_mapping(app): result = CapabilityGateway(transports={"rest": _Capture(None)}).call( capability="in_transit_transfer.query_inventory", context={}, - params=_params(external_org="TGHX", targets=[{"material_no": "M-9", "from_warehouse": "W1", "lot_no": "L-9"}]), + params=_params(external_org="TGHX", targets=[{"material_no": "M-9", "warehouse_code": "W1", "lot_no": "L-9"}]), operation_id="OP-PM", environment="prod", ) assert captured["params"] == {"organization": "TGHX", "condition": "img04 = 'L-9'"} @@ -272,3 +296,46 @@ def test_call_read_capability_failure_passthrough(app): ) assert result.status == "business_failed" assert result.error_code == "HTTP_500" + + +# ---- 引擎落库 wire_json / business_ref(Task 4:`_wire` 保留键剥离 + 业务锚点透传)---- + +def test_record_call_persists_wire_json(app): + """读能力执行落 IntegrationCall:传输层 `_wire` 剥离落 wire_json,不混入响应摘要。""" + _seed("in_transit_transfer.query_inventory") + fake = FakeTransport({"found": True, "quantity": "100", "_wire": {"kind": "database", "rowcount": 1}}) + result = CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-WIRE", environment="prod", + ) + assert result.status == "success" + call_row = IntegrationCall.query.filter_by(operation_id="OP-WIRE").first() + assert call_row is not None + # `_wire` 剥离后原样落 wire_json(线级事实独立成列)。 + assert call_row.wire_json == {"kind": "database", "rowcount": 1} + # wire 不混入响应摘要。 + assert "_wire" not in (call_row.response_summary_json or {}) + + +def test_call_persists_business_ref(app): + """写能力 business_ref 透传落库(执行服务以 doc_no 为业务锚点);不传时为 NULL。""" + _seed("in_transit_transfer.create_transfer") + fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"}) + gateway = CapabilityGateway(transports={"rest": fake}) + gateway.call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-BR-1", environment="prod", + business_ref="TGHX1-OR-26092600002", + ) + call_row = IntegrationCall.query.filter_by(operation_id="OP-BR-1").first() + assert call_row is not None + # business_ref 透传落库(写能力多步路径经 _execute_step 逐步审计同样携带)。 + assert call_row.business_ref == "TGHX1-OR-26092600002" + # 不传 business_ref:现有消费者零改动,落 NULL。 + gateway.call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-BR-2", environment="prod", + ) + row_without = IntegrationCall.query.filter_by(operation_id="OP-BR-2").first() + assert row_without is not None + assert row_without.business_ref is None diff --git a/backend/tests/services/integration_connector/test_engine_steps.py b/backend/tests/services/integration_connector/test_engine_steps.py new file mode 100644 index 00000000..b5170ec7 --- /dev/null +++ b/backend/tests/services/integration_connector/test_engine_steps.py @@ -0,0 +1,539 @@ +"""tests/services/integration_connector/test_engine_steps.py + +用途:Task 4(R8 修订:末步判定 = response_mapping 映射 + 六态分类,无二次解释层)—— + 写能力多步顺序执行引擎:多步顺序、 + resume 跳过非末步、非末步失败/超时中止(超时中止对外=技术失败、审计保 timeout 真相)、 + 末步映射→classify→data 恒带 mapped 全链、每步审计同 operation_id、读能力回归、 + on_nonfinal_success 步进回调(时序与异常中止)。 +依赖:capability/binding/mapping/transports、engine.CapabilityGateway、 + IntegrationCall 模型、errors。 +逻辑:假 transport(ScriptedTransport 记录调用并可脚本化响应/异常)注入 + CapabilityGateway(transports={...});绑定用 steps_json 两步形态 + (stage=database / submit=soap,TIPTOP C0089 响应形状);审计断言查 IntegrationCall 表。 + 审计契约:每步一条、同裸 operation_id(一单一次执行 = N 条;模型唯一约束已由 + 迁移 tt5b6c7d8e9f 解除并补普通索引),步骤定位靠 binding_snapshot_json.step_index。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app import db +from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.in_transit_transfer.capabilities import register_transfer_capabilities +from app.services.integration_connector.capability import reset_capability_registry_for_tests +from app.services.integration_connector.engine import CapabilityGateway + +# TIPTOP C0089 WS 响应形状(与 Task 15 接口定义同源):status 由 @code enum-map 推导 +# (映射表仅 '0'→success,非 0 业务码原样穿透),code 缺失/为空时映射不产出 status、 +# classify 按原始响应兜底分类;document_no 经 pick 从键值 Field 列表提取。 +_TIPTOP_RESPONSE_MAPPING = { + "status": {"expr": "Response.Execution.Status.@code", "transform": "enum-map", + "args": {"mapping": {"0": "success"}}}, + "code": {"expr": "Response.Execution.Status.@code"}, + "message": {"expr": "Response.Execution.Status.@description"}, + "document_no": {"expr": "Response.ResponseContent.Parameter.Record.Field", + "transform": "pick", + "args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}}, +} +_TIPTOP_OUTPUT_SCHEMA = { + "type": "object", + "properties": { + "status": {"type": "string"}, "code": {"type": "string"}, + "message": {"type": "string"}, "document_no": {"type": "string"}, + }, +} + + +def _tiptop_raw(*, code: str, description: str = "ok", doc_no: str | None = None) -> dict: + """构造归一化后的 SOAP 响应;doc_no=None 模拟 ERP 查不到 30 行的失败形态。""" + content: dict = {"Response": {"Execution": {"Status": {"@code": code, "@description": description}}}} + if doc_no is not None: + content["Response"]["ResponseContent"] = { + "Parameter": {"Record": {"Field": [{"@name": "doc_no", "@value": doc_no}]}}, + } + return content + + +class ScriptedTransport: + """可脚本化响应/异常并记录调用的传输替身(按 connector_type 注入网关)。""" + + def __init__(self, connector_type: str, response=None): + self.connector_type = connector_type + self._response = response + self.calls: list[dict] = [] + + def call(self, *, client, interface, request): + self.calls.append(request) + if isinstance(self._response, Exception): + raise self._response + return self._response + + +@pytest.fixture(autouse=True) +def _transfer_capabilities(): + """每用例前重建在途调拨能力注册:reset 后依赖领域包注册函数重建(write 标志随能力走)。""" + reset_capability_registry_for_tests() + register_transfer_capabilities() + yield + reset_capability_registry_for_tests() + + +def _seed_write_two_steps( + *, + stage_param_mapping=None, + submit_param_mapping=None, +): + """造两客户端 + 两接口 + 有序两步写绑定(create_transfer 形态)。""" + stage_spec = {"sql": {"mode": "execute", "pre": [], "bulk": None, "post": []}} + submit_spec = {"method": "POST", "path": "/submit"} + db.session.add_all([ + IntegrationClientInstance( + code="CLI-STAGE", name="stage", connector_type="database", environment="prod", + config_json={}, endpoint="127.0.0.1:1521/ORCL", db_kind="oracle", + ), + IntegrationClientInstance( + code="CLI-WS", name="ws", connector_type="soap", environment="prod", + config_json={"endpoint": "https://ws.invalid"}, + ), + IntegrationInterfaceDefinition( + code="IFACE-STAGE", name="stage", client_instance_code="CLI-STAGE", + connector_type="database", request_spec_json=stage_spec, + input_schema_json={}, response_mapping_json={}, output_schema_json={}, + version=1, status="published", + ), + IntegrationInterfaceDefinition( + code="IFACE-SUBMIT", name="submit", client_instance_code="CLI-WS", + connector_type="soap", request_spec_json=submit_spec, + input_schema_json={}, response_mapping_json=_TIPTOP_RESPONSE_MAPPING, + output_schema_json=_TIPTOP_OUTPUT_SCHEMA, + version=2, status="published", + ), + IntegrationBinding( + capability="in_transit_transfer.create_transfer", context_selector_json={}, + steps_json=[ + {"interface_code": "IFACE-STAGE", "param_mapping_json": stage_param_mapping or {}}, + {"interface_code": "IFACE-SUBMIT", "param_mapping_json": submit_param_mapping or {}}, + ], + client_instance_code="CLI-STAGE", interface_definition_code="IFACE-STAGE", + param_mapping_json=stage_param_mapping or {}, + mapping_version=1, priority=0, environment="prod", status="published", + ), + ]) + db.session.commit() + + +def _seed_read_single_step(): + """读能力单步绑定(query_inventory 形态),供回归对照。""" + db.session.add_all([ + IntegrationClientInstance( + code="CLI-Q", name="client", connector_type="rest", environment="prod", + config_json={"endpoint": "https://erp.invalid"}, + ), + IntegrationInterfaceDefinition( + code="IFACE-Q", name="iface", client_instance_code="CLI-Q", connector_type="rest", + request_spec_json={"method": "GET", "path": "/stock"}, + input_schema_json={}, + response_mapping_json={"found": {"expr": "found"}, + "quantity": {"expr": "quantity", "transform": "decimal"}}, + output_schema_json={"type": "object", "properties": {"found": {"type": "boolean"}, + "quantity": {"type": "number"}}}, + version=3, status="published", + ), + IntegrationBinding( + capability="in_transit_transfer.query_inventory", context_selector_json={}, + steps_json=[{"interface_code": "IFACE-Q", "param_mapping_json": {}}], + client_instance_code="CLI-Q", interface_definition_code="IFACE-Q", + param_mapping_json={}, mapping_version=2, priority=0, + environment="prod", status="published", + ), + ]) + db.session.commit() + + +def _params(**overrides): + """读能力(query_inventory)入参:external_org + targets(_INVENTORY_QUERY_INPUT_SCHEMA)。""" + values = { + "external_org": "HX-CN01", + "targets": [{"material_no": "M-1", "warehouse_code": "W1", "lot_no": "L-1"}], + } + values.update(overrides) + return values + + +def _order_params(**overrides): + """写能力(create_transfer)单据级入参:对齐 _TICKET_INPUT_SCHEMA 七必填(R9 加制单人)。""" + values = { + "external_org": "HX-CN01", + "doc_no": "HX-CN01-OR-26092300001", + "submit_timestamp": "0f1e2d3c4b5a69788796a5b4c3d2e1f0" + "20260923010101123", + "doc_date": "2026-09-23", + "posting_date": "2026-09-23", + "maker_account": "15070211", + "lines": [{"line_no": 1, "material_no": "M-1", "from_warehouse": "W1", + "to_warehouse": "W2", "lot_no": "L-1", "quantity": 100, "unit": "KG"}], + } + values.update(overrides) + return values + + +def _gateway(stage, submit) -> CapabilityGateway: + return CapabilityGateway(transports={"database": stage, "soap": submit}) + + +# --------------------------------------------------------------------------- +# ① 多步顺序执行:步序 + 各步收到各自 param_mapping 翻译后的参数 +# --------------------------------------------------------------------------- + + +def test_write_multi_step_executes_in_order_with_per_step_param_mapping(app): + """两步按绑定顺序执行;每步 transport 收到该步 param_mapping 翻译后的接口参数(非域参数)。""" + _seed_write_two_steps( + stage_param_mapping={"schema": {"expr": "external_org"}}, + submit_param_mapping={"source_ip": {"template": "0.0.0.0"}}, + ) + stage = ScriptedTransport("database", {"status": "success"}) + submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-2609230007")) + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-MS", environment="prod", + ) + + # 断言意图:步序锁定 stage→submit,各恰好一次;跨步不串参(每步只见自己的翻译结果) + assert len(stage.calls) == 1 + assert len(submit.calls) == 1 + assert stage.calls[0]["params"] == {"schema": "HX-CN01"} + assert submit.calls[0]["params"] == {"source_ip": "0.0.0.0"} + # 断言意图:末步全链产出 success,data 恒带映射结果 + assert result.status == "success" + assert result.document_no == "1401-2609230007" + assert result.data["code"] == "0" + assert result.data["document_no"] == "1401-2609230007" + + +# --------------------------------------------------------------------------- +# ② resume=True 跳过全部非末步(非末步 transport 零调用、不审计) +# --------------------------------------------------------------------------- + + +def test_resume_skips_all_non_final_steps(app): + """resume=True 只执行末步(断点续跑禁重插):stage 零调用、审计仅末步一条。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", {"status": "success"}) + submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1")) + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-RS", environment="prod", resume=True, + ) + + # 断言意图:非末步不建连不执行;末步照常产出结果 + assert stage.calls == [] + assert len(submit.calls) == 1 + assert result.status == "success" + rows = IntegrationCall.query.filter_by(operation_id="OP-RS").order_by(IntegrationCall.id).all() + assert len(rows) == 1 + assert rows[0].binding_snapshot_json["step_index"] == 1 + + +# --------------------------------------------------------------------------- +# ③ 非末步失败 → 中止(后续步零调用),返回该步失败态 +# --------------------------------------------------------------------------- + + +def test_non_final_step_failure_aborts_remaining_steps(app): + """stage 判 technical_failed → 立即中止:submit 零调用,返回 technical_failed,仅 1 条审计。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", {"status": "technical_failed", "code": "DB_ERROR", "message": "boom"}) + submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1")) + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-ABF", environment="prod", + ) + + # 断言意图:非末步失败禁止继续触发 WS(防漏插先提交) + assert result.status == "technical_failed" + assert submit.calls == [] + rows = IntegrationCall.query.filter_by(operation_id="OP-ABF").order_by(IntegrationCall.id).all() + assert len(rows) == 1 + assert rows[0].status == "technical_failed" + assert rows[0].binding_snapshot_json["step_index"] == 0 + + +# --------------------------------------------------------------------------- +# ④ 非末步超时 → 中止(后续步零调用),status=timeout 交上层按中止规则落位 +# --------------------------------------------------------------------------- + + +def test_non_final_step_timeout_aborts_remaining_steps(app): + """stage 抛 TimeoutError → 中止=技术失败:submit 零调用;审计行保 'timeout' 技术真相, + 引擎对外返回 technical_failed(error_code 与末步超时区分,防误入 result_unknown 红线态)。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", TimeoutError()) + submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1")) + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-ABT", environment="prod", + ) + + # 断言意图:非末步超时对外按技术失败落位(恢复路径=全量重跑,stage SQL 幂等), + # error_code=EXTERNAL_TIMEOUT_ABORTED 与末步超时 EXTERNAL_TIMEOUT_UNKNOWN 可区分 + assert result.status == "technical_failed" + assert result.error_code == "EXTERNAL_TIMEOUT_ABORTED" + assert submit.calls == [] + rows = IntegrationCall.query.filter_by(operation_id="OP-ABT").all() + assert len(rows) == 1 + # 断言意图:审计保留技术真相——该步 IntegrationCall.status 仍记 timeout(与对外口径分离) + assert rows[0].status == "timeout" + assert rows[0].binding_snapshot_json["step_index"] == 0 + + +# --------------------------------------------------------------------------- +# ⑤ 末步映射 → classify 全链(success 带 mapped data) +# --------------------------------------------------------------------------- + + +def test_final_step_mapping_classify_chain_success(app): + """code='0':enum-map 映射出 status=success → classify success;data 恒带 mapped。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", {"status": "success"}) + submit = ScriptedTransport("soap", _tiptop_raw(code="0", description="ok", doc_no="1401-2609230008")) + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-CHAIN", environment="prod", + ) + + # 断言意图:末步 data 恒带 mapped(非原始响应);单号经 pick 提取 + assert result.status == "success" + assert result.document_no == "1401-2609230008" + assert result.data["status"] == "success" + assert result.data["code"] == "0" + + +# --------------------------------------------------------------------------- +# ⑥ 末步超时 → status=timeout(上层执行服务落 result_unknown,引擎不管) +# --------------------------------------------------------------------------- + + +def test_final_step_timeout_returns_timeout(app): + """末步(submit)抛 TimeoutError → status=timeout,且非末步已照常执行并审计。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", {"status": "success"}) + submit = ScriptedTransport("soap", TimeoutError()) + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-FT", environment="prod", + ) + + assert result.status == "timeout" + # 断言意图:超时发生在末步——stage 已成功执行,两步各落一条审计 + assert len(stage.calls) == 1 + rows = IntegrationCall.query.filter_by(operation_id="OP-FT").order_by(IntegrationCall.id).all() + assert [row.binding_snapshot_json["step_index"] for row in rows] == [0, 1] + + +# --------------------------------------------------------------------------- +# ⑦ code='0' → success;code 缺失(映射未覆盖 status)→ classify 兜底 technical_failed +# --------------------------------------------------------------------------- + + +def test_final_step_classify_fallback_on_zero_or_missing_code(app): + """code='0' 经 enum-map 映射 success;code 缺失(空 Status)时映射不产出 status, + classify 按原始响应兜底归 technical_failed(畸形/无码响应禁止误判成功)。""" + _seed_write_two_steps() + stage_ok = ScriptedTransport("database", {"status": "success"}) + submit_ok = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1")) + result_ok = _gateway(stage_ok, submit_ok).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-Z0", environment="prod", + ) + assert result_ok.status == "success" + + stage_miss = ScriptedTransport("database", {"status": "success"}) + submit_miss = ScriptedTransport("soap", {"Response": {"Execution": {"Status": {}}}}) + result_miss = _gateway(stage_miss, submit_miss).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-ZM", environment="prod", + ) + # 断言意图:缺失 code 的畸形响应按技术失败兜底(classify 未知 status 不猜测语义) + assert result_miss.status == "technical_failed" + + +# --------------------------------------------------------------------------- +# ⑧ ERP 业务拒单(code≠0)→ technical_failed,code/message 随 data 透传 +# --------------------------------------------------------------------------- + + +def test_erp_business_reject_maps_technical_failed_with_data_passthrough(app): + """R8 用户口径:ERP 返回非 0 业务码(查不到 30 行)= 失败+原因——classify 归 + technical_failed(enum-map 未命中原样穿透为未知 status),ERP 业务码与描述 + 经 result.data 原样携带供上层消费;不再二次改判 business_failed。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", {"status": "success"}) + submit = ScriptedTransport("soap", _tiptop_raw(code="B1234", description="料号无有效成本")) + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-REJ", environment="prod", + ) + + # 断言意图:非 0 码即失败(technical_failed),不再区分业务/技术内部标签; + # 描述透传走 data(code/message 原样保留),失败态下 data 恒带 mapped + assert result.status == "technical_failed" + assert result.data["code"] == "B1234" + assert result.data["message"] == "料号无有效成本" + assert result.document_no is None + + +# --------------------------------------------------------------------------- +# ⑨ 每步一条 IntegrationCall:同 operation_id + step_index 定位 +# --------------------------------------------------------------------------- + + +def test_each_step_records_integration_call_with_step_index(app): + """成功两步 → 两条审计同裸 operation_id;step_index 递增可排序、定位各步接口/客户端。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", {"status": "success"}) + submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1")) + + _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-AUD", environment="prod", + ) + + rows = IntegrationCall.query.filter_by(operation_id="OP-AUD").order_by(IntegrationCall.id).all() + # 断言意图:一单一次执行 = N 条审计同 operation_id(串联键),step_index 递增可排序 + assert len(rows) == 2 + assert all(row.operation_id == "OP-AUD" for row in rows) + assert [row.binding_snapshot_json["step_index"] for row in rows] == [0, 1] + assert [row.binding_snapshot_json["step_count"] for row in rows] == [2, 2] + assert [row.binding_snapshot_json["interface_code"] for row in rows] == ["IFACE-STAGE", "IFACE-SUBMIT"] + assert [row.binding_snapshot_json["client_code"] for row in rows] == ["CLI-STAGE", "CLI-WS"] + assert all(row.capability == "in_transit_transfer.create_transfer" for row in rows) + assert rows[1].status == "success" + + +def test_integration_call_operation_id_index_contract(): + """模型元数据契约:operation_id 无唯一约束(多步审计 N 行同值)、有普通索引补位查询。 + + 断言意图:锁定「删 uq_integration_calls_operation_id + 建 ix_integration_calls_operation_id」 + 的迁移终态不被模型改动悄悄回退(唯一约束会让多步审计落库直接失败)。 + """ + import sqlalchemy as sa + + table = IntegrationCall.__table__ + unique_col_sets = { + tuple(sorted(col.name for col in constraint.columns)) + for constraint in table.constraints + if isinstance(constraint, sa.UniqueConstraint) + } + assert ('operation_id',) not in unique_col_sets + index_col_sets = { + tuple(sorted(col.name for col in index.columns)) + for index in table.indexes + } + assert ('operation_id',) in index_col_sets + + +# --------------------------------------------------------------------------- +# ⑩ 读能力行为不变(回归):单步 + 成功态映射 + 失败直通 +# --------------------------------------------------------------------------- + + +def test_read_capability_behavior_unchanged(app): + """读能力回归:success 映射出 data(decimal 转换保留);传输层失败态原样分类。""" + _seed_read_single_step() + fake = ScriptedTransport("rest", {"found": True, "quantity": "100"}) + result = CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-RD", environment="prod", + ) + # 断言意图:读路径输出映射/分类语义与 Task 4 之前完全一致 + assert result.status == "success" + assert result.data["quantity"] == Decimal("100") + rows = IntegrationCall.query.filter_by(operation_id="OP-RD").all() + assert len(rows) == 1 + assert rows[0].binding_snapshot_json["step_index"] == 0 + + fake_fail = ScriptedTransport("rest", {"status": "business_failed", "code": "HTTP_500", "message": "boom"}) + result_fail = CapabilityGateway(transports={"rest": fake_fail}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-RD2", environment="prod", + ) + assert result_fail.status == "business_failed" + assert result_fail.error_code == "HTTP_500" + + +# --------------------------------------------------------------------------- +# ⑪⑫ on_nonfinal_success 步进回调(T10 断点标记机制) +# --------------------------------------------------------------------------- + + +class _EventTransport(ScriptedTransport): + """在 ScriptedTransport 之上向全局事件表记录传输调用时序。""" + + def __init__(self, connector_type: str, response, events: list, label: str): + super().__init__(connector_type, response) + self._events = events + self._label = label + + def call(self, **kwargs): + self._events.append(f"transport:{self._label}") + return super().call(**kwargs) + + +def test_nonfinal_success_callback_fires_between_steps(app): + """回调在非末步成功放行(审计落库)后、末步执行前同步触发一次,收到该步快照与步号。""" + _seed_write_two_steps() + events: list[str] = [] + seen: list[tuple[str, int]] = [] + stage = _EventTransport("database", {"status": "success"}, events, "stage") + submit = _EventTransport("soap", _tiptop_raw(code="0", doc_no="1401-2609230007"), events, "submit") + + def on_stage_confirmed(step, index): + seen.append((step.interface_code, index)) + events.append(f"callback:{index}") + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-CB1", environment="prod", + on_nonfinal_success=on_stage_confirmed, + ) + + # 断言意图:回调恰好一次、收到步 0 的 BindingStep 定位信息 + assert seen == [("IFACE-STAGE", 0)] + # 断言意图:时序锁定 stage 传输成功 → 回调(断点标记)→ submit 传输(先落库再触发) + assert events == ["transport:stage", "callback:0", "transport:submit"] + assert result.status == "success" + + +def test_nonfinal_success_callback_exception_aborts_as_technical_failed(app): + """回调抛异常 → 按该步失败处理:中止 technical_failed、后续步零调用、异常结果追加落审计。""" + _seed_write_two_steps() + stage = ScriptedTransport("database", {"status": "success"}) + submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1")) + + def boom(step, index): + raise RuntimeError("stage_confirmed_at flush failed") + + result = _gateway(stage, submit).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_order_params(), operation_id="OP-CB2", environment="prod", + on_nonfinal_success=boom, + ) + + # 断言意图:回调异常禁止继续触发末步(断点未落库不得触发),对外按技术失败 + assert result.status == "technical_failed" + assert result.error_code == "STEP_CALLBACK_FAILED" + assert submit.calls == [] + rows = IntegrationCall.query.filter_by(operation_id="OP-CB2").order_by(IntegrationCall.id).all() + # 断言意图:append-only 审计——原传输成功行保留,追加一行回调异常(同 operation_id 同步号) + assert [row.status for row in rows] == ["success", "technical_failed"] + assert all(row.binding_snapshot_json["step_index"] == 0 for row in rows) diff --git a/backend/tests/services/integration_connector/test_mapping.py b/backend/tests/services/integration_connector/test_mapping.py index 8efd5a5d..5d68b805 100644 --- a/backend/tests/services/integration_connector/test_mapping.py +++ b/backend/tests/services/integration_connector/test_mapping.py @@ -133,10 +133,23 @@ def test_pick_exists_boolean(): assert mapped_absent["found"] is False +def test_pick_single_dict_normalized_as_one_element_list(): + """单条 Field(dict)按单元素列表语义 pick(回归:ERP 返回单条 doc_no Field + 时 pick_target_not_list → 单号丢失,调拨单被误判 technical_failed)。""" + mapped = map_response( + {"doc_no": {"expr": "Parameter.Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}}}, + {"Parameter": {"Record": {"Field": {"@name": "doc_no", "@value": "1406-2609260001"}}}}, + {}, + ) + assert mapped["doc_no"] == "1406-2609260001" + + def test_pick_requires_list_and_key_args(): + # 标量目标仍拒绝(既非 dict 也非 list,无键值对语义) with pytest.raises(AppError): map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name", "key_value": "x"}}}, - {"rows": {"not": "a list"}}, {}) + {"rows": "not-a-structure"}, {}) with pytest.raises(AppError): map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name"}}}, {"rows": _field_rows()}, {}) @@ -183,16 +196,16 @@ def test_template_missing_param_fail_closed(): assert exc.value.code == "INTEGRATION.MAPPING_INVALID" -# ---- dict 项列表模板:域元组列表 → OR 拼接条件(料号+库位+批号批量查询)---- +# ---- dict 项列表模板:域元组列表 → OR 拼接条件(料号+仓库+批号批量查询)---- def test_template_renders_dict_items_with_field_refs(): mapped = map_response( {"condition": {"template": "{targets}", - "args": {"list_item_template": "(img01 = '{material_no}' AND img02 = '{from_warehouse}' AND img04 = '{lot_no}')", + "args": {"list_item_template": "(img01 = '{material_no}' AND img02 = '{warehouse_code}' AND img04 = '{lot_no}')", "separator": " OR ", "escape": "quote"}}}, {"targets": [ - {"material_no": "M-1", "from_warehouse": "HTP-D43", "lot_no": "LOT-1"}, - {"material_no": "M'2", "from_warehouse": "HTP-D49", "lot_no": "LOT-2"}, + {"material_no": "M-1", "warehouse_code": "HTP-D43", "lot_no": "LOT-1"}, + {"material_no": "M'2", "warehouse_code": "HTP-D49", "lot_no": "LOT-2"}, ]}, {"type": "object", "properties": {"condition": {"type": "string"}}}, ) diff --git a/backend/tests/services/integration_connector/test_mapping_repeated_record_batch.py b/backend/tests/services/integration_connector/test_mapping_repeated_record_batch.py index 23476da0..4fef00ca 100644 --- a/backend/tests/services/integration_connector/test_mapping_repeated_record_batch.py +++ b/backend/tests/services/integration_connector/test_mapping_repeated_record_batch.py @@ -21,30 +21,33 @@ from app.services.integration_connector.mapping import extract_path, map_respons from app.services.integration_connector.transports.base import IntegrationCallResult from app.services.integration_connector.transports.soap import _parse_soap_payload -# 生产绑定同构的 rows 映射(expr/each/pick 与 2026-09-22 回归用例一致, -# from_warehouse 按 img02、批号 img04、库存数 img10)。 +# 生产绑定同构的 rows 映射(expr/each/pick 与生产 response_mapping 一致: +# material_no=img01 料件编号、warehouse_code=img02 仓库编号、lot_no=img04 批号、 +# stock_quantity=img10 库存数量、stock_unit=img09 库存单位)。 _ROWS_MAPPING = {"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master", "transform": "each", "args": {"fields": { "material_no": {"expr": "Record.Field", "transform": "pick", "args": {"key_field": "@name", "key_value": "img01", "value_field": "@value"}}, - "from_warehouse": {"expr": "Record.Field", "transform": "pick", + "warehouse_code": {"expr": "Record.Field", "transform": "pick", "args": {"key_field": "@name", "key_value": "img02", "value_field": "@value"}}, "lot_no": {"expr": "Record.Field", "transform": "pick", "args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}, - "quantity": {"expr": "Record.Field", "transform": "pick", - "args": {"key_field": "@name", "key_value": "img10", "value_field": "@value", - "cast": "decimal"}}}}}} + "stock_quantity": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img10", "value_field": "@value", + "cast": "decimal"}}, + "stock_unit": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img09", "value_field": "@value"}}}}}} _ROWS_OUTPUT_SCHEMA = {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array", "items": { - "type": "object", "required": ["material_no", "from_warehouse", "lot_no", "quantity"]}}}} + "type": "object", "required": ["material_no", "warehouse_code", "lot_no", "stock_quantity"]}}}} def _field(name: str, value: str) -> dict: return {"@name": name, "@value": value} -def _record(material: str, warehouse: str, lot: str, qty: str) -> dict: +def _record(material: str, warehouse: str, lot: str, qty: str, unit: str = "PCS") -> dict: return {"Field": [_field("img01", material), _field("img02", warehouse), - _field("img04", lot), _field("img10", qty)]} + _field("img04", lot), _field("img09", unit), _field("img10", qty)]} def _stock_response(record_sets: list[dict]) -> dict: @@ -69,7 +72,8 @@ def test_single_target_single_record_maps_one_row(): {"@id": "1", "Master": {"@name": "img_file", "Record": _record("M-1", "W-1", "L-1", "30")}}, ]) rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] - assert rows == [{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")}] + assert rows == [{"material_no": "M-1", "warehouse_code": "W-1", "lot_no": "L-1", + "stock_quantity": Decimal("30"), "stock_unit": "PCS"}] def test_multi_record_master_maps_every_record_row(): @@ -89,9 +93,12 @@ def test_multi_record_master_maps_every_record_row(): rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] # [断言意图] 同料号不同批号(L-1/L-2)与同批号不同料号(M-1/M-2)全部保留。 assert rows == [ - {"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")}, - {"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-2", "quantity": Decimal("40")}, - {"material_no": "M-2", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("36")}, + {"material_no": "M-1", "warehouse_code": "W-1", "lot_no": "L-1", + "stock_quantity": Decimal("30"), "stock_unit": "PCS"}, + {"material_no": "M-1", "warehouse_code": "W-1", "lot_no": "L-2", + "stock_quantity": Decimal("40"), "stock_unit": "PCS"}, + {"material_no": "M-2", "warehouse_code": "W-1", "lot_no": "L-1", + "stock_quantity": Decimal("36"), "stock_unit": "PCS"}, ] @@ -107,8 +114,9 @@ def test_multi_recordset_with_multi_record_master_keeps_all_rows(): rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] # [断言意图] RecordSet 逐元素扇出 + 重复 Record 展开叠加时行数完整(2+1=3 行)。 assert len(rows) == 3 - assert rows[0]["quantity"] == Decimal("30") - assert rows[2] == {"material_no": "M-2", "from_warehouse": "W-2", "lot_no": "L-9", "quantity": Decimal("40")} + assert rows[0]["stock_quantity"] == Decimal("30") + assert rows[2] == {"material_no": "M-2", "warehouse_code": "W-2", "lot_no": "L-9", + "stock_quantity": Decimal("40"), "stock_unit": "PCS"} def test_batch_vs_single_lookup_parity_on_multi_record_response(): @@ -130,19 +138,19 @@ def test_batch_vs_single_lookup_parity_on_multi_record_response(): batch_rows = map_response(_ROWS_MAPPING, raw_batch, _ROWS_OUTPUT_SCHEMA)["rows"] single_rows = map_response(_ROWS_MAPPING, raw_single, _ROWS_OUTPUT_SCHEMA)["rows"] - targets = [StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1"), - StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-2"), - StockTarget(material_no="M-2", from_warehouse="W-1", lot_no="L-1")] + targets = [StockTarget(material_no="M-1", warehouse_code="W-1", lot_no="L-1"), + StockTarget(material_no="M-1", warehouse_code="W-1", lot_no="L-2"), + StockTarget(material_no="M-2", warehouse_code="W-1", lot_no="L-1")] batch_result = _client_with_rows(batch_rows).query_stock( operation_id="op-batch", external_org="HX-CN01", targets=targets) single_result = _client_with_rows(single_rows).query_stock( operation_id="op-single", external_org="HX-CN01", targets=[targets[0]]) # [断言意图] 批量与单查逐 target 对账一致:批量不再整批 0(inventory_not_found)。 - assert single_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30") - assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30") - assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-2") == Decimal("40") - assert batch_result.lookup(material_no="M-2", from_warehouse="W-1", lot_no="L-1") == Decimal("36") + assert single_result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-1") == Decimal("30") + assert batch_result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-1") == Decimal("30") + assert batch_result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-2") == Decimal("40") + assert batch_result.lookup(material_no="M-2", warehouse_code="W-1", lot_no="L-1") == Decimal("36") def test_soap_multi_record_payload_end_to_end_mapping(): @@ -163,7 +171,7 @@ def test_soap_multi_record_payload_end_to_end_mapping(): raw = _parse_soap_payload(xml) rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] # [断言意图] 转义内嵌报文同样走归一化+映射:两条 Record(不同批号)都成行。 - assert [(r["lot_no"], str(r["quantity"])) for r in rows] == [("L-1", "30"), ("L-2", "40")] + assert [(r["lot_no"], str(r["stock_quantity"])) for r in rows] == [("L-1", "30"), ("L-2", "40")] def test_extract_path_fanout_nested_list_flattened(): @@ -193,11 +201,11 @@ def test_case_and_space_variants_pass_through_exact_match(): ]) rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] # [断言意图] 行值原样保留(未改写大小写、未截断空格)。 - assert rows == [{"material_no": "m-1 ", "from_warehouse": "W-1", "lot_no": "l-1", - "quantity": Decimal("30")}] + assert rows == [{"material_no": "m-1 ", "warehouse_code": "W-1", "lot_no": "l-1", + "stock_quantity": Decimal("30"), "stock_unit": "PCS"}] result = _client_with_rows(rows).query_stock( operation_id="op-case", external_org="HX-CN01", - targets=[StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1")]) + targets=[StockTarget(material_no="M-1", warehouse_code="W-1", lot_no="L-1")]) # [断言意图] 精确匹配下大小写/空格不同的键不命中(两侧路径同语义)。 - assert result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") is None - assert result.lookup(material_no="m-1 ", from_warehouse="W-1", lot_no="l-1") == Decimal("30") + assert result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-1") is None + assert result.lookup(material_no="m-1 ", warehouse_code="W-1", lot_no="l-1") == Decimal("30") diff --git a/backend/tests/services/integration_connector/test_rest_transport.py b/backend/tests/services/integration_connector/test_rest_transport.py new file mode 100644 index 00000000..e6794177 --- /dev/null +++ b/backend/tests/services/integration_connector/test_rest_transport.py @@ -0,0 +1,49 @@ +"""tests/services/integration_connector/test_rest_transport.py + +用途:Task 3——RestTransport call 返回 dict 附带保留键 `_wire`(线级事实), + 供调用日志引擎(Task 4)剥离落库 IntegrationCall.wire_json。 +依赖:transports.rest(http_request 注入替身,不触网)。 +逻辑:FakeResponse 提供 text/status_code/raise_for_status 三件套;断言 _wire 含 + kind/method/url/请求头(脱敏)/请求体/状态码/响应体(脱敏、截断)。 +""" + +from __future__ import annotations + +from app.services.integration_connector.transports.rest import RestTransport + + +class FakeResponse: + """HTTP 响应替身:text/status_code/raise_for_status 三件套(与 requests.Response 同形)。""" + + def __init__(self, text: str = '', status_code: int = 200): + self.text = text + self.status_code = status_code + + def raise_for_status(self) -> None: + """模拟 requests 语义:≥400 抛 HTTPError(当前传输层不调用,仅为形状完整)。""" + if self.status_code >= 400: + import requests + raise requests.HTTPError(f'HTTP {self.status_code}') + + +def test_call_attaches_wire_with_method_url_headers_body(monkeypatch): + """call 后 _wire 记录 method/url/脱敏请求头/请求体/状态码/响应体(线级事实)。""" + captured = {} + + def fake_http(method, url, **kwargs): + captured.update(method=method, url=url, kwargs=kwargs) + return FakeResponse(text='{"ok": true}', status_code=200) + + transport = RestTransport(http_request=fake_http) + result = transport.call( + client={'config_json': {'endpoint': 'http://api', 'headers': {'X-App': 'hxops'}}}, + interface={'request_spec_json': {'method': 'POST', 'path': 'v1/things'}}, + request={'body': {'a': 1}}, + ) + wire = result['_wire'] + # 关键断言:url 为 endpoint+path 拼接、请求体为 JSON 序列化的最终报文 + assert wire['kind'] == 'rest' + assert wire['method'] == 'POST' + assert wire['url'] == 'http://api/v1/things' + assert wire['http_status'] == 200 + assert '"a": 1' in wire['request_body'] or wire['request_body'] == '{"a":1}' diff --git a/backend/tests/services/integration_connector/test_soap_transport.py b/backend/tests/services/integration_connector/test_soap_transport.py new file mode 100644 index 00000000..b3d649f0 --- /dev/null +++ b/backend/tests/services/integration_connector/test_soap_transport.py @@ -0,0 +1,75 @@ +"""tests/services/integration_connector/test_soap_transport.py + +用途:Task 3——SoapTransport call 返回 dict 附带保留键 `_wire`(线级事实), + 供调用日志引擎(Task 4)剥离落库 IntegrationCall.wire_json。 +依赖:transports.soap(http_request 注入替身,不触网)。 +逻辑:FakeResponse 提供 text/status_code/raise_for_status 三件套;断言 _wire 含 + method/url/soap_action/request_body/http_status/response_body,且 + request_body 中的凭据值已脱敏;既有 NON_XML / HTTP≥400 分类行为不变。 +""" + +from __future__ import annotations + +from app.services.integration_connector.transports.soap import SoapTransport + + +class FakeResponse: + """HTTP 响应替身:text/status_code/raise_for_status 三件套(与 requests.Response 同形)。""" + + def __init__(self, text: str = '', status_code: int = 200): + self.text = text + self.status_code = status_code + + def raise_for_status(self) -> None: + """模拟 requests 语义:≥400 抛 HTTPError(当前传输层不调用,仅为形状完整)。""" + if self.status_code >= 400: + import requests + raise requests.HTTPError(f'HTTP {self.status_code}') + + +def test_call_attaches_wire_with_url_body_and_response(): + """call 成功后 _wire 记录 method/url/soap_action/请求体/状态码/响应体(线级事实)。""" + captured = {} + + def fake_http(method, url, **kwargs): + captured['method'], captured['url'], captured['kwargs'] = method, url, kwargs + return FakeResponse(text='1', status_code=200) + + transport = SoapTransport(http_request=fake_http) + result = transport.call( + # 凭据值避免单字母(如 'u'):mask_secrets 按值做子串替换,单字母会把 + # Envelope 等普通文本一并打码,无法区分"脱敏生效"与"误伤"。 + client={'config_json': {'endpoint': 'http://erp/WS?wsdl', 'timeout_seconds': 30}, + 'credential': {'username': 'u1', 'password': 'p1'}}, + interface={'request_spec_json': {'method': 'POST', 'soap': { + 'action': 'do.it', + 'body_template': '{credential_username}{v}'}}}, + request={'params': {'v': '1'}}, + ) + wire = result['_wire'] + # 关键断言:soap_action 按规范带引号、request_body 为凭据脱敏后的最终报文 + # (mask_secrets 按凭据值替换:username 'u' 注入报文后同被替换为 ***, + # 与任务书接口规格 request_body(masked) 一致)、response_body 无凭据时保持原文。 + assert wire['kind'] == 'soap' + assert wire['method'] == 'POST' + assert wire['url'] == 'http://erp/WS?wsdl' + assert wire['soap_action'] == '"do.it"' + assert wire['request_body'] == '***1' + assert wire['http_status'] == 200 + assert 'Envelope' in wire['response_body'] + + +def test_call_wire_masks_credential_in_body(): + """_wire.request_body 中的凭据值必须替换为 ***,防凭据进审计列。""" + + def fake_http(method, url, **kwargs): + return FakeResponse(text='', status_code=200) + + transport = SoapTransport(http_request=fake_http) + result = transport.call( + client={'config_json': {'endpoint': 'http://erp/WS'}, 'credential': {'password': 'sup3r'}}, + interface={'request_spec_json': {'soap': {'action': '', 'body_template': '

{credential_password}

'}}}, + request={'params': {}}, + ) + # 关键断言:凭据明文不得出现在落库线级事实中 + assert 'sup3r' not in result['_wire']['request_body'] diff --git a/backend/tests/services/integration_connector/test_transports.py b/backend/tests/services/integration_connector/test_transports.py index a191a39a..17481f81 100644 --- a/backend/tests/services/integration_connector/test_transports.py +++ b/backend/tests/services/integration_connector/test_transports.py @@ -53,7 +53,8 @@ def test_rest_builds_url_and_sends_request(): assert captured["url"] == "https://erp.invalid/stock" assert captured["method"] == "GET" assert captured["params"] == {"invoice_no": "INV-001"} - assert result == {"found": True, "quantity": "100"} + # `_wire` 为调用日志新增的保留键(线级事实,由引擎剥离落库),全等断言排除该键。 + assert {k: v for k, v in result.items() if k != "_wire"} == {"found": True, "quantity": "100"} def test_rest_business_error_maps_to_dict(): @@ -389,3 +390,66 @@ def test_soap_probe_failure_paths(): with pytest.raises(TransportNotFrozenError): SoapTransport().probe(client={"config_json": {}}) + + +# ---- Oracle thick 模式 lib_dir 取值优先级(11g 等老服务端必须 thick) ---- + +def test_oracle_connect_lib_dir_client_config_overrides_env(monkeypatch): + """oracle thick 目录:按客户端 config_json.oracle_lib_dir 优先于全局环境变量。""" + import sys + import types + + from app.services.integration_connector.transports.database import _connect_oracle + + captured = {} + fake_oracledb = types.SimpleNamespace( + init_oracle_client=lambda lib_dir=None: captured.setdefault('lib_dir', lib_dir), + connect=lambda **kw: types.SimpleNamespace(), + ) + monkeypatch.setitem(sys.modules, 'oracledb', fake_oracledb) + monkeypatch.setenv('ORACLE_CLIENT_LIB_DIR', r'C:\global\instantclient') + + _connect_oracle( + config={'endpoint': 'h:1521/svc', 'oracle_lib_dir': r'C:\client\dir'}, + credential={'username': 'u', 'password': 'p'}, + ) + # 按客户端配置优先(关键断言) + assert captured['lib_dir'] == r'C:\client\dir' + + +def test_oracle_connect_lib_dir_falls_back_to_env(monkeypatch): + """oracle thick 目录:未配置 oracle_lib_dir 时回退 ORACLE_CLIENT_LIB_DIR 环境变量。""" + import sys + import types + + from app.services.integration_connector.transports.database import _connect_oracle + + captured = {} + fake_oracledb = types.SimpleNamespace( + init_oracle_client=lambda lib_dir=None: captured.setdefault('lib_dir', lib_dir), + connect=lambda **kw: types.SimpleNamespace(), + ) + monkeypatch.setitem(sys.modules, 'oracledb', fake_oracledb) + monkeypatch.setenv('ORACLE_CLIENT_LIB_DIR', r'C:\global\instantclient') + + _connect_oracle(config={'endpoint': 'h:1521/svc'}, credential={'username': 'u', 'password': 'p'}) + assert captured['lib_dir'] == r'C:\global\instantclient' + + +def test_oracle_connect_without_lib_dir_skips_thick_init(monkeypatch): + """oracle thick 目录:两侧均未配置时不调 init_oracle_client(保持 thin 模式)。""" + import sys + import types + + from app.services.integration_connector.transports.database import _connect_oracle + + monkeypatch.delenv('ORACLE_CLIENT_LIB_DIR', raising=False) + called = {'init': 0} + fake_oracledb = types.SimpleNamespace( + init_oracle_client=lambda lib_dir=None: called.__setitem__('init', called['init'] + 1), + connect=lambda **kw: types.SimpleNamespace(), + ) + monkeypatch.setitem(sys.modules, 'oracledb', fake_oracledb) + + _connect_oracle(config={'endpoint': 'h:1521/svc'}, credential={'username': 'u', 'password': 'p'}) + assert called['init'] == 0 diff --git a/backend/tests/test_integration_calls_operation_id_migration.py b/backend/tests/test_integration_calls_operation_id_migration.py new file mode 100644 index 00000000..3f3cbb99 --- /dev/null +++ b/backend/tests/test_integration_calls_operation_id_migration.py @@ -0,0 +1,114 @@ +""" +backend/tests/test_integration_calls_operation_id_migration.py + +用途:验证 integration_calls.operation_id 唯一约束删除迁移(tt5b6c7d8e9f)可完整 + upgrade/downgrade 往返(多步顺序引擎审计契约的库级防线)。 +依赖:Alembic Operations、SQLite 内存数据库、tt5b6c7d8e9f 迁移。 +逻辑:前置建含 uq_integration_calls_operation_id 唯一约束的 integration_calls 表 + (ic1a2b3c4d5f 原状),upgrade 后唯一约束删除、同名普通索引补回且同 + operation_id 两行可共存(一票一次执行 = N 步审计);清理多步行后 downgrade + 重建唯一约束,重复插入被 IntegrityError 拒绝。带重复行直接 downgrade 按迁移 + 文档预期报错(旧唯一约束与多步审计不兼容),不属本往返用例覆盖范围。 +""" + +from __future__ import annotations + +import importlib + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +_MIGRATION_MODULE = ( + 'migrations.versions.tt5b6c7d8e9f_drop_integration_calls_operation_unique' +) +_UQ_NAME = 'uq_integration_calls_operation_id' +_IX_NAME = 'ix_integration_calls_operation_id' + + +def _pre_migration_schema(engine: sa.Engine) -> None: + """迁移前形态:integration_calls 带 operation_id 唯一约束(单步审计时代原状)。""" + metadata = sa.MetaData() + sa.Table( + 'integration_calls', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('operation_id', sa.String(128), nullable=False), + sa.Column('capability', sa.String(128)), + sa.Column('status', sa.String(32)), + sa.UniqueConstraint('operation_id', name=_UQ_NAME), + ) + metadata.create_all(engine) + + +def _insert_call(connection: sa.Connection, operation_id: str) -> None: + """插入一条最小审计行(仅唯一约束相关列有业务含义,其余可空)。""" + connection.execute( + sa.text( + 'INSERT INTO integration_calls (operation_id, capability, status) ' + 'VALUES (:operation_id, :capability, :status)' + ), + { + 'operation_id': operation_id, + 'capability': 'in_transit_transfer.create_transfer', + 'status': 'success', + }, + ) + + +def test_integration_calls_operation_unique_drop_round_trip(monkeypatch): + """关键断言:upgrade 后同 operation_id 两行可共存且普通索引补回; + downgrade 重建唯一约束、重复插入被拒。""" + migration = importlib.import_module(_MIGRATION_MODULE) + engine = sa.create_engine('sqlite:///:memory:') + _pre_migration_schema(engine) + + with engine.begin() as connection: + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + + migration.upgrade() + inspector = sa.inspect(connection) + # [断言意图] 唯一约束已删除,同名普通索引补回(查询性能不回退)。 + unique_names = { + constraint['name'] + for constraint in inspector.get_unique_constraints('integration_calls') + } + assert _UQ_NAME not in unique_names + indexes = { + index['name']: index + for index in inspector.get_indexes('integration_calls') + } + assert indexes[_IX_NAME]['column_names'] == ['operation_id'] + # SQLite 方言 unique 返回 0/1,用真值断言而非 `is False`。 + assert not indexes[_IX_NAME]['unique'] + + # [断言意图] 核心契约:同 operation_id 两行共存——多步顺序引擎一次能力 + # 调用按步骤落 N 条审计、共享同一 operation_id 串联。 + _insert_call(connection, 'OP-1') + _insert_call(connection, 'OP-1') + same_op_count = connection.execute( + sa.text("SELECT count(*) FROM integration_calls WHERE operation_id = 'OP-1'") + ).scalar_one() + assert same_op_count == 2 + + # 清理多步行再回滚:带重复行 downgrade 按迁移文档预期报错(多步审计本身 + # 不兼容旧唯一约束),该预期错误行为不在本往返用例覆盖。 + connection.execute(sa.text('DELETE FROM integration_calls')) + + migration.downgrade() + inspector = sa.inspect(connection) + restored_unique = { + constraint['name'] + for constraint in inspector.get_unique_constraints('integration_calls') + } + assert _UQ_NAME in restored_unique + assert _IX_NAME not in { + index['name'] for index in inspector.get_indexes('integration_calls') + } + + # [断言意图] 旧唯一约束恢复后,重复 operation_id 插入被 IntegrityError 拒绝。 + _insert_call(connection, 'OP-2') + with pytest.raises(sa.exc.IntegrityError): + _insert_call(connection, 'OP-2') diff --git a/docs/platform/integration-connector-framework-design.md b/docs/platform/integration-connector-framework-design.md index 40da4bd2..09403dac 100644 --- a/docs/platform/integration-connector-framework-design.md +++ b/docs/platform/integration-connector-framework-design.md @@ -504,3 +504,44 @@ verify_duplicate # 确认重复 Invoice 对应原单 - [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) - 在途仓自动调拨实现(Phase 0/1):`backend/app/services/in_transit_transfer/` - Chat Action Registry(Agent 挂载点):`backend/app/services/chat/action_registry.py` + +--- + +## 19. 调用日志与线级事实捕获(2026-09-27) + +### 19.1 目标与定位 + +传输层在调用现场捕获**线级事实(wire-level facts)**并落 `integration_calls.wire_json`,为排障、复现与审计提供"当时真正发生了什么"的一手证据。捕获在引擎(CapabilityGateway)统一收口:脱敏(`mask_secrets`)与文本截断(20000 字符)在同一处完成,各 Transport 只负责产出原始事实,不重复实现安全策略。 + +### 19.2 wire_json 结构(按 connector_type 三形态) + +| connector_type | wire_json 记录的关键事实 | +| --- | --- | +| `database` | 标识符(identifiers)白名单替换后的**最终 SQL**、绑定变量首行参数、影响/返回行数 | +| `soap` | endpoint、SOAPAction、渲染后完整 XML 请求、原始 XML 响应 | +| `rest` | method、完整 URL、请求 headers、请求 body、原始响应 | + +公共约束: + +- 凭据与敏感字段经 `mask_secrets` 统一脱敏后再落库; +- 文本类字段统一 20000 字符截断(引擎收口,Transport 无感知); +- 多步绑定(`steps_json`)逐步各落一条 `IntegrationCall`,同 `operation_id` 串联、`step_index` 定位,wire_json 随各步调用分别记录。 + +### 19.3 business_ref 通用业务锚点 + +`business_ref` 为可选透传的通用业务锚点(如调拨票号、单据 ID),由调用方随请求传入,随 `IntegrationCall` 落库并支持查询筛选。框架不解释其语义,仅保证存储与检索,便于从业务单据反查当时的全部线级调用。 + +### 19.4 查询 API(require_admin) + +- `GET /api/integration-connector/calls` — 调用日志分页筛选:能力/接口/客户端/连接类型/状态/operation_id/trace_id/business_ref/参数关键字/时间起止; +- `GET /api/integration-connector/calls/{id}` — 单条调用详情:步骤时间线、原始报文/归一化 JSON 双栏、外部工具复现(curl / 绑定内联 SQL,写入类附事务警示)。 + +### 19.5 管理端入口 + +管理端「集成连接器 → 调用日志」(`features/admin/modules/integration-connector`):列表分页筛选 + 步骤时间线详情抽屉(原始报文 / 归一化 JSON 双栏对照)+ curl / SQL 复现片段复制。 + +### 19.6 已知边界 + +- **历史行无 wire**:wire_json 捕获自上线起生效,历史 `IntegrationCall` 行不含 wire_json,详情页按缺失降级展示; +- **keyword 检索为 `CAST ILIKE` 模糊匹配**:未建全文/ trigram 索引,数据量上来之前建议配合时间窗筛选使用;如需高频关键字检索,建议增加时间窗约束或为相应列建 `pg_trgm` GIN 索引; +- **`config_json.headers` 禁止放静态密钥**:headers 属配置而非凭据引用,线级捕获只对凭据引用(credential_*)做 `mask_secrets` 脱敏,配置里手写的静态密钥**不会**被脱敏——静态密钥必须走凭据引用机制。 diff --git a/docs/superpowers/plans/2026-09-27-integration-call-logs.md b/docs/superpowers/plans/2026-09-27-integration-call-logs.md new file mode 100644 index 00000000..3293e724 --- /dev/null +++ b/docs/superpowers/plans/2026-09-27-integration-call-logs.md @@ -0,0 +1,1062 @@ +# 集成调用日志(wire 捕获 + 查询 API + 前台展示)实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 集成连接器每次能力调用在传输层捕获"线级事实"(database=最终 SQL+绑定+行数;soap=endpoint+渲染后 XML+原始响应;rest=method/URL/headers/body+原始响应),落库 `wire_json`,并提供管理端「调用日志」查询页(筛选 + 步骤时间线 + 原始/归一化双栏 + 外部工具复现命令)。 + +**Architecture:** 三层。① 记录增强:三个传输层执行时在返回 dict 上附加保留键 `_wire`,引擎 `_record_call` 取出并写入 `integration_calls.wire_json`(新列,Alembic 迁移);同迁移加可选业务锚点列 `business_ref`(VARCHAR(128)+索引),引擎入口可选透传、不传为 NULL(现有消费者零改动);② 查询 API:`GET /api/integration-connector/calls`(分页+筛选)与 `GET /calls/{id}`(全量+同 operation_id 时间线),全部 `require_admin`;③ 前台:admin 集成连接器页新增「调用日志」tab(列表+筛选+详情抽屉,能力无关的通用展示)。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic;Vue 3 ` +``` + +模板区按框线图实现:筛选条(input/select 绑 `filters` 各键,连接类型/状态下拉为固定枚举值)+ 表格 + 分页 + `` 抽屉(`v-if="detail"`,stepper 用 `detail.timeline` 渲染,双栏 `
` 展示 `wire_json` 与 `request/response_summary_json`,复制按钮调 `copy()`/`replayCommand()`)。
+
+- [ ] **Step 3: 面板测试**
+
+`IntegrationCallLogsPanel.spec.ts`:mock `../api/integration-connector.api`(`listIntegrationCalls` 返回 2 行、`getIntegrationCall` 返回含 wire_json 的详情),断言:挂载即拉列表;填 interface_code 点查询→带参调用;点行→抽屉出现且呈现 wire 文本;soap wire 时出现「复制 curl」。用例如 4 个。
+
+- [ ] **Step 4: 跑面板与复现命令测试**
+
+```bash
+npx vitest run src/features/admin/modules/integration-connector
+```
+
+Expected: PASS。
+
+---
+
+### Task 8: 页面挂 tab + i18n 四语言
+
+**Files:**
+- Modify: `frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue`(TabKey/tabs/模板分支)
+- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json`
+
+- [ ] **Step 1: 页面挂 tab**
+
+`TabKey` 增 `'calls'`;`tabs` 数组追加 `{ key: 'calls', labelKey: 'admin.integrationConnector.tabs.calls' }`;模板区按既有 tab 分支模式追加:
+
+```vue
+
+```
+
+(import 该组件;capability 只读 tab 的分支模式即参照。)
+
+- [ ] **Step 2: i18n 四语言**(admin.json `integrationConnector` 命名空间内)
+
+zh-CN(zh-TW/en/th 同键异文;en 关键词:Call logs / Interface / Client / Connector type / Status / Operation ID / Trace ID / Keyword in request / Time from / Time to / Query / Reset / Time / Capability / Step / Elapsed / Copy / Close / No wire details (historical record)):
+
+```json
+"tabs": { "calls": "调用日志" },
+"callLogs": {
+  "title": "调用记录",
+  "filterInterface": "接口编码",
+  "filterClient": "客户端编码",
+  "filterConnector": "连接类型",
+  "filterStatus": "状态",
+  "filterOperationId": "operation_id",
+  "filterTraceId": "trace_id",
+  "filterKeyword": "参数关键字(模糊搜请求内容)",
+  "dateFrom": "执行时间起",
+  "dateTo": "执行时间止",
+  "query": "查询",
+  "reset": "重置",
+  "colTime": "时间",
+  "colCapability": "能力",
+  "colInterface": "接口",
+  "colStep": "步骤",
+  "colStatus": "状态",
+  "colElapsed": "耗时",
+  "detailTitle": "调用详情",
+  "timeline": "步骤时间线",
+  "request": "请求",
+  "response": "响应",
+  "wire": "线级请求(wire)",
+  "rawPayload": "原始报文",
+  "normalized": "业务参数(归一化)",
+  "copyBody": "复制 body",
+  "copyCurl": "复制 curl",
+  "copySql": "复制 SQL",
+  "copyRaw": "复制原始报文",
+  "copyJson": "复制 JSON",
+  "copyOperationId": "复制 operation_id",
+  "copied": "已复制",
+  "noWire": "无线级详情(历史记录)",
+  "sqlWriteWarning": "⚠ 写入语句:请确认目标环境后再执行"
+}
+```
+
+(th 文案可参照既有 admin.json 泰语条目风格直译。)
+
+- [ ] **Step 3: 验证**
+
+```bash
+npm run build && npx vitest run src/features/admin
+```
+
+Expected: 类型检查 + build 通过;admin 相关 spec 全绿(IntegrationConnectorPage.spec 若断言 tab 数量需同步 +1)。
+
+---
+
+### Task 9: 全量回归
+
+- [ ] **Step 1: 后端**
+
+```bash
+./.venv/Scripts/python.exe -m pytest tests/services/integration_connector tests/api/test_integration_connector_api.py -q
+```
+
+- [ ] **Step 2: 前端**
+
+```bash
+npm run build && npx vitest run src/features/admin
+```
+
+Expected: 全绿。人工验收:起本地栈 → 管理端「集成连接器 → 调用日志」→ 触发一次在途调拨重试 → 刷新列表可见新调用 → 打开 step1 详情 → 验证原始 XML/curl/单号等要素齐全。
+
+---
+
+## Self-Review
+
+- **Spec coverage**:wire 捕获(Task 2/3)→ 落库(Task 1/4)→ API(Task 5)→ 前台(Task 6/7/8)→ 回归(Task 9)全覆盖;用户要求四项(前台查看/原始调用内容+SQL/返回报文+执行结果/外部工具复现)分别由 Task 7 抽屉、Task 2/3 wire、Task 3 response_body、Task 7 复现命令满足。
+- **Placeholder 扫描**:无 TBD;迁移 down_revision 以 `flask db heads` 实测值为准(显式动作步骤,非占位)。
+- **类型一致性**:`IntegrationCallWire`/`IntegrationCallDetail`/`IntegrationCallFilters`(Task 6)与 Task 7 面板、Task 5 API 返回键一致。
diff --git a/frontend/src/features/admin/modules/integration-connector/IntegrationCallLogsPanel.spec.ts b/frontend/src/features/admin/modules/integration-connector/IntegrationCallLogsPanel.spec.ts
new file mode 100644
index 00000000..699ebaa4
--- /dev/null
+++ b/frontend/src/features/admin/modules/integration-connector/IntegrationCallLogsPanel.spec.ts
@@ -0,0 +1,212 @@
+/**
+ * features/admin/modules/integration-connector/IntegrationCallLogsPanel.spec.ts
+ * 用途:锁定集成调用日志面板行为——挂载即拉列表、筛选带参查询、行点击开抽屉呈现
+ *       wire 关键文本与步骤时间线、复制按钮按连接类型分流(soap=复制 curl,
+ *       database=复制 SQL 绑定内联)、wire_json 为 NULL 的历史行显示「无线级详情」。
+ * 依赖:vi.mock(./api/integration-connector.api)、@vue/test-utils、i18n。
+ * 逻辑:mock 列表固定返回 2 行(同 operation_id 两步),详情按用例切换 soap /
+ *       database / 无 wire 三种 wire_json 形态,断言渲染与复制链路。
+ */
+import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import i18n from '@/i18n';
+import IntegrationCallLogsPanel from './components/IntegrationCallLogsPanel.vue';
+import { getIntegrationCall, listIntegrationCalls } from './api/integration-connector.api';
+import type {
+  IntegrationCallDetail,
+  IntegrationCallLogRow,
+} from './types/integration-connector.types';
+
+vi.mock('./api/integration-connector.api', () => ({
+  listIntegrationCalls: vi.fn(),
+  getIntegrationCall: vi.fn(),
+}));
+
+const mockList = vi.mocked(listIntegrationCalls);
+const mockDetail = vi.mocked(getIntegrationCall);
+
+// 列表 2 行:同一次能力调用的 step0(database 成功)+ step1(soap 失败)
+const rows: IntegrationCallLogRow[] = [
+  {
+    id: 261, created_at: '2026-09-27T00:29:22', capability: 'in_transit_transfer.create_transfer',
+    operation_id: 'op-cbf5aaaa-1111', trace_id: 'ic-244fbbbb-2222', status: 'business_failed',
+    elapsed_ms: 324, business_ref: 'TGHX1-OR-26092600002', client_code: 'tiptop-ws',
+    interface_code: 'erp-ws-submit-transfer', connector_type: 'soap', step_index: 1, step_count: 2,
+  },
+  {
+    id: 260, created_at: '2026-09-27T00:29:21', capability: 'in_transit_transfer.create_transfer',
+    operation_id: 'op-cbf5aaaa-1111', trace_id: 'ic-244fbbbb-2222', status: 'success',
+    elapsed_ms: 2366, business_ref: null, client_code: 'erp-db',
+    interface_code: 'submit-stage-table', connector_type: 'database', step_index: 0, step_count: 2,
+  },
+];
+
+function makeDetail(call: Partial, wireJson: IntegrationCallDetail['call']['wire_json']): IntegrationCallDetail {
+  return {
+    call: {
+      id: 261, created_at: '2026-09-27T00:29:22', capability: 'in_transit_transfer.create_transfer',
+      operation_id: 'op-cbf5aaaa-1111', trace_id: 'ic-244fbbbb-2222', status: 'business_failed',
+      elapsed_ms: 324, business_ref: 'TGHX1-OR-26092600002',
+      binding_snapshot_json: {}, request_summary_json: { doc_no: 'TGHX1-OR-26092600002' },
+      response_summary_json: { code: 'HTTP_500' }, wire_json: wireJson,
+      ...call,
+    },
+    timeline: [
+      { id: 260, step_index: 0, step_count: 2, interface_code: 'submit-stage-table', status: 'success', elapsed_ms: 2366 },
+      { id: 261, step_index: 1, step_count: 2, interface_code: 'erp-ws-submit-transfer', status: 'business_failed', elapsed_ms: 324 },
+    ],
+  };
+}
+
+const soapDetail = makeDetail({}, {
+  kind: 'soap', method: 'POST', url: 'http://erp/WS?wsdl', soap_action: '"urn:CreateTransfer"',
+  request_body: 'demo',
+  http_status: 500, response_body: '',
+});
+
+const databaseDetail = makeDetail({ id: 260, status: 'success', elapsed_ms: 2366 }, {
+  kind: 'database',
+  statements: [{ phase: 'pre', sql: 'INSERT INTO t (batch) VALUES (:batch)', binds: { batch: 'B1' }, rowcount: 1, row_count: 1 }],
+  rowcount: 1,
+});
+
+const noWireDetail = makeDetail({}, null);
+
+function mountPanel() {
+  return mount(IntegrationCallLogsPanel, { global: { plugins: [i18n] } });
+}
+
+enableAutoUnmount(afterEach);
+
+describe('IntegrationCallLogsPanel', () => {
+  beforeEach(() => {
+    vi.clearAllMocks();
+    mockList.mockResolvedValue({ total: 2, page: 1, page_size: 20, items: rows });
+  });
+
+  it('挂载即拉取列表并渲染 2 行:时间/单号(business_ref 与 operation_id 前 8 位兜底)/步骤', async () => {
+    // [断言意图] 面板挂载必须自主触发列表查询,不依赖外部触发
+    const wrapper = mountPanel();
+    await flushPromises();
+    expect(mockList).toHaveBeenCalledTimes(1);
+    expect(wrapper.findAll('[data-testid="call-row"]')).toHaveLength(2);
+    // 行 261 有 business_ref:单号列显示业务单号
+    expect(wrapper.text()).toContain('TGHX1-OR-26092600002');
+    // 行 260 无 business_ref:单号列回退 operation_id 前 8 位
+    expect(wrapper.text()).toContain('op-cbf5a');
+    // 步骤列 1-based 展示(step_index 0/1 → 1/2、2/2)、状态徽章含原始状态值、耗时带 ms 后缀
+    expect(wrapper.text()).toContain('1/2');
+    expect(wrapper.text()).toContain('2/2');
+    expect(wrapper.text()).toContain('business_failed');
+    expect(wrapper.text()).toContain('2366ms');
+  });
+
+  it('填 interface_code 后点查询:带筛选参数且回第一页重新拉取', async () => {
+    // [断言意图] 筛选值必须原样进入 listIntegrationCalls 入参(querystring 由 api 层拼装)
+    const wrapper = mountPanel();
+    await flushPromises();
+    await wrapper.find('[data-testid="call-filter-interface"]').setValue('erp-ws-submit-transfer');
+    await wrapper.find('[data-testid="call-filter-query"]').trigger('click');
+    await flushPromises();
+    expect(mockList).toHaveBeenCalledTimes(2);
+    expect(mockList).toHaveBeenLastCalledWith(
+      expect.objectContaining({ interface_code: 'erp-ws-submit-transfer', page: 1, page_size: 20 }),
+    );
+  });
+
+  it('点行开详情抽屉:呈现 soap wire 关键文本、两步时间线与复制 operation_id 按钮', async () => {
+    // [断言意图] 抽屉必须展示线级事实原文(请求 body XML)与同 operation_id 的各步时间线
+    mockDetail.mockResolvedValue(soapDetail);
+    const wrapper = mountPanel();
+    await flushPromises();
+    await wrapper.findAll('[data-testid="call-row"]')[0].trigger('click');
+    await flushPromises();
+    expect(wrapper.find('[data-testid="call-detail-drawer"]').exists()).toBe(true);
+    expect(wrapper.text()).toContain('demo');
+    // 时间线两步均渲染(step1 / step2,1-based 展示),当前步高亮存在
+    expect(wrapper.text()).toContain('step1');
+    expect(wrapper.text()).toContain('step2');
+    expect(wrapper.text()).not.toContain('step0');
+    expect(wrapper.text()).toContain('submit-stage-table');
+    expect(wrapper.text()).toContain('erp-ws-submit-transfer');
+    expect(wrapper.find('[data-testid="call-copy-operation-id"]').exists()).toBe(true);
+  });
+
+  it('soap wire 出现复制 curl,点击后写入的命令含 url 与 SOAPAction', async () => {
+    // [断言意图] soap 连接类型只提供 curl 复现入口,命令由 buildCurl 生成(可直接粘贴 bash)
+    const writeText = vi.fn().mockResolvedValue(undefined);
+    Object.assign(navigator, { clipboard: { writeText } });
+    mockDetail.mockResolvedValue(soapDetail);
+    const wrapper = mountPanel();
+    await flushPromises();
+    await wrapper.findAll('[data-testid="call-row"]')[0].trigger('click');
+    await flushPromises();
+    const curlBtn = wrapper.find('[data-testid="call-copy-curl"]');
+    expect(curlBtn.exists()).toBe(true);
+    expect(wrapper.find('[data-testid="call-copy-sql"]').exists()).toBe(false);
+    await curlBtn.trigger('click');
+    await flushPromises();
+    expect(writeText).toHaveBeenCalledTimes(1);
+    const cmd = String(writeText.mock.calls[0][0]);
+    expect(cmd).toContain("curl -X POST 'http://erp/WS?wsdl'");
+    expect(cmd).toContain('SOAPAction');
+  });
+
+  it('database wire 出现复制 SQL(绑定已内联)且不出现复制 curl;写入类带环境警示', async () => {
+    // [断言意图] database 连接类型只提供 SQL 复现入口,:batch 绑定必须内联为字面量
+    const writeText = vi.fn().mockResolvedValue(undefined);
+    Object.assign(navigator, { clipboard: { writeText } });
+    mockDetail.mockResolvedValue(databaseDetail);
+    const wrapper = mountPanel();
+    await flushPromises();
+    await wrapper.findAll('[data-testid="call-row"]')[1].trigger('click');
+    await flushPromises();
+    const sqlBtn = wrapper.find('[data-testid="call-copy-sql"]');
+    expect(sqlBtn.exists()).toBe(true);
+    expect(wrapper.find('[data-testid="call-copy-curl"]').exists()).toBe(false);
+    expect(wrapper.find('[data-testid="call-sql-write-warning"]').exists()).toBe(true);
+    await sqlBtn.trigger('click');
+    await flushPromises();
+    expect(writeText).toHaveBeenCalledWith(expect.stringContaining("INSERT INTO t (batch) VALUES ('B1')"));
+  });
+
+  it('wire_json 为 NULL 的历史行:抽屉显示「无线级详情(历史记录)」且无复制 body/raw 入口', async () => {
+    // [断言意图] 历史存量不回填,前端必须如实显示无线级详情而非留白或报错
+    mockDetail.mockResolvedValue(noWireDetail);
+    const wrapper = mountPanel();
+    await flushPromises();
+    await wrapper.findAll('[data-testid="call-row"]')[0].trigger('click');
+    await flushPromises();
+    expect(wrapper.find('[data-testid="call-no-wire"]').exists()).toBe(true);
+    expect(wrapper.text()).toContain('无线级详情(历史记录)');
+    expect(wrapper.find('[data-testid="call-copy-body"]').exists()).toBe(false);
+    expect(wrapper.find('[data-testid="call-copy-raw"]').exists()).toBe(false);
+  });
+
+  it('状态下拉与后端 RESULT_STATUSES 七值对齐;duplicate_success 绿 / duplicate_unverified 红', async () => {
+    // [断言意图] 幂等重放审计行落入 duplicate_* 状态,筛选下拉缺值会导致该类日志无法筛出
+    mockList.mockResolvedValue({
+      total: 2, page: 1, page_size: 20,
+      items: [
+        { ...rows[0], id: 270, status: 'duplicate_success', business_ref: null, interface_code: 'if-dup-ok' },
+        { ...rows[0], id: 271, status: 'duplicate_unverified', business_ref: null, interface_code: 'if-dup-unverified' },
+      ],
+    });
+    const wrapper = mountPanel();
+    await flushPromises();
+    const options = wrapper.find('[data-testid="call-filter-status"]').findAll('option')
+      .map((o) => o.element.value).filter((v) => v !== '');
+    expect(options).toEqual([
+      'success', 'duplicate_success', 'duplicate_unverified',
+      'business_failed', 'technical_failed', 'timeout', 'result_unknown',
+    ]);
+    // [断言意图] 成功族判定:duplicate_success(幂等重放命中,业务已成功)徽章走绿色成功侧
+    const dupOkRow = wrapper.findAll('[data-testid="call-row"]')[0];
+    expect(dupOkRow.text()).toContain('duplicate_success');
+    expect(dupOkRow.find('span.bg-green-100').exists()).toBe(true);
+    // [断言意图] duplicate_unverified(回执未核实)保守归非成功态,徽章保持红色 ✗
+    const dupUnknownRow = wrapper.findAll('[data-testid="call-row"]')[1];
+    expect(dupUnknownRow.text()).toContain('duplicate_unverified');
+    expect(dupUnknownRow.find('span.bg-red-100').exists()).toBe(true);
+  });
+});
diff --git a/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts
index a2db1a8e..43894651 100644
--- a/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts
+++ b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts
@@ -23,11 +23,15 @@ const mockState = vi.hoisted(() => {
   const bindings = [
     {
       id: 1, capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
-      client_instance_code: '1001', interface_definition_code: 'IF-A',
+      client_instance_code: '1001', interface_definition_code: 'IF-A', steps_json: [],
+      param_mapping_json: {},
       mapping_version: 1, priority: 0, environment: 'prod',
       effective_from: null, effective_to: null, status: 'published',
     },
   ];
+  const interfaces: Array> = [];
+  const clients: Array> = [];
+  let activeEntity = 'credential';
   const credentials = [
     {
       id: 1, code: 'tiptop-erp', secret_ref: 'db:tiptop-erp', secret_provider: 'db',
@@ -41,14 +45,14 @@ const mockState = vi.hoisted(() => {
     },
   ];
   const noop = () => vi.fn();
-  return { credentials, capabilities, bindings };
+  return { credentials, capabilities, bindings, interfaces, clients, get activeEntity() { return activeEntity; }, set activeEntity(v: string) { activeEntity = v; } };
 });
 
 vi.mock('./composables/useIntegrationConnectorAdmin', () => ({
   useIntegrationConnectorAdmin: () => ({
-    clients: ref([]), interfaces: ref([]), bindings: ref(mockState.bindings),
+    clients: ref(mockState.clients), interfaces: ref(mockState.interfaces), bindings: ref(mockState.bindings),
     credentials: ref(mockState.credentials), capabilities: ref(mockState.capabilities), credentialTypes: ref([]),
-    isLoading: ref(false), activeEntity: ref('credential'), showFormModal: ref(false), isSaving: ref(false),
+    isLoading: ref(false), activeEntity: ref(mockState.activeEntity), showFormModal: ref(false), isSaving: ref(false),
     clientForm: ref(createEmptyClientInstanceForm()),
     interfaceForm: ref(createEmptyInterfaceDefinitionForm()),
     bindingForm: ref(createEmptyBindingForm()),
@@ -133,4 +137,47 @@ describe('IntegrationConnectorPage credential list', () => {
     expect(text).toContain('在途库存查询');
     expect(text).toContain('in_transit_transfer.query_inventory');
   });
+
+  it('绑定列表按有序步骤渲染接口链与每步客户端;steps_json 为空的存量行走旧列兜底', async () => {
+    const ifaceRow = (id: number, code: string, name: string, clientCode: string) => ({
+      id, code, name, client_instance_code: clientCode, connector_type: 'rest', http_method: null,
+      request_path: null, request_spec_json: {}, input_schema_json: {}, response_mapping_json: {},
+      output_schema_json: {}, version: 1, status: 'published', enabled: true,
+    });
+    const clientRow = (id: number, code: string, name: string) => ({
+      id, code, name, connector_type: 'rest', environment: 'prod', endpoint: null,
+      timeout_seconds: null, config_json: {}, credential_ref_code: null, enabled: true,
+    });
+    mockState.interfaces = [ifaceRow(1, 'IF-A', '写入中间表', 'CLI-1'), ifaceRow(2, 'IF-B', '回读结果', 'CLI-2')] as never;
+    mockState.clients = [clientRow(1, 'CLI-1', '生产库'), clientRow(2, 'CLI-2', '生产接口')] as never;
+    mockState.bindings = [{
+      id: 9, capability: 'cap.multi', context_selector_json: {},
+      steps_json: [{ interface_code: 'IF-A', param_mapping_json: {} }, { interface_code: 'IF-B', param_mapping_json: {} }],
+      param_mapping_json: {}, client_instance_code: 'CLI-1', interface_definition_code: 'IF-A',
+      mapping_version: 1, priority: 0, environment: 'prod', effective_from: null, effective_to: null, status: 'published',
+    }] as never;
+    const wrapper = mountPage();
+    const bindTab = wrapper.findAll('[role="tab"]').find((b) => b.text() === '绑定')!;
+    await bindTab.trigger('click');
+    const text = wrapper.text();
+    // 两步全部渲染(编号 + 接口名),每步客户端与接口逐步对齐;列头为「接口步骤(有序)」
+    expect(text).toContain('写入中间表');
+    expect(text).toContain('回读结果');
+    expect(text).toContain('生产库');
+    expect(text).toContain('生产接口');
+    expect(wrapper.findAll('th').some((th) => th.text().includes('接口步骤'))).toBe(true);
+
+    // 存量行兜底:steps_json 为空时由旧单步列合成一步
+    mockState.bindings = [{
+      id: 10, capability: 'cap.single', context_selector_json: {}, steps_json: [],
+      param_mapping_json: {}, client_instance_code: 'CLI-1', interface_definition_code: 'IF-A',
+      mapping_version: 1, priority: 0, environment: 'prod', effective_from: null, effective_to: null, status: 'draft',
+    }] as never;
+    const legacy = mountPage();
+    const legacyTab = legacy.findAll('[role="tab"]').find((b) => b.text() === '绑定')!;
+    await legacyTab.trigger('click');
+    expect(legacy.text()).toContain('写入中间表');
+    expect(legacy.text()).not.toContain('回读结果');
+    mockState.bindings = [];
+  });
 });
diff --git a/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue
index 4ef2504f..275471f7 100644
--- a/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue
+++ b/frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue
@@ -1,7 +1,8 @@
 
+                

+ {{ idx + 1 }}.{{ clientNameOf(step.client_code) || step.client_code }} +

-

{{ interfaceNameOf(row.interface_definition_code) || row.interface_definition_code }}

-

{{ row.interface_definition_code }}

+ +

+ {{ idx + 1 }}.{{ interfaceNameOf(step.interface_code) || step.interface_code }} +

{{ statusLabel(row.status) }} @@ -478,6 +498,9 @@ function selectTab(key: TabKey) { + + +
diff --git a/frontend/src/features/admin/modules/integration-connector/api/integration-connector.api.ts b/frontend/src/features/admin/modules/integration-connector/api/integration-connector.api.ts index 8ddf6a59..5510df62 100644 --- a/frontend/src/features/admin/modules/integration-connector/api/integration-connector.api.ts +++ b/frontend/src/features/admin/modules/integration-connector/api/integration-connector.api.ts @@ -1,6 +1,6 @@ /** * features/admin/modules/integration-connector/api/integration-connector.api.ts - * 集成连接器管理 API 客户端:客户端实例/接口定义/绑定/凭据引用 CRUD + 能力清单 + 连接测试。 + * 集成连接器管理 API 客户端:客户端实例/接口定义/绑定/凭据引用 CRUD + 能力清单 + 连接测试 + 调用日志查询。 * 依赖:@/shared/api/client(requestJson / BusinessError)、@/shared/utils/auth。 * 逻辑:薄封装后端 /api/integration-connector/* 全部端点;JSON 写请求带 Content-Type。 * 错误码(INTEGRATION.*)由 requestJson 解析到四语言文案。 @@ -9,6 +9,9 @@ import { requestJson } from '@/shared/api/client'; import { getAuthHeaders } from '@/shared/utils/auth'; import type { IntegrationBindingRow, + IntegrationCallDetail, + IntegrationCallFilters, + IntegrationCallLogRow, IntegrationCallResultRow, IntegrationCapabilityRow, IntegrationClientInstanceRow, @@ -121,3 +124,31 @@ export const updateIntegrationCredentialReference = (code: string, payload: Reco requestJson(`${BASE}/credential-references/${encodeURIComponent(code)}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload), }); + +// ---- 调用日志 ---- + +/** + * 把调用日志筛选对象序列化为 querystring。 + * 约束:过滤 undefined / null / 空串(空筛选拼出无参 URL);数字(page/page_size)转字符串。 + * 返回值:形如 `?a=1&b=2`(无有效参数时为空串),直接拼接在端点路径后。 + */ +function buildCallLogQuery(filters: IntegrationCallFilters): string { + const search = new URLSearchParams(); + Object.entries(filters).forEach(([key, value]) => { + if (value === undefined || value === null || String(value).trim() === '') return; + search.set(key, String(value)); + }); + const qs = search.toString(); + return qs ? `?${qs}` : ''; +} + +/** 集成调用日志分页查询(能力无关;keyword 对请求摘要 JSON 模糊)。 */ +export const listIntegrationCalls = (filters: IntegrationCallFilters = {}) => + requestJson<{ total: number; page: number; page_size: number; items: IntegrationCallLogRow[] }>( + `${BASE}/calls${buildCallLogQuery(filters)}`, + auth(), + ); + +/** 调用全量详情(含 wire_json 与同 operation_id 步骤时间线)。 */ +export const getIntegrationCall = (id: number) => + requestJson(`${BASE}/calls/${id}`, auth()); diff --git a/frontend/src/features/admin/modules/integration-connector/components/IntegrationCallLogsPanel.vue b/frontend/src/features/admin/modules/integration-connector/components/IntegrationCallLogsPanel.vue new file mode 100644 index 00000000..8d1c96bc --- /dev/null +++ b/frontend/src/features/admin/modules/integration-connector/components/IntegrationCallLogsPanel.vue @@ -0,0 +1,493 @@ + + + + diff --git a/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts b/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts index d8e7c916..cda7a427 100644 --- a/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts +++ b/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts @@ -1,8 +1,9 @@ /** * features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts * 用途:锁定表单按连接器类型动态显示字段——REST 显示超时/HTTP方法/请求路径, - * SOAP 显示 WSDL;以及抽屉化后的 JSON 编辑字段(格式化/失焦校验)、 - * 脏检查关闭确认与 Esc 关闭行为。 + * SOAP 显示 WSDL,database 显示 db_kind 专属下拉与数据库连接串 label; + * 绑定表单的有序步骤编辑器(添加/删除/上移下移/每步独立参数映射); + * 以及抽屉化后的 JSON 编辑字段(格式化/失焦校验)、脏检查关闭确认与 Esc 关闭行为。 * 依赖:@vue/test-utils、vitest、i18n。 * 逻辑:切换 connector_type 断言字段可见性;对 JsonTextareaField 断言格式化改写 * 与非法 JSON 提示;mock window.confirm 断言脏表单关闭拦截与放行。 @@ -13,11 +14,13 @@ import i18n from '@/i18n'; import IntegrationConnectorFormDrawer from './IntegrationConnectorFormDrawer.vue'; import JsonTextareaField from './JsonTextareaField.vue'; import { + bindingRowToForm, createEmptyClientInstanceForm, createEmptyInterfaceDefinitionForm, createEmptyBindingForm, createEmptyCredentialReferenceForm, type InterfaceDefinitionFormState, + type IntegrationBindingRow, } from '../types/integration-connector.types'; enableAutoUnmount(afterEach); @@ -117,7 +120,7 @@ describe('IntegrationConnectorFormDrawer connector-type fields', () => { expect(chip.attributes('title')).toContain('发布'); }); - it('绑定:选定接口定义后客户端实例自动带出并锁定', async () => { + it('绑定:添加步骤并选接口后,只读提示该步接口归属的客户端实例', async () => { const bindingForm = createEmptyBindingForm(); const wrapper = mountDrawer({ activeEntity: 'binding', @@ -128,12 +131,12 @@ describe('IntegrationConnectorFormDrawer connector-type fields', () => { ], interfaceOptions: [{ code: '1001-iface', name: '接口A', client_instance_code: '1001' }], }); - // 未选接口定义前客户端实例可维护 - expect(wrapper.find('[data-testid="binding-client"]').attributes('disabled')).toBeUndefined(); - await wrapper.find('[data-testid="binding-interface"]').setValue('1001-iface'); - // 选定接口定义后:客户端实例按接口归属联动带出且锁定 - expect(bindingForm.client_instance_code).toBe('1001'); - expect(wrapper.find('[data-testid="binding-client"]').attributes('disabled')).toBeDefined(); + // 绑定表单不再单独维护客户端实例下拉(client 由各步接口归属自带) + expect(wrapper.find('[data-testid="binding-client"]').exists()).toBe(false); + // 添加一步并选择接口定义 → 只读提示其归属客户端实例 + await wrapper.find('[data-testid="binding-add-step"]').trigger('click'); + await wrapper.find('[data-testid="binding-step-interface-0"]').setValue('1001-iface'); + expect(wrapper.find('[data-testid="binding-step-client-0"]').text()).toContain('1001'); }); it('绑定能力下拉选项本地化:有翻译显示「中文名(注册名)」,无翻译兜底注册名', () => { @@ -153,6 +156,143 @@ describe('IntegrationConnectorFormDrawer connector-type fields', () => { }); }); +describe('IntegrationConnectorFormDrawer database connector type', () => { + it('类型下拉含「数据库直连」;选中后显示 db_kind 四选一下拉、数据库连接串 label,超时照显', async () => { + const wrapper = mountDrawer(); + const typeOptions = wrapper.find('[data-testid="client-connector-type"]').findAll('option'); + expect(typeOptions.map((o) => o.text())).toEqual(['REST API', 'SOAP 服务', '数据库直连']); + // 非 database 类型不渲染 db_kind 下拉 + expect(wrapper.find('[data-testid="client-db-kind"]').exists()).toBe(false); + await wrapper.find('[data-testid="client-connector-type"]').setValue('database'); + const dbKind = wrapper.find('[data-testid="client-db-kind"]'); + expect(dbKind.exists()).toBe(true); + // db_kind 专属下拉四选一(含未选占位项),label 即库名 + expect(dbKind.findAll('option').map((o) => o.text())).toEqual(['—', 'MySQL', 'Oracle', 'SQL Server', 'PostgreSQL']); + // endpoint label 切换为数据库连接串语义;超时字段照常显示 + const labels = wrapper.findAll('label').map((l) => l.text()); + expect(labels.some((t) => t.includes('数据库连接串'))).toBe(true); + expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true); + }); + + it('database 类型不显示 HTTP 方法/请求路径(接口表单随客户端联动 database 类型)', async () => { + const interfaceForm = createEmptyInterfaceDefinitionForm(); + const wrapper = mountDrawer({ + activeEntity: 'interface', + interfaceForm, + clientOptions: [{ code: 'erp-db', name: 'ERP Oracle', connector_type: 'database' }], + }); + await wrapper.find('[data-testid="interface-client"]').setValue('erp-db'); + // 接口类型随客户端联动为 database + expect(interfaceForm.connector_type).toBe('database'); + const labels = wrapper.findAll('label').map((l) => l.text()); + expect(labels.some((t) => t.includes('HTTP 方法'))).toBe(false); + expect(labels.some((t) => t.includes('请求路径'))).toBe(false); + // 类型只读下拉显示本地化 database 文案 + expect(wrapper.find('[data-testid="interface-connector-type"]').text()).toContain('数据库直连'); + }); + + it('切回非 database 类型后 db_kind 下拉隐藏且残留值清空', async () => { + const clientForm = createEmptyClientInstanceForm(); + const wrapper = mountDrawer({ clientForm }); + await wrapper.find('[data-testid="client-connector-type"]').setValue('database'); + await wrapper.find('[data-testid="client-db-kind"]').setValue('oracle'); + expect(clientForm.db_kind).toBe('oracle'); + await wrapper.find('[data-testid="client-connector-type"]').setValue('rest'); + expect(wrapper.find('[data-testid="client-db-kind"]').exists()).toBe(false); + expect(clientForm.db_kind).toBe(''); + }); + + it('database 类型高级配置提示列出生效键 oracle_lib_dir', async () => { + const wrapper = mountDrawer(); + await wrapper.find('[data-testid="client-connector-type"]').setValue('database'); + expect(wrapper.text()).toContain('"oracle_lib_dir"'); + }); +}); + +describe('IntegrationConnectorFormDrawer binding steps editor', () => { + function mountBinding(overrides: Partial> = {}) { + return mountDrawer({ + activeEntity: 'binding', + clientOptions: [ + { code: 'erp-db', name: 'ERP Oracle', connector_type: 'database' }, + { code: 'tiptop-ws', name: '鼎捷WS', connector_type: 'soap' }, + ], + interfaceOptions: [ + { code: 'IF-STAGE', name: '写中间表', client_instance_code: 'erp-db' }, + { code: 'IF-SUBMIT', name: '触发WS', client_instance_code: 'tiptop-ws' }, + ], + ...overrides, + }); + } + + it('接口从单选改为有序多选:添加两步,每步独立接口下拉与归属客户端只读提示', async () => { + const bindingForm = createEmptyBindingForm(); + const wrapper = mountBinding({ bindingForm }); + // 空态无步骤行 + expect(wrapper.findAll('[data-testid="binding-step-row"]').length).toBe(0); + // 添加两步 + await wrapper.find('[data-testid="binding-add-step"]').trigger('click'); + await wrapper.find('[data-testid="binding-add-step"]').trigger('click'); + expect(bindingForm.steps).toHaveLength(2); + await wrapper.find('[data-testid="binding-step-interface-0"]').setValue('IF-STAGE'); + await wrapper.find('[data-testid="binding-step-interface-1"]').setValue('IF-SUBMIT'); + // 每步显示归属客户端只读提示(跨客户端步骤:database + soap) + expect(wrapper.find('[data-testid="binding-step-client-0"]').text()).toContain('erp-db'); + expect(wrapper.find('[data-testid="binding-step-client-1"]').text()).toContain('tiptop-ws'); + }); + + it('上移/下移重排步骤顺序;首步无上移、末步无下移(禁用)', async () => { + const bindingForm = createEmptyBindingForm(); + const wrapper = mountBinding({ bindingForm }); + await wrapper.find('[data-testid="binding-add-step"]').trigger('click'); + await wrapper.find('[data-testid="binding-add-step"]').trigger('click'); + await wrapper.find('[data-testid="binding-step-interface-0"]').setValue('IF-STAGE'); + await wrapper.find('[data-testid="binding-step-interface-1"]').setValue('IF-SUBMIT'); + expect(wrapper.find('[data-testid="binding-step-up-0"]').attributes('disabled')).toBeDefined(); + expect(wrapper.find('[data-testid="binding-step-down-1"]').attributes('disabled')).toBeDefined(); + // 下移首步 → 顺序翻转 + await wrapper.find('[data-testid="binding-step-down-0"]').trigger('click'); + expect(bindingForm.steps[0].interface_code).toBe('IF-SUBMIT'); + expect(bindingForm.steps[1].interface_code).toBe('IF-STAGE'); + // 再上移还原 + await wrapper.find('[data-testid="binding-step-up-1"]').trigger('click'); + expect(bindingForm.steps[0].interface_code).toBe('IF-STAGE'); + expect(bindingForm.steps[1].interface_code).toBe('IF-SUBMIT'); + }); + + it('删除步骤移除对应行;每步参数映射独立编辑写回对应步骤', async () => { + const bindingForm = createEmptyBindingForm(); + const wrapper = mountBinding({ bindingForm }); + await wrapper.find('[data-testid="binding-add-step"]').trigger('click'); + await wrapper.find('[data-testid="binding-add-step"]').trigger('click'); + // 每步独立的 param_mapping JSON 编辑(沿用 JsonTextareaField 交互) + const stepRows = wrapper.findAll('[data-testid="binding-step-row"]'); + await stepRows[0].findComponent(JsonTextareaField).find('[data-testid="json-textarea"]') + .setValue('{"erp_org":{"expr":"external_org"}}'); + expect(bindingForm.steps[0].param_mapping_json).toBe('{"erp_org":{"expr":"external_org"}}'); + expect(bindingForm.steps[1].param_mapping_json).toBe(''); + // 删除首步 → 只剩原第二步 + await wrapper.find('[data-testid="binding-step-remove-0"]').trigger('click'); + expect(bindingForm.steps).toHaveLength(1); + expect(wrapper.findAll('[data-testid="binding-step-row"]').length).toBe(1); + }); + + it('既有单接口绑定编辑回归:steps_json 单步行回显为一步且接口预选', () => { + const bindingForm = bindingRowToForm({ + id: 5, capability: 'in_transit_transfer.create_transfer', context_selector_json: {}, + steps_json: [{ interface_code: 'IF-STAGE', param_mapping_json: { erp_org: { expr: 'external_org' } } }], + param_mapping_json: { erp_org: { expr: 'external_org' } }, + client_instance_code: 'erp-db', interface_definition_code: 'IF-STAGE', + mapping_version: 1, priority: 0, environment: 'prod', + effective_from: null, effective_to: null, status: 'draft', + } as IntegrationBindingRow); + const wrapper = mountBinding({ bindingForm }); + expect(wrapper.findAll('[data-testid="binding-step-row"]').length).toBe(1); + expect((wrapper.find('[data-testid="binding-step-interface-0"]').element as HTMLSelectElement).value).toBe('IF-STAGE'); + expect(wrapper.find('[data-testid="binding-step-client-0"]').text()).toContain('erp-db'); + }); +}); + describe('IntegrationConnectorFormDrawer JSON fields', () => { function findJsonField(wrapper: ReturnType, labelPart: string) { const field = wrapper @@ -363,7 +503,7 @@ describe('IntegrationConnectorFormDrawer client form redesign', () => { const code = wrapper.find('[data-testid="client-code"]'); expect((code.element as HTMLInputElement).disabled).toBe(true); const typeOptions = wrapper.find('[data-testid="client-connector-type"]').findAll('option'); - expect(typeOptions.map((o) => o.text())).toEqual(['REST API', 'SOAP 服务']); + expect(typeOptions.map((o) => o.text())).toEqual(['REST API', 'SOAP 服务', '数据库直连']); const envOptions = wrapper.find('[data-testid="client-environment"]').findAll('option'); expect(envOptions.map((o) => o.text())).toEqual(['开发', '测试', '生产']); }); diff --git a/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue b/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue index 4a430a48..bdc827b0 100644 --- a/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue +++ b/frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue @@ -7,10 +7,13 @@ 客户端编码留空时按名称自动建议、 接口编码留空时按「客户端实例编码-名称」自动建议(均可手改,已填不覆盖,编辑态编码锁定); 客户端实例的连接器类型/环境/凭据引用均为下拉(选项来自模块常量与凭据列表,未知值兜底); + connector_type=database 时显示 db_kind 专属四选一下拉(必填校验在 composable 提交层), + endpoint label 按类型切换(REST=接口地址 / SOAP=WSDL / database=数据库连接串),切离 database 清空 db_kind; 接口定义的连接器类型随所选客户端实例联动只读展示(提交由后端以客户端为准推导); - 绑定的客户端实例随所选接口定义联动带出并锁定(接口归属即客户端归属); + 绑定的接口为有序步骤编辑器:添加/删除/上移下移,每步独立 param_mapping JSON, + 步骤归属客户端以只读提示展示(client 由各步接口自带,表单不再单独维护); 绑定表单的能力下拉选项本地化为「中文名(注册名)」(未注册翻译兜底注册名); - 接口与绑定的状态均为只读徽章(发布/退役走列表生命周期按钮),四个 JSON 契约字段常显不折叠; + 接口与绑定的状态均为只读徽章(发布/退役走列表生命周期按钮),JSON 契约字段常显不折叠; 凭据引用:状态不进表单(由列表生命周期按钮流转);编辑态以「基本信息」只读信息区 展示编码/类型/来源/状态(label+值行,与接口定义只读字段同款式),新建态下拉选项 文案本地化与列表一致;高级配置帮助文案按连接器类型的生效键动态切换。 @@ -24,6 +27,7 @@ import JsonTextareaField from './JsonTextareaField.vue'; import { CONNECTOR_CONFIG_KEYS, CONNECTOR_TYPE_OPTIONS, + DB_KIND_OPTIONS, ENVIRONMENT_OPTIONS, suggestClientCode, suggestInterfaceCode, @@ -33,6 +37,7 @@ import type { ClientInstanceFormState, CredentialReferenceFormState, InterfaceDefinitionFormState, + IntegrationConnectorType, } from '../types/integration-connector.types'; const props = defineProps<{ @@ -43,9 +48,9 @@ const props = defineProps<{ bindingForm: BindingFormState; credentialForm: CredentialReferenceFormState; isSaving: boolean; - /** 客户端实例选项:connector_type 供接口表单联动展示连接器类型。 */ + /** 客户端实例选项:connector_type 供接口表单联动展示连接器类型;name 供步骤 client 只读提示。 */ clientOptions: Array<{ code: string; name: string; connector_type?: string }>; - /** 接口定义选项:client_instance_code 供绑定表单联动带出客户端实例。 */ + /** 接口定义选项:client_instance_code 供绑定步骤的归属客户端只读提示。 */ interfaceOptions: Array<{ code: string; name: string; client_instance_code?: string }>; capabilityOptions: Array<{ name: string }>; credentialTypeOptions: Array<{ type: string; fields: Array<{ key: string; secret: boolean; required: boolean }> }>; @@ -103,6 +108,30 @@ function capabilityOptionLabel(name: string) { return label === name ? name : `${label}(${name})`; } +/** + * 切换客户端实例的连接器类型:非 database 类型清空 db_kind 残留值, + * 避免切走后旧值随保存提交(database 时 db_kind 必填,校验在 composable 提交层)。 + */ +function onConnectorTypeChange() { + if (props.clientForm.connector_type !== 'database') { + props.clientForm.db_kind = ''; + } +} + +/** 连接地址 label 按类型切换:REST=接口地址 / SOAP=WSDL 地址 / database=数据库连接串。 */ +const endpointLabelKey = computed(() => { + if (props.clientForm.connector_type === 'database') return 'admin.integrationConnector.endpointLabel.database'; + if (props.clientForm.connector_type === 'soap') return 'admin.integrationConnector.fields.wsdl'; + return 'admin.integrationConnector.fields.endpoint'; +}); + +/** 连接地址占位符随 label 同步切换(示例格式按类型区分)。 */ +const endpointPlaceholderKey = computed(() => { + if (props.clientForm.connector_type === 'database') return 'admin.integrationConnector.placeholders.database'; + if (props.clientForm.connector_type === 'soap') return 'admin.integrationConnector.placeholders.wsdl'; + return 'admin.integrationConnector.placeholders.endpoint'; +}); + /** 接口编码仍为空且已选客户端实例时,按「客户端编码-名称」补建议(已手填不覆盖)。 */ function suggestInterfaceCodeIfEmpty() { const form = props.interfaceForm; @@ -119,21 +148,45 @@ function onInterfaceNameBlur() { /** 切换接口的客户端实例:联动展示其连接器类型(仅展示,提交由后端以客户端为准推导),并补编码建议。 */ function onInterfaceClientChange() { const selected = props.clientOptions.find((item) => item.code === props.interfaceForm.client_instance_code); - if (selected?.connector_type === 'rest' || selected?.connector_type === 'soap') { - props.interfaceForm.connector_type = selected.connector_type; + const type = selected?.connector_type as IntegrationConnectorType | undefined; + if (type && CONNECTOR_TYPE_OPTIONS.some((opt) => opt.value === type)) { + props.interfaceForm.connector_type = type; } suggestInterfaceCodeIfEmpty(); } +// ---- 绑定有序步骤编辑器:接口从单选改为有序多选,client 由各步接口归属自带 ---- + +/** 添加步骤:追加到末尾(新步骤默认未选接口、空映射)。 */ +function addBindingStep() { + props.bindingForm.steps.push({ interface_code: '', param_mapping_json: '' }); +} + +/** 删除指定步骤(按索引,删除后后续步骤序号自动前移)。 */ +function removeBindingStep(index: number) { + props.bindingForm.steps.splice(index, 1); +} + /** - * 切换绑定的接口定义:联动带出其所属客户端实例并锁定(接口归属即客户端归属)。 - * 后端创建/更新仍做成对校验(INTEGRATION.BINDING_PAIR_MISMATCH)兜底直连 API 的场景。 + * 上移/下移指定步骤:delta=-1 上移、+1 下移;越界直接忽略(按钮层已禁用,双保险)。 */ -function onBindingInterfaceChange() { - const selected = props.interfaceOptions.find((item) => item.code === props.bindingForm.interface_definition_code); - if (selected?.client_instance_code) { - props.bindingForm.client_instance_code = selected.client_instance_code; - } +function moveBindingStep(index: number, delta: number) { + const target = index + delta; + const steps = props.bindingForm.steps; + if (target < 0 || target >= steps.length) return; + const [moved] = steps.splice(index, 1); + if (!moved) return; + steps.splice(target, 0, moved); +} + +/** 步骤归属客户端只读提示:由接口定义归属唯一确定(跨步可不同客户端,如 database+soap)。 */ +function bindingStepClientHint(index: number): string { + const step = props.bindingForm.steps[index]; + const iface = props.interfaceOptions.find((item) => item.code === step?.interface_code); + if (!iface?.client_instance_code) return ''; + const client = props.clientOptions.find((item) => item.code === iface.client_instance_code); + const clientLabel = client ? optionLabel(client.name, client.code) : iface.client_instance_code; + return t('admin.integrationConnector.bindingSteps.clientHint', { client: clientLabel }); } /** 高级配置示例(JSON 属代码示例,不入 i18n——字面大括号会破坏 vue-i18n 消息编译)。 */ @@ -269,10 +322,18 @@ onBeforeUnmount(() => document.removeEventListener('keydown', onKeydown));
-
+
+ + + +
+ +
@@ -377,7 +438,7 @@ onBeforeUnmount(() => document.removeEventListener('keydown', onKeydown)); - +