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