Files
syops/backend/app/services/integration_connector/mapping.py
T
hugo 6b53b563e7 feat(in-transit-transfer): 实现在途仓自动调拨Agent一期完整功能
包含后端服务层、任务处理器与消费Worker、前端聊天组件、数据库模型与迁移脚本、测试用例,同时新增外部系统连接器框架基础能力并更新相关文档。
2026-08-28 17:16:06 +08:00

211 lines
7.1 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.
"""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