Skip to main content

link_cli/protocol/
links_operations.rs

1//! The links interface (`ILinks` in C#, [`doublets::Links`] in Rust) as LiNo
2//! documents, so a store behind a [`LinksServer`](super::LinksServer) is used
3//! exactly like a local one through [`RemoteLinks`](super::RemoteLinks).
4//!
5//! Every request is one top-level link named after the operation and holding
6//! exactly one value. The substitution query language ignores that shape (a
7//! query needs a restriction *and* a substitution), so an operation never
8//! collides with a query sent to the same server.
9//!
10//! | Request                          | Reply                                  |
11//! |----------------------------------|----------------------------------------|
12//! | `(count: (index source target))` | `(count: N)`                           |
13//! | `(each: (index source target))`  | one `(index: source target)` per match |
14//! | `(create: (source target))`      | `() ((index: source target))`          |
15//! | `(update: (index source target))`| `((index: s t)) ((index: source target))` per changed link |
16//! | `(delete: index)`                | `((index: source target)) ()` per removed link |
17//! | `(get-name: link)`               | `(name: 'text')`, or nothing           |
18//! | `(set-name: (link 'text'))`      | `(link: N)`                            |
19//! | `(get-by-name: 'text')`          | `(link: N)`, or nothing                |
20//! | `(remove-name: link)`            | nothing                                |
21//!
22//! A restriction holds up to three parts, matched like the raw links
23//! interface matches a query: none matches every link, `(index)` one link,
24//! `(index value)` links of that index whose source or target is `value`,
25//! and `(index source target)` matches part by part. `*` matches anything.
26//! Every reference in a reply is a number; failures are `(error: 'message')`.
27//!
28//! The changes of a `create`, `update` or `delete` are the net change of every
29//! link it touched, the way `clink --changes` reports a query: a cascading
30//! delete is one `((index: source target)) ()` per removed link, without the
31//! intermediate steps by which the store behind the server got there, which
32//! differ between the C# and the Rust stores.
33
34use super::error::{ProtocolError, ProtocolResult};
35use crate::changes_simplifier::simplify_changes;
36use crate::link::Link;
37use crate::named_type_links::NamedTypeLinks;
38use links_notation::binary::{format_document, format_link, LinoDocument};
39use links_notation::LiNo;
40
41/// The wire spelling of "any value" in a restriction.
42pub const ANY: &str = "*";
43
44/// One part of a restriction: `None` matches any value.
45pub type Part = Option<u32>;
46
47/// One call of the links interface.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub enum LinksOperation {
50    /// Number of links matching the restriction.
51    Count(Vec<Part>),
52    /// Every link matching the restriction, ordered by index.
53    Each(Vec<Part>),
54    /// Creates a link.
55    Create { source: u32, target: u32 },
56    /// Points an existing link at a new source and target; an update that
57    /// would duplicate an existing link merges into it instead.
58    Update {
59        index: u32,
60        source: u32,
61        target: u32,
62    },
63    /// Deletes a link, and every link that still refers to it.
64    Delete(u32),
65    /// The name of a link.
66    GetName(u32),
67    /// Names a link.
68    SetName(u32, String),
69    /// The link with a name.
70    GetByName(String),
71    /// Removes the name of a link.
72    RemoveName(u32),
73}
74
75/// A `(before, after)` change; a missing side is [`Link::null`].
76pub type Change = (Link, Link);
77
78impl LinksOperation {
79    /// The request document for this operation.
80    pub fn to_document(&self) -> LinoDocument {
81        let (name, argument) = match self {
82            Self::Count(restriction) => ("count", restriction_lino(restriction)),
83            Self::Each(restriction) => ("each", restriction_lino(restriction)),
84            Self::Create { source, target } => ("create", numbers_lino(&[*source, *target])),
85            Self::Update {
86                index,
87                source,
88                target,
89            } => ("update", numbers_lino(&[*index, *source, *target])),
90            Self::Delete(index) => ("delete", number(*index)),
91            Self::GetName(index) => ("get-name", number(*index)),
92            Self::SetName(index, name) => (
93                "set-name",
94                group(vec![number(*index), LiNo::Ref(name.clone())]),
95            ),
96            Self::GetByName(name) => ("get-by-name", LiNo::Ref(name.clone())),
97            Self::RemoveName(index) => ("remove-name", number(*index)),
98        };
99        vec![named(name, vec![argument])]
100    }
101
102    /// Recognises an operation request; `Ok(None)` for any other document,
103    /// such as a substitution query.
104    pub fn from_document(document: &[LiNo<String>]) -> ProtocolResult<Option<Self>> {
105        let [LiNo::Link {
106            id: Some(name),
107            values,
108        }] = document
109        else {
110            return Ok(None);
111        };
112        let [argument] = values.as_slice() else {
113            return Ok(None);
114        };
115        let operation = match name.as_str() {
116            "count" => Self::Count(parse_restriction(argument)?),
117            "each" => Self::Each(parse_restriction(argument)?),
118            "create" => {
119                let [source, target] = parse_numbers::<2>(argument)?;
120                Self::Create { source, target }
121            }
122            "update" => {
123                let [index, source, target] = parse_numbers::<3>(argument)?;
124                Self::Update {
125                    index,
126                    source,
127                    target,
128                }
129            }
130            "delete" => Self::Delete(parse_number(argument)?),
131            "get-name" => Self::GetName(parse_number(argument)?),
132            "set-name" => match parts(argument) {
133                [index, LiNo::Ref(name)] => Self::SetName(parse_number(index)?, name.clone()),
134                _ => return Err(malformed_argument("set-name", argument)),
135            },
136            "get-by-name" => match argument {
137                LiNo::Ref(name) => Self::GetByName(name.clone()),
138                _ => return Err(malformed_argument("get-by-name", argument)),
139            },
140            "remove-name" => Self::RemoveName(parse_number(argument)?),
141            _ => return Ok(None),
142        };
143        Ok(Some(operation))
144    }
145
146    /// Runs the operation against `storage` and returns the reply document.
147    pub fn execute<S: NamedTypeLinks + ?Sized>(
148        &self,
149        storage: &mut S,
150    ) -> anyhow::Result<LinoDocument> {
151        Ok(match self {
152            Self::Count(restriction) => {
153                let count = matching(storage, restriction).len();
154                vec![named("count", vec![LiNo::Ref(count.to_string())])]
155            }
156            Self::Each(restriction) => matching(storage, restriction)
157                .iter()
158                .map(link_lino)
159                .collect(),
160            Self::Create { source, target } => {
161                // `create` makes exactly `(index: source target)`.
162                let created = Link::new(storage.create(*source, *target), *source, *target);
163                storage.save()?;
164                changes_document(&[(Link::null(), created)])
165            }
166            Self::Update {
167                index,
168                source,
169                target,
170            } => {
171                let mut changes = Vec::new();
172                storage.update_observed(*index, *source, *target, &mut |before, after| {
173                    changes.push((before, after))
174                })?;
175                storage.save()?;
176                changes_document(&simplify_changes(changes))
177            }
178            Self::Delete(index) => {
179                let mut changes = Vec::new();
180                storage
181                    .delete_observed(*index, &mut |before, after| changes.push((before, after)))?;
182                storage.save()?;
183                changes_document(&simplify_changes(changes))
184            }
185            Self::GetName(index) => match storage.get_name(*index)? {
186                Some(name) => vec![named("name", vec![LiNo::Ref(name)])],
187                None => Vec::new(),
188            },
189            Self::SetName(index, name) => {
190                let link = storage.set_name(*index, name)?;
191                storage.save()?;
192                link_reply(Some(link))
193            }
194            Self::GetByName(name) => link_reply(storage.get_by_name(name)?),
195            Self::RemoveName(index) => {
196                storage.remove_name(*index)?;
197                storage.save()?;
198                Vec::new()
199            }
200        })
201    }
202}
203
204/// Whether `link` matches `restriction`, with the shapes of the raw links
205/// interface: see the [module documentation](self).
206pub fn matches(link: &Link, restriction: &[Part]) -> bool {
207    let is = |part: Part, value: u32| part.is_none_or(|part| part == value);
208    match *restriction {
209        [] => true,
210        [index] => is(index, link.index),
211        [index, value] => {
212            is(index, link.index) && (is(value, link.source) || is(value, link.target))
213        }
214        [index, source, target] => {
215            is(index, link.index) && is(source, link.source) && is(target, link.target)
216        }
217        _ => false,
218    }
219}
220
221fn matching<S: NamedTypeLinks + ?Sized>(storage: &mut S, restriction: &[Part]) -> Vec<Link> {
222    let mut links = match restriction.first() {
223        Some(Some(index)) => storage.get_link(*index).into_iter().collect(),
224        _ => storage.all_links(),
225    };
226    links.retain(|link| matches(link, restriction));
227    links.sort_by_key(|link| link.index);
228    links
229}
230
231/// The `count` of a `(count: N)` reply.
232pub fn parse_count(document: &[LiNo<String>]) -> ProtocolResult<u32> {
233    match document {
234        [LiNo::Link {
235            id: Some(id),
236            values,
237        }] if id == "count" => match values.as_slice() {
238            [count] => parse_number(count),
239            _ => Err(malformed_reply("count", document)),
240        },
241        _ => Err(malformed_reply("count", document)),
242    }
243}
244
245/// The links of an `each` reply.
246pub fn parse_links(document: &[LiNo<String>]) -> ProtocolResult<Vec<Link>> {
247    document.iter().map(parse_link).collect()
248}
249
250/// The `(before) (after)` pairs of a `create`, `update` or `delete` reply.
251pub fn parse_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<Change>> {
252    document
253        .iter()
254        .map(|change| match parts(change) {
255            [before, after] => Ok((parse_change_side(before)?, parse_change_side(after)?)),
256            _ => Err(malformed_reply("change", document)),
257        })
258        .collect()
259}
260
261/// The name of a `get-name` reply.
262pub fn parse_name(document: &[LiNo<String>]) -> ProtocolResult<Option<String>> {
263    match document {
264        [] => Ok(None),
265        [LiNo::Link {
266            id: Some(id),
267            values,
268        }] if id == "name" => match values.as_slice() {
269            [LiNo::Ref(name)] => Ok(Some(name.clone())),
270            _ => Err(malformed_reply("name", document)),
271        },
272        _ => Err(malformed_reply("name", document)),
273    }
274}
275
276/// The link of a `set-name` or `get-by-name` reply.
277pub fn parse_link_reply(document: &[LiNo<String>]) -> ProtocolResult<Option<u32>> {
278    match document {
279        [] => Ok(None),
280        [LiNo::Link {
281            id: Some(id),
282            values,
283        }] if id == "link" => match values.as_slice() {
284            [link] => parse_number(link).map(Some),
285            _ => Err(malformed_reply("link", document)),
286        },
287        _ => Err(malformed_reply("link", document)),
288    }
289}
290
291/// A reply listing `changes`, one `(before) (after)` line each.
292pub fn changes_document(changes: &[Change]) -> LinoDocument {
293    changes
294        .iter()
295        .map(|(before, after)| group(vec![change_side(before), change_side(after)]))
296        .collect()
297}
298
299/// `(index: source target)` with plain numbers.
300pub fn link_lino(link: &Link) -> LiNo<String> {
301    named(
302        &link.index.to_string(),
303        vec![number(link.source), number(link.target)],
304    )
305}
306
307fn link_reply(link: Option<u32>) -> LinoDocument {
308    link.map(|link| vec![named("link", vec![number(link)])])
309        .unwrap_or_default()
310}
311
312fn change_side(link: &Link) -> LiNo<String> {
313    if link.is_null() {
314        group(Vec::new())
315    } else {
316        group(vec![link_lino(link)])
317    }
318}
319
320fn parse_change_side(side: &LiNo<String>) -> ProtocolResult<Link> {
321    match side {
322        LiNo::Link { id: None, values } if values.is_empty() => Ok(Link::null()),
323        LiNo::Link { id: None, values } if values.len() == 1 => parse_link(&values[0]),
324        // `((index: source target))` loses its wrapper when the side is the
325        // single named link itself.
326        link @ LiNo::Link { id: Some(_), .. } => parse_link(link),
327        _ => Err(ProtocolError::malformed(format!(
328            "expected a change side, found {}",
329            format_link(side)
330        ))),
331    }
332}
333
334fn parse_link(link: &LiNo<String>) -> ProtocolResult<Link> {
335    match link {
336        LiNo::Link {
337            id: Some(index),
338            values,
339        } => match values.as_slice() {
340            [source, target] => Ok(Link::new(
341                parse_text_number(index)?,
342                parse_number(source)?,
343                parse_number(target)?,
344            )),
345            _ => Err(ProtocolError::malformed(format!(
346                "expected (index: source target), found {}",
347                format_link(link)
348            ))),
349        },
350        _ => Err(ProtocolError::malformed(format!(
351            "expected (index: source target), found {}",
352            format_link(link)
353        ))),
354    }
355}
356
357fn restriction_lino(restriction: &[Part]) -> LiNo<String> {
358    group(
359        restriction
360            .iter()
361            .map(|part| part.map_or_else(|| LiNo::Ref(ANY.to_string()), number))
362            .collect(),
363    )
364}
365
366fn parse_restriction(argument: &LiNo<String>) -> ProtocolResult<Vec<Part>> {
367    let parts = parts(argument);
368    if parts.len() > 3 {
369        return Err(malformed_argument("restriction", argument));
370    }
371    parts
372        .iter()
373        .map(|part| match part {
374            LiNo::Ref(text) if text == ANY => Ok(None),
375            part => parse_number(part).map(Some),
376        })
377        .collect()
378}
379
380fn numbers_lino(numbers: &[u32]) -> LiNo<String> {
381    group(numbers.iter().copied().map(number).collect())
382}
383
384fn parse_numbers<const N: usize>(argument: &LiNo<String>) -> ProtocolResult<[u32; N]> {
385    let numbers = parts(argument)
386        .iter()
387        .map(parse_number)
388        .collect::<ProtocolResult<Vec<_>>>()?;
389    numbers
390        .try_into()
391        .map_err(|_| malformed_argument(&format!("{N} numbers"), argument))
392}
393
394/// The values of an unnamed group; a lone reference is a group of one, since
395/// the canonical document model unwraps `(x)` to `x`.
396fn parts(argument: &LiNo<String>) -> &[LiNo<String>] {
397    match argument {
398        LiNo::Link { id: None, values } => values,
399        reference => std::slice::from_ref(reference),
400    }
401}
402
403fn parse_number(value: &LiNo<String>) -> ProtocolResult<u32> {
404    match value {
405        LiNo::Ref(text) => parse_text_number(text),
406        _ => Err(ProtocolError::malformed(format!(
407            "expected a number, found {}",
408            format_link(value)
409        ))),
410    }
411}
412
413fn parse_text_number(text: &str) -> ProtocolResult<u32> {
414    text.parse()
415        .map_err(|_| ProtocolError::malformed(format!("expected a number, found '{text}'")))
416}
417
418fn number(value: u32) -> LiNo<String> {
419    LiNo::Ref(value.to_string())
420}
421
422fn named(id: &str, values: Vec<LiNo<String>>) -> LiNo<String> {
423    LiNo::Link {
424        id: Some(id.to_string()),
425        values,
426    }
427}
428
429fn group(values: Vec<LiNo<String>>) -> LiNo<String> {
430    LiNo::Link { id: None, values }
431}
432
433fn malformed_argument(expected: &str, argument: &LiNo<String>) -> ProtocolError {
434    ProtocolError::malformed(format!(
435        "expected {expected}, found {}",
436        format_link(argument)
437    ))
438}
439
440fn malformed_reply(expected: &str, document: &[LiNo<String>]) -> ProtocolError {
441    ProtocolError::malformed(format!(
442        "expected a {expected} reply, found {}",
443        format_document(document)
444    ))
445}