Skip to main content

link_cli/graphql/
store.rs

1//! The rows of Deep over triplets.
2//!
3//! A row of `links` is a triplet with the external id `deep:<id>`, since Deep's
4//! ids are not the addresses of the store. Deep's type `0` is a triplet of its
5//! own, `DeepNoType`, because a triplet always has a type. A row of `strings`,
6//! `numbers` or `objects` is a triplet `(row: DeepString owner 0)`, so deleting
7//! the owner takes it along, and its text is the name `<row>:<text>`. Addresses
8//! and values are also kept in memory, rebuilt from the links when opening.
9
10use std::collections::{BTreeMap, HashMap, HashSet};
11
12use anyhow::{anyhow, bail, Result};
13
14use super::json::Json;
15use super::plan::Position;
16use crate::external_ids::LinksExternalIds;
17use crate::link::Link;
18use crate::named_type_links::NamedTypeLinks;
19use crate::permissions::{PermissionPolicy, PermissionsDecorator};
20use crate::triplets::{cascade_of, Triplet, TripletQuery, Triplets, TripletsOverDoublets};
21use crate::undoable_links::UndoableLinksDecorator;
22
23/// The tables of values.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum ValueKind {
26    String,
27    Number,
28    Object,
29}
30
31impl ValueKind {
32    pub const ALL: [ValueKind; 3] = [ValueKind::String, ValueKind::Number, ValueKind::Object];
33
34    pub fn table(self) -> &'static str {
35        match self {
36            ValueKind::String => "strings",
37            ValueKind::Number => "numbers",
38            ValueKind::Object => "objects",
39        }
40    }
41
42    pub fn of_table(table: &str) -> Option<Self> {
43        Self::ALL.into_iter().find(|kind| kind.table() == table)
44    }
45
46    fn marker_name(self) -> &'static str {
47        match self {
48            ValueKind::String => "DeepString",
49            ValueKind::Number => "DeepNumber",
50            ValueKind::Object => "DeepObject",
51        }
52    }
53
54    fn encode(self, value: &Json) -> String {
55        match (self, value) {
56            (ValueKind::String, Json::String(text)) => text.clone(),
57            _ => value.write(),
58        }
59    }
60
61    fn decode(self, text: &str) -> Json {
62        match self {
63            ValueKind::String => Json::str(text),
64            _ => Json::parse(text).unwrap_or(Json::Null),
65        }
66    }
67}
68
69/// A row of `links`.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct LinkRow {
72    pub id: i64,
73    pub type_id: i64,
74    pub from_id: i64,
75    pub to_id: i64,
76}
77
78impl LinkRow {
79    pub fn to_json(self) -> Json {
80        Json::object(vec![
81            ("id", Json::Int(self.id)),
82            ("type_id", Json::Int(self.type_id)),
83            ("from_id", Json::Int(self.from_id)),
84            ("to_id", Json::Int(self.to_id)),
85        ])
86    }
87}
88
89#[derive(Debug, Clone)]
90pub struct ValueRow {
91    pub kind: ValueKind,
92    pub owner: i64,
93    pub value: Json,
94}
95
96pub struct DeepStore<'s> {
97    triplets: TripletsOverDoublets<UndoableLinksDecorator<&'s mut (dyn NamedTypeLinks + 's)>>,
98    policy: Option<PermissionPolicy>,
99    created: HashMap<u32, HashSet<u32>>,
100    ids: LinksExternalIds,
101    to_triplet: HashMap<i64, u32>,
102    to_deep: HashMap<u32, i64>,
103    values: BTreeMap<u32, ValueRow>,
104    by_owner: HashMap<(ValueKind, i64), u32>,
105    markers: [u32; 3],
106    no_type: u32,
107    next_id: i64,
108    /// `x-hasura-admin-secret`: the request is not judged by the policy.
109    pub admin: bool,
110    /// Bumped by every committed write, for what is derived from the rows.
111    pub generation: u64,
112    /// Derived tables by name, for the `generation` they were computed at.
113    pub derived: HashMap<&'static str, (u64, Vec<Json>)>,
114    /// Inside a mutation what is derived is not kept: it may yet change.
115    pub in_mutation: bool,
116}
117
118fn named_point<T: Triplets + NamedTypeLinks>(triplets: &mut T, name: &str) -> Result<u32> {
119    if let Some(found) = triplets.get_by_name(name)? {
120        return Ok(found);
121    }
122    let point = triplets.create_triplet_point()?;
123    triplets.set_name(point, name)?;
124    Ok(point)
125}
126
127impl<'s> DeepStore<'s> {
128    pub fn open(
129        links: &'s mut (dyn NamedTypeLinks + 's),
130        policy: Option<PermissionPolicy>,
131    ) -> Result<Self> {
132        let mut triplets =
133            TripletsOverDoublets::with_named_markers(UndoableLinksDecorator::new(links))?;
134        let no_type = named_point(&mut triplets, "DeepNoType")?;
135        let mut markers = [0; 3];
136        for (slot, kind) in markers.iter_mut().zip(ValueKind::ALL) {
137            *slot = named_point(&mut triplets, kind.marker_name())?;
138        }
139        let mut store = Self {
140            triplets,
141            policy,
142            created: HashMap::new(),
143            ids: LinksExternalIds::new("deep")?,
144            to_triplet: HashMap::new(),
145            to_deep: HashMap::new(),
146            values: BTreeMap::new(),
147            by_owner: HashMap::new(),
148            markers,
149            no_type,
150            next_id: 1,
151            admin: false,
152            generation: 0,
153            derived: HashMap::new(),
154            in_mutation: false,
155        };
156        store.reload()?;
157        Ok(store)
158    }
159
160    /// Rebuilds what is kept in memory from the links.
161    fn reload(&mut self) -> Result<()> {
162        self.to_triplet.clear();
163        self.to_deep.clear();
164        self.values.clear();
165        self.by_owner.clear();
166        self.next_id = 1;
167        for triplet in self.triplets.each_triplet(TripletQuery::any()) {
168            if let Some(id) = self.ids.id_of(&mut self.triplets, triplet.index)? {
169                if let Ok(id) = id.parse::<i64>() {
170                    self.to_triplet.insert(id, triplet.index);
171                    self.to_deep.insert(triplet.index, id);
172                    self.next_id = self.next_id.max(id + 1);
173                }
174            }
175        }
176        for (marker, kind) in self.markers.into_iter().zip(ValueKind::ALL) {
177            for row in self.triplets.each_triplet(TripletQuery::by_type(marker)) {
178                let Some(&owner) = self.to_deep.get(&row.from) else {
179                    continue;
180                };
181                let name = self.triplets.get_name(row.index)?.unwrap_or_default();
182                let text = name.split_once(':').map_or("", |(_, text)| text);
183                self.by_owner.insert((kind, owner), row.index);
184                self.values.insert(
185                    row.index,
186                    ValueRow {
187                        kind,
188                        owner,
189                        value: kind.decode(text),
190                    },
191                );
192            }
193        }
194        Ok(())
195    }
196
197    /// Runs `read` over the triplets as `subject` sees them.
198    pub fn view<R>(&mut self, subject: u32, read: impl FnOnce(&mut dyn Triplets) -> R) -> R {
199        match &mut self.policy {
200            Some(_) if self.admin => read(&mut self.triplets),
201            None => read(&mut self.triplets),
202            Some(policy) => {
203                let created = self.created.remove(&subject).unwrap_or_default();
204                let mut view = PermissionsDecorator::new(&mut self.triplets, policy, subject)
205                    .with_created(created);
206                let result = read(&mut view);
207                let created = view.created().clone();
208                self.created.insert(subject, created);
209                result
210            }
211        }
212    }
213
214    pub fn has_policy(&self) -> bool {
215        self.policy.is_some()
216    }
217
218    pub fn triplet_of(&self, id: i64) -> Option<u32> {
219        self.to_triplet.get(&id).copied()
220    }
221
222    /// The address a Deep id stands for in `position` of a query.
223    pub fn address(&self, position: Position, id: i64) -> Option<u32> {
224        if id == 0 && position == Position::Type {
225            return Some(self.no_type);
226        }
227        self.triplet_of(id)
228    }
229
230    pub fn deep_of(&self, triplet: u32) -> Option<i64> {
231        self.to_deep.get(&triplet).copied()
232    }
233
234    /// The row of a triplet, if it is a row of `links`.
235    pub fn row_of(&self, triplet: &Triplet) -> Option<LinkRow> {
236        let id = self.deep_of(triplet.index)?;
237        let part = |address: u32| {
238            if address == 0 {
239                Some(0)
240            } else {
241                self.deep_of(address)
242            }
243        };
244        let type_id = if triplet.type_id == self.no_type {
245            0
246        } else {
247            self.deep_of(triplet.type_id)?
248        };
249        Some(LinkRow {
250            id,
251            type_id,
252            from_id: part(triplet.from)?,
253            to_id: part(triplet.to)?,
254        })
255    }
256
257    pub fn values(&self) -> impl Iterator<Item = (u32, &ValueRow)> {
258        self.values.iter().map(|(row, value)| (*row, value))
259    }
260
261    pub fn value_of_owner(&self, kind: ValueKind, owner: i64) -> Option<(u32, &ValueRow)> {
262        let row = *self.by_owner.get(&(kind, owner))?;
263        self.values.get(&row).map(|value| (row, value))
264    }
265
266    pub fn value(&self, row: u32) -> Option<&ValueRow> {
267        self.values.get(&row)
268    }
269
270    pub fn reserve(&mut self, count: i64) -> Vec<i64> {
271        let first = self.next_id;
272        self.next_id += count.max(0);
273        (first..self.next_id).collect()
274    }
275
276    pub fn begin(&mut self) {
277        self.in_mutation = true;
278        self.triplets.links_mut().begin();
279    }
280
281    pub fn commit(&mut self) -> Result<()> {
282        self.in_mutation = false;
283        self.triplets.links_mut().commit();
284        self.generation += 1;
285        self.triplets.save()
286    }
287
288    pub fn rollback(&mut self) -> Result<()> {
289        self.in_mutation = false;
290        self.triplets.links_mut().rollback()?;
291        self.reload()
292    }
293
294    fn type_address(&self, type_id: i64) -> Result<u32> {
295        self.address(Position::Type, type_id)
296            .ok_or_else(|| anyhow!("Foreign key violation: no link {type_id} for type_id."))
297    }
298
299    fn part_address(&self, id: i64, column: &str) -> Result<u32> {
300        if id == 0 {
301            return Ok(0);
302        }
303        self.triplet_of(id)
304            .ok_or_else(|| anyhow!("Foreign key violation: no link {id} for {column}."))
305    }
306
307    /// Inserts a row of `links`; a part may name the id being inserted.
308    pub fn create_link(
309        &mut self,
310        subject: u32,
311        id: Option<i64>,
312        type_id: i64,
313        from_id: i64,
314        to_id: i64,
315    ) -> Result<i64> {
316        let id = id.unwrap_or(self.next_id);
317        if self.to_triplet.contains_key(&id) {
318            bail!("Uniqueness violation: duplicate key value violates unique constraint \"links_pkey\": {id}.");
319        }
320        if type_id == id || from_id == id || to_id == id {
321            let point = self.view(subject, |view| view.create_triplet_point())?;
322            self.install(id, point)?;
323            self.update_link(subject, id, type_id, from_id, to_id)?;
324        } else {
325            let (type_address, from, to) = (
326                self.type_address(type_id)?,
327                self.part_address(from_id, "from_id")?,
328                self.part_address(to_id, "to_id")?,
329            );
330            let triplet = self.view(subject, |view| view.create_triplet(type_address, from, to))?;
331            self.install(id, triplet)?;
332        }
333        Ok(id)
334    }
335
336    fn install(&mut self, id: i64, triplet: u32) -> Result<()> {
337        self.ids
338            .bind(&mut self.triplets, &id.to_string(), triplet)?;
339        self.to_triplet.insert(id, triplet);
340        self.to_deep.insert(triplet, id);
341        self.next_id = self.next_id.max(id + 1);
342        Ok(())
343    }
344
345    pub fn update_link(
346        &mut self,
347        subject: u32,
348        id: i64,
349        type_id: i64,
350        from_id: i64,
351        to_id: i64,
352    ) -> Result<()> {
353        let index = self.part_address(id, "id")?;
354        let (type_address, from, to) = (
355            self.type_address(type_id)?,
356            self.part_address(from_id, "from_id")?,
357            self.part_address(to_id, "to_id")?,
358        );
359        self.view(subject, |view| {
360            view.update_triplet(index, type_address, from, to)
361        })?;
362        Ok(())
363    }
364
365    /// Deletes a row of `links` and all that uses it; returns the ids deleted.
366    pub fn delete_link(&mut self, subject: u32, id: i64) -> Result<Vec<i64>> {
367        let index = self.part_address(id, "id")?;
368        let Some(first) = self.triplets.get_triplet(index) else {
369            bail!("Link {id} is not a triplet.");
370        };
371        let cascade = cascade_of(&mut self.triplets, first);
372        let mut deleted = Vec::new();
373        // The external ids and value names point at the rows: they go first.
374        for triplet in &cascade {
375            if let Some(deep) = self.deep_of(triplet.index) {
376                self.ids.unbind(&mut self.triplets, &deep.to_string())?;
377                deleted.push(deep);
378            }
379            if self.values.contains_key(&triplet.index) {
380                self.triplets.remove_name(triplet.index)?;
381            }
382        }
383        self.view(subject, |view| view.delete_triplet(index))?;
384        for triplet in &cascade {
385            if let Some(deep) = self.to_deep.remove(&triplet.index) {
386                self.to_triplet.remove(&deep);
387            }
388            if let Some(row) = self.values.remove(&triplet.index) {
389                self.by_owner.remove(&(row.kind, row.owner));
390            }
391        }
392        Ok(deleted)
393    }
394
395    /// Whether `subject` may change what hangs on the link `owner`.
396    fn require_owner_writable(&mut self, subject: u32, owner: i64) -> Result<u32> {
397        let address = self.part_address(owner, "link_id")?;
398        if let (Some(policy), false) = (&mut self.policy, self.admin) {
399            let outer = self.triplets.get_link(address);
400            let created = self.created.remove(&subject).unwrap_or_default();
401            let mut view = PermissionsDecorator::new(&mut self.triplets, policy, subject)
402                .with_created(created);
403            let allowed = outer.is_some_and(|outer: Link| view.can_write_triplet(&outer));
404            let created = view.created().clone();
405            self.created.insert(subject, created);
406            if !allowed {
407                bail!("Forbidden: {subject} may not write the value of {owner}.");
408            }
409        }
410        Ok(address)
411    }
412
413    pub fn create_value(
414        &mut self,
415        subject: u32,
416        kind: ValueKind,
417        owner: i64,
418        value: Json,
419    ) -> Result<u32> {
420        let address = self.require_owner_writable(subject, owner)?;
421        if self.by_owner.contains_key(&(kind, owner)) {
422            bail!(
423                "Uniqueness violation: link {owner} already has a row in {}.",
424                kind.table()
425            );
426        }
427        let marker = self.markers[ValueKind::ALL.iter().position(|k| *k == kind).unwrap_or(0)];
428        let row = self.triplets.create_triplet(marker, address, 0)?;
429        self.triplets
430            .set_name(row, &format!("{row}:{}", kind.encode(&value)))?;
431        self.by_owner.insert((kind, owner), row);
432        self.values.insert(row, ValueRow { kind, owner, value });
433        Ok(row)
434    }
435
436    pub fn update_value(&mut self, subject: u32, row: u32, value: Json) -> Result<()> {
437        let Some(found) = self.values.get(&row).cloned() else {
438            bail!("No value row {row}.");
439        };
440        self.require_owner_writable(subject, found.owner)?;
441        self.triplets
442            .set_name(row, &format!("{row}:{}", found.kind.encode(&value)))?;
443        if let Some(stored) = self.values.get_mut(&row) {
444            stored.value = value;
445        }
446        Ok(())
447    }
448
449    pub fn delete_value(&mut self, subject: u32, row: u32) -> Result<()> {
450        let Some(found) = self.values.get(&row).cloned() else {
451            bail!("No value row {row}.");
452        };
453        self.require_owner_writable(subject, found.owner)?;
454        self.triplets.remove_name(row)?;
455        self.triplets.delete_triplet(row)?;
456        self.values.remove(&row);
457        self.by_owner.remove(&(found.kind, found.owner));
458        Ok(())
459    }
460
461    /// Loads rows `{id, type_id, from_id, to_id, string?, number?, object?}`,
462    /// such as a dump of `@deep-foundation/core`; rows already there are left
463    /// alone, so loading twice changes nothing. Ids may refer forward, so all
464    /// the points are made first.
465    pub fn load_package(&mut self, rows: &Json) -> Result<usize> {
466        let rows = rows.as_list();
467        let int = |row: &Json, key: &str| row.get(key).and_then(Json::as_i64).unwrap_or(0);
468        let fresh: Vec<&Json> = rows
469            .iter()
470            .copied()
471            .filter(|row| self.triplet_of(int(row, "id")).is_none())
472            .collect();
473        for row in &fresh {
474            let point = self.triplets.create_triplet_point()?;
475            self.install(int(row, "id"), point)?;
476        }
477        for row in &fresh {
478            let (index, type_address, from, to) = (
479                self.part_address(int(row, "id"), "id")?,
480                self.type_address(int(row, "type_id"))?,
481                self.part_address(int(row, "from_id"), "from_id")?,
482                self.part_address(int(row, "to_id"), "to_id")?,
483            );
484            self.triplets
485                .update_triplet(index, type_address, from, to)?;
486        }
487        for row in &fresh {
488            for (key, kind) in [
489                ("string", ValueKind::String),
490                ("number", ValueKind::Number),
491                ("object", ValueKind::Object),
492            ] {
493                if let Some(value) = row.get(key) {
494                    let address = self.part_address(int(row, "id"), "id")?;
495                    let marker =
496                        self.markers[ValueKind::ALL.iter().position(|k| *k == kind).unwrap_or(0)];
497                    let value_row = self.triplets.create_triplet(marker, address, 0)?;
498                    self.triplets
499                        .set_name(value_row, &format!("{value_row}:{}", kind.encode(value)))?;
500                    self.by_owner.insert((kind, int(row, "id")), value_row);
501                    self.values.insert(
502                        value_row,
503                        ValueRow {
504                            kind,
505                            owner: int(row, "id"),
506                            value: value.clone(),
507                        },
508                    );
509                }
510            }
511        }
512        self.triplets.save()?;
513        self.generation += 1;
514        Ok(fresh.len())
515    }
516
517    /// The grants of the policy as `(marker name, subject, object)`, in Deep ids
518    /// (`None` where the rule says `Anything`).
519    pub fn grants(&mut self) -> Vec<(bool, Option<i64>, Option<i64>)> {
520        let Some(policy) = &mut self.policy else {
521            return Vec::new();
522        };
523        use crate::permissions::AccessPolicy;
524        let markers = policy.markers();
525        let mut grants = Vec::new();
526        for (write, marker) in [(false, markers.allow_read), (true, markers.allow_write)] {
527            for (subject, object) in policy.granted(&mut self.triplets, marker) {
528                let side = |side: u32| {
529                    if side == markers.anything {
530                        Some(None)
531                    } else {
532                        self.to_deep.get(&side).map(|id| Some(*id))
533                    }
534                };
535                if let (Some(subject), Some(object)) = (side(subject), side(object)) {
536                    grants.push((write, subject, object));
537                }
538            }
539        }
540        grants
541    }
542}