- 新增 database 传输:直连 MySQL/Oracle/SQLServer/PostgreSQL 执行绑定 SQL(新增 pymysql/pymssql 驱动依赖) - 绑定支持 steps_json 多步编排:每步独立传输调用与审计,无 steps 的既有绑定走单步兼容路径 - 客户端实例校验 connector_type ∈ rest/soap/database,database 强制 db_kind 白名单,非 database 置空 - 三个传输层捕获线级事实(最终 SQL/渲染后 XML/原始响应)随调用记录落库,引擎可选透传 business_ref 业务锚点 - 新增调用日志查询 API(列表/详情/同 operation 步骤时间线,仅管理员)与管理端「调用日志」tab:筛选、双栏对照、外部工具复现命令 - 迁移 tt7a/tta9/tt5b:连接器类型枚举、绑定 steps_json、放开 calls 操作唯一约束 - 说明:wire_json 列迁移挂链尾(依赖域表迁移),随后续批次单独落地
1063 lines
49 KiB
Python
1063 lines
49 KiB
Python
"""api/integration_connector.py
|
||
|
||
用途: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
|
||
转移(绑定发布附加就绪门禁:每步接口须已发布且每步客户端启用);绑定以
|
||
steps_json 有序数组表达一对多配方(每步 interface_code + param_mapping_json),
|
||
客户端由各步接口归属自带;旧单步字段可合成单元素 steps(兼容窗)。
|
||
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
|
||
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
|
||
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
|
||
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
|
||
/api/integration Dify 文件代理)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import uuid
|
||
|
||
from flask import Blueprint, request
|
||
|
||
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
|
||
from app.core.decorators import require_admin
|
||
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,
|
||
get_credential_type,
|
||
list_credential_types,
|
||
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,
|
||
resolve_credential,
|
||
)
|
||
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
|
||
|
||
integration_connector_bp = Blueprint('integration_connector', __name__)
|
||
|
||
# 与模型 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),「轮换中」
|
||
# 现语义等于断供且真实版本化轮换未实现(属 P2),故 PUT 只允许在 active/retired 间切换,
|
||
# rotating 不再可进入;存量 rotating 数据保留只读展示,经 PUT 置 active 即恢复。
|
||
VALID_CREDENTIAL_UI_STATUSES = ('active', 'retired')
|
||
|
||
# 配置实体生命周期转移表(接口定义与绑定共用):动作 → (源状态, 目标状态)。状态不再
|
||
# 由 PUT 直接改写,只能经动作端点按此表转移(draft→published 发布;published→draft 撤回;
|
||
# published→retired 退役;retired→draft 恢复为草稿,作为无版本化阶段的保险阀)。
|
||
CONFIG_STATUS_TRANSITIONS = {
|
||
'publish': ('draft', 'published'),
|
||
'unpublish': ('published', 'draft'),
|
||
'retire': ('published', 'retired'),
|
||
'reopen': ('retired', 'draft'),
|
||
}
|
||
|
||
|
||
def _require(value, field: str) -> None:
|
||
"""字段必填校验。"""
|
||
if value is None or (isinstance(value, str) and not value.strip()):
|
||
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()
|
||
if client is None:
|
||
raise ValidationError(
|
||
'client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND',
|
||
details={'client_instance_code': code},
|
||
)
|
||
return client
|
||
|
||
|
||
def _apply_status_transition(entity, action: str, *, kind: str) -> None:
|
||
"""按转移表校验并落库状态;非法动作或源状态不符即 400。"""
|
||
transition = CONFIG_STATUS_TRANSITIONS.get(action)
|
||
if transition is None:
|
||
raise ValidationError(
|
||
'unknown lifecycle action', details={'allowed': sorted(CONFIG_STATUS_TRANSITIONS)})
|
||
src, dst = transition
|
||
if entity.status != src:
|
||
raise ValidationError(
|
||
f'{kind} status is {entity.status}, cannot {action}',
|
||
code='INTEGRATION.ILLEGAL_STATUS_TRANSITION',
|
||
details={'action': action, 'from': entity.status, 'to': dst},
|
||
)
|
||
entity.status = dst
|
||
|
||
|
||
def _require_interface(code: str) -> IntegrationInterfaceDefinition:
|
||
"""按编码取接口定义;不存在即 400(绑定成对校验以其所属客户端为准,而非依赖外键报 500)。"""
|
||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||
if iface is None:
|
||
raise ValidationError(
|
||
'interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND',
|
||
details={'interface_definition_code': code},
|
||
)
|
||
return iface
|
||
|
||
|
||
def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClientInstance, IntegrationInterfaceDefinition]:
|
||
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
|
||
|
||
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
|
||
400(fail-fast),不留给调用期 fail-closed。多步绑定时仅用于可选的绑定级
|
||
client_instance_code 与首步接口的一致性检查。
|
||
"""
|
||
client = _require_client(str(client_code).strip())
|
||
iface = _require_interface(str(interface_code).strip())
|
||
if iface.client_instance_code != client.code:
|
||
raise ValidationError(
|
||
'interface definition does not belong to the selected client instance',
|
||
code='INTEGRATION.BINDING_PAIR_MISMATCH',
|
||
details={
|
||
'client_instance_code': client.code,
|
||
'interface_definition_code': iface.code,
|
||
'interface_client_instance_code': iface.client_instance_code,
|
||
},
|
||
)
|
||
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,
|
||
}
|
||
|
||
|
||
def _serialize_interface(iface) -> dict:
|
||
return {
|
||
'id': iface.id, 'code': iface.code, 'name': iface.name,
|
||
'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type,
|
||
'http_method': iface.http_method, 'request_path': iface.request_path,
|
||
'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {},
|
||
'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {},
|
||
'version': iface.version, 'status': iface.status, 'enabled': iface.enabled,
|
||
}
|
||
|
||
|
||
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,
|
||
'mapping_version': binding.mapping_version, 'priority': binding.priority,
|
||
'environment': binding.environment, 'effective_from': binding.effective_from,
|
||
'effective_to': binding.effective_to, 'status': binding.status,
|
||
}
|
||
|
||
|
||
def _decrypted_secret(cred) -> dict:
|
||
"""db 模式下解密凭据字典;密文缺失或主密钥异常时返回空 dict(fail-closed 不炸列表)。"""
|
||
if cred.secret_provider != 'db' or not cred.secret_ciphertext:
|
||
return {}
|
||
try:
|
||
raw = decrypt_secret(
|
||
cred.secret_ciphertext,
|
||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||
codes=_DB_SECRET_CODES,
|
||
)
|
||
parsed = json.loads(raw)
|
||
return parsed if isinstance(parsed, dict) else {}
|
||
except AppError:
|
||
return {}
|
||
|
||
|
||
def _serialize_credential(cred) -> dict:
|
||
secret_dict = _decrypted_secret(cred)
|
||
return {
|
||
'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref,
|
||
'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type,
|
||
# 非密字段按类型定义回显(如 username);密文字段与密文本身永不回显。
|
||
'secret_fields': visible_fields(cred.credential_type, secret_dict),
|
||
'has_secret': bool(cred.secret_ciphertext),
|
||
'version': cred.version, 'status': cred.status,
|
||
'updated_at': cred.updated_at.isoformat() if cred.updated_at else None,
|
||
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
|
||
}
|
||
|
||
|
||
def _apply_db_secret(cred, body) -> None:
|
||
"""db 模式:按凭据类型定义组装字段并加密落库;只改部分字段可沿用解密出的旧值。
|
||
|
||
类型必须在凭据类型注册表内(fail-closed);合并旧值后必填字段仍缺失即拒绝。
|
||
"""
|
||
ctype = str(body.get('credential_type') or cred.credential_type or 'password').strip()
|
||
if get_credential_type(ctype) is None:
|
||
raise ValidationError('unknown credential_type', details={'credential_type': ctype})
|
||
cred.credential_type = ctype
|
||
current = _decrypted_secret(cred) if cred.secret_ciphertext else {}
|
||
values: dict = dict(current)
|
||
for key in (field['key'] for field in get_credential_type(ctype)['fields']):
|
||
incoming = body.get(key)
|
||
if incoming is not None and str(incoming) != '':
|
||
values[key] = str(incoming)
|
||
merged = build_secret_dict(ctype, values)
|
||
cred.secret_ciphertext = encrypt_secret(
|
||
json.dumps(merged, ensure_ascii=False),
|
||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||
codes=_DB_SECRET_CODES,
|
||
)
|
||
|
||
|
||
def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||
return {
|
||
'status': result.status,
|
||
'data': result.data,
|
||
'error_code': result.error_code,
|
||
'error_message': result.error_message,
|
||
'document_no': result.document_no,
|
||
'trace_id': result.trace_id,
|
||
}
|
||
|
||
|
||
# ---- 能力清单与调用 ----
|
||
|
||
@integration_connector_bp.route('/capabilities', methods=['GET'])
|
||
@require_admin
|
||
def list_capabilities_endpoint():
|
||
data = [{
|
||
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
|
||
'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
|
||
} for spec in list_capabilities()]
|
||
return ok(data)
|
||
|
||
|
||
@integration_connector_bp.route('/capabilities/<capability>', methods=['POST'])
|
||
@require_admin
|
||
def call_capability(capability):
|
||
body = request.get_json(silent=True) or {}
|
||
if body.get('interface_id') is not None:
|
||
raise ValidationError(
|
||
'interface_id is not allowed for capability calls',
|
||
code='INTEGRATION.INTERFACE_ID_NOT_ALLOWED',
|
||
)
|
||
params = body.get('params') or {}
|
||
context = body.get('context') or {}
|
||
operation_id = str(body.get('operation_id') or f'api-{uuid.uuid4().hex}')
|
||
idempotency_key = body.get('idempotency_key')
|
||
result = get_capability_gateway().call(
|
||
capability=capability, context=context, params=params,
|
||
operation_id=operation_id, idempotency_key=idempotency_key,
|
||
)
|
||
return ok(_result_to_dict(result))
|
||
|
||
|
||
# ---- 客户端实例 ----
|
||
|
||
@integration_connector_bp.route('/client-instances', methods=['GET'])
|
||
@require_admin
|
||
def list_client_instances():
|
||
rows = IntegrationClientInstance.query.order_by(IntegrationClientInstance.code).all()
|
||
return ok([_serialize_client(row) for row in rows])
|
||
|
||
|
||
@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')
|
||
_require(body.get('name'), 'name')
|
||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||
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)),
|
||
)
|
||
from app import db
|
||
db.session.add(client)
|
||
db.session.commit()
|
||
return ok(_serialize_client(client), status=201)
|
||
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>', methods=['GET'])
|
||
@require_admin
|
||
def get_client_instance(code):
|
||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||
if client is None:
|
||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||
return ok(_serialize_client(client))
|
||
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>', methods=['DELETE'])
|
||
@require_admin
|
||
def delete_client_instance(code):
|
||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||
if client is None:
|
||
raise NotFoundError('client instance not found')
|
||
from app import db
|
||
db.session.delete(client)
|
||
db.session.commit()
|
||
return ok({'deleted': True})
|
||
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
||
@require_admin
|
||
def update_client_instance(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')
|
||
body = request.get_json(silent=True) or {}
|
||
connector_type = str(body.get('connector_type') or client.connector_type)
|
||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||
if body.get('name') is not None:
|
||
_require(body.get('name'), 'name')
|
||
client.name = str(body['name']).strip()
|
||
if body.get('connector_type') is not None:
|
||
client.connector_type = connector_type
|
||
if body.get('environment') is not None:
|
||
client.environment = str(body['environment']).strip()
|
||
if 'endpoint' in body:
|
||
client.endpoint = str(body.get('endpoint') or '').strip() or None
|
||
if 'timeout_seconds' in body:
|
||
client.timeout_seconds = int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None
|
||
if 'config_json' in body:
|
||
client.config_json = body.get('config_json') or {}
|
||
if 'credential_ref_code' in body:
|
||
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))
|
||
|
||
|
||
# ---- 接口定义 ----
|
||
|
||
@integration_connector_bp.route('/interface-definitions', methods=['GET'])
|
||
@require_admin
|
||
def list_interface_definitions():
|
||
rows = IntegrationInterfaceDefinition.query.order_by(IntegrationInterfaceDefinition.code).all()
|
||
return ok([_serialize_interface(row) for row in rows])
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions', methods=['POST'])
|
||
@require_admin
|
||
def create_interface_definition():
|
||
body = request.get_json(silent=True) or {}
|
||
code = str(body.get('code') or '').strip()
|
||
_require(code, 'code')
|
||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||
# 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值,
|
||
# 杜绝接口与客户端类型不一致);客户端不存在即 400,而非依赖外键报 500。
|
||
client = _require_client(str(body['client_instance_code']).strip())
|
||
status = str(body.get('status') or 'draft')
|
||
if status not in VALID_STATUSES:
|
||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||
iface = IntegrationInterfaceDefinition(
|
||
code=code, name=str(body.get('name') or code).strip(),
|
||
client_instance_code=client.code, connector_type=client.connector_type,
|
||
http_method=(str(body.get('http_method') or '').strip().upper() or None),
|
||
request_path=(str(body.get('request_path') or '').strip() or None),
|
||
request_spec_json=body.get('request_spec_json') or {},
|
||
input_schema_json=body.get('input_schema_json') or {},
|
||
response_mapping_json=body.get('response_mapping_json') or {},
|
||
output_schema_json=body.get('output_schema_json') or {},
|
||
version=int(body.get('version') or 1), status=status,
|
||
# enabled 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略;
|
||
# 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。
|
||
enabled=True,
|
||
)
|
||
from app import db
|
||
db.session.add(iface)
|
||
db.session.commit()
|
||
return ok(_serialize_interface(iface), status=201)
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
|
||
@require_admin
|
||
def update_interface_definition(code):
|
||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema 与所属客户端)。
|
||
|
||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||
连接器类型由所属客户端实例服务端推导,请求体传值被忽略。
|
||
"""
|
||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||
if iface is None:
|
||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||
body = request.get_json(silent=True) or {}
|
||
if body.get('name') is not None:
|
||
_require(body.get('name'), 'name')
|
||
iface.name = str(body['name']).strip()
|
||
if body.get('client_instance_code') is not None:
|
||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||
client = _require_client(str(body['client_instance_code']).strip())
|
||
iface.client_instance_code = client.code
|
||
iface.connector_type = client.connector_type
|
||
if 'http_method' in body:
|
||
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
|
||
if 'request_path' in body:
|
||
iface.request_path = str(body.get('request_path') or '').strip() or None
|
||
for json_field in ('request_spec_json', 'input_schema_json', 'response_mapping_json', 'output_schema_json'):
|
||
if json_field in body:
|
||
setattr(iface, json_field, body.get(json_field) or {})
|
||
if body.get('version') is not None:
|
||
iface.version = int(body.get('version') or 1)
|
||
from app import db
|
||
db.session.commit()
|
||
return ok(_serialize_interface(iface))
|
||
|
||
|
||
# ---- 接口定义生命周期(状态只经动作端点按转移表流转) ----
|
||
|
||
def _do_interface_lifecycle(code: str, action: str):
|
||
"""动作端点共用体:取接口 → 按转移表转移 → 落库并回显。"""
|
||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||
if iface is None:
|
||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||
_interface_transition(iface, action)
|
||
from app import db
|
||
db.session.commit()
|
||
return ok(_serialize_interface(iface))
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>/publish', methods=['POST'])
|
||
@require_admin
|
||
def publish_interface_definition(code):
|
||
"""发布接口定义(draft → published):发布后才会被绑定解析选中。"""
|
||
return _do_interface_lifecycle(code, 'publish')
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>/unpublish', methods=['POST'])
|
||
@require_admin
|
||
def unpublish_interface_definition(code):
|
||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||
return _do_interface_lifecycle(code, 'unpublish')
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>/retire', methods=['POST'])
|
||
@require_admin
|
||
def retire_interface_definition(code):
|
||
"""退役(published → retired):该接口引用的所有绑定同时失效。"""
|
||
return _do_interface_lifecycle(code, 'retire')
|
||
|
||
|
||
@integration_connector_bp.route('/interface-definitions/<code>/reopen', methods=['POST'])
|
||
@require_admin
|
||
def reopen_interface_definition(code):
|
||
"""恢复为草稿(retired → draft):版本化发布上线前的保险阀,重新走发布流程。"""
|
||
return _do_interface_lifecycle(code, 'reopen')
|
||
|
||
|
||
# ---- Binding ----
|
||
|
||
@integration_connector_bp.route('/bindings', methods=['GET'])
|
||
@require_admin
|
||
def list_bindings():
|
||
rows = IntegrationBinding.query.order_by(IntegrationBinding.capability, IntegrationBinding.priority.desc()).all()
|
||
return ok([_serialize_binding(row) for row in rows])
|
||
|
||
|
||
@integration_connector_bp.route('/bindings', methods=['POST'])
|
||
@require_admin
|
||
def create_binding():
|
||
"""创建绑定:校验 steps_json 后落库;新建固定落 draft,发布走 /publish 动作端点。
|
||
|
||
核心逻辑:归一化 steps → 镜像首步到旧列(NOT NULL)→ 落 draft。
|
||
仍接受旧单步字段(无 steps_json 时合成一元素数组)。
|
||
"""
|
||
body = request.get_json(silent=True) or {}
|
||
_require(body.get('capability'), 'capability')
|
||
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 {},
|
||
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(),
|
||
status='draft',
|
||
)
|
||
from app import db
|
||
db.session.add(binding)
|
||
db.session.commit()
|
||
return ok(_serialize_binding(binding), status=201)
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||
@require_admin
|
||
def update_binding(binding_id):
|
||
"""更新绑定(可改 context / steps_json / 映射版本 / 优先级 / 环境 / 生效区间)。
|
||
|
||
状态不在此改写(须经动作端点按转移表流转)。规则(评审修正轮收紧后):
|
||
[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)
|
||
if binding is None:
|
||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||
body = request.get_json(silent=True) or {}
|
||
if body.get('capability') is not None:
|
||
_require(body.get('capability'), 'capability')
|
||
binding.capability = body['capability']
|
||
if 'context_selector_json' in body:
|
||
binding.context_selector_json = body.get('context_selector_json') or {}
|
||
|
||
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 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:
|
||
binding.priority = int(body.get('priority') or 0)
|
||
if body.get('environment') is not None:
|
||
binding.environment = str(body['environment']).strip()
|
||
if body.get('effective_from') is not None:
|
||
binding.effective_from = body['effective_from'] or None
|
||
if body.get('effective_to') is not None:
|
||
binding.effective_to = body['effective_to'] or None
|
||
db.session.commit()
|
||
return ok(_serialize_binding(binding))
|
||
|
||
|
||
# ---- 绑定生命周期(状态只经动作端点按转移表流转) ----
|
||
|
||
def _do_binding_lifecycle(binding_id: int, action: str):
|
||
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
|
||
|
||
发布(publish)附加就绪门禁:steps_json 每步接口须已发布、每步客户端须启用,
|
||
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
|
||
(与 binding.resolve_binding 的调用期门禁同一语义)。
|
||
"""
|
||
from app import db
|
||
binding = db.session.get(IntegrationBinding, binding_id)
|
||
if binding is None:
|
||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||
if action == 'publish':
|
||
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: steps_json is empty',
|
||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||
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))
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>/publish', methods=['POST'])
|
||
@require_admin
|
||
def publish_binding(binding_id):
|
||
"""发布绑定(draft → published):发布后才会被绑定解析选中。"""
|
||
return _do_binding_lifecycle(binding_id, 'publish')
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>/unpublish', methods=['POST'])
|
||
@require_admin
|
||
def unpublish_binding(binding_id):
|
||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||
return _do_binding_lifecycle(binding_id, 'unpublish')
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>/retire', methods=['POST'])
|
||
@require_admin
|
||
def retire_binding(binding_id):
|
||
"""退役(published → retired):绑定退出自动调用。"""
|
||
return _do_binding_lifecycle(binding_id, 'retire')
|
||
|
||
|
||
@integration_connector_bp.route('/bindings/<int:binding_id>/reopen', methods=['POST'])
|
||
@require_admin
|
||
def reopen_binding(binding_id):
|
||
"""恢复为草稿(retired → draft):重新走发布流程。"""
|
||
return _do_binding_lifecycle(binding_id, 'reopen')
|
||
|
||
|
||
# ---- 凭据引用 ----
|
||
|
||
@integration_connector_bp.route('/credential-references', methods=['GET'])
|
||
@require_admin
|
||
def list_credential_references():
|
||
rows = IntegrationCredentialReference.query.order_by(IntegrationCredentialReference.code).all()
|
||
return ok([_serialize_credential(row) for row in rows])
|
||
|
||
|
||
@integration_connector_bp.route('/credential-references', methods=['POST'])
|
||
@require_admin
|
||
def create_credential_reference():
|
||
"""创建凭据引用:db 模式(默认)按凭据类型加密字段落库;env 模式只存配置键名。"""
|
||
body = request.get_json(silent=True) or {}
|
||
_require(body.get('code'), 'code')
|
||
# 缺省保持 env(兼容既有直连 API 调用);管理端 db 模式显式传 secret_provider='db'。
|
||
provider = str(body.get('secret_provider') or 'env').strip()
|
||
if provider not in VALID_SECRET_PROVIDERS:
|
||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||
code = str(body['code']).strip()
|
||
if IntegrationCredentialReference.query.filter_by(code=code).first():
|
||
raise ValidationError('credential reference code already exists', code='RESOURCE.CONFLICT')
|
||
status = str(body.get('status') or 'active')
|
||
if status not in ('active', 'rotating', 'retired'):
|
||
raise ValidationError('invalid credential status', details={'allowed': ['active', 'rotating', 'retired']})
|
||
cred = IntegrationCredentialReference(
|
||
code=code,
|
||
secret_ref=str(body.get('secret_ref') or '').strip(),
|
||
secret_provider=provider,
|
||
credential_type=str(body.get('credential_type') or 'password').strip(),
|
||
version=int(body.get('version') or 1),
|
||
status=status,
|
||
)
|
||
if provider == 'db':
|
||
_apply_db_secret(cred, body)
|
||
cred.secret_ref = f'db:{code}'
|
||
else:
|
||
_require(cred.secret_ref, 'secret_ref')
|
||
from app import db
|
||
db.session.add(cred)
|
||
db.session.commit()
|
||
# 永不回显真实凭据值;只回元数据与非密字段。
|
||
return ok(_serialize_credential(cred), status=201)
|
||
|
||
|
||
@integration_connector_bp.route('/credential-references/types', methods=['GET'])
|
||
@require_admin
|
||
def list_credential_type_specs():
|
||
"""凭据类型注册表清单(类型 + 字段定义),供管理端动态渲染表单与占位符提示。"""
|
||
return ok(list_credential_types())
|
||
|
||
|
||
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
|
||
@require_admin
|
||
def update_credential_reference(code):
|
||
"""更新凭据引用(code 不变);db 模式可只改部分字段(其余沿用旧值),永不回显明文。"""
|
||
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
|
||
if cred is None:
|
||
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
|
||
body = request.get_json(silent=True) or {}
|
||
if body.get('secret_provider') is not None:
|
||
provider = str(body['secret_provider']).strip()
|
||
if provider not in VALID_SECRET_PROVIDERS:
|
||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||
cred.secret_provider = provider
|
||
if provider == 'env':
|
||
# 切回 env 模式时清掉遗留密文,避免失效凭据残留库中。
|
||
cred.secret_ciphertext = None
|
||
field_keys = tuple(
|
||
field['key'] for field in (get_credential_type(
|
||
str(body.get('credential_type') or cred.credential_type or 'password')) or {'fields': []}
|
||
)['fields']
|
||
)
|
||
has_secret_input = any(body.get(key) is not None for key in field_keys)
|
||
if cred.secret_provider == 'db':
|
||
if has_secret_input or body.get('credential_type') is not None or not cred.secret_ciphertext:
|
||
_apply_db_secret(cred, body)
|
||
cred.secret_ref = f'db:{cred.code}'
|
||
else:
|
||
if body.get('secret_ref') is not None:
|
||
_require(body.get('secret_ref'), 'secret_ref')
|
||
cred.secret_ref = str(body['secret_ref']).strip()
|
||
if has_secret_input:
|
||
raise ValidationError('credential fields only apply to db credentials')
|
||
if body.get('status') is not None:
|
||
# 状态改写冻结为两态开关:仅允许 active/retired(管理端行内开关即走此通道);
|
||
# rotating 不可进入——其现语义等于断供(resolve_credential 只解析 active),
|
||
# 真实版本化轮换属 P2;存量 rotating 数据经置 active 即恢复。
|
||
status = str(body['status']).strip()
|
||
if status not in VALID_CREDENTIAL_UI_STATUSES:
|
||
raise ValidationError(
|
||
'invalid credential status', details={'allowed': list(VALID_CREDENTIAL_UI_STATUSES)})
|
||
cred.status = status
|
||
from app import db
|
||
db.session.commit()
|
||
return ok(_serialize_credential(cred))
|
||
|
||
|
||
# ---- 连接测试 ----
|
||
|
||
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
|
||
@require_admin
|
||
def test_connection(code):
|
||
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
|
||
|
||
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds/db_kind
|
||
独立列拼回 config_json 后再交给 transport,否则存独立列的地址/库种会被误判为未冻结。
|
||
"""
|
||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||
if client is None:
|
||
raise NotFoundError('client instance not found')
|
||
gateway = get_capability_gateway()
|
||
transport = gateway.transports.get(client.connector_type)
|
||
if transport is None:
|
||
raise ValidationError(
|
||
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
|
||
)
|
||
client_payload = {
|
||
'config_json': merge_client_config({
|
||
'config_json': client.config_json or {},
|
||
'endpoint': client.endpoint,
|
||
'timeout_seconds': client.timeout_seconds,
|
||
'db_kind': client.db_kind,
|
||
}),
|
||
# 连接测试按设计须证明「网络与认证」可用(数据库直连无凭据无法建连):
|
||
# 有凭据引用时解析真实凭据(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:
|
||
raw = probe(client=client_payload)
|
||
ok_flag = bool(raw.get('ok'))
|
||
else:
|
||
# 测试替身等未实现 probe 的传输:回退 call(空 interface 规格)。
|
||
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
|
||
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
|
||
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
|
||
|
||
|
||
# ---- 集成调用日志查询 ----
|
||
|
||
@integration_connector_bp.route('/calls', methods=['GET'])
|
||
@require_admin
|
||
def list_integration_calls_api():
|
||
"""集成调用日志分页查询(能力无关通用口径)。
|
||
|
||
筛选:capability/interface_code/client_code/connector_type/status/
|
||
operation_id/trace_id/business_ref 精确;keyword 对请求摘要 JSON 文本模糊;
|
||
date_from/date_to=YYYY-MM-DD(按 created_at 闭区间,date_to 补全天)。
|
||
"""
|
||
from sqlalchemy import cast, String
|
||
|
||
args = request.args
|
||
query = IntegrationCall.query
|
||
for field in ('capability', 'status', 'operation_id', 'trace_id', 'business_ref'):
|
||
value = (args.get(field) or '').strip()
|
||
if value:
|
||
query = query.filter(getattr(IntegrationCall, field) == value)
|
||
for json_field in ('interface_code', 'client_code', 'connector_type'):
|
||
value = (args.get(json_field) or '').strip()
|
||
if value:
|
||
query = query.filter(
|
||
IntegrationCall.binding_snapshot_json[json_field].as_string() == value)
|
||
keyword = (args.get('keyword') or '').strip()
|
||
if keyword:
|
||
query = query.filter(
|
||
cast(IntegrationCall.request_summary_json, String).ilike(f'%{keyword}%'))
|
||
date_from = (args.get('date_from') or '').strip()
|
||
if date_from:
|
||
query = query.filter(IntegrationCall.created_at >= f'{date_from} 00:00:00')
|
||
date_to = (args.get('date_to') or '').strip()
|
||
if date_to:
|
||
query = query.filter(IntegrationCall.created_at <= f'{date_to} 23:59:59.999999')
|
||
|
||
page = max(int(args.get('page') or 1), 1)
|
||
page_size = min(max(int(args.get('page_size') or 20), 1), 100)
|
||
total = query.count()
|
||
rows = (query.order_by(IntegrationCall.id.desc())
|
||
.offset((page - 1) * page_size).limit(page_size).all())
|
||
|
||
def _row(c: IntegrationCall) -> dict:
|
||
snap = c.binding_snapshot_json or {}
|
||
return {'id': c.id, 'created_at': c.created_at.isoformat() if c.created_at else None,
|
||
'capability': c.capability, 'operation_id': c.operation_id,
|
||
'trace_id': c.trace_id, 'status': c.status, 'elapsed_ms': c.elapsed_ms,
|
||
'business_ref': c.business_ref,
|
||
'client_code': snap.get('client_code'), 'interface_code': snap.get('interface_code'),
|
||
'connector_type': snap.get('connector_type'),
|
||
'step_index': snap.get('step_index'), 'step_count': snap.get('step_count')}
|
||
|
||
return ok({'total': total, 'page': page, 'page_size': page_size,
|
||
'items': [_row(c) for c in rows]})
|
||
|
||
|
||
@integration_connector_bp.route('/calls/<int:call_id>', methods=['GET'])
|
||
@require_admin
|
||
def get_integration_call_api(call_id: int):
|
||
"""单条全量(含 wire_json/request/response/绑定快照)+ 同 operation_id 步骤时间线。"""
|
||
call = IntegrationCall.query.get(call_id)
|
||
if call is None:
|
||
raise NotFoundError('integration call not found', code='INTEGRATION.CALL_NOT_FOUND')
|
||
full = {'id': call.id, 'created_at': call.created_at.isoformat() if call.created_at else None,
|
||
'capability': call.capability, 'operation_id': call.operation_id,
|
||
'trace_id': call.trace_id, 'status': call.status, 'elapsed_ms': call.elapsed_ms,
|
||
'business_ref': call.business_ref,
|
||
'binding_snapshot_json': call.binding_snapshot_json or {},
|
||
'request_summary_json': call.request_summary_json or {},
|
||
'response_summary_json': call.response_summary_json or {},
|
||
'wire_json': call.wire_json}
|
||
siblings = (IntegrationCall.query.filter_by(operation_id=call.operation_id)
|
||
.order_by(IntegrationCall.id.asc()).all())
|
||
timeline = [{'id': c.id, 'step_index': (c.binding_snapshot_json or {}).get('step_index'),
|
||
'step_count': (c.binding_snapshot_json or {}).get('step_count'),
|
||
'interface_code': (c.binding_snapshot_json or {}).get('interface_code'),
|
||
'status': c.status, 'elapsed_ms': c.elapsed_ms} for c in siblings]
|
||
return ok({'call': full, 'timeline': timeline})
|