- 新增 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 列迁移挂链尾(依赖域表迁移),随后续批次单独落地
261 lines
9.9 KiB
Python
261 lines
9.9 KiB
Python
"""services/integration_connector/binding.py
|
||
|
||
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
|
||
有序 BindingStep 快照(一对多配方),并冻结调用期配置。
|
||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、
|
||
errors.py、transports.base.merge_client_config。
|
||
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
|
||
每步接口须 published、每步客户端须 enabled(fail-closed);同 context 下 priority
|
||
高者优先;无命中或任一步门禁失败抛 BindingNotFoundError。
|
||
存量空 steps_json 时由旧列合成单步(迁移兜底);读能力=单步,形状与多步统一。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from dataclasses import dataclass
|
||
from datetime import datetime, timezone
|
||
|
||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||
from app.services.integration_connector.errors import BindingNotFoundError
|
||
from app.services.integration_connector.transports.base import merge_client_config
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class BindingStep:
|
||
"""绑定中的单步冻结快照:接口 + 归属客户端配置 + 该步参数映射。"""
|
||
|
||
interface_code: str
|
||
connector_type: str
|
||
client_code: str
|
||
config: dict
|
||
request_spec: dict
|
||
response_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:
|
||
if dt is None:
|
||
return None
|
||
if dt.tzinfo is not None:
|
||
return dt.astimezone(timezone.utc).replace(tzinfo=None)
|
||
return dt
|
||
|
||
|
||
def _within_window(binding: IntegrationBinding, now: datetime) -> bool:
|
||
effective_from = _to_naive(binding.effective_from)
|
||
effective_to = _to_naive(binding.effective_to)
|
||
if effective_from is not None and now < effective_from:
|
||
return False
|
||
if effective_to is not None and now > effective_to:
|
||
return False
|
||
return True
|
||
|
||
|
||
def _is_subset(selector: dict, context: dict) -> bool:
|
||
"""selector 的键值须全部存在于 context(空 selector 恒命中)。"""
|
||
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(steps 至少一元素;读能力通常单步)。
|
||
|
||
Raises:
|
||
BindingNotFoundError: 无可用绑定,或任一步接口未发布/客户端停用/目标缺失
|
||
(与列表「发布/退役」「启停」语义闭环;不向调用方泄露配置细节)。
|
||
"""
|
||
base_now = now or datetime.utcnow()
|
||
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
|
||
candidates: list[tuple[IntegrationBinding, dict]] = []
|
||
for row in rows:
|
||
if not _within_window(row, base_now):
|
||
continue
|
||
selector = row.context_selector_json or {}
|
||
if not _is_subset(selector, context or {}):
|
||
continue
|
||
candidates.append((row, selector))
|
||
if not candidates:
|
||
# 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]
|
||
|
||
raw_steps = _raw_steps_from_binding(row)
|
||
if not raw_steps:
|
||
logger.warning(
|
||
"connector binding empty steps: capability=%s binding_id=%s",
|
||
capability, row.id,
|
||
)
|
||
raise BindingNotFoundError(capability=capability)
|
||
|
||
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=dict(row.context_selector_json or {}),
|
||
steps=tuple(steps),
|
||
mapping_version=row.mapping_version,
|
||
credential_ref_code=steps[0].credential_ref_code,
|
||
)
|