Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理 # Conflicts: # backend/app/models/__init__.py
This commit is contained in:
1 parent
85d27e9ffa
commit
91b7233872
812 files changed
+73763
-18908
No files matched your search
@@ -0,0 +1,7 @@
|
||||
"""services/integration_connector/__init__.py
|
||||
|
||||
Integration Connector(外部系统连接器框架):能力契约、绑定解析、REST/SOAP 传输、
|
||||
声明式映射、凭据引用与调用引擎(CapabilityGateway)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -0,0 +1,124 @@
|
||||
"""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 {},
|
||||
)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""services/integration_connector/capability.py
|
||||
|
||||
用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。
|
||||
依赖:app.core.errors、errors.py;纯代码,不依赖 DB。
|
||||
逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.integration_connector.errors import CapabilityNotFoundError
|
||||
|
||||
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
|
||||
_QUERY_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"],
|
||||
"properties": {
|
||||
"invoice_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"to_warehouse": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
},
|
||||
}
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"found": {"type": "boolean"},
|
||||
"quantity": {"type": ["number", "null"]},
|
||||
},
|
||||
}
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilitySpec:
|
||||
"""强类型能力契约(由代码注册)。"""
|
||||
|
||||
name: str
|
||||
input_schema: dict
|
||||
output_schema: dict
|
||||
idempotency: str
|
||||
write: bool
|
||||
|
||||
|
||||
_CAPABILITIES: dict[str, CapabilitySpec] = {}
|
||||
_LOADED = False
|
||||
|
||||
|
||||
def register_capability(spec: CapabilitySpec) -> CapabilitySpec:
|
||||
"""注册能力;同名重复注册抛 ValidationError。"""
|
||||
if spec.name in _CAPABILITIES:
|
||||
raise ValidationError(
|
||||
f"capability already registered: {spec.name}",
|
||||
code="INTEGRATION.CAPABILITY_DUPLICATE",
|
||||
details={"name": spec.name},
|
||||
)
|
||||
_CAPABILITIES[spec.name] = spec
|
||||
return spec
|
||||
|
||||
|
||||
def get_capability(name: str) -> CapabilitySpec:
|
||||
"""按名查询能力;未注册抛 CapabilityNotFoundError(fail-closed)。"""
|
||||
spec = _CAPABILITIES.get(name)
|
||||
if spec is None:
|
||||
raise CapabilityNotFoundError(name=name)
|
||||
return spec
|
||||
|
||||
|
||||
def list_capabilities() -> list[CapabilitySpec]:
|
||||
"""返回全部已注册能力(按名排序)。"""
|
||||
return sorted(_CAPABILITIES.values(), key=lambda s: s.name)
|
||||
|
||||
|
||||
def ensure_capabilities_loaded() -> None:
|
||||
"""惰性注册内置能力(幂等);由网关/API 在解析前调用。"""
|
||||
global _LOADED # noqa: PLW0603
|
||||
if _LOADED:
|
||||
return
|
||||
_LOADED = True
|
||||
_register_transfer_capabilities()
|
||||
|
||||
|
||||
def _register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。"""
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
))
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=True,
|
||||
))
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.verify_duplicate",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=False,
|
||||
))
|
||||
|
||||
|
||||
def reset_capability_registry_for_tests() -> None:
|
||||
"""单测隔离:清空注册表并重置加载标记。"""
|
||||
global _LOADED # noqa: PLW0603
|
||||
_CAPABILITIES.clear()
|
||||
_LOADED = False
|
||||
@@ -0,0 +1,153 @@
|
||||
"""services/integration_connector/engine.py
|
||||
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。
|
||||
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
|
||||
逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout;
|
||||
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import replace
|
||||
|
||||
from app import db
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability
|
||||
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
|
||||
from app.services.integration_connector.mapping import map_response, schema_errors
|
||||
from app.services.integration_connector.security import sanitize
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
|
||||
from app.models import IntegrationCall
|
||||
|
||||
|
||||
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
|
||||
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
|
||||
request_spec = request_spec or {}
|
||||
spec_path = str(request_spec.get('path') or '')
|
||||
try:
|
||||
path = spec_path.format(**params)
|
||||
except (KeyError, IndexError, ValueError):
|
||||
path = spec_path
|
||||
headers = dict(config.get('headers') or {})
|
||||
spec_params = list(request_spec.get('params') or [])
|
||||
selected = {k: params[k] for k in spec_params if k in params} or params
|
||||
template = request_spec.get('template')
|
||||
if isinstance(template, dict):
|
||||
body = _fill_template(template, params)
|
||||
else:
|
||||
body = selected
|
||||
return {'path': path, 'params': selected, 'body': body, 'headers': headers}
|
||||
|
||||
|
||||
def _fill_template(template: dict, params: dict) -> dict:
|
||||
"""填充模板 dict 中的 {placeholder} 占位符。"""
|
||||
filled: dict = {}
|
||||
for key, value in template.items():
|
||||
if isinstance(value, str) and '{' in value:
|
||||
try:
|
||||
filled[key] = value.format(**params)
|
||||
except (KeyError, IndexError, ValueError):
|
||||
filled[key] = value
|
||||
else:
|
||||
filled[key] = value
|
||||
return filled
|
||||
|
||||
|
||||
def _environment() -> str:
|
||||
"""从 Flask 配置推导环境(dev/test/prod),缺省 prod。"""
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
if has_app_context():
|
||||
value = str(current_app.config.get('ENV_NAME') or '').strip().lower()
|
||||
if value in {'dev', 'test', 'prod'}:
|
||||
return value
|
||||
except Exception:
|
||||
pass
|
||||
return 'prod'
|
||||
|
||||
|
||||
class CapabilityGateway:
|
||||
"""能力调用引擎;transports 为 {connector_type: Transport} 可注入。"""
|
||||
|
||||
def __init__(self, transports: dict[str, Transport] | None = None) -> None:
|
||||
self.transports = dict(transports or {})
|
||||
|
||||
def call(
|
||||
self,
|
||||
*,
|
||||
capability: str,
|
||||
context: dict,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
idempotency_key: str | None = None,
|
||||
environment: str | None = None,
|
||||
transports: dict[str, Transport] | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
ensure_capabilities_loaded()
|
||||
spec = get_capability(capability)
|
||||
input_errors = schema_errors(params, spec.input_schema)
|
||||
if input_errors:
|
||||
raise InputInvalidError(details={'errors': input_errors})
|
||||
|
||||
env = environment or _environment()
|
||||
snapshot = resolve_binding(capability, context, env)
|
||||
transport = (transports or self.transports).get(snapshot.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
|
||||
|
||||
request = build_request(snapshot.request_spec, snapshot.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': {}},
|
||||
interface={'request_spec_json': snapshot.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
|
||||
return result
|
||||
|
||||
result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success')
|
||||
if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
|
||||
data = map_response(snapshot.response_mapping, raw, snapshot.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)
|
||||
return result
|
||||
|
||||
|
||||
def _record_call(
|
||||
operation_id: str,
|
||||
capability: str,
|
||||
snapshot: BindingSnapshot,
|
||||
params: dict,
|
||||
raw: dict | None,
|
||||
result: IntegrationCallResult,
|
||||
start_ms: int,
|
||||
trace_id: str,
|
||||
) -> None:
|
||||
"""落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。"""
|
||||
elapsed_ms = int(time.time() * 1000) - start_ms
|
||||
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,
|
||||
'mapping_version': snapshot.mapping_version,
|
||||
'credential_ref_code': snapshot.credential_ref_code,
|
||||
},
|
||||
request_summary_json=sanitize(params),
|
||||
response_summary_json=sanitize(raw or {}),
|
||||
status=result.status,
|
||||
elapsed_ms=elapsed_ms,
|
||||
trace_id=trace_id,
|
||||
)
|
||||
db.session.add(call)
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""services/integration_connector/errors.py
|
||||
|
||||
用途:Integration Connector 框架统一业务异常类(INTEGRATION.* 错误码)。
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:fail-closed —— 缺绑定/缺凭据/映射不合法/契约未冻结均抛出,绝不猜测。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
INTEGRATION_CAPABILITY_NOT_FOUND = "INTEGRATION.CAPABILITY_NOT_FOUND"
|
||||
INTEGRATION_INPUT_INVALID = "INTEGRATION.INPUT_INVALID"
|
||||
INTEGRATION_BINDING_NOT_FOUND = "INTEGRATION.BINDING_NOT_FOUND"
|
||||
INTEGRATION_TRANSPORT_NOT_FROZEN = "INTEGRATION.TRANSPORT_NOT_FROZEN"
|
||||
INTEGRATION_MAPPING_INVALID = "INTEGRATION.MAPPING_INVALID"
|
||||
INTEGRATION_CREDENTIAL_UNRESOLVED = "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
INTEGRATION_RESULT_UNKNOWN = "INTEGRATION.RESULT_UNKNOWN"
|
||||
INTEGRATION_CALL_FAILED = "INTEGRATION.CALL_FAILED"
|
||||
|
||||
|
||||
class CapabilityNotFoundError(AppError):
|
||||
"""能力未注册(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "capability not registered", *, name: str | None = None):
|
||||
details = {"name": name} if name else {}
|
||||
super().__init__(
|
||||
code=INTEGRATION_CAPABILITY_NOT_FOUND, message=message, http_status=404, details=details,
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class InputInvalidError(AppError):
|
||||
"""入参不合能力输入 Schema。"""
|
||||
|
||||
def __init__(self, message: str = "input invalid", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code=INTEGRATION_INPUT_INVALID, message=message, http_status=400, details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class BindingNotFoundError(AppError):
|
||||
"""无可用绑定(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "no binding for capability", *, capability: str | None = None):
|
||||
details = {"capability": capability} if capability else {}
|
||||
super().__init__(
|
||||
code=INTEGRATION_BINDING_NOT_FOUND, message=message, http_status=503, details=details,
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class TransportNotFrozenError(AppError):
|
||||
"""传输契约未冻结(缺 endpoint/wsdl)。"""
|
||||
|
||||
def __init__(self, message: str = "transport not frozen"):
|
||||
super().__init__(
|
||||
code=INTEGRATION_TRANSPORT_NOT_FROZEN, message=message, http_status=503, retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class MappingInvalidError(AppError):
|
||||
"""映射结果不合输出 Schema(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "mapping invalid", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code=INTEGRATION_MAPPING_INVALID, message=message, http_status=503, details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class CredentialUnresolvedError(AppError):
|
||||
"""凭据无法解析(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "credential unresolved", *, ref: str | None = None):
|
||||
details = {"secret_ref": ref} if ref else {}
|
||||
super().__init__(
|
||||
code=INTEGRATION_CREDENTIAL_UNRESOLVED, message=message, http_status=503, details=details,
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ResultUnknownError(AppError):
|
||||
"""写结果无法确认;禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(
|
||||
code=INTEGRATION_RESULT_UNKNOWN, message=message, http_status=503, details=details,
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class CallFailedError(AppError):
|
||||
"""调用技术失败(非业务失败)。"""
|
||||
|
||||
def __init__(self, message: str = "call failed", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code=INTEGRATION_CALL_FAILED, message=message, http_status=502, details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""services/integration_connector/gateway.py
|
||||
|
||||
用途:模块级 CapabilityGateway 装配与测试注入点。
|
||||
依赖:engine.CapabilityGateway、transports.rest/soap。
|
||||
逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.engine import CapabilityGateway
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
_override: CapabilityGateway | None = None
|
||||
|
||||
|
||||
def set_capability_gateway(gateway: CapabilityGateway | None) -> None:
|
||||
"""测试注入点:设置/清除 CapabilityGateway 覆盖。"""
|
||||
global _override # noqa: PLW0603
|
||||
_override = gateway
|
||||
|
||||
|
||||
def get_capability_gateway() -> CapabilityGateway:
|
||||
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()})
|
||||
@@ -0,0 +1,210 @@
|
||||
"""services/integration_connector/mapping.py
|
||||
|
||||
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
|
||||
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
|
||||
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL;
|
||||
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.services.integration_connector.errors import MappingInvalidError
|
||||
|
||||
# 表达式安全边界:路径长度/深度上限(失败即 fail-closed)。
|
||||
MAX_PATH_LENGTH = 256
|
||||
MAX_DEPTH = 8
|
||||
|
||||
# 缺字段哨兵:与合法值 None 区分。
|
||||
MISSING = object()
|
||||
|
||||
|
||||
def _tokenize(path: str) -> list[str]:
|
||||
"""把点路径 + 数组下标拆成 token 序列,如 a.b[0].c -> ['a','b','0','c']。"""
|
||||
tokens: list[str] = []
|
||||
current = ""
|
||||
i = 0
|
||||
n = len(path)
|
||||
while i < n:
|
||||
c = path[i]
|
||||
if c == "[":
|
||||
if current:
|
||||
tokens.append(current)
|
||||
current = ""
|
||||
j = path.index("]", i)
|
||||
tokens.append(path[i + 1:j])
|
||||
i = j + 1
|
||||
elif c == ".":
|
||||
if current:
|
||||
tokens.append(current)
|
||||
current = ""
|
||||
i += 1
|
||||
else:
|
||||
current += c
|
||||
i += 1
|
||||
if current:
|
||||
tokens.append(current)
|
||||
return tokens
|
||||
|
||||
|
||||
def extract_path(obj: Any, path: str) -> Any:
|
||||
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。"""
|
||||
path = str(path or "")
|
||||
if len(path) > MAX_PATH_LENGTH:
|
||||
raise MappingInvalidError(details={"reason": "path_too_long"})
|
||||
tokens = _tokenize(path)
|
||||
if len(tokens) > MAX_DEPTH:
|
||||
raise MappingInvalidError(details={"reason": "path_too_deep"})
|
||||
cur = obj
|
||||
for tok in tokens:
|
||||
if isinstance(cur, list) and tok.isdigit():
|
||||
idx = int(tok)
|
||||
if idx >= len(cur):
|
||||
return MISSING
|
||||
cur = cur[idx]
|
||||
elif isinstance(cur, dict) and tok in cur:
|
||||
cur = cur[tok]
|
||||
else:
|
||||
return MISSING
|
||||
return cur
|
||||
|
||||
|
||||
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
|
||||
|
||||
def _default(value: Any, default: Any) -> Any:
|
||||
return default if value is MISSING else value
|
||||
|
||||
|
||||
def _fallback(value: Any, fallback: Any) -> Any:
|
||||
return fallback if value is MISSING or value in (None, "") else value
|
||||
|
||||
|
||||
def _decimal(value: Any) -> Any:
|
||||
if value is MISSING:
|
||||
return MISSING
|
||||
return Decimal(str(value))
|
||||
|
||||
|
||||
def _cast(value: Any, to: str) -> Any:
|
||||
if value is MISSING or value is None:
|
||||
return MISSING
|
||||
if to == "int":
|
||||
return int(value)
|
||||
if to == "float":
|
||||
return float(value)
|
||||
if to == "str":
|
||||
return str(value)
|
||||
if to == "bool":
|
||||
return bool(value)
|
||||
return value
|
||||
|
||||
|
||||
def _enum_map(value: Any, mapping: dict[str, str]) -> Any:
|
||||
if value is MISSING:
|
||||
return MISSING
|
||||
return mapping.get(str(value), value)
|
||||
|
||||
|
||||
def _list_map(value: Any, mapping: dict[str, str]) -> list[Any]:
|
||||
if value is MISSING:
|
||||
return MISSING
|
||||
return [mapping.get(str(item), item) for item in (value or [])]
|
||||
|
||||
|
||||
def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
|
||||
if value is MISSING:
|
||||
return MISSING
|
||||
return then if condition == "truthy" and bool(value) else else_
|
||||
|
||||
|
||||
TRANSFORMS: dict[str, Any] = {
|
||||
"default": _default,
|
||||
"fallback": _fallback,
|
||||
"decimal": _decimal,
|
||||
"cast": _cast,
|
||||
"enum-map": _enum_map,
|
||||
"list-map": _list_map,
|
||||
"if-else": _if_else,
|
||||
}
|
||||
|
||||
|
||||
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
|
||||
|
||||
def _matches_type(value: Any, type_spec: Any) -> bool:
|
||||
if isinstance(type_spec, list):
|
||||
return any(_matches_type(value, t) for t in type_spec)
|
||||
if type_spec == "object":
|
||||
return isinstance(value, dict)
|
||||
if type_spec == "array":
|
||||
return isinstance(value, (list, tuple))
|
||||
if type_spec == "string":
|
||||
return isinstance(value, str)
|
||||
if type_spec == "number":
|
||||
return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
|
||||
if type_spec == "integer":
|
||||
return isinstance(value, int) and not isinstance(value, bool)
|
||||
if type_spec == "boolean":
|
||||
return isinstance(value, bool)
|
||||
if type_spec == "null":
|
||||
return value is None
|
||||
return True
|
||||
|
||||
|
||||
def _validate_against_schema(value: Any, schema: dict, path: str = "") -> list[tuple[str, str]]:
|
||||
"""返回不合规项 [(字段路径, 原因)];空列表表示合规。"""
|
||||
if not isinstance(schema, dict):
|
||||
return []
|
||||
errors: list[tuple[str, str]] = []
|
||||
if "enum" in schema and value not in schema["enum"]:
|
||||
errors.append((path, f"not in enum: {value!r}"))
|
||||
if "type" in schema and not _matches_type(value, schema["type"]):
|
||||
errors.append((path, f"expected {schema['type']}, got {type(value).__name__}"))
|
||||
if isinstance(value, dict):
|
||||
for req in schema.get("required") or []:
|
||||
if req not in value:
|
||||
errors.append((f"{path}.{req}" if path else req, "required missing"))
|
||||
for key, sub in (schema.get("properties") or {}).items():
|
||||
if key in value:
|
||||
errors.extend(_validate_against_schema(value[key], sub, f"{path}.{key}" if path else key))
|
||||
elif isinstance(value, list) and "items" in schema:
|
||||
for i, item in enumerate(value):
|
||||
errors.extend(_validate_against_schema(item, schema["items"], f"{path}[{i}]"))
|
||||
return errors
|
||||
|
||||
|
||||
def schema_errors(value: Any, schema: dict) -> list[tuple[str, str]]:
|
||||
"""对 value 做最小 Schema 校验,返回不合规项 [(字段路径, 原因)];空列表表示合规。"""
|
||||
return _validate_against_schema(value, schema or {})
|
||||
|
||||
|
||||
def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
|
||||
"""按 mapping 从 raw 提取并转换字段,组装 result 后经 output_schema 校验。
|
||||
|
||||
Raises:
|
||||
MappingInvalidError: 未知转换函数 / 缺必需字段 / 类型或枚举不合。
|
||||
"""
|
||||
mapping = mapping or {}
|
||||
result: dict[str, Any] = {}
|
||||
for field, spec in mapping.items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
value = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
value = extract_path(raw, expr) if expr is not None else MISSING
|
||||
transform = spec.get("transform")
|
||||
if transform:
|
||||
fn = TRANSFORMS.get(transform)
|
||||
if fn is None:
|
||||
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
|
||||
value = fn(value, **(spec.get("args") or {}))
|
||||
if value is not MISSING:
|
||||
result[field] = value
|
||||
|
||||
errors = _validate_against_schema(result, output_schema or {})
|
||||
if errors:
|
||||
raise MappingInvalidError(details={"errors": errors})
|
||||
return result
|
||||
@@ -0,0 +1,83 @@
|
||||
"""services/integration_connector/security.py
|
||||
|
||||
用途:凭据引用解析(fail-closed)与敏感字段脱敏。
|
||||
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
|
||||
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError;
|
||||
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import IntegrationCredentialReference
|
||||
from app.services.integration_connector.errors import CredentialUnresolvedError
|
||||
|
||||
DEFAULT_SENSITIVE_KEYS = frozenset({
|
||||
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
|
||||
'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
|
||||
})
|
||||
|
||||
|
||||
def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
|
||||
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。
|
||||
|
||||
Raises:
|
||||
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
cred = IntegrationCredentialReference.query.filter_by(
|
||||
code=credential_ref_code, status='active',
|
||||
).first()
|
||||
if cred is None:
|
||||
raise CredentialUnresolvedError(ref=credential_ref_code)
|
||||
secret_ref = cred.secret_ref
|
||||
value = current_app.config.get(secret_ref) if has_app_ctx() else None
|
||||
if value is None or value == '':
|
||||
raise CredentialUnresolvedError(ref=secret_ref)
|
||||
if isinstance(value, dict):
|
||||
return dict(value)
|
||||
return {'value': value}
|
||||
|
||||
|
||||
def has_app_ctx() -> bool:
|
||||
"""当前是否处于 Flask app 上下文(无则返回 False)。"""
|
||||
try:
|
||||
from flask import has_app_context
|
||||
return has_app_context()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def sanitize(obj: Any, sensitive_keys: set[str] | None = None) -> Any:
|
||||
"""递归脱敏:把敏感键对应的值替换为 ***;保留原始结构。
|
||||
|
||||
Args:
|
||||
obj: 待脱敏对象(dict/list/标量)。
|
||||
sensitive_keys: 附加敏感键集合;缺省用 DEFAULT_SENSITIVE_KEYS。
|
||||
Returns:
|
||||
脱敏后的新对象(不修改入参)。
|
||||
"""
|
||||
keys = DEFAULT_SENSITIVE_KEYS | (sensitive_keys or set())
|
||||
if isinstance(obj, dict):
|
||||
return {
|
||||
key: ('***' if str(key).lower() in keys else sanitize(value, sensitive_keys))
|
||||
for key, value in obj.items()
|
||||
}
|
||||
if isinstance(obj, (list, tuple)):
|
||||
return [sanitize(item, sensitive_keys) for item in obj]
|
||||
return obj
|
||||
|
||||
|
||||
def credential_summary(cred: IntegrationCredentialReference) -> dict[str, Any]:
|
||||
"""只回凭据元数据,绝不含解析出的明文。"""
|
||||
return {
|
||||
'code': cred.code,
|
||||
'secret_ref': cred.secret_ref,
|
||||
'secret_provider': cred.secret_provider,
|
||||
'credential_type': cred.credential_type,
|
||||
'version': cred.version,
|
||||
'status': cred.status,
|
||||
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
"""services/integration_connector/transports/__init__.py
|
||||
|
||||
集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
__all__ = [
|
||||
'IntegrationCallResult',
|
||||
'Transport',
|
||||
'classify_transport_response',
|
||||
'RestTransport',
|
||||
'SoapTransport',
|
||||
]
|
||||
@@ -0,0 +1,73 @@
|
||||
"""services/integration_connector/transports/base.py
|
||||
|
||||
用途:Transport 统一契约 + 结果分类(IntegrationCallResult)。
|
||||
依赖:typing.Protocol、dataclass;无 Flask/DB。
|
||||
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
|
||||
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol
|
||||
|
||||
# 结果状态集(与在途调拨写入结果分类一致):success / duplicate_success /
|
||||
# duplicate_unverified / business_failed / technical_failed / timeout / result_unknown
|
||||
RESULT_STATUSES = (
|
||||
'success', 'duplicate_success', 'duplicate_unverified', 'business_failed',
|
||||
'technical_failed', 'timeout', 'result_unknown',
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IntegrationCallResult:
|
||||
"""一次调用归一后的结果对象。"""
|
||||
|
||||
status: str
|
||||
data: dict[str, Any] | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
document_no: str | None = None
|
||||
trace_id: str | None = None
|
||||
|
||||
|
||||
class Transport(Protocol):
|
||||
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。"""
|
||||
|
||||
connector_type: str
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
...
|
||||
|
||||
|
||||
def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
|
||||
"""按原始响应文本归一化结果分类(复用调拨六态分类语义)。
|
||||
|
||||
Args:
|
||||
raw: 原始响应 dict,含 status/document_no/verified_posted/code/message。
|
||||
Returns:
|
||||
IntegrationCallResult。
|
||||
"""
|
||||
status = str(raw.get('status') or 'technical_failed')
|
||||
document_no = raw.get('document_no')
|
||||
if status == 'success':
|
||||
return IntegrationCallResult(status='success', data=raw, document_no=document_no)
|
||||
if status == 'duplicate_success':
|
||||
posted = bool(raw.get('verified_posted'))
|
||||
if posted:
|
||||
return IntegrationCallResult(status='duplicate_success', data=raw, document_no=document_no)
|
||||
return IntegrationCallResult(
|
||||
status='duplicate_unverified', data=raw, document_no=document_no,
|
||||
error_code='INTEGRATION_DUPLICATE_NOT_VERIFIED',
|
||||
)
|
||||
if status == 'business_failed':
|
||||
return IntegrationCallResult(
|
||||
status='business_failed', data=raw,
|
||||
error_code=str(raw.get('code') or 'ERP_BUSINESS_REJECT'),
|
||||
error_message=str(raw.get('message') or ''),
|
||||
)
|
||||
if status == 'timeout':
|
||||
return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN')
|
||||
if status == 'result_unknown':
|
||||
return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no)
|
||||
return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE')
|
||||
@@ -0,0 +1,62 @@
|
||||
"""services/integration_connector/transports/rest.py
|
||||
|
||||
用途:REST Transport——按 client 配置与 interface 请求规格构造 HTTP 请求并返回原始 dict。
|
||||
依赖:requests(默认注入),可注入 http_request 供测试替身。
|
||||
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
|
||||
business_failed dict;非 JSON 响应映射为 technical_failed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
import requests
|
||||
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
|
||||
HttpRequest = Callable[..., Any]
|
||||
|
||||
|
||||
class RestTransport:
|
||||
"""REST 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
|
||||
|
||||
connector_type = 'rest'
|
||||
|
||||
def __init__(self, http_request: HttpRequest | None = None) -> None:
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)')
|
||||
|
||||
spec = interface.get('request_spec_json') or {}
|
||||
method = str(spec.get('method') or 'GET').upper()
|
||||
path = str(spec.get('path') or '').strip()
|
||||
url = endpoint.rstrip('/') + '/' + path.lstrip('/')
|
||||
headers = {**(config.get('headers') or {}), **(request.get('headers') or {})}
|
||||
timeout = int(config.get('timeout_seconds') or 60)
|
||||
|
||||
response = self._http_request(
|
||||
method,
|
||||
url,
|
||||
params=request.get('params'),
|
||||
json=request.get('body'),
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
)
|
||||
if int(getattr(response, 'status_code', 0)) >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
'message': str(getattr(response, 'text', ''))[:500],
|
||||
}
|
||||
try:
|
||||
return response.json()
|
||||
except Exception:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_JSON',
|
||||
'message': str(getattr(response, 'text', ''))[:500],
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
"""services/integration_connector/transports/soap.py
|
||||
|
||||
用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。
|
||||
依赖:zeep(延时导入);errors.py。
|
||||
逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
|
||||
|
||||
class SoapTransport:
|
||||
"""SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。"""
|
||||
|
||||
connector_type = 'soap'
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
config = client.get('config_json') or {}
|
||||
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
|
||||
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
|
||||
wsdl = str(config.get('endpoint') or '').strip()
|
||||
if not wsdl:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
|
||||
|
||||
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
|
||||
raise NotImplementedError('SOAP implementation pending frozen WSDL')
|
||||
Reference in new issue
Block a user