Skip to main content

link_cli/graphql/
virtual_tables.rs

1//! Tables Deep derives from links with triggers and views. Here they are
2//! computed from the links when asked, for as long as nothing is written:
3//! values and `can` always, `tree` and `selectors` from the `Tree*` and
4//! `Selector*` links, `mp` the same paths under its own column names.
5//! `handlers` is empty, as Deep's handlers do not run here.
6
7use std::collections::{BTreeMap, HashMap, HashSet};
8
9use super::execute::{Exec, GqlResult};
10use super::json::Json;
11use super::store::{LinkRow, ValueRow};
12use crate::triplets::TripletQuery;
13
14/// Which `(parent, child)` edges a link of an included type makes, over its
15/// `from`, itself and its `to`. These are the groups of include types Deep's
16/// `isAllowSpread*` conditions test, in `1621815803572-materialized-path.ts`.
17const SPREADS: [(&str, [&str; 4]); 4] = [
18    (
19        "from-link",
20        [
21            "TreeIncludeDown",
22            "TreeIncludeIn",
23            "TreeIncludeFromCurrent",
24            "TreeIncludeFromCurrentTo",
25        ],
26    ),
27    (
28        "to-link",
29        [
30            "TreeIncludeUp",
31            "TreeIncludeIn",
32            "TreeIncludeToCurrent",
33            "TreeIncludeToCurrentFrom",
34        ],
35    ),
36    (
37        "link-to",
38        [
39            "TreeIncludeDown",
40            "TreeIncludeOut",
41            "TreeIncludeCurrentTo",
42            "TreeIncludeFromCurrentTo",
43        ],
44    ),
45    (
46        "link-from",
47        [
48            "TreeIncludeUp",
49            "TreeIncludeOut",
50            "TreeIncludeCurrentFrom",
51            "TreeIncludeToCurrentFrom",
52        ],
53    ),
54];
55
56/// Every other include type: it only makes a link a member of its tree.
57const MEMBERSHIP_ONLY: [&str; 1] = ["TreeIncludeNode"];
58
59impl Exec<'_, '_> {
60    pub fn value_json(row: u32, value: &ValueRow) -> Json {
61        Json::object(vec![
62            ("id", Json::Int(i64::from(row))),
63            ("link_id", Json::Int(value.owner)),
64            ("value", value.value.clone()),
65        ])
66    }
67
68    /// The row of a triplet below permissions, for the server's own lookups.
69    pub fn raw_row(&mut self, triplet: u32) -> Option<LinkRow> {
70        let admin = std::mem::replace(&mut self.store.admin, true);
71        let found = self.store.view(0, |view| view.get_triplet(triplet));
72        self.store.admin = admin;
73        self.store.row_of(&found?)
74    }
75
76    fn all_links(&mut self) -> Vec<LinkRow> {
77        let admin = std::mem::replace(&mut self.store.admin, true);
78        let all = self
79            .store
80            .view(0, |view| view.each_triplet(TripletQuery::any()));
81        self.store.admin = admin;
82        all.iter()
83            .filter_map(|triplet| self.store.row_of(triplet))
84            .collect()
85    }
86
87    /// Every row of a table that is not `links`, as the subject sees them.
88    pub fn table_rows(&mut self, table: &str) -> GqlResult<Vec<Json>> {
89        Ok(match table {
90            "strings" | "numbers" | "objects" => {
91                let kind = super::store::ValueKind::of_table(table);
92                let rows: Vec<(u32, ValueRow)> = self
93                    .store
94                    .values()
95                    .filter(|(_, value)| Some(value.kind) == kind)
96                    .map(|(row, value)| (row, value.clone()))
97                    .collect();
98                // A value is seen with its owner.
99                let subject = self.subject;
100                let policy = self.store.has_policy();
101                let mut out = Vec::with_capacity(rows.len());
102                for (row, value) in rows {
103                    let seen = !policy || {
104                        let address = self.store.triplet_of(value.owner);
105                        address.is_some_and(|address| {
106                            self.store
107                                .view(subject, |view| view.get_triplet(address))
108                                .is_some()
109                        })
110                    };
111                    if seen {
112                        out.push(Self::value_json(row, &value));
113                    }
114                }
115                out
116            }
117            "can" => self.can_rows(),
118            "tree" => self.derived("tree", Self::tree_rows),
119            "selectors" => self.derived("selectors", Self::selector_rows),
120            "mp" => self.mp_rows(),
121            "healthz" => vec![Json::object(vec![("status", Json::str("ok"))])],
122            _ => Vec::new(),
123        })
124    }
125
126    /// A table computed from the links, kept until the next write.
127    fn derived(&mut self, table: &'static str, compute: fn(&mut Self) -> Vec<Json>) -> Vec<Json> {
128        let generation = self.store.generation;
129        if !self.store.in_mutation {
130            if let Some((at, rows)) = self.store.derived.get(table) {
131                if *at == generation {
132                    return rows.clone();
133                }
134            }
135        }
136        let rows = compute(self);
137        if !self.store.in_mutation {
138            self.store.derived.insert(table, (generation, rows.clone()));
139        }
140        rows
141    }
142
143    /// The policy's grants as Deep's `can`: a rule on `Anything` stands as the
144    /// id `0` rather than one row for each link it reaches.
145    fn can_rows(&mut self) -> Vec<Json> {
146        let (select, update) = (self.core_id("AllowSelect"), self.core_id("AllowUpdate"));
147        let mut rows = Vec::new();
148        for (write, subject, object) in self.store.grants() {
149            let action = if write { update } else { select };
150            rows.push(Json::object(vec![
151                ("rule_id", Json::Int(0)),
152                ("action_id", action.map_or(Json::Int(0), Json::Int)),
153                ("object_id", Json::Int(object.unwrap_or(0))),
154                ("subject_id", Json::Int(subject.unwrap_or(0))),
155            ]));
156        }
157        rows
158    }
159
160    /// `tree`: every path from a root to a link, one row per link on it, as
161    /// Deep's materialized path stores them. `typesTree` is built in: a link's
162    /// parent is its type.
163    fn tree_rows(&mut self) -> Vec<Json> {
164        let links = self.all_links();
165        let any = self.core_id("Any");
166        let types_tree = self.core_id("typesTree");
167        let mut spreads: HashMap<i64, Vec<&'static str>> = HashMap::new();
168        for (spread, names) in SPREADS {
169            for name in names {
170                if let Some(id) = self.core_id(name) {
171                    spreads.entry(id).or_default().push(spread);
172                }
173            }
174        }
175        for name in MEMBERSHIP_ONLY {
176            if let Some(id) = self.core_id(name) {
177                spreads.entry(id).or_default();
178            }
179        }
180        // tree -> included type -> the edges its links make.
181        let mut trees: BTreeMap<i64, HashMap<i64, HashSet<&'static str>>> = BTreeMap::new();
182        for link in &links {
183            if Some(link.from_id) == types_tree {
184                continue;
185            }
186            if let Some(made) = spreads.get(&link.type_id) {
187                trees
188                    .entry(link.from_id)
189                    .or_default()
190                    .entry(link.to_id)
191                    .or_default()
192                    .extend(made.iter().copied());
193            }
194        }
195        let mut rows = Vec::new();
196        if let Some(tree) = types_tree {
197            let parents = links
198                .iter()
199                .filter(|link| link.type_id != link.id && link.type_id != 0)
200                .map(|link| (link.id, link.type_id))
201                .fold(HashMap::<i64, Vec<i64>>::new(), |mut all, (id, parent)| {
202                    all.entry(id).or_default().push(parent);
203                    all
204                });
205            let nodes: Vec<i64> = links.iter().map(|link| link.id).collect();
206            push_paths(&mut rows, tree, nodes, &parents);
207        }
208        for (tree, includes) in trees {
209            let wanted = |type_id: i64| {
210                includes.contains_key(&type_id) || any.is_some_and(|a| includes.contains_key(&a))
211            };
212            let members: HashSet<i64> = links
213                .iter()
214                .filter(|link| wanted(link.type_id))
215                .map(|link| link.id)
216                .collect();
217            let mut parents: HashMap<i64, Vec<i64>> = HashMap::new();
218            for link in links.iter().filter(|link| members.contains(&link.id)) {
219                let made = includes.get(&link.type_id);
220                for spread in made.into_iter().flatten() {
221                    let (parent, child) = match *spread {
222                        "from-link" => (link.from_id, link.id),
223                        "to-link" => (link.to_id, link.id),
224                        "link-to" => (link.id, link.to_id),
225                        _ => (link.id, link.from_id),
226                    };
227                    if parent != child && members.contains(&parent) && members.contains(&child) {
228                        let list = parents.entry(child).or_default();
229                        if !list.contains(&parent) {
230                            list.push(parent);
231                        }
232                    }
233                }
234            }
235            // The rows do not depend on the order the includes were hashed in.
236            parents.values_mut().for_each(|list| list.sort_unstable());
237            let mut nodes: Vec<i64> = members.into_iter().collect();
238            nodes.sort_unstable();
239            push_paths(&mut rows, tree, nodes, &parents);
240        }
241        rows
242    }
243
244    /// `mp`: the rows of `tree`, as Deep's own table names their columns.
245    fn mp_rows(&mut self) -> Vec<Json> {
246        let renamed = [
247            ("id", "id"),
248            ("item_id", "link_id"),
249            ("path_item_id", "parent_id"),
250            ("path_item_depth", "depth"),
251            ("root_id", "root_id"),
252            ("position_id", "position_id"),
253            ("group_id", "tree_id"),
254        ];
255        self.derived("tree", Self::tree_rows)
256            .iter()
257            .map(|row| {
258                Json::object(
259                    renamed
260                        .iter()
261                        .map(|(name, column)| {
262                            (*name, row.get(column).cloned().unwrap_or(Json::Null))
263                        })
264                        .collect(),
265                )
266            })
267            .collect()
268    }
269
270    /// `selectors`: what a `SelectorInclude` reaches down its tree.
271    fn selector_rows(&mut self) -> Vec<Json> {
272        let (Some(include), Some(tree_link)) = (
273            self.core_id("SelectorInclude"),
274            self.core_id("SelectorTree"),
275        ) else {
276            return Vec::new();
277        };
278        let filter = self.core_id("SelectorFilter");
279        let links = self.all_links();
280        let tree_rows = self.derived("tree", Self::tree_rows);
281        let mut reached: HashMap<(i64, i64), Vec<i64>> = HashMap::new();
282        let int = |row: &Json, key: &str| row.get(key).and_then(Json::as_i64).unwrap_or(0);
283        for row in &tree_rows {
284            reached
285                .entry((int(row, "tree_id"), int(row, "parent_id")))
286                .or_default()
287                .push(int(row, "link_id"));
288        }
289        let mut trees_of: HashMap<i64, Vec<i64>> = HashMap::new();
290        let mut query_of: HashMap<i64, i64> = HashMap::new();
291        for link in &links {
292            if link.type_id == tree_link {
293                trees_of.entry(link.from_id).or_default().push(link.to_id);
294            } else if Some(link.type_id) == filter {
295                query_of.insert(link.from_id, link.to_id);
296            }
297        }
298        let mut rows = Vec::new();
299        for link in links.iter().filter(|link| link.type_id == include) {
300            for tree in trees_of.get(&link.id).into_iter().flatten() {
301                for item in reached.get(&(*tree, link.to_id)).into_iter().flatten() {
302                    rows.push(Json::object(vec![
303                        ("item_id", Json::Int(*item)),
304                        ("selector_id", Json::Int(link.from_id)),
305                        ("selector_include_id", Json::Int(link.id)),
306                        (
307                            "query_id",
308                            Json::Int(query_of.get(&link.from_id).copied().unwrap_or(0)),
309                        ),
310                    ]));
311                }
312            }
313        }
314        rows
315    }
316}
317
318/// The rows of every path to each of `nodes`. Deep refuses cycles when they are
319/// written; here a link already on a path ends it.
320fn push_paths(rows: &mut Vec<Json>, tree: i64, nodes: Vec<i64>, parents: &HashMap<i64, Vec<i64>>) {
321    fn walk(
322        node: i64,
323        parents: &HashMap<i64, Vec<i64>>,
324        path: &mut Vec<i64>,
325        out: &mut Vec<Vec<i64>>,
326    ) {
327        path.push(node);
328        let above: Vec<i64> = parents
329            .get(&node)
330            .into_iter()
331            .flatten()
332            .copied()
333            .filter(|parent| !path.contains(parent))
334            .collect();
335        if above.is_empty() {
336            out.push(path.iter().rev().copied().collect());
337        }
338        for parent in above {
339            walk(parent, parents, path, out);
340        }
341        path.pop();
342    }
343    for node in nodes {
344        let mut paths = Vec::new();
345        walk(node, parents, &mut Vec::new(), &mut paths);
346        for (position, path) in paths.iter().enumerate() {
347            for (depth, parent) in path.iter().enumerate() {
348                let id = rows.len() as i64 + 1;
349                rows.push(Json::object(vec![
350                    ("id", Json::Int(id)),
351                    ("link_id", Json::Int(node)),
352                    ("tree_id", Json::Int(tree)),
353                    ("root_id", Json::Int(path[0])),
354                    ("parent_id", Json::Int(*parent)),
355                    ("depth", Json::Int(depth as i64)),
356                    (
357                        "position_id",
358                        Json::String(format!("{tree}-{node}-{position}")),
359                    ),
360                    ("self", Json::Bool(*parent == node)),
361                ]));
362            }
363        }
364    }
365}