Files
syops/backend/app/models/integration_connector.py
hugo e750fa8602 feat(integration-connector): database 传输类型、两步绑定编排与调用日志捕获查询
- 新增 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 列迁移挂链尾(依赖域表迁移),随后续批次单独落地
2026-09-27 18:05:08 +08:00

237 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""models/integration_connector.py
用途:Integration Connector(外部系统连接器框架)配置与运行时模型:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap/database)与状态均用 CheckConstraint 兜底;database 客户端
另有 db_kind 专列(mysql/oracle/sqlserver/postgresql),fail-closed 语义在服务层。
Binding.steps_json 表达一对多有序接口配方(D10);旧单步列保留至 P2。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import JSONB
from app.models.base import Base
# 连接器类型白名单;模型 CHECK 由本常量动态生成,扩枚举须配套 Alembic 迁移重建 CHECK。
CONNECTOR_TYPES = ('rest', 'soap', 'database')
# database 专属库种(D16):专列 db_kind,非 config_json;API/transport 同源 fail-closed。
DB_KINDS = ('mysql', 'oracle', 'sqlserver', 'postgresql')
CONFIG_STATUSES = ('draft', 'published', 'retired')
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
# context_selector_json 需要参与唯一约束/索引:PostgreSQL 的 JSON 无默认 btree 操作符表,
# 无法建唯一索引;映射为 JSONB 即可。SQLite/测试仍用 JSON(TEXT)。
CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql')
class IntegrationCredentialReference(Base):
"""凭据引用:真实凭据加密落库(db 模式)或引用环境注入键(env 模式),绝不落库明文。"""
__tablename__ = 'integration_credential_references'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_credential_references_code'),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CREDENTIAL_STATUSES)})",
name='ck_integration_credential_references_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
secret_ref: Mapped[str] = mapped_column(String(128), nullable=False)
# db 模式:凭据 JSON(如 {"username","password"})的 Fernet 密文;主密钥由
# INTEGRATION_CREDENTIAL_KEY 环境注入。env 模式为空。绝不回显、绝不写日志。
secret_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env')
credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password')
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
last_verified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationClientInstance(Base):
"""客户端实例:一份到外部系统的连接配置(连到哪 + 凭据引用 + 超时/TLS/默认 org)。"""
__tablename__ = 'integration_client_instances'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_client_instances_code'),
CheckConstraint(
f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})",
name='ck_integration_client_instances_connector_type',
),
Index('ix_integration_client_instances_type_env', 'connector_type', 'environment'),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点);
# database 为 host:port[/database|service_name]。
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# database 专属库种(仅 connector_type='database' 有值;rest/soap 为 NULL)。
db_kind: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
credential_ref_code: Mapped[Optional[str]] = mapped_column(
ForeignKey('integration_credential_references.code'), nullable=True,
)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true'))
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationInterfaceDefinition(Base):
"""接口定义:一个可调操作(请求模板 + 入参 Schema + 返回值映射 + 出参 Schema)。"""
__tablename__ = 'integration_interface_definitions'
__table_args__ = (
UniqueConstraint('code', name='uq_integration_interface_definitions_code'),
CheckConstraint(
f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})",
name='ck_integration_interface_definitions_connector_type',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})",
name='ck_integration_interface_definitions_status',
),
Index('ix_integration_interface_definitions_client', 'client_instance_code'),
)
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
# 关键强类型字段独立列(JSON 保留作兜底)。
http_method: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
request_path: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
request_spec_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
output_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true'))
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationBinding(Base):
"""绑定:(Capability, context_selector) → 有序接口步骤配方;版本化、可发布、可退役。
一对多有序(D10/D13):steps_json = [{interface_code, param_mapping_json}, ...];
每步客户端由接口归属自带。旧列 interface_definition_code / param_mapping_json /
client_instance_code 迁移后保留镜像首步,解析不再读取,P2 删除。
"""
__tablename__ = 'integration_bindings'
__table_args__ = (
UniqueConstraint(
'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})",
name='ck_integration_bindings_status',
),
CheckConstraint(
"priority >= 0", name='ck_integration_bindings_priority',
),
Index('ix_integration_bindings_cap_env_status', 'capability', 'environment', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
# 有序步骤配方:每步 {interface_code, param_mapping_json};客户端由接口归属推导。
steps_json: Mapped[list[dict[str, Any]]] = mapped_column(
CONTEXT_SELECTOR_JSON, nullable=False, default=list,
)
# 域参数 → 接口参数的声明式映射(旧单步列,P2 删;迁移后镜像 steps_json[0])。
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
interface_definition_code: Mapped[str] = mapped_column(
ForeignKey('integration_interface_definitions.code'), nullable=False,
)
mapping_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
priority: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
class IntegrationCall(Base):
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。
多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id
(一票一次执行 = N 条,按 operation_id 串联 + binding_snapshot_json.step_index
定位),故 operation_id 无唯一约束;原唯一约束兼作的索引由普通索引
ix_integration_calls_operation_id 补回(迁移 tt5b6c7d8e9f)。
"""
__tablename__ = 'integration_calls'
__table_args__ = (
Index('ix_integration_calls_operation_id', 'operation_id'),
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
Index('ix_integration_calls_trace_id', 'trace_id'),
Index('ix_integration_calls_business_ref', 'business_ref'),
)
id: Mapped[int] = mapped_column(primary_key=True)
operation_id: Mapped[str] = mapped_column(String(128), nullable=False)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
binding_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
request_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False)
elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
# 线级事实(database 最终 SQL/绑定/行数;soap endpoint+XML;rest HTTP 往返)。
# 可空:历史行与未捕获场景为 NULL,前台如实展示。
wire_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
# 通用业务锚点:调用方透传的业务单号/任务号(能力无关;不传为 NULL)。
business_ref: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)