Files
syops/backend/app/models/integration_connector.py
T
hugo 31591e663e feat(integration-connector): 绑定参数映射与凭据 DB 加密落库模式
- 绑定新增 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_* 配置,外部端点/凭据移交连接器客户端实例管理
2026-09-23 00:44:56 +08:00

210 lines
11 KiB
Python
Raw 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(外部系统连接器框架)P1 配置与运行时模型:
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。
"""
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
# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。
CONNECTOR_TYPES = ('rest', 'soap')
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 内含服务端点)。
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, 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) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。"""
__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)
# 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}});
# 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。
# 与 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):
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。"""
__tablename__ = 'integration_calls'
__table_args__ = (
UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
Index('ix_integration_calls_trace_id', 'trace_id'),
)
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='')
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)