- 绑定新增 param_mapping_json:域参数→接口参数声明式映射(map_response 规范),空对象同名直通 - 凭据引用新增 db 维护模式:secret_ciphertext Fernet 加密落库,主密钥 INTEGRATION_CREDENTIAL_KEY 仅环境注入,与 env 引用模式并存 - 新增 credential_types 凭据形态注册表:代码注册各类型字段清单,UI 动态渲染与 API 组装校验的唯一事实来源 - 移除绑定 context_source_code 独立列,路由条件统一 context_selector_json - 管理端表单 Modal 重构为 Drawer,新增 JSON 编辑字段组件与页面级测试 - 迁移 rd1/re1 重挂当前唯一 head dd22ee33ff44,维持单 head 链 - settings 移除 IN_TRANSIT_TRANSFER_ERP_* 配置,外部端点/凭据移交连接器客户端实例管理
153 lines
6.6 KiB
Python
153 lines
6.6 KiB
Python
"""services/integration_connector/binding.py
|
||
|
||
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
|
||
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
|
||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
|
||
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
|
||
且接口定义须为 published、客户端实例须 enabled(管理端「发布/退役」「启停」的总开关);
|
||
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
|
||
"""
|
||
|
||
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 BindingSnapshot:
|
||
"""一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。"""
|
||
|
||
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
|
||
config: dict
|
||
request_spec: dict
|
||
response_mapping: dict
|
||
output_schema: dict
|
||
# 域参数→接口参数映射(空 = 同名直通)与接口入参 Schema(映射结果校验)。
|
||
param_mapping: dict
|
||
input_schema: dict
|
||
|
||
|
||
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 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。
|
||
Raises:
|
||
BindingNotFoundError: 无可用绑定(fail-closed);接口未发布或客户端已停用同样按
|
||
无可用绑定处理(与列表「发布/退役」「启停」按钮语义闭环,且不向调用方泄露配置细节)。
|
||
"""
|
||
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 都没有」与「有但路由选择器/生效窗口不命中」,
|
||
# 否则调用方只看到 no binding for capability(2026-09 排障实测痛点)。
|
||
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:
|
||
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,
|
||
)
|
||
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 {})
|
||
|
||
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,
|
||
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 {},
|
||
)
|