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_* 配置,外部端点/凭据移交连接器客户端实例管理
This commit is contained in:
1 parent
5df204fdea
commit
31591e663e
35 files changed
+4345
-750
No files matched your search
@@ -2,12 +2,14 @@
|
||||
|
||||
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
|
||||
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
|
||||
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL;
|
||||
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。
|
||||
逻辑:只允许点路径/数组下标提取与白名单转换函数(含 pick 键值取值、template 参数模板、
|
||||
each 列表逐元素子映射),禁止任意 Python/JS/SQL;缺字段且不可满足→MappingInvalidError;
|
||||
输出不合 Schema→MappingInvalidError(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import string
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
@@ -50,25 +52,37 @@ def _tokenize(path: str) -> list[str]:
|
||||
|
||||
|
||||
def extract_path(obj: Any, path: str) -> Any:
|
||||
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。"""
|
||||
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。
|
||||
|
||||
路径途经重复节点列表(名称段撞上列表)时逐元素收集剩余路径的命中:
|
||||
全部未命中视为 MISSING,部分命中收集为列表——同一配置在单/多记录
|
||||
(如多条件查询返回多个 RecordSet)之间不再随机失效。
|
||||
"""
|
||||
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 _walk(obj, tokens)
|
||||
|
||||
|
||||
def _walk(cur: Any, tokens: list[str]) -> Any:
|
||||
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。"""
|
||||
if not tokens:
|
||||
return cur
|
||||
tok, rest = tokens[0], tokens[1:]
|
||||
if isinstance(cur, list) and tok.isdigit():
|
||||
idx = int(tok)
|
||||
if idx >= len(cur):
|
||||
return MISSING
|
||||
return cur
|
||||
return _walk(cur[idx], rest)
|
||||
if isinstance(cur, dict) and tok in cur:
|
||||
return _walk(cur[tok], rest)
|
||||
if isinstance(cur, list):
|
||||
collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING]
|
||||
return collected if collected else MISSING
|
||||
return MISSING
|
||||
|
||||
|
||||
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
|
||||
@@ -119,6 +133,81 @@ def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
|
||||
return then if condition == "truthy" and bool(value) else else_
|
||||
|
||||
|
||||
def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
|
||||
value_field: str | None = None, exists: bool = False, cast: str | None = None) -> Any:
|
||||
"""从「键值对记录列表」按 key_field==key_value 取值(行转列通用需求)。
|
||||
|
||||
Args:
|
||||
value: 目标列表(每项为 dict,如 XML 归一化后的 Field 列表)。
|
||||
key_field / key_value: 匹配键字段名与期望值(按字符串比较)。
|
||||
value_field: 命中后取的字段名;缺省返回整条记录。
|
||||
exists: True 时返回布尔(是否命中),不取值。
|
||||
cast: 可选 "decimal" 或 _cast 支持的标量类型。
|
||||
"""
|
||||
if value is MISSING:
|
||||
return MISSING
|
||||
if key_field is None or key_value is None:
|
||||
raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"})
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "pick_target_not_list"})
|
||||
for item in value:
|
||||
if isinstance(item, dict) and str(item.get(key_field)) == str(key_value):
|
||||
if exists:
|
||||
return True
|
||||
found = item.get(value_field) if value_field is not None else item
|
||||
if cast == "decimal":
|
||||
return _decimal(found)
|
||||
return _cast(found, cast) if cast else found
|
||||
if exists:
|
||||
return False
|
||||
return MISSING
|
||||
|
||||
|
||||
def _each(value: Any, fields: dict | None = None) -> Any:
|
||||
"""对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。
|
||||
|
||||
Args:
|
||||
value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。
|
||||
fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致:
|
||||
元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。
|
||||
"""
|
||||
if value is MISSING:
|
||||
# 目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 归一为空列表:
|
||||
# 空结果是合法答案(如库存查无此批号),交领域层归类为"未找到",
|
||||
# 不得因输出 Schema 校验 fail-closed 成映射错误。
|
||||
return []
|
||||
# XML 重复节点归一化后单条记录是 dict、多条是 list:单记录归一为单元素列表,
|
||||
# 否则同一配置在单/多记录间会随机 fail-closed。
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "each_target_not_list"})
|
||||
out: list[Any] = []
|
||||
for item in value:
|
||||
row: dict[str, Any] = {}
|
||||
for field, spec in (fields or {}).items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
v: Any = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
v = extract_path(item, 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}"})
|
||||
v = fn(v, **(spec.get("args") or {}))
|
||||
if v is not MISSING:
|
||||
row[field] = v
|
||||
if row:
|
||||
# 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过,
|
||||
# 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
TRANSFORMS: dict[str, Any] = {
|
||||
"default": _default,
|
||||
"fallback": _fallback,
|
||||
@@ -127,9 +216,64 @@ TRANSFORMS: dict[str, Any] = {
|
||||
"enum-map": _enum_map,
|
||||
"list-map": _list_map,
|
||||
"if-else": _if_else,
|
||||
"pick": _pick,
|
||||
"each": _each,
|
||||
}
|
||||
|
||||
|
||||
# ---- 参数模板填充(spec 级 "template",对整个参数表渲染,多用于域参数→接口参数翻译)----
|
||||
|
||||
def _render_template_value(value: Any, args: dict) -> str:
|
||||
"""渲染单个占位符值:列表按 list_item_template 逐项渲染后用 separator 连接。
|
||||
|
||||
列表项为 dict 时,item_template 的占位符对 item 的键校验(缺失即
|
||||
template_item_field_missing,fail-closed)并按字段转义渲染,
|
||||
如 list_item_template = "(img01 = '{material_no}' AND img04 = '{lot_no}')"。
|
||||
"""
|
||||
item_template = str(args.get("list_item_template") or "{item}")
|
||||
separator = str(args.get("separator") if args.get("separator") is not None else ",")
|
||||
escape = args.get("escape")
|
||||
|
||||
def _escape(text: Any) -> str:
|
||||
text = str(text)
|
||||
if escape == "quote":
|
||||
text = text.replace("'", "''")
|
||||
return text
|
||||
|
||||
if isinstance(value, (list, tuple)):
|
||||
rendered: list[str] = []
|
||||
for item in value:
|
||||
if isinstance(item, dict):
|
||||
placeholders = {f for _, f, _, _ in string.Formatter().parse(item_template) if f}
|
||||
missing = sorted(p for p in placeholders if p not in item)
|
||||
if missing:
|
||||
raise MappingInvalidError(details={"reason": "template_item_field_missing", "field": missing[0]})
|
||||
rendered.append(item_template.format(**{k: _escape(v) for k, v in item.items()}))
|
||||
else:
|
||||
rendered.append(item_template.format(item=_escape(item)))
|
||||
return separator.join(rendered)
|
||||
return _escape(value)
|
||||
|
||||
|
||||
def fill_param_template(template: str, params: dict, args: dict | None = None) -> str:
|
||||
"""按 {param} 占位符对参数表渲染模板(str.format 语义,{{}} 转义字面大括号)。
|
||||
|
||||
缺占位符即抛 MappingInvalidError(fail-closed),绝不静默输出空串。
|
||||
"""
|
||||
template = str(template or "")
|
||||
args = args or {}
|
||||
placeholders = {fname for _, fname, _, _ in string.Formatter().parse(template) if fname}
|
||||
rendered: dict[str, str] = {}
|
||||
for name in placeholders:
|
||||
if name not in (params or {}):
|
||||
raise MappingInvalidError(details={"reason": "template_param_missing", "param": name})
|
||||
rendered[name] = _render_template_value(params[name], args)
|
||||
try:
|
||||
return template.format(**rendered)
|
||||
except (KeyError, IndexError, ValueError) as exc:
|
||||
raise MappingInvalidError(details={"reason": "template_invalid"}) from exc
|
||||
|
||||
|
||||
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
|
||||
|
||||
def _matches_type(value: Any, type_spec: Any) -> bool:
|
||||
@@ -190,7 +334,10 @@ def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
|
||||
for field, spec in mapping.items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
if "template" in spec:
|
||||
# 参数模板:对整个 raw(参数表)渲染,与单字段 expr 提取互补。
|
||||
value = fill_param_template(spec["template"], raw, spec.get("args") or {})
|
||||
elif "default" in spec:
|
||||
value = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
|
||||
Reference in new issue
Block a user