rust-store-core 4.6.1

One data engine for MongoDB, MySQL, PostgreSQL and SQLite: a MongoDB-style GQL query language, permission checks, computed columns, command planning and SQL dialect translation. Pure logic, no IO.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! processNode 同步处理链:默认值填充 → 同步 fn 计算列 → 递归下钻 → 权限裁剪。

use std::collections::HashSet;

use serde_json::Value;

use crate::permission::{
    evaluate, get_readable_computes, get_readable_fields, get_readable_relations, Context, Doc,
    RoleRules,
};
use crate::pipeline::{flatten_object_fields_impl, RelAst};
use crate::schema::{Registry, Schema};

use super::super::cache::{ensure_cache, Cache};
use super::super::defaults::{is_object_field, raw_field_default};
use super::super::registry::FnRegistry;

/// GQL 请求字段 + fn 计算列依赖字段(去重,保序)
fn collect_needed(fields: &[String], cache: &Cache) -> Vec<String> {
    let mut needed: Vec<String> = fields.to_vec();
    let mut seen: HashSet<String> = needed.iter().cloned().collect();
    for entry in &cache.fn_list {
        for dep in &entry.depends {
            if seen.insert(dep.clone()) {
                needed.push(dep.clone());
            }
        }
    }
    needed
}

/// 收集点号嵌套字段信息 `root → [subPath, ...]`
fn collect_dot(fields: &[String]) -> Vec<(String, Vec<String>)> {
    let mut dot_fields: Vec<(String, Vec<String>)> = Vec::new();
    for f in fields {
        let Some(idx) = f.find('.') else { continue };
        let root = &f[..idx];
        let sub = &f[idx + 1..];
        match dot_fields.iter_mut().find(|(k, _)| k == root) {
            Some((_, subs)) => subs.push(sub.to_string()),
            None => dot_fields.push((root.to_string(), vec![sub.to_string()])),
        }
    }
    dot_fields
}

/// 补字段默认值(含点号字段的根字段)
fn fill_defaults(
    doc: &mut Value,
    cache: &Cache,
    needed: &[String],
    dot_fields: &[(String, Vec<String>)],
) {
    let Some(o) = doc.as_object_mut() else { return };
    let mut fill = |key: &str| {
        let absent = o.get(key).map(|v| v.is_null()).unwrap_or(true);
        if absent {
            if let Some(d) = cache.field_defaults.get(key) {
                o.insert(key.to_string(), d.clone());
            }
        }
    };
    for key in needed {
        fill(key);
    }
    for (root, _) in dot_fields {
        fill(root);
    }
}

/// 填充嵌套 object 的点号精确子字段默认值
fn fill_dot_nested(doc: &mut Value, schema: &Schema, root: &str, sub_path: &str) {
    let Some(field) = schema.fields.get(root) else {
        return;
    };
    if !is_object_field(field) {
        return;
    }
    let Some(sub_def) = field
        .fields
        .as_ref()
        .and_then(|v| v.as_object())
        .and_then(|m| m.get(sub_path))
        .cloned()
    else {
        return;
    };
    let Some(root_obj) = doc.as_object_mut().and_then(|o| o.get_mut(root)) else {
        return;
    };
    let Some(ro) = root_obj.as_object_mut() else {
        return;
    };
    let absent = ro.get(sub_path).map(|v| v.is_null()).unwrap_or(true);
    if absent {
        if let Some(d) = raw_field_default(&sub_def) {
            ro.insert(sub_path.to_string(), d);
        }
    }
}

/// 递归填充嵌套 object 子字段默认值(含点号精确子字段)
///
/// 语义(对拍 JS / MongoDB):**仅当**请求以点号精确引用某子字段时,才为缺失的
/// 该子字段补默认值(`_fillDotNested`);请求整个 object 字段时**原样返回存储值**,
/// 不做嵌套默认值回填——否则 `$set` 整体替换存储的 `{cover:"x"}` 会被默认值补回
/// `{level,seo}`,破坏「对象整体替换、返回即所存」契约(B-05)。
fn fill_nested_objects(doc: &mut Value, schema: &Schema, needed: &[String]) {
    for key in needed {
        if let Some(idx) = key.find('.') {
            fill_dot_nested(doc, schema, &key[..idx], &key[idx + 1..]);
        }
    }
}

/// 跑 fn 计算列,再补计算列默认值(对应 JS `_runComputes`)
pub fn run_computes(
    doc: &mut Value,
    cache: &Cache,
    fn_registry: Option<&dyn FnRegistry>,
) -> Result<(), String> {
    if cache.fn_list.is_empty() {
        return Ok(());
    }
    // `doc[key] = fn(doc)`;fn 声明了但 Host 未注册实现 → 报错(与 JS 直接调用缺失函数一致)
    for entry in &cache.fn_list {
        let v = match fn_registry {
            Some(r) => r.call_sync(&entry.fn_ref, doc)?,
            None => return Err(format!("计算列 {} 未注册同步实现", entry.key)),
        };
        if let Some(o) = doc.as_object_mut() {
            o.insert(entry.key.clone(), v);
        }
    }
    // 补计算列默认值:fn 返回 nullish 且 type 有零值时
    for entry in &cache.fn_list {
        let Some(o) = doc.as_object_mut() else {
            continue;
        };
        let absent = o.get(&entry.key).map(|v| v.is_null()).unwrap_or(true);
        if absent {
            if let Some(d) = cache.compute_defaults.get(&entry.key) {
                if !d.is_null() {
                    o.insert(entry.key.clone(), d.clone());
                }
            }
        }
    }
    Ok(())
}

/// 递归下钻嵌套关系文档(跳过不可读关系)
fn descend_relations(
    doc: &mut Value,
    relations: &mut [(String, RelAst)],
    schema: &Schema,
    ctx: Option<&Context>,
    registry: &Registry,
    fn_registry: Option<&dyn FnRegistry>,
) -> Result<(), String> {
    let readable = if ctx.is_some() {
        get_readable_relations(registry.role_rules(), schema, ctx)
    } else {
        None
    };

    for (rel_name, rel_ast) in relations.iter_mut() {
        if let Some(set) = &readable {
            if !set.contains(rel_name) {
                continue;
            }
        }
        let Some(rel_def) = schema.relations.get(&*rel_name) else {
            continue;
        };
        let rel_schema = registry.get(&rel_def.model)?;
        let is_one = rel_def.rel_type == "one";

        let Some(o) = doc.as_object_mut() else {
            continue;
        };
        let stored = o.get(rel_name).cloned();
        let Some(mut rel_val) = stored.filter(|v| !v.is_null()) else {
            // S3:one 关系无匹配 → `null`;many 关系无匹配 → `[]`
            // (对齐 C-01/C-07 形状契约:不得一边 [] 一边 null、也不得缺键)
            o.insert(
                rel_name.clone(),
                if is_one {
                    Value::Null
                } else {
                    Value::Array(Vec::new())
                },
            );
            continue;
        };

        // 关系子文档是否应保留 `_id`:仅当 GQL 显式请求 `{_id}`(S4 读裁剪,C-09/C-10)
        let keep_id = rel_ast.fields.iter().any(|f| f == "_id");
        match &mut rel_val {
            Value::Array(arr) => {
                for item in arr.iter_mut() {
                    process_node(
                        item,
                        &mut rel_ast.fields,
                        &mut rel_ast.relations,
                        rel_schema,
                        ctx,
                        registry,
                        fn_registry,
                    )?;
                    if !keep_id {
                        if let Value::Object(so) = item {
                            so.remove("_id");
                        }
                    }
                }
            }
            Value::Object(_) => {
                process_node(
                    &mut rel_val,
                    &mut rel_ast.fields,
                    &mut rel_ast.relations,
                    rel_schema,
                    ctx,
                    registry,
                    fn_registry,
                )?;
                if !keep_id {
                    if let Some(so) = rel_val.as_object_mut() {
                        so.remove("_id");
                    }
                }
            }
            _ => {}
        }
        // 写回(处理后的关系值;含 one 的 object 与 many 的数组)
        o.insert(rel_name.clone(), rel_val);
    }

    Ok(())
}

/// 仅保留 GQL 字段 + 关系名 + 点号根字段(_id 始终保留)
fn compute_keep(
    fields: &[String],
    relations: &[(String, RelAst)],
    dot_fields: &[(String, Vec<String>)],
) -> HashSet<String> {
    let mut keep: HashSet<String> = fields.iter().cloned().collect();
    for (root, _) in dot_fields {
        keep.insert(root.clone());
    }
    for (rel_name, _) in relations {
        keep.insert(rel_name.clone());
    }
    keep.insert("_id".to_string());
    keep
}

/// 从 keep 中移除用户不可读的字段 / 计算列 / 关系(读权限,不含 Owner 级)。
/// 字段 / 计算列维度叠加 RBAC readFields 交集(deny-wins);关系维度沿用静态
/// `relation.read`(RBAC grant 不覆盖关系维度)。
fn apply_readable_prune(
    fields: &[String],
    relations: &[(String, RelAst)],
    schema: &Schema,
    ctx: Option<&Context>,
    registry: &Registry,
    keep: &mut HashSet<String>,
) {
    let readable_fields = crate::rbac::overlay_readable_fields(
        registry,
        &schema.name,
        ctx,
        get_readable_fields(registry.role_rules(), schema, ctx),
    );
    let readable_computes = crate::rbac::overlay_readable_fields(
        registry,
        &schema.name,
        ctx,
        get_readable_computes(registry.role_rules(), schema, ctx),
    );
    let readable_relations = get_readable_relations(registry.role_rules(), schema, ctx);

    for key in fields {
        if key == "_id" {
            continue;
        }
        let unreadable_field = schema.fields.contains_key(key)
            && readable_fields
                .as_ref()
                .map(|s| !s.contains(key))
                .unwrap_or(false);
        let unreadable_compute = schema.compute(key).is_some()
            && readable_computes
                .as_ref()
                .map(|s| !s.contains(key))
                .unwrap_or(false);
        if unreadable_field || unreadable_compute {
            keep.remove(key);
        }
    }

    if let Some(rels) = readable_relations {
        for (rel_name, _) in relations {
            if !rels.contains(rel_name) {
                keep.remove(rel_name);
            }
        }
    }
}

/// 字段 / 计算列 / 关系的 Owner read 校验(逐条传入 doc 做 creator 检查)
fn apply_owner_read_prune(
    doc: &Value,
    fields: &[String],
    relations: &[(String, RelAst)],
    rules: &RoleRules,
    schema: &Schema,
    ctx: Option<&Context>,
    keep: &mut HashSet<String>,
) {
    for key in fields {
        if key == "_id" || !keep.contains(key) {
            continue;
        }
        if let Some(field) = schema.fields.get(key) {
            if let Some(rl) = &field.read {
                if !evaluate(rules, ctx, Some(rl), Doc::Doc(doc)) {
                    keep.remove(key);
                }
            }
        }
    }

    for (key, comp) in &schema.computes {
        if !keep.contains(key) {
            continue;
        }
        if let Some(rl) = &comp.read {
            if !evaluate(rules, ctx, Some(rl), Doc::Doc(doc)) {
                keep.remove(key);
            }
        }
    }

    for (rel_name, _) in relations {
        if !keep.contains(rel_name) {
            continue;
        }
        if let Some(rel) = schema.relations.get(rel_name) {
            if let Some(rl) = &rel.read {
                if !evaluate(rules, ctx, Some(rl), Doc::Doc(doc)) {
                    keep.remove(rel_name);
                }
            }
        }
    }
}

/// 裁剪点号字段父对象中未请求的子字段
fn prune_dot_subfields(doc: &mut Value, dot_fields: &[(String, Vec<String>)]) {
    for (root, subs) in dot_fields {
        let Some(obj) = doc.as_object_mut().and_then(|o| o.get_mut(root)) else {
            continue;
        };
        if let Some(m) = obj.as_object_mut() {
            m.retain(|k, _| subs.contains(k));
        }
    }
}

/// 递归处理单条文档:补默认值 → 跑 fn 计算列 → 补计算列默认值 → 递归下钻 → 裁剪 → 权限裁剪
///
/// 时序严格(对应 JS `processNode`):
/// 1. 展平 object 子字段
/// 2. 收集 needed / dotFields
/// 3. 补字段默认值
/// 4. 跑 fn 计算列 + 补计算列默认值
/// 5. 递归下钻
/// 6. 权限裁剪
/// 7. 裁剪字段
// 文档后处理需同时携带 schema / registry / ctx / 关系路径等上下文,拆结构体收益低
#[allow(clippy::too_many_arguments)]
pub fn process_node(
    doc: &mut Value,
    fields: &mut Vec<String>,
    relations: &mut Vec<(String, RelAst)>,
    schema: &Schema,
    ctx: Option<&Context>,
    registry: &Registry,
    fn_registry: Option<&dyn FnRegistry>,
) -> Result<(), String> {
    if doc.is_null() {
        return Ok(());
    }

    let cache = ensure_cache(schema);

    // ① 展平 object 子字段花括号语法 → dot-notation
    flatten_object_fields_impl(fields, relations, schema);

    // ② 收集 needed 字段(请求字段 + fn 依赖)与点号字段信息
    let needed = collect_needed(fields, &cache);
    let dot_fields = collect_dot(fields);

    // ③ 补字段默认值 + 递归填充嵌套 object 子字段
    fill_defaults(doc, &cache, &needed, &dot_fields);
    fill_nested_objects(doc, schema, &needed);

    // ④ 跑 fn 计算列 + 补计算列默认值
    run_computes(doc, &cache, fn_registry)?;

    // ⑤ 递归下钻(跳过不可读的关系)
    descend_relations(doc, relations, schema, ctx, registry, fn_registry)?;

    // ⑥ 计算 keep(GQL 字段 + 关系名 + 点号根字段 + _id)
    let mut keep = compute_keep(fields, relations, &dot_fields);

    // ⑦ 权限裁剪(读权限 + Owner 级 read 校验;字段/计算列维度叠加 RBAC 交集)
    if ctx.is_some() {
        apply_readable_prune(fields, relations, schema, ctx, registry, &mut keep);
        apply_owner_read_prune(
            doc,
            fields,
            relations,
            registry.role_rules(),
            schema,
            ctx,
            &mut keep,
        );
    }

    // ⑧ 裁剪字段 + 点号父对象中未请求的子字段
    if let Some(o) = doc.as_object_mut() {
        o.retain(|k, _| keep.contains(k));
    }
    prune_dot_subfields(doc, &dot_fields);

    Ok(())
}