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_generic_changes;
44use crate::link::{GenericLink, Link};
45use crate::named_type_links::NamedTypeLinks;
46use crate::query_address::QueryAddress;
47use links_notation::binary::{format_document, format_link, LinoDocument};
48use links_notation::LiNo;
49
50/// The wire spelling of "any value" in a restriction.
51pub const ANY: &str = "*";
52
53/// One part of a restriction: `None` matches any value.
54pub type Part<T = u32> = Option<T>;
55
56/// One call of the links interface.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum GenericLinksOperation<T> {
59    /// Number of links matching the restriction.
60    Count(Vec<Part<T>>),
61    /// Every link matching the restriction, ordered by index.
62    Each(Vec<Part<T>>),
63    /// Creates a link.
64    Create { source: T, target: T },
65    /// Points an existing link at a new source and target; an update that
66    /// would duplicate an existing link merges into it instead.
67    Update { index: T, source: T, target: T },
68    /// Deletes a link, and every link that still refers to it.
69    Delete(T),
70    /// The name of a link.
71    GetName(T),
72    /// Names a link.
73    SetName(T, String),
74    /// The link with a name.
75    GetByName(String),
76    /// Removes the name of a link.
77    RemoveName(T),
78    /// Asks a [`LinksServer`](super::LinksServer) to push the changes other
79    /// connections make to the links matching the restriction; the reply is
80    /// `(subscription: N)` and every later push a [`notification_document`].
81    ///
82    /// A subscription belongs to the connection that made it: only the server
83    /// can run it, so [`execute`](Self::execute) on a store fails.
84    Subscribe(Vec<Part<T>>),
85    /// Stops a subscription of this connection; the reply is empty, even for
86    /// an unknown number.
87    Unsubscribe(T),
88}
89
90/// A change a [`LinksServer`](super::LinksServer) pushed to a subscriber: the
91/// subscription it fits and its changes, a missing side being [`Link::null`].
92///
93/// Each side is the link as the subscription sees it: a side that does not fit
94/// the restriction (or that the subscriber may not read) is the null link, so a
95/// link that leaves the subscription arrives as a deletion and one that comes
96/// into it as a creation.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct LinksNotification {
99    /// The number the `subscribe` reply gave.
100    pub subscription: u32,
101    /// The `(before, after)` changes.
102    pub changes: Vec<Change>,
103}
104
105/// A `(before, after)` change; a missing side is [`GenericLink::null`].
106pub type Change<T = u32> = (GenericLink<T>, GenericLink<T>);
107
108/// The existing u32 links operation facade.
109pub type LinksOperation = GenericLinksOperation<u32>;
110
111impl<T: QueryAddress> GenericLinksOperation<T> {
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_for::<T, 2>(argument)?;
155                Self::Create { source, target }
156            }
157            "update" => {
158                let [index, source, target] = parse_numbers_for::<T, 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<T> + ?Sized>(
185        &self,
186        storage: &mut S,
187    ) -> anyhow::Result<LinoDocument> {
188        if let Some(limits) = storage.query_limits() {
189            match self {
190                Self::Count(parts) | Self::Each(parts) | Self::Subscribe(parts) => {
191                    anyhow::ensure!(parts.len() <= 3, "expected at most three restriction parts")
192                }
193                Self::SetName(_, name) | Self::GetByName(name) => anyhow::ensure!(
194                    name.len() <= limits.max_bytes,
195                    "protocol byte limit exceeded"
196                ),
197                _ => {}
198            }
199            let addresses: Vec<T> = match self {
200                Self::Count(parts) | Self::Each(parts) | Self::Subscribe(parts) => {
201                    parts.iter().flatten().copied().collect()
202                }
203                Self::Create { source, target } => vec![*source, *target],
204                Self::Update {
205                    index,
206                    source,
207                    target,
208                } => vec![*index, *source, *target],
209                Self::Delete(index)
210                | Self::GetName(index)
211                | Self::SetName(index, _)
212                | Self::RemoveName(index)
213                | Self::Unsubscribe(index) => vec![*index],
214                Self::GetByName(_) => Vec::new(),
215            };
216            anyhow::ensure!(
217                addresses.iter().all(|value| value
218                    .to_u128()
219                    .is_some_and(|value| value <= limits.max_address)),
220                "protocol address out of range"
221            );
222        }
223        Ok(match self {
224            Self::Count(restriction) => {
225                let count = matching(storage, restriction).len();
226                vec![named("count", vec![LiNo::Ref(count.to_string())])]
227            }
228            Self::Each(restriction) => {
229                let links = matching(storage, restriction);
230                if let Some(limits) = storage.query_limits() {
231                    anyhow::ensure!(
232                        links.len() <= limits.max_results,
233                        "protocol result limit exceeded"
234                    );
235                }
236                links.iter().map(link_lino).collect()
237            }
238            Self::Create { source, target } => {
239                // `create` makes exactly `(index: source target)`.
240                let created =
241                    GenericLink::new(storage.try_create(*source, *target)?, *source, *target);
242                storage.save()?;
243                changes_document_for(&[(GenericLink::null(), created)])
244            }
245            Self::Update {
246                index,
247                source,
248                target,
249            } => {
250                let mut changes = Vec::new();
251                storage.update_observed(*index, *source, *target, &mut |before, after| {
252                    changes.push((before, after))
253                })?;
254                storage.save()?;
255                changes_document_for(&simplify_generic_changes(changes))
256            }
257            Self::Delete(index) => {
258                let mut changes = Vec::new();
259                storage
260                    .delete_observed(*index, &mut |before, after| changes.push((before, after)))?;
261                storage.save()?;
262                changes_document_for(&simplify_generic_changes(changes))
263            }
264            Self::GetName(index) => match storage.get_name(*index)? {
265                Some(name) => vec![named("name", vec![LiNo::Ref(name)])],
266                None => Vec::new(),
267            },
268            Self::SetName(index, name) => {
269                let link = storage.set_name(*index, name)?;
270                storage.save()?;
271                link_reply(Some(link))
272            }
273            Self::GetByName(name) => link_reply(storage.get_by_name(name)?),
274            Self::RemoveName(index) => {
275                storage.remove_name(*index)?;
276                storage.save()?;
277                Vec::new()
278            }
279            Self::Subscribe(_) | Self::Unsubscribe(_) => {
280                anyhow::bail!("subscriptions belong to a connection to a links server")
281            }
282        })
283    }
284}
285
286/// Whether `link` matches `restriction`, with the shapes of the raw links
287/// interface: see the [module documentation](self).
288pub fn matches<T: QueryAddress>(link: &GenericLink<T>, restriction: &[Part<T>]) -> bool {
289    let is = |part: Part<T>, value: T| part.is_none_or(|part| part == value);
290    match *restriction {
291        [] => true,
292        [index] => is(index, link.index),
293        [index, value] => {
294            is(index, link.index) && (is(value, link.source) || is(value, link.target))
295        }
296        [index, source, target] => {
297            is(index, link.index) && is(source, link.source) && is(target, link.target)
298        }
299        _ => false,
300    }
301}
302
303fn matching<T: QueryAddress, S: NamedTypeLinks<T> + ?Sized>(
304    storage: &mut S,
305    restriction: &[Part<T>],
306) -> Vec<GenericLink<T>> {
307    let mut links = match restriction.first() {
308        Some(Some(index)) => storage.get_link(*index).into_iter().collect(),
309        _ => storage.all_links(),
310    };
311    links.retain(|link| matches(link, restriction));
312    links.sort_by_key(|link| link.index);
313    links
314}
315
316/// The `count` of a `(count: N)` reply.
317pub fn parse_count(document: &[LiNo<String>]) -> ProtocolResult<u32> {
318    match document {
319        [LiNo::Link {
320            id: Some(id),
321            values,
322        }] if id == "count" => match values.as_slice() {
323            [count] => parse_number(count),
324            _ => Err(malformed_reply("count", document)),
325        },
326        _ => Err(malformed_reply("count", document)),
327    }
328}
329
330/// The number of a `(subscription: N)` reply.
331pub fn parse_subscription(document: &[LiNo<String>]) -> ProtocolResult<u32> {
332    match document {
333        [LiNo::Link {
334            id: Some(id),
335            values,
336        }] if id == "subscription" => match values.as_slice() {
337            [subscription] => parse_number(subscription),
338            _ => Err(malformed_reply("subscription", document)),
339        },
340        _ => Err(malformed_reply("subscription", document)),
341    }
342}
343
344/// The reply to a [`LinksOperation::Subscribe`]: `(subscription: N)`.
345pub fn subscription_document(subscription: u32) -> LinoDocument {
346    vec![named("subscription", vec![number(subscription)])]
347}
348
349/// Whether `document` is a push rather than a reply: its first link is
350/// `(notify: N)`.
351///
352/// No reply starts that way: the replies to operations name their first link
353/// after the operation's result or leave it unnamed, and the links a server
354/// lists are `(index: source target)`, with two values.
355pub fn is_notification(document: &[LiNo<String>]) -> bool {
356    notification_number(document).is_some()
357}
358
359pub(super) fn notification_number(document: &[LiNo<String>]) -> Option<u32> {
360    match document.first()? {
361        LiNo::Link {
362            id: Some(id),
363            values,
364        } if id == "notify" => match values.as_slice() {
365            [LiNo::Ref(text)] if text.bytes().all(|byte| byte.is_ascii_digit()) => {
366                text.parse().ok()
367            }
368            _ => None,
369        },
370        _ => None,
371    }
372}
373
374/// A push: `(notify: N)` followed by one `(before) (after)` line per change,
375/// with plain numbers.
376pub fn notification_document(subscription: u32, changes: &[Change]) -> LinoDocument {
377    let mut document = vec![named("notify", vec![number(subscription)])];
378    document.extend(changes_document(changes));
379    document
380}
381
382/// The subscription and the changes of a [`notification_document`].
383pub fn parse_notification(document: &[LiNo<String>]) -> ProtocolResult<LinksNotification> {
384    let subscription =
385        notification_number(document).ok_or_else(|| malformed_reply("notify", document))?;
386    Ok(LinksNotification {
387        subscription,
388        changes: parse_changes(&document[1..])?,
389    })
390}
391
392/// The links of an `each` reply.
393pub fn parse_links_for<T: QueryAddress>(
394    document: &[LiNo<String>],
395) -> ProtocolResult<Vec<GenericLink<T>>> {
396    document.iter().map(parse_link).collect()
397}
398
399/// The `(before) (after)` pairs of a `create`, `update` or `delete` reply.
400pub fn parse_changes_for<T: QueryAddress>(
401    document: &[LiNo<String>],
402) -> ProtocolResult<Vec<Change<T>>> {
403    document
404        .iter()
405        .map(|change| match parts(change) {
406            [before, after] => Ok((parse_change_side(before)?, parse_change_side(after)?)),
407            _ => Err(malformed_reply("change", document)),
408        })
409        .collect()
410}
411
412/// The name of a `get-name` reply.
413pub fn parse_name(document: &[LiNo<String>]) -> ProtocolResult<Option<String>> {
414    match document {
415        [] => Ok(None),
416        [LiNo::Link {
417            id: Some(id),
418            values,
419        }] if id == "name" => match values.as_slice() {
420            [LiNo::Ref(name)] => Ok(Some(name.clone())),
421            _ => Err(malformed_reply("name", document)),
422        },
423        _ => Err(malformed_reply("name", document)),
424    }
425}
426
427/// The link of a `set-name` or `get-by-name` reply.
428pub fn parse_link_reply_for<T: QueryAddress>(
429    document: &[LiNo<String>],
430) -> ProtocolResult<Option<T>> {
431    match document {
432        [] => Ok(None),
433        [LiNo::Link {
434            id: Some(id),
435            values,
436        }] if id == "link" => match values.as_slice() {
437            [link] => parse_number(link).map(Some),
438            _ => Err(malformed_reply("link", document)),
439        },
440        _ => Err(malformed_reply("link", document)),
441    }
442}
443
444/// A reply listing `changes`, one `(before) (after)` line each.
445pub fn changes_document_for<T: QueryAddress>(changes: &[Change<T>]) -> LinoDocument {
446    changes
447        .iter()
448        .map(|(before, after)| group(vec![change_side(before), change_side(after)]))
449        .collect()
450}
451
452/// `(index: source target)` with plain numbers.
453pub fn link_lino<T: QueryAddress>(link: &GenericLink<T>) -> LiNo<String> {
454    named(
455        &link.index.to_string(),
456        vec![number(link.source), number(link.target)],
457    )
458}
459
460fn link_reply<T: QueryAddress>(link: Option<T>) -> LinoDocument {
461    link.map(|link| vec![named("link", vec![number(link)])])
462        .unwrap_or_default()
463}
464
465fn change_side<T: QueryAddress>(link: &GenericLink<T>) -> LiNo<String> {
466    if link.is_null() {
467        group(Vec::new())
468    } else {
469        group(vec![link_lino(link)])
470    }
471}
472
473fn parse_change_side<T: QueryAddress>(side: &LiNo<String>) -> ProtocolResult<GenericLink<T>> {
474    match side {
475        LiNo::Link { id: None, values } if values.is_empty() => Ok(GenericLink::null()),
476        LiNo::Link { id: None, values } if values.len() == 1 => parse_link(&values[0]),
477        // `((index: source target))` loses its wrapper when the side is the
478        // single named link itself.
479        link @ LiNo::Link { id: Some(_), .. } => parse_link(link),
480        _ => Err(ProtocolError::malformed(format!(
481            "expected a change side, found {}",
482            format_link(side)
483        ))),
484    }
485}
486
487fn parse_link<T: QueryAddress>(link: &LiNo<String>) -> ProtocolResult<GenericLink<T>> {
488    match link {
489        LiNo::Link {
490            id: Some(index),
491            values,
492        } => match values.as_slice() {
493            [source, target] => Ok(GenericLink::new(
494                parse_text_number(index)?,
495                parse_number(source)?,
496                parse_number(target)?,
497            )),
498            _ => Err(ProtocolError::malformed(format!(
499                "expected (index: source target), found {}",
500                format_link(link)
501            ))),
502        },
503        _ => Err(ProtocolError::malformed(format!(
504            "expected (index: source target), found {}",
505            format_link(link)
506        ))),
507    }
508}
509
510pub(super) fn restriction_lino<T: QueryAddress>(restriction: &[Part<T>]) -> LiNo<String> {
511    group(
512        restriction
513            .iter()
514            .map(|part| part.map_or_else(|| LiNo::Ref(ANY.to_string()), number))
515            .collect(),
516    )
517}
518
519pub(super) fn parse_restriction<T: QueryAddress>(
520    argument: &LiNo<String>,
521) -> ProtocolResult<Vec<Part<T>>> {
522    parse_restriction_of(argument, 3)
523}
524
525pub(super) fn parse_restriction_of<T: QueryAddress>(
526    argument: &LiNo<String>,
527    longest: usize,
528) -> ProtocolResult<Vec<Part<T>>> {
529    let parts = parts(argument);
530    if parts.len() > longest {
531        return Err(malformed_argument("restriction", argument));
532    }
533    parts
534        .iter()
535        .map(|part| match part {
536            LiNo::Ref(text) if text == ANY => Ok(None),
537            part => parse_number(part).map(Some),
538        })
539        .collect()
540}
541
542pub(super) fn numbers_lino<T: QueryAddress>(numbers: &[T]) -> LiNo<String> {
543    group(numbers.iter().copied().map(number).collect())
544}
545
546fn parse_numbers_for<T: QueryAddress, const N: usize>(
547    argument: &LiNo<String>,
548) -> ProtocolResult<[T; N]> {
549    let numbers = parts(argument)
550        .iter()
551        .map(parse_number)
552        .collect::<ProtocolResult<Vec<_>>>()?;
553    numbers
554        .try_into()
555        .map_err(|_| malformed_argument(&format!("{N} numbers"), argument))
556}
557
558/// The values of an unnamed group; a lone reference is a group of one, since
559/// the canonical document model unwraps `(x)` to `x`.
560pub(super) fn parts(argument: &LiNo<String>) -> &[LiNo<String>] {
561    match argument {
562        LiNo::Link { id: None, values } => values,
563        reference => std::slice::from_ref(reference),
564    }
565}
566
567pub(super) fn parse_number<T: QueryAddress>(value: &LiNo<String>) -> ProtocolResult<T> {
568    match value {
569        LiNo::Ref(text) => parse_text_number(text),
570        _ => Err(ProtocolError::malformed(format!(
571            "expected a number, found {}",
572            format_link(value)
573        ))),
574    }
575}
576
577pub(super) fn parse_text_number<T: QueryAddress>(text: &str) -> ProtocolResult<T> {
578    text.parse()
579        .map_err(|_| ProtocolError::malformed(format!("expected a number, found '{text}'")))
580}
581
582pub(super) fn number<T: QueryAddress>(value: T) -> LiNo<String> {
583    LiNo::Ref(value.to_string())
584}
585
586pub(super) fn named(id: &str, values: Vec<LiNo<String>>) -> LiNo<String> {
587    LiNo::Link {
588        id: Some(id.to_string()),
589        values,
590    }
591}
592
593pub(super) fn group(values: Vec<LiNo<String>>) -> LiNo<String> {
594    LiNo::Link { id: None, values }
595}
596
597pub(super) fn malformed_argument(expected: &str, argument: &LiNo<String>) -> ProtocolError {
598    ProtocolError::malformed(format!(
599        "expected {expected}, found {}",
600        format_link(argument)
601    ))
602}
603
604pub(super) fn malformed_reply(expected: &str, document: &[LiNo<String>]) -> ProtocolError {
605    ProtocolError::malformed(format!(
606        "expected a {expected} reply, found {}",
607        format_document(document)
608    ))
609}
610
611/// The links of an `each` reply using the existing u32 facade.
612pub fn parse_links(document: &[LiNo<String>]) -> ProtocolResult<Vec<Link>> {
613    parse_links_for(document)
614}
615
616/// The changes of a mutation reply using the existing u32 facade.
617pub fn parse_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<Change>> {
618    parse_changes_for(document)
619}
620
621/// A named-link reply using the existing u32 facade.
622pub fn parse_link_reply(document: &[LiNo<String>]) -> ProtocolResult<Option<u32>> {
623    parse_link_reply_for(document)
624}
625
626/// A change document using the existing u32 facade.
627pub fn changes_document(changes: &[Change]) -> LinoDocument {
628    changes_document_for(changes)
629}
630
631pub(super) fn parse_numbers<const N: usize>(argument: &LiNo<String>) -> ProtocolResult<[u32; N]> {
632    parse_numbers_for::<u32, N>(argument)
633}