Skip to main content

link_cli/
external_ids.rs

1//! The ids other systems give our links, stored as links (issue #149): a UUID
2//! of a service, an ObjectId of a document database, a URL, bound to a link of
3//! ours and back, so the code that talks to the other system never keeps a
4//! table of its own.
5//!
6//! The ids of one kind share a scheme, such as `uuid`. The point named
7//! `ExternalId` is `E`, the scheme is the link `(S: E S)` named after it, and
8//! a link `l` bound to the id `x` has a pair `(p: S l)` named `scheme:x`, so a
9//! link has one id of a scheme and an id one link. No link of the table but a
10//! pair starts at `S`, so a pair is never a link of the table itself, whatever
11//! address `l` has. The table lives in the data or in a store of its own, as
12//! the rules of permissions do; in a store of its own every address it holds
13//! but its own is an address of the data.
14//!
15//! The C# twin is `LinksExternalIds`; in JavaScript a `RemapLinks` reads the
16//! links under such ids directly.
17
18use anyhow::{bail, Result};
19
20use crate::named_type_links::NamedTypeLinks;
21use crate::types::ensure_point;
22
23/// The name of the point every scheme starts from.
24pub const EXTERNAL_ID_NAME: &str = "ExternalId";
25
26/// The ids of one scheme; see the [module documentation](self). Every method
27/// takes the store of the table: the data or a store of its own.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct LinksExternalIds {
30    scheme: String,
31}
32
33impl LinksExternalIds {
34    /// The ids of `scheme`, such as `uuid`; a scheme has no colon.
35    pub fn new(scheme: &str) -> Result<Self> {
36        if scheme.is_empty() || scheme.contains(':') {
37            bail!("A scheme is not empty and has no colon: {scheme:?}");
38        }
39        Ok(Self {
40            scheme: scheme.to_string(),
41        })
42    }
43
44    /// The kind of the ids.
45    pub fn scheme(&self) -> &str {
46        &self.scheme
47    }
48
49    /// The name of the pair of `id`.
50    pub fn name_of(&self, id: &str) -> Result<String> {
51        if id.is_empty() {
52            bail!("An id is not empty.");
53        }
54        Ok(format!("{}:{id}", self.scheme))
55    }
56
57    /// The link `id` is bound to, `None` when it is bound to none.
58    pub fn find(&self, store: &mut dyn NamedTypeLinks, id: &str) -> Result<Option<u32>> {
59        Ok(self
60            .pair_of(store, id)?
61            .and_then(|pair| store.get_link(pair))
62            .map(|pair| pair.target))
63    }
64
65    /// The id `link` is bound to, `None` when it has none.
66    pub fn id_of(&self, store: &mut dyn NamedTypeLinks, link: u32) -> Result<Option<String>> {
67        let Some(point) = self.scheme_link(store)? else {
68            return Ok(None);
69        };
70        if link == 0 {
71            return Ok(None);
72        }
73        let Some(pair) = store.search(point, link) else {
74            return Ok(None);
75        };
76        let prefix = format!("{}:", self.scheme);
77        Ok(store
78            .get_name(pair)?
79            .and_then(|name| name.strip_prefix(&prefix).map(str::to_string)))
80    }
81
82    /// Binds `id` to `link`, instead of any link it had and of any id the
83    /// link had; returns the pair that binds them.
84    pub fn bind(&self, store: &mut dyn NamedTypeLinks, id: &str, link: u32) -> Result<u32> {
85        let name = self.name_of(id)?;
86        if link == 0 {
87            bail!("The null link has no id.");
88        }
89        self.unbind(store, id)?;
90        let point = match self.scheme_link(store)? {
91            Some(point) => point,
92            None => {
93                let root = ensure_point(store, EXTERNAL_ID_NAME)?;
94                let point = store.try_create(0, 0)?;
95                store.update(point, root, point)?;
96                store.set_name(point, &self.scheme)?;
97                point
98            }
99        };
100        let pair = match store.search(point, link) {
101            Some(pair) => pair,
102            None => store.try_create(point, link)?,
103        };
104        store.set_name(pair, &name)?;
105        Ok(pair)
106    }
107
108    /// The link `id` is bound to, a new point `(l: l l)` of `data` bound to
109    /// it when it has none. `data` is `None` when the table is in the data.
110    pub fn ensure(
111        &self,
112        store: &mut dyn NamedTypeLinks,
113        data: Option<&mut dyn NamedTypeLinks>,
114        id: &str,
115    ) -> Result<u32> {
116        if let Some(found) = self.find(store, id)? {
117            return Ok(found);
118        }
119        let link = match data {
120            Some(data) => new_point(data)?,
121            None => new_point(store)?,
122        };
123        self.bind(store, id, link)?;
124        Ok(link)
125    }
126
127    /// Unbinds `id`; whether it was bound.
128    pub fn unbind(&self, store: &mut dyn NamedTypeLinks, id: &str) -> Result<bool> {
129        let Some(pair) = self.pair_of(store, id)? else {
130            return Ok(false);
131        };
132        store.remove_name(pair)?;
133        store.delete(pair)?;
134        Ok(true)
135    }
136
137    fn pair_of(&self, store: &mut dyn NamedTypeLinks, id: &str) -> Result<Option<u32>> {
138        let name = self.name_of(id)?;
139        let Some(point) = self.scheme_link(store)? else {
140            return Ok(None);
141        };
142        let Some(pair) = store.get_by_name(&name)?.filter(|&pair| pair != 0) else {
143            return Ok(None);
144        };
145        Ok(store
146            .get_link(pair)
147            .filter(|link| link.source == point)
148            .map(|_| pair))
149    }
150
151    /// The link `(S: E S)` of the scheme, `None` when the table has none yet.
152    fn scheme_link(&self, store: &mut dyn NamedTypeLinks) -> Result<Option<u32>> {
153        let Some(root) = store
154            .get_by_name(EXTERNAL_ID_NAME)?
155            .filter(|&root| root != 0)
156        else {
157            return Ok(None);
158        };
159        let Some(point) = store.get_by_name(&self.scheme)?.filter(|&point| point != 0) else {
160            return Ok(None);
161        };
162        Ok(store
163            .get_link(point)
164            .filter(|link| link.source == root && link.target == point)
165            .map(|_| point))
166    }
167}
168
169fn new_point(links: &mut dyn NamedTypeLinks) -> Result<u32> {
170    let link = links.try_create(0, 0)?;
171    links.update(link, link, link)?;
172    Ok(link)
173}