Skip to main content

rust_store_core/schema/
registry.rs

1//! Schema 注册表:注册/定位/配置(数据结构与规范化见 [`super::definition`])。
2
3use std::collections::HashMap;
4
5use serde_json::{json, Map, Value};
6
7use crate::types::{is_truthy, str_list, AGG_OPS};
8
9use super::definition::{normalize_fields, ComputeDef, FieldDef, RelationDef, Schema};
10
11/// 查询档位:判决唯一在 core(照 [`Registry::require_context`] 既有范式)。
12///
13/// - [`Profile::Standard`](默认):标准调用 —— 跨方言对齐的公共能力集;
14///   DB 独有能力可用但须代码注释标注「不建议业务查询」(见执行文档 §4.5)。
15/// - [`Profile::Text2Query`]:AI 问数 —— 功能收缩 + 硬性限制(行数/深度/准入全收紧)。
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub enum Profile {
18    /// 标准调用:跨方言对齐的公共能力集;DB 独有能力可用但须注释标注(不建议业务查询)
19    #[default]
20    Standard,
21    /// AI 问数:功能收缩 + 硬性限制
22    Text2Query,
23}
24
25impl Profile {
26    /// 档位字符串(Host / 绑定层单点取用)
27    pub fn as_str(&self) -> &'static str {
28        match self {
29            Profile::Standard => "standard",
30            Profile::Text2Query => "text2query",
31        }
32    }
33
34    /// 字符串 → 档位;未知值 **Err**(禁静默回落 `Standard`,见执行文档 §7)
35    pub fn from_str_or_err(s: &str) -> Result<Profile, String> {
36        match s {
37            "standard" => Ok(Profile::Standard),
38            "text2query" => Ok(Profile::Text2Query),
39            other => Err(format!("未知 profile: {other}(仅 standard / text2query)")),
40        }
41    }
42}
43
44#[derive(Debug, Clone, Default)]
45pub struct Registry {
46    schemas: HashMap<String, Schema>,
47    order: Vec<String>,
48    /// 上下文强制开关(默认关闭 = fail-open,与 JS 原版 parity);
49    /// 开启后所有 plan 入口对 `ctx: None` 显式报错(fail-secure,见 `permission` 模块文档)。
50    /// 内部调用请传显式系统上下文(JSON `{"internal": true}` / `Context::system()`)。
51    require_context: bool,
52    /// 查询档位(默认 [`Profile::Standard`];text2query 由 AI 问数链路显式进入)。
53    profile: Profile,
54    /// RBAC 动态策略(`None` = 未启用,判决原语直通、行为与现状一致)。见 [`crate::rbac`]
55    rbac: Option<crate::rbac::RbacPolicy>,
56}
57
58impl Registry {
59    pub fn new() -> Self {
60        Self::default()
61    }
62
63    /// 注册一个 schema(含自动注册 `<Name>Deleted` 归档表),对应 JS `register`
64    pub fn register(&mut self, defn: &Value) -> Result<(), String> {
65        let obj = defn
66            .as_object()
67            .ok_or_else(|| "schema 定义必须是对象".to_string())?;
68        let name = obj
69            .get("name")
70            .and_then(|v| v.as_str())
71            .ok_or_else(|| "schema 缺少 name".to_string())?
72            .to_string();
73        let collection = obj
74            .get("collection")
75            .and_then(|v| v.as_str())
76            .filter(|s| !s.is_empty())
77            .map(String::from)
78            .unwrap_or_else(|| name.clone());
79
80        let schema = build_schema(obj, name.clone(), collection.clone())?;
81
82        // 定位三元组唯一性(fail fast,绝不静默串源):同名覆盖除外
83        self.check_location_unique(&name, &schema)?;
84
85        let is_archive = obj.get("_isArchive").map(is_truthy).unwrap_or(false);
86        self.schemas.insert(name.clone(), schema);
87        self.order.push(name.clone());
88
89        // 自动注册删除附表 schema —— 每个业务表对应一个 `<collection>_deleted` 归档表
90        if !is_archive && !name.ends_with("Deleted") {
91            self.register(&archive_defn(obj, &name, &collection))?;
92        }
93
94        Ok(())
95    }
96
97    /// 按名称获取 schema
98    pub fn get(&self, name: &str) -> Result<&Schema, String> {
99        self.schemas
100            .get(name)
101            .ok_or_else(|| format!("Schema 未注册: {}", name))
102    }
103
104    pub fn has(&self, name: &str) -> bool {
105        self.schemas.contains_key(name)
106    }
107
108    /// 清空 schema 注册表(`schemas` + `order`),对应绑定层的测试隔离 / 动态重建场景。
109    ///
110    /// 只清 schema,**不动**配置开关(`require_context` / `profile` / `rbac`)与
111    /// 回调表(`clear_fns` 对称:各清各的)——开关生命周期属 Registry 配置面,
112    /// 不随 schema 集合重建而丢。
113    pub fn clear(&mut self) {
114        self.schemas.clear();
115        self.order.clear();
116    }
117
118    /// 开关「上下文强制」(默认关闭 = fail-open,保持 JS parity)。
119    /// 开启后:plan 入口遇 `ctx: None` 报 `ERR_NO_CONTEXT`(fail-secure)。
120    /// 内部调用须显式传系统上下文(`{"internal": true}`)。
121    pub fn set_require_context(&mut self, require: bool) {
122        self.require_context = require;
123    }
124
125    /// 「上下文强制」开关当前值
126    pub fn require_context(&self) -> bool {
127        self.require_context
128    }
129
130    /// 设置查询档位(`standard` / `text2query`)。
131    ///
132    /// 档位为**单值状态**(非栈):由 Host 的 `text2query()` 上下文管理器负责
133    /// 进入时设档、退出时恢复(见 `py-store` / `nodejs-store` 门面)。判决一律在 core。
134    pub fn set_profile(&mut self, profile: Profile) {
135        self.profile = profile;
136    }
137
138    /// 当前查询档位
139    pub fn profile(&self) -> Profile {
140        self.profile
141    }
142
143    /// 注入/清除 RBAC 动态策略;`None` = 关闭(判决原语直通)。
144    /// 解析失败 Err(fail-fast,禁静默吞配置错误),成功后判决链路即刻生效。
145    pub fn set_rbac(&mut self, policy: Option<&Value>) -> Result<(), String> {
146        match policy {
147            None => {
148                self.rbac = None;
149                Ok(())
150            }
151            Some(v) => {
152                let p = crate::rbac::RbacPolicy::from_json(v)?;
153                self.rbac = Some(p);
154                Ok(())
155            }
156        }
157    }
158
159    /// 当前 RBAC 策略(`None` = 未启用)
160    pub fn rbac(&self) -> Option<&crate::rbac::RbacPolicy> {
161        self.rbac.as_ref()
162    }
163
164    /// 按定位三元组精确获取 schema(命令路由的唯一定位入口)
165    ///
166    /// `(source, namespace, collection)` 三元组在 Registry 内唯一(注册期校验),
167    /// 故此处零候选 = 未注册;一候选 = 精确命中。**不做任何猜测回落**。
168    pub fn get_by_location(
169        &self,
170        source: &str,
171        namespace: Option<&str>,
172        collection: &str,
173    ) -> Result<&Schema, String> {
174        let ns = namespace.filter(|s| !s.is_empty());
175        self.schemas
176            .values()
177            .find(|s| s.collection == collection && s.source() == source && s.ns() == ns)
178            .ok_or_else(|| {
179                format!(
180                    "Schema 未定位(source = {}, namespace = {:?}, collection = {})",
181                    source, ns, collection
182                )
183            })
184    }
185
186    /// 命令结构定位(方言翻译用):优先三元组精确命中;未命中时(`route_override`
187    /// 改写 namespace 的多租户场景)回落 `(source, collection)` 定位 —— 结构 schema
188    /// 与定位 namespace 正交(见 multi-datasource-routing-plan.md §6:权限/字段
189    /// 校验仍按结构 schema)。
190    ///
191    /// `(source, collection)` 恰一候选 → 命中;多候选时取 `namespace = null` 的
192    /// 结构声明,无 null 声明 → 报错(拒绝猜测,铁律 3)。
193    pub fn get_for_command(
194        &self,
195        source: &str,
196        namespace: Option<&str>,
197        collection: &str,
198    ) -> Result<&Schema, String> {
199        if let Ok(s) = self.get_by_location(source, namespace, collection) {
200            return Ok(s);
201        }
202        let candidates: Vec<&Schema> = self
203            .schemas
204            .values()
205            .filter(|s| s.collection == collection && s.source() == source)
206            .collect();
207        match candidates.len() {
208            0 => self.get_by_location(source, namespace, collection),
209            1 => Ok(candidates[0]),
210            _ => candidates
211                .iter()
212                .find(|s| s.ns().is_none())
213                .copied()
214                .ok_or_else(|| {
215                    format!(
216                        "命令定位 ({}, {:?}, {}) 存在多个结构 schema(多租户 override 需唯一的 (source, collection) 结构声明)",
217                        source, namespace, collection
218                    )
219                }),
220        }
221    }
222
223    /// 定位三元组唯一性校验:不同 schema 名占用同一 `(source, namespace, collection)`
224    /// → Err(同名覆盖 = 更新语义,放行)。
225    fn check_location_unique(&self, name: &str, schema: &Schema) -> Result<(), String> {
226        let conflict = self.schemas.iter().find(|(n, s)| {
227            n.as_str() != name
228                && s.collection == schema.collection
229                && s.source() == schema.source()
230                && s.ns() == schema.ns()
231        });
232        match conflict {
233            None => Ok(()),
234            Some((other, s)) => Err(format!(
235                "定位三元组冲突: ({}, {:?}, {}) 已被 schema `{}`(collection = {})占用",
236                schema.source(),
237                schema.ns(),
238                schema.collection,
239                other,
240                s.collection
241            )),
242        }
243    }
244
245    pub fn list(&self) -> Vec<String> {
246        self.order.clone()
247    }
248
249    /// schema 声明的数据源名(未声明 → `None`,语义为 `default`)
250    pub fn schema_datasource(&self, name: &str) -> Result<Option<String>, String> {
251        Ok(self.get(name)?.datasource.clone())
252    }
253
254    /// 解析 schema 绑定的数据源(`config` 为 `{ "sources": { name: kind } }`)
255    ///
256    /// 纯逻辑:不持有连接(连接句柄留在 Host)。`null` / 空配置下等价单源 Mongo,
257    /// 保证既有调用方与 parity fixture 零变更。见 [`crate::datasource`]。
258    pub fn resolve_datasource(
259        &self,
260        schema_name: &str,
261        config: &Value,
262    ) -> Result<crate::datasource::DataSource, String> {
263        let declared = self.get(schema_name)?.datasource.as_deref();
264        let cfg = crate::datasource::DataSourceConfig::from_json(config)?;
265        cfg.resolve(declared)
266    }
267}
268
269/// 由原始定义构建 [`Schema`](字段/关系/计算列/元数据分块解析,保持单一职责)
270fn build_schema(
271    obj: &Map<String, Value>,
272    name: String,
273    collection: String,
274) -> Result<Schema, String> {
275    let timestamps = parse_timestamps(obj)?;
276    let mut fields = normalize_fields(obj.get("fields"))?;
277    if timestamps {
278        add_timestamp_fields(&mut fields);
279    }
280    let relations = parse_relations(obj);
281    // 计算列的 agg 需要校验「引用的关系存在」→ 必须晚于 relations 解析
282    let computes = parse_computes(obj, &relations)?;
283    Ok(Schema {
284        name,
285        collection,
286        id_prefix: obj
287            .get("idPrefix")
288            .and_then(|v| v.as_str())
289            .unwrap_or("")
290            .to_string(),
291        timestamps,
292        fields,
293        relations,
294        computes,
295        read: str_list(obj.get("read")),
296        write: str_list(obj.get("write")),
297        indexes: obj
298            .get("indexes")
299            .and_then(|v| v.as_array())
300            .cloned()
301            .unwrap_or_default(),
302        datasource: opt_nonempty_str(obj.get("datasource")),
303        namespace: opt_nonempty_str(obj.get("namespace")),
304    })
305}
306
307/// `timestamps` 仅接受 true/false/'ms'/'s';单位换算在 Host(core 无时钟,now 由 Host 传入)
308fn parse_timestamps(obj: &Map<String, Value>) -> Result<bool, String> {
309    match obj.get("timestamps") {
310        None | Some(Value::Null) | Some(Value::Bool(true)) => Ok(true),
311        Some(Value::Bool(false)) => Ok(false),
312        Some(Value::String(s)) if s == "ms" || s == "s" => Ok(true),
313        Some(Value::String(s)) => Err(format!(
314            "timestamps 仅支持 true/false/'ms'/'s',实际 {:?}",
315            s
316        )),
317        Some(other) => Err(format!(
318            "timestamps 仅支持 true/false/'ms'/'s',实际 {}",
319            other
320        )),
321    }
322}
323
324/// 自动补时间戳字段(`timestamps !== false` 时;已声明则不覆盖)
325fn add_timestamp_fields(fields: &mut HashMap<String, FieldDef>) {
326    for key in ["createdAt", "updatedAt"] {
327        fields.entry(key.to_string()).or_insert_with(|| FieldDef {
328            field_type: "number".to_string(),
329            required: false,
330            default: None,
331            read: None,
332            write: None,
333            fields: None,
334            strategy: None,
335        });
336    }
337}
338
339fn parse_relations(obj: &Map<String, Value>) -> HashMap<String, RelationDef> {
340    let mut relations = HashMap::new();
341    if let Some(Value::Object(rm)) = obj.get("relations") {
342        for (key, val) in rm {
343            let vo = val.as_object();
344            let get_str = |k: &str| -> Option<String> {
345                vo.and_then(|o| o.get(k))
346                    .and_then(|v| v.as_str())
347                    .filter(|s| !s.is_empty())
348                    .map(String::from)
349            };
350            relations.insert(
351                key.clone(),
352                RelationDef {
353                    model: get_str("model").unwrap_or_default(),
354                    rel_type: get_str("type").unwrap_or_else(|| "many".to_string()),
355                    local_field: get_str("localField").unwrap_or_else(|| "_id".to_string()),
356                    foreign_field: get_str("foreignField").unwrap_or_else(|| key.clone()),
357                    read: str_list(vo.and_then(|o| o.get("read"))),
358                },
359            );
360        }
361    }
362    relations
363}
364
365fn parse_computes(
366    obj: &Map<String, Value>,
367    relations: &HashMap<String, RelationDef>,
368) -> Result<Vec<(String, ComputeDef)>, String> {
369    let mut computes = Vec::new();
370    if let Some(Value::Object(cm)) = obj.get("computes") {
371        for (key, val) in cm {
372            let vo = val.as_object();
373            let get = |k: &str| vo.and_then(|o| o.get(k)).cloned();
374            let has_fn = get("fn").map(|v| is_truthy(&v)).unwrap_or(false);
375            let has_async_fn = get("asyncFn").map(|v| is_truthy(&v)).unwrap_or(false);
376            let agg = parse_agg(key, get("agg").as_ref(), relations, has_fn || has_async_fn)?;
377            computes.push((
378                key.clone(),
379                ComputeDef {
380                    comp_type: get("type")
381                        .and_then(|v| v.as_str().map(String::from))
382                        .filter(|s| !s.is_empty())
383                        .unwrap_or_else(|| "any".to_string()),
384                    has_fn,
385                    has_async_fn,
386                    fn_ref: get("fnRef")
387                        .and_then(|v| v.as_str().map(String::from))
388                        .filter(|s| !s.is_empty()),
389                    agg,
390                    depends: str_list(get("depends").as_ref()).unwrap_or_default(),
391                    read: str_list(get("read").as_ref()),
392                },
393            ));
394        }
395    }
396    Ok(computes)
397}
398
399/// 解析并校验归一聚合计算列(§9.2(2)):`{"$count":"lessons"}` / `{"$sum":"lessons.duration"}`。
400///
401/// - 算子白名单 `$count/$sum/$avg/$min/$max`,不在白名单 → Err(绝不静默);
402/// - 取值必须是**关系路径**:`$count` 仅关系整行计数(`lessons`,不接受字段),
403///   其余算子必须带字段(`lessons.duration`);
404/// - 二级关系路径(`orders.items.price`)首批不支持 → Err;
405/// - 与 `fn` / `asyncFn` 互斥。
406fn parse_agg(
407    key: &str,
408    raw: Option<&Value>,
409    relations: &HashMap<String, RelationDef>,
410    has_callback: bool,
411) -> Result<Option<Value>, String> {
412    let Some(v) = raw.filter(|v| is_truthy(v)) else {
413        return Ok(None);
414    };
415    if has_callback {
416        return Err(format!(
417            "计算列 \"{key}\" 不能同时声明 agg 与 fn/asyncFn(二选一)"
418        ));
419    }
420    let obj = v.as_object().ok_or_else(|| {
421        format!("计算列 \"{key}\" 的 agg 必须是对象,如 {{\"$count\": \"lessons\"}}")
422    })?;
423    let mut it = obj.iter();
424    let (op, arg) = match (it.next(), it.next()) {
425        (Some(kv), None) => kv,
426        _ => return Err(format!("计算列 \"{key}\" 的 agg 必须且只能声明一个算子键")),
427    };
428    if !AGG_OPS.contains(&op.as_str()) {
429        return Err(format!(
430            "计算列 \"{key}\" 的 agg 算子 {op} 不在白名单($count/$sum/$avg/$min/$max)"
431        ));
432    }
433    let path = arg
434        .as_str()
435        .filter(|s| !s.is_empty() && *s != "*")
436        .ok_or_else(|| {
437            format!("计算列 \"{key}\" 的 agg 取值必须是关系路径字符串(如 \"lessons\" / \"lessons.duration\")")
438        })?;
439    let (rel, field) = match path.split_once('.') {
440        Some((r, f)) => (r, Some(f)),
441        None => (path, None),
442    };
443    if !relations.contains_key(rel) {
444        return Err(format!(
445            "计算列 \"{key}\" 的 agg 引用的关系 \"{rel}\" 未在 schema 中定义"
446        ));
447    }
448    if field
449        .map(|f| f.is_empty() || f.contains('.'))
450        .unwrap_or(false)
451    {
452        return Err(format!(
453            "计算列 \"{key}\" 的 agg 关系路径 \"{path}\" 非法:仅支持单级「关系.字段」(二级路径首批不支持)"
454        ));
455    }
456    match op.as_str() {
457        "$count" if field.is_some() => Err(format!(
458            "计算列 \"{key}\" 的 $count 仅支持关系整行计数(如 \"lessons\"),按字段计数待 P5"
459        )),
460        "$count" => Ok(Some(v.clone())),
461        _ if field.is_none() => Err(format!(
462            "计算列 \"{key}\" 的 agg 算子 {op} 必须引用关系字段(如 \"lessons.duration\")"
463        )),
464        _ => Ok(Some(v.clone())),
465    }
466}
467
468/// 取非空字符串字段(空串归一为 `None`)
469fn opt_nonempty_str(v: Option<&Value>) -> Option<String> {
470    v.and_then(|v| v.as_str())
471        .filter(|s| !s.is_empty())
472        .map(String::from)
473}
474
475/// 构造 `<Name>Deleted` 归档表 schema 定义(字段 = 原字段 + `deletedAt`);
476/// 归档表与原表同库 —— `datasource` 与 `namespace` 一并继承。
477fn archive_defn(obj: &Map<String, Value>, name: &str, collection: &str) -> Value {
478    let mut arch_fields = obj
479        .get("fields")
480        .and_then(|v| v.as_object())
481        .cloned()
482        .unwrap_or_default();
483    arch_fields.insert("deletedAt".to_string(), json!({ "type": "number" }));
484    // 剔除 `_id` 的自增策略:归档表显式拷贝源行 `_id` 值(upsert-by-_id 幂等),
485    // 不走数据库自增;DDL 侧也据此保持归档表 `_id` 为普通主键列
486    if let Some(idf) = arch_fields.get_mut("_id") {
487        if let Some(o) = idf.as_object_mut() {
488            o.remove("strategy");
489        }
490    }
491    let mut arch = json!({
492        "name": format!("{}Deleted", name),
493        "collection": format!("{}_deleted", collection),
494        "idPrefix": "",
495        "_isArchive": true,
496        "fields": Value::Object(arch_fields),
497        "indexes": obj.get("indexes").cloned().unwrap_or_else(|| json!([])),
498    });
499    if let Some(ds) = obj.get("datasource") {
500        arch["datasource"] = ds.clone();
501    }
502    if let Some(ns) = obj.get("namespace") {
503        arch["namespace"] = ns.clone();
504    }
505    arch
506}