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//! | `(subscribe: (index source target))` | `(subscription: N)`; later pushes of `(notify: N)` and its changes |
22//! | `(unsubscribe: N)`               | nothing                                |
23//!
24//! A restriction holds up to three parts, matched like the raw links
25//! interface matches a query: none matches every link, `(index)` one link,
26//! `(index value)` links of that index whose source or target is `value`,
27//! and `(index source target)` matches part by part. `*` matches anything.
28//! Every reference in a reply is a number; failures are `(error: 'message')`.
29//!
30//! The changes of a `create`, `update` or `delete` are the net change of every
31//! link it touched, the way `clink --changes` reports a query: a cascading
32//! delete is one `((index: source target)) ()` per removed link, without the
33//! intermediate steps by which the store behind the server got there, which
34//! differ between the C# and the Rust stores.
35//!
36//! A subscription belongs to the connection that made it: once a connection
37//! sent `(subscribe: restriction)`, the server pushes it every later change
38//! another connection makes to a matching link, as `(notify: N)` followed by
39//! the `(before) (after)` lines of the change. A side that does not match is
40//! left empty, so a link that leaves the subscription arrives as a deletion.
41
42use super::error::{ProtocolError, ProtocolResult};
43use crate::changes_simplifier::simplify_changes;
44use crate::link::Link;
45use crate::named_type_links::NamedTypeLinks;
46use links_notation::binary::{format_document, format_link, LinoDocument};
47use links_notation::LiNo;
48
49/// The wire spelling of "any value" in a restriction.
50pub const ANY: &str = "*";
51
52/// One part of a restriction: `None` matches any value.
53pub type Part = Option<u32>;
54
55/// One call of the links interface.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum LinksOperation {
58    /// Number of links matching the restriction.
59    Count(Vec<Part>),
60    /// Every link matching the restriction, ordered by index.
61    Each(Vec<Part>),
62    /// Creates a link.
63    Create { source: u32, target: u32 },
64    /// Points an existing link at a new source and target; an update that
65    /// would duplicate an existing link merges into it instead.
66    Update {
67        index: u32,
68        source: u32,
69        target: u32,
70    },
71    /// Deletes a link, and every link that still refers to it.
72    Delete(u32),
73    /// The name of a link.
74    GetName(u32),
75    /// Names a link.
76    SetName(u32, String),
77    /// The link with a name.
78    GetByName(String),
79    /// Removes the name of a link.
80    RemoveName(u32),
81    /// Asks a [`LinksServer`](super::LinksServer) to push the changes other
82    /// connections make to the links matching the restriction; the reply is
83    /// `(subscription: N)` and every later push a [`notification_document`].
84    ///
85    /// A subscription belongs to the connection that made it: only the server
86    /// can run it, so [`execute`](Self::execute) on a store fails.
87    Subscribe(Vec<Part>),
88    /// Stops a subscription of this connection; the reply is empty, even for
89    /// an unknown number.
90    Unsubscribe(u32),
91}
92
93/// A change a [`LinksServer`](super::LinksServer) pushed to a subscriber: the
94/// subscription it fits and its changes, a missing side being [`Link::null`].
95///
96/// Each side is the link as the subscription sees it: a side that does not fit
97/// the restriction (or that the subscriber may not read) is the null link, so a
98/// link that leaves the subscription arrives as a deletion and one that comes
99/// into it as a creation.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct LinksNotification {
102    /// The number the `subscribe` reply gave.
103    pub subscription: u32,
104    /// The `(before, after)` changes.
105    pub changes: Vec<Change>,
106}
107
108/// A `(before, after)` change; a missing side is [`Link::null`].
109pub type Change = (Link, Link);
110
111impl LinksOperation {
112    /// The request document for this operation.
113    pub fn to_document(&self) -> LinoDocument {
114        let (name, argument) = match self {
115            Self::Count(restriction) => ("count", restriction_lino(restriction)),
116            Self::Each(restriction) => ("each", restriction_lino(restriction)),
117            Self::Create { source, target } => ("create", numbers_lino(&[*source, *target])),
118            Self::Update {
119                index,
120                source,
121                target,
122            } => ("update", numbers_lino(&[*index, *source, *target])),
123            Self::Delete(index) => ("delete", number(*index)),
124            Self::GetName(index) => ("get-name", number(*index)),
125            Self::SetName(index, name) => (
126                "set-name",
127                group(vec![number(*index), LiNo::Ref(name.clone())]),
128            ),
129            Self::GetByName(name) => ("get-by-name", LiNo::Ref(name.clone())),
130            Self::RemoveName(index) => ("remove-name", number(*index)),
131            Self::Subscribe(restriction) => ("subscribe", restriction_lino(restriction)),
132            Self::Unsubscribe(subscription) => ("unsubscribe", number(*subscription)),
133        };
134        vec![named(name, vec![argument])]
135    }
136
137    /// Recognises an operation request; `Ok(None)` for any other document,
138    /// such as a substitution query.
139    pub fn from_document(document: &[LiNo<String>]) -> ProtocolResult<Option<Self>> {
140        let [LiNo::Link {
141            id: Some(name),
142            values,
143        }] = document
144        else {
145            return Ok(None);
146        };
147        let [argument] = values.as_slice() else {
148            return Ok(None);
149        };
150        let operation = match name.as_str() {
151            "count" => Self::Count(parse_restriction(argument)?),
152            "each" => Self::Each(parse_restriction(argument)?),
153            "create" => {
154                let [source, target] = parse_numbers::<2>(argument)?;
155                Self::Create { source, target }
156            }
157            "update" => {
158                let [index, source, target] = parse_numbers::<3>(argument)?;
159                Self::Update {
160                    index,
161                    source,
162                    target,
163                }
164            }
165            "delete" => Self::Delete(parse_number(argument)?),
166            "get-name" => Self::GetName(parse_number(argument)?),
167            "set-name" => match parts(argument) {
168                [index, LiNo::Ref(name)] => Self::SetName(parse_number(index)?, name.clone()),
169                _ => return Err(malformed_argument("set-name", argument)),
170            },
171            "get-by-name" => match argument {
172                LiNo::Ref(name) => Self::GetByName(name.clone()),
173                _ => return Err(malformed_argument("get-by-name", argument)),
174            },
175            "remove-name" => Self::RemoveName(parse_number(argument)?),
176            "subscribe" => Self::Subscribe(parse_restriction(argument)?),
177            "unsubscribe" => Self::Unsubscribe(parse_number(argument)?),
178            _ => return Ok(None),
179        };
180        Ok(Some(operation))
181    }
182
183    /// Runs the operation against `storage` and returns the reply document.
184    pub fn execute<S: NamedTypeLinks + ?Sized>(
185        &self,
186        storage: &mut S,
187    ) -> anyhow::Result<LinoDocument> {
188        Ok(match self {
189            Self::Count(restriction) => {
190                let count = matching(storage, restriction).len();
191                vec![named("count", vec![LiNo::Ref(count.to_string())])]
192            }
193            Self::Each(restriction) => matching(storage, restriction)
194                .iter()
195                .map(link_lino)
196                .collect(),
197            Self::Create { source, target } => {
198                // `create` makes exactly `(index: source target)`.
199                let created = Link::new(storage.try_create(*source, *target)?, *source, *target);
200                storage.save()?;
201                changes_document(&[(Link::null(), created)])
202            }
203            Self::Update {
204                index,
205                source,
206                target,
207            } => {
208                let mut changes = Vec::new();
209                storage.update_observed(*index, *source, *target, &mut |before, after| {
210                    changes.push((before, after))
211                })?;
212                storage.save()?;
213                changes_document(&simplify_changes(changes))
214            }
215            Self::Delete(index) => {
216                let mut changes = Vec::new();
217                storage
218                    .delete_observed(*index, &mut |before, after| changes.push((before, after)))?;
219                storage.save()?;
220                changes_document(&simplify_changes(changes))
221            }
222            Self::GetName(index) => match storage.get_name(*index)? {
223                Some(name) => vec![named("name", vec![LiNo::Ref(name)])],
224                None => Vec::new(),
225            },
226            Self::SetName(index, name) => {
227                let link = storage.set_name(*index, name)?;
228                storage.save()?;
229                link_reply(Some(link))
230            }
231            Self::GetByName(name) => link_reply(storage.get_by_name(name)?),
232            Self::RemoveName(index) => {
233                storage.remove_name(*index)?;
234                storage.save()?;
235                Vec::new()
236            }
237            Self::Subscribe(_) | Self::Unsubscribe(_) => {
238                anyhow::bail!("subscriptions belong to a connection to a links server")
239            }
240        })
241    }
242}
243
244/// Whether `link` matches `restriction`, with the shapes of the raw links
245/// interface: see the [module documentation](self).
246pub fn matches(link: &Link, restriction: &[Part]) -> bool {
247    let is = |part: Part, value: u32| part.is_none_or(|part| part == value);
248    match *restriction {
249        [] => true,
250        [index] => is(index, link.index),
251        [index, value] => {
252            is(index, link.index) && (is(value, link.source) || is(value, link.target))
253        }
254        [index, source, target] => {
255            is(index, link.index) && is(source, link.source) && is(target, link.target)
256        }
257        _ => false,
258    }
259}
260
261fn matching<S: NamedTypeLinks + ?Sized>(storage: &mut S, restriction: &[Part]) -> Vec<Link> {
262    let mut links = match restriction.first() {
263        Some(Some(index)) => storage.get_link(*index).into_iter().collect(),
264        _ => storage.all_links(),
265    };
266    links.retain(|link| matches(link, restriction));
267    links.sort_by_key(|link| link.index);
268    links
269}
270
271/// The `count` of a `(count: N)` reply.
272pub fn parse_count(document: &[LiNo<String>]) -> ProtocolResult<u32> {
273    match document {
274        [LiNo::Link {
275            id: Some(id),
276            values,
277        }] if id == "count" => match values.as_slice() {
278            [count] => parse_number(count),
279            _ => Err(malformed_reply("count", document)),
280        },
281        _ => Err(malformed_reply("count", document)),
282    }
283}
284
285/// The number of a `(subscription: N)` reply.
286pub fn parse_subscription(document: &[LiNo<String>]) -> ProtocolResult<u32> {
287    match document {
288        [LiNo::Link {
289            id: Some(id),
290            values,
291        }] if id == "subscription" => match values.as_slice() {
292            [subscription] => parse_number(subscription),
293            _ => Err(malformed_reply("subscription", document)),
294        },
295        _ => Err(malformed_reply("subscription", document)),
296    }
297}
298
299/// The reply to a [`LinksOperation::Subscribe`]: `(subscription: N)`.
300pub fn subscription_document(subscription: u32) -> LinoDocument {
301    vec![named("subscription", vec![number(subscription)])]
302}
303
304/// Whether `document` is a push rather than a reply: its first link is
305/// `(notify: N)`.
306///
307/// No reply starts that way: the replies to operations name their first link
308/// after the operation's result or leave it unnamed, and the links a server
309/// lists are `(index: source target)`, with two values.
310pub fn is_notification(document: &[LiNo<String>]) -> bool {
311    notification_number(document).is_some()
312}
313
314fn notification_number(document: &[LiNo<String>]) -> Option<u32> {
315    match document.first()? {
316        LiNo::Link {
317            id: Some(id),
318            values,
319        } if id == "notify" => match values.as_slice() {
320            [LiNo::Ref(text)] if text.bytes().all(|byte| byte.is_ascii_digit()) => {
321                text.parse().ok()
322            }
323            _ => None,
324        },
325        _ => None,
326    }
327}
328
329/// A push: `(notify: N)` followed by one `(before) (after)` line per change,
330/// with plain numbers.
331pub fn notification_document(subscription: u32, changes: &[Change]) -> LinoDocument {
332    let mut document = vec![named("notify", vec![number(subscription)])];
333    document.extend(changes_document(changes));
334    document
335}
336
337/// The subscription and the changes of a [`notification_document`].
338pub fn parse_notification(document: &[LiNo<String>]) -> ProtocolResult<LinksNotification> {
339    let subscription =
340        notification_number(document).ok_or_else(|| malformed_reply("notify", document))?;
341    Ok(LinksNotification {
342        subscription,
343        changes: parse_changes(&document[1..])?,
344    })
345}
346
347/// The links of an `each` reply.
348pub fn parse_links(document: &[LiNo<String>]) -> ProtocolResult<Vec<Link>> {
349    document.iter().map(parse_link).collect()
350}
351
352/// The `(before) (after)` pairs of a `create`, `update` or `delete` reply.
353pub fn parse_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<Change>> {
354    document
355        .iter()
356        .map(|change| match parts(change) {
357            [before, after] => Ok((parse_change_side(before)?, parse_change_side(after)?)),
358            _ => Err(malformed_reply("change", document)),
359        })
360        .collect()
361}
362
363/// The name of a `get-name` reply.
364pub fn parse_name(document: &[LiNo<String>]) -> ProtocolResult<Option<String>> {
365    match document {
366        [] => Ok(None),
367        [LiNo::Link {
368            id: Some(id),
369            values,
370        }] if id == "name" => match values.as_slice() {
371            [LiNo::Ref(name)] => Ok(Some(name.clone())),
372            _ => Err(malformed_reply("name", document)),
373        },
374        _ => Err(malformed_reply("name", document)),
375    }
376}
377
378/// The link of a `set-name` or `get-by-name` reply.
379pub fn parse_link_reply(document: &[LiNo<String>]) -> ProtocolResult<Option<u32>> {
380    match document {
381        [] => Ok(None),
382        [LiNo::Link {
383            id: Some(id),
384            values,
385        }] if id == "link" => match values.as_slice() {
386            [link] => parse_number(link).map(Some),
387            _ => Err(malformed_reply("link", document)),
388        },
389        _ => Err(malformed_reply("link", document)),
390    }
391}
392
393/// A reply listing `changes`, one `(before) (after)` line each.
394pub fn changes_document(changes: &[Change]) -> LinoDocument {
395    changes
396        .iter()
397        .map(|(before, after)| group(vec![change_side(before), change_side(after)]))
398        .collect()
399}
400
401/// `(index: source target)` with plain numbers.
402pub fn link_lino(link: &Link) -> LiNo<String> {
403    named(
404        &link.index.to_string(),
405        vec![number(link.source), number(link.target)],
406    )
407}
408
409fn link_reply(link: Option<u32>) -> LinoDocument {
410    link.map(|link| vec![named("link", vec![number(link)])])
411        .unwrap_or_default()
412}
413
414fn change_side(link: &Link) -> LiNo<String> {
415    if link.is_null() {
416        group(Vec::new())
417    } else {
418        group(vec![link_lino(link)])
419    }
420}
421
422fn parse_change_side(side: &LiNo<String>) -> ProtocolResult<Link> {
423    match side {
424        LiNo::Link { id: None, values } if values.is_empty() => Ok(Link::null()),
425        LiNo::Link { id: None, values } if values.len() == 1 => parse_link(&values[0]),
426        // `((index: source target))` loses its wrapper when the side is the
427        // single named link itself.
428        link @ LiNo::Link { id: Some(_), .. } => parse_link(link),
429        _ => Err(ProtocolError::malformed(format!(
430            "expected a change side, found {}",
431            format_link(side)
432        ))),
433    }
434}
435
436fn parse_link(link: &LiNo<String>) -> ProtocolResult<Link> {
437    match link {
438        LiNo::Link {
439            id: Some(index),
440            values,
441        } => match values.as_slice() {
442            [source, target] => Ok(Link::new(
443                parse_text_number(index)?,
444                parse_number(source)?,
445                parse_number(target)?,
446            )),
447            _ => Err(ProtocolError::malformed(format!(
448                "expected (index: source target), found {}",
449                format_link(link)
450            ))),
451        },
452        _ => Err(ProtocolError::malformed(format!(
453            "expected (index: source target), found {}",
454            format_link(link)
455        ))),
456    }
457}
458
459fn restriction_lino(restriction: &[Part]) -> LiNo<String> {
460    group(
461        restriction
462            .iter()
463            .map(|part| part.map_or_else(|| LiNo::Ref(ANY.to_string()), number))
464            .collect(),
465    )
466}
467
468fn parse_restriction(argument: &LiNo<String>) -> ProtocolResult<Vec<Part>> {
469    let parts = parts(argument);
470    if parts.len() > 3 {
471        return Err(malformed_argument("restriction", argument));
472    }
473    parts
474        .iter()
475        .map(|part| match part {
476            LiNo::Ref(text) if text == ANY => Ok(None),
477            part => parse_number(part).map(Some),
478        })
479        .collect()
480}
481
482fn numbers_lino(numbers: &[u32]) -> LiNo<String> {
483    group(numbers.iter().copied().map(number).collect())
484}
485
486fn parse_numbers<const N: usize>(argument: &LiNo<String>) -> ProtocolResult<[u32; N]> {
487    let numbers = parts(argument)
488        .iter()
489        .map(parse_number)
490        .collect::<ProtocolResult<Vec<_>>>()?;
491    numbers
492        .try_into()
493        .map_err(|_| malformed_argument(&format!("{N} numbers"), argument))
494}
495
496/// The values of an unnamed group; a lone reference is a group of one, since
497/// the canonical document model unwraps `(x)` to `x`.
498fn parts(argument: &LiNo<String>) -> &[LiNo<String>] {
499    match argument {
500        LiNo::Link { id: None, values } => values,
501        reference => std::slice::from_ref(reference),
502    }
503}
504
505fn parse_number(value: &LiNo<String>) -> ProtocolResult<u32> {
506    match value {
507        LiNo::Ref(text) => parse_text_number(text),
508        _ => Err(ProtocolError::malformed(format!(
509            "expected a number, found {}",
510            format_link(value)
511        ))),
512    }
513}
514
515fn parse_text_number(text: &str) -> ProtocolResult<u32> {
516    text.parse()
517        .map_err(|_| ProtocolError::malformed(format!("expected a number, found '{text}'")))
518}
519
520fn number(value: u32) -> LiNo<String> {
521    LiNo::Ref(value.to_string())
522}
523
524fn named(id: &str, values: Vec<LiNo<String>>) -> LiNo<String> {
525    LiNo::Link {
526        id: Some(id.to_string()),
527        values,
528    }
529}
530
531fn group(values: Vec<LiNo<String>>) -> LiNo<String> {
532    LiNo::Link { id: None, values }
533}
534
535fn malformed_argument(expected: &str, argument: &LiNo<String>) -> ProtocolError {
536    ProtocolError::malformed(format!(
537        "expected {expected}, found {}",
538        format_link(argument)
539    ))
540}
541
542fn malformed_reply(expected: &str, document: &[LiNo<String>]) -> ProtocolError {
543    ProtocolError::malformed(format!(
544        "expected a {expected} reply, found {}",
545        format_document(document)
546    ))
547}