"""图模型定义:节点类型、主属性与关系语义(**单一来源**)。 为什么必须集中定义: 1. **标签与属性名要拼进 Cypher**(Neo4j 的标签不能用查询参数占位),因此它们**必须**来自 受控常量,绝不能接受调用方传入的任意字符串,否则就是 Cypher 注入。 2. 读服务(`RelationshipService`)与投影侧需要就"客户节点长什么样"达成一致。此前投影写 `:Entity {entity_id}`、读服务查 `:Customer {customer_id}`,两边各写各的,结果是**写进去的 关系永远读不出来**。把节点规格放在一处,两边都从这里取,才不会再次漂移。 3. `RELATION_SEMANTICS` 记录每种关系连接哪两类节点,用于在投影时拒绝无意义的边 (例如把 `TRADED` 写成 Customer→Tag)。底座已有关系白名单(8 种),这里补的是 "谁指向谁"的语义约束。 """ from dataclasses import dataclass from typing import Any @dataclass(frozen=True) class NodeSpec: """一个节点类型的规格。`cast` 决定主键类型:客户 id 是整数(与读服务查询一致)。""" type_key: str label: str property: str cast: type # payload 里使用的类型名 → 节点规格。未登记的类型一律拒绝。 NODE_SPECS: dict[str, NodeSpec] = { "customer": NodeSpec("customer", "Customer", "customer_id", int), "product": NodeSpec("product", "Product", "product_code", str), "tag": NodeSpec("tag", "Tag", "tag_key", str), "industry": NodeSpec("industry", "Industry", "category", str), "event": NodeSpec("event", "Event", "event_id", str), } # 关系 → (允许的源节点类型, 允许的目标节点类型) RELATION_SEMANTICS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = { "PREFERS": (("customer",), ("tag",)), "HAS_GOAL": (("customer",), ("tag",)), "INTERESTED_IN": (("customer",), ("product", "industry")), "TRADED": (("customer",), ("product",)), "HOLDS": (("customer",), ("product",)), "TRIGGERED_RISK": (("customer",), ("event",)), "BELONGS_TO_CATEGORY": (("product",), ("tag",)), "EXPOSED_TO_INDUSTRY": (("product", "customer"), ("industry",)), } def node_spec(type_key: object) -> NodeSpec: """按类型名取节点规格;未登记的类型抛 `ValueError`(宁可失败也不拼出任意标签)。""" key = str(type_key or "").strip().lower() spec = NODE_SPECS.get(key) if spec is None: raise ValueError(f"node type is not allowed: {type_key!r}") return spec def node_id(spec: NodeSpec, value: Any) -> Any: """把主键值转成该节点应有的类型。""" return value if spec.cast is str else spec.cast(value) def relation_allowed(relation: str, source_type: str, target_type: str) -> bool: """该关系是否允许连接这两类节点。""" expected = RELATION_SEMANTICS.get(relation) if expected is None: return False sources, targets = expected return source_type in sources and target_type in targets def merge_node_clause(variable: str, spec: NodeSpec, id_parameter: str) -> str: """生成 `MERGE (a:Label {prop: $param})` 子句。 只有 `spec` 里的标签与属性名会进入查询文本(它们来自本模块常量),`$param` 走参数绑定, 因此调用方无法通过数据影响 Cypher 结构。 """ return f"MERGE ({variable}:{spec.label} {{{spec.property}: ${id_parameter}}})"