125 lines
4.9 KiB
Python
125 lines
4.9 KiB
Python
"""services/integration_connector/binding.py
|
||
|
||
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
|
||
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
|
||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
|
||
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
|
||
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
from datetime import datetime, timezone
|
||
|
||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||
from app.services.integration_connector.errors import BindingNotFoundError
|
||
|
||
|
||
@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
|
||
|
||
|
||
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:
|
||
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:
|
||
raise BindingNotFoundError(capability=capability)
|
||
|
||
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
|
||
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
|
||
config = dict(client.config_json or {})
|
||
if client.endpoint is not None:
|
||
config['endpoint'] = client.endpoint
|
||
if client.timeout_seconds is not None:
|
||
config['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 {})
|
||
if row.context_source_code is not None and 'source_code' not in selector:
|
||
selector['source_code'] = row.context_source_code
|
||
|
||
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 {},
|
||
)
|