- 新增 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 列迁移挂链尾(依赖域表迁移),随后续批次单独落地
422 lines
18 KiB
Python
422 lines
18 KiB
Python
"""services/integration_connector/mapping.py
|
||
|
||
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
|
||
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
|
||
逻辑:只允许点路径/数组下标提取与白名单转换函数(含 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
|
||
|
||
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。
|
||
|
||
路径途经重复节点列表(名称段撞上列表)时逐元素收集剩余路径的命中:
|
||
全部未命中视为 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"})
|
||
return _walk(obj, tokens)
|
||
|
||
|
||
def _walk(cur: Any, tokens: list[str]) -> Any:
|
||
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。
|
||
|
||
[缺陷修复 2026-09-23] 扇出收集的命中值本身可能是列表(更深层重复节点,如
|
||
多 RecordSet 的 Master 列表、单 Master 多 Record 的 Field 列表)。若不拍平,
|
||
嵌套 list 会让 each/pick 等消费方取不到任何字段 → 行被静默丢弃——后果是
|
||
批量库存查询整批误判为查无库存(机制推演;该嵌套形态尚未在生产观测到)。
|
||
收集结果统一拍平一层:语义仍是"路径在重复结构中的全部命中"。
|
||
"""
|
||
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 _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]
|
||
if not collected:
|
||
return MISSING
|
||
return _flatten(collected)
|
||
return MISSING
|
||
|
||
|
||
def _flatten(items: list[Any]) -> list[Any]:
|
||
"""把扇出收集结果拍平一层:列表命中拼接、标量/字典命中保留,顺序不变。"""
|
||
flat: list[Any] = []
|
||
for item in items:
|
||
if isinstance(item, list):
|
||
flat.extend(item)
|
||
else:
|
||
flat.append(item)
|
||
return flat
|
||
|
||
|
||
# ---- 白名单转换函数(纯函数,无 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_
|
||
|
||
|
||
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"})
|
||
# [形态归一] XML 归一化后重复子节点"单条=dict、多条=list"二态并存(如单条
|
||
# Field);单 dict 等价单元素列表,直接按列表语义 pick(回归:ERP 返回单条
|
||
# doc_no Field 时 pick_target_not_list → 单号丢失,单被误判 technical_failed)。
|
||
if isinstance(value, dict):
|
||
value = [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 _expand_repeated_child(item: Any, fields: dict) -> list[Any]:
|
||
"""把"容器记录"沿 fields 表达式引用的重复子节点展开成逐子记录单元。
|
||
|
||
[缺陷修复 2026-09-23] 假说防御:若 ERP 返回"单 Master 容器挂多条库存 Record"
|
||
的形态,fields 的 expr 都以同一首段(如 Record)开头时,扁平映射会让 pick 只
|
||
取到首条记录,其余行(不同批号/料号的库存)被静默丢弃——批量查询整批误判为
|
||
查无库存。本修复对该形态按首段逐元素拆开,保证"一条 Record 一行"。
|
||
真实留档响应(IntegrationCall 审计)均为扁平形态(每 Master 单 Record),
|
||
该嵌套形态尚未在生产观测到;此处按通用归一化语义防御。
|
||
|
||
Args:
|
||
item: each 的单个元素(dict 容器记录;非 dict 原样返回)。
|
||
fields: each 的子映射(expr 首段即候选重复子节点名)。
|
||
Returns:
|
||
展开后的单元列表(无可展开的重复子节点时为 [item])。
|
||
仅当全部 expr 首段一致且该子节点是"非空 dict 列表"时才展开,
|
||
其余形态维持原行为(fail-safe,不做有歧义的拆分)。
|
||
"""
|
||
if not isinstance(item, dict):
|
||
return [item]
|
||
roots = {
|
||
str(spec.get("expr") or "").split(".", 1)[0].split("[", 1)[0]
|
||
for spec in fields.values() if isinstance(spec, dict)
|
||
}
|
||
if "" in roots or len(roots) != 1:
|
||
return [item]
|
||
root = next(iter(roots))
|
||
children = item.get(root)
|
||
if not isinstance(children, list) or not children or not all(isinstance(c, dict) for c in children):
|
||
return [item]
|
||
return [{**item, root: child} for child in children]
|
||
|
||
|
||
def _each(value: Any, fields: dict | None = None) -> Any:
|
||
"""对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。
|
||
|
||
Args:
|
||
value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。
|
||
fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致:
|
||
元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。
|
||
Note:
|
||
元素是"容器记录"(同一 Master 下挂多条 Record,见 _expand_repeated_child)
|
||
时按子记录逐条展开成行——批量查询多条库存不得丢行(2026-09-23 缺陷修复)。
|
||
"""
|
||
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:
|
||
# [缺陷修复 2026-09-23] 容器记录内挂多条子记录(重复节点)时逐条展开,
|
||
# 保证"一条外部记录一行";单条 dict 子节点行为不变。
|
||
for unit in _expand_repeated_child(item, fields or {}):
|
||
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(unit, 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,
|
||
"decimal": _decimal,
|
||
"cast": _cast,
|
||
"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:
|
||
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 "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")
|
||
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
|