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