Skip to main content

link_cli/protocol/
triplets_operations.rs

1//! The triplets of a server in triplet mode (issue #152) as LiNo documents, so
2//! a store behind a [`LinksServer`](super::LinksServer) is used exactly like a
3//! local [`Triplets`] store through [`RemoteLinks`](super::RemoteLinks).
4//!
5//! `(delete: i)`, `(count: ())` and a substitution query read the same in both
6//! worlds, so the shape of a request cannot tell a triplet from a doublet.
7//! That is why triplets are a mode of the server,
8//! [`ServerOptions::triplets`](super::ServerOptions::triplets) (`clink --serve
9//! --triplets`): a server without it answers exactly as it always did, and one
10//! with it reads every request as triplets.
11//!
12//! | Request                       | Reply                                   |
13//! |-------------------------------|-----------------------------------------|
14//! | `(count: (index type from to))` | `(count: N)`                          |
15//! | `(each: (index type from to))`  | one `(index: type from to)` per match |
16//! | `(create: (type from to))`    | `() ((index: type from to))`            |
17//! | `(create: (0 0 0))`           | `() ((index: index 0 0))`, a point: a triplet that is its own type |
18//! | `(update: (index type from to))` | `((index: t f t)) ((index: type from to))` |
19//! | `(delete: index)`             | `((index: type from to)) ()` per removed triplet, `index` first |
20//! | `(subscribe: (index type from to))` | `(subscription: N)`; later pushes of `(notify: N)` and its changes |
21//!
22//! `get-name`, `set-name`, `get-by-name`, `remove-name`, `unsubscribe` and
23//! `auth` are the same as [without triplets](super::links_operations), and the
24//! empty request lists every triplet. Any other document is a substitution
25//! query over triplets ([`process_triplets_query`]); its reply names the
26//! references that have a name, like a query over doublets.
27//!
28//! A restriction holds up to four parts, matched part by part: the parts it
29//! leaves out match anything, as does `*`; an empty `from` or `to` is `0`.
30//! The wrappers and pairs that store a triplet in doublets never appear.
31//!
32//! A reply or push in a binary format whose arity holds three references but
33//! not the five of `(index: type from to)`, such as `2..3`, carries every
34//! triplet as `(index: (type from to))`, which travels as one link of three
35//! references; see [`pack_triplets`]. Every parser here reads both forms.
36
37use super::error::{ProtocolError, ProtocolResult};
38use super::links_operations::{
39    group, malformed_argument, malformed_reply, named, notification_number, number, numbers_lino,
40    parse_number, parse_numbers, parse_restriction_of, parse_text_number, parts, restriction_lino,
41    LinksOperation, Part,
42};
43use super::protocols::MessageFormat;
44use super::server::{error_document, reference_name};
45use crate::triplets::{process_triplets_query, Triplet, TripletChange, TripletQuery, Triplets};
46use links_notation::binary::{format_document, format_link, LinoDocument};
47use links_notation::LiNo;
48
49/// One call of the [`Triplets`] interface.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub enum TripletsOperation {
52    /// Number of triplets matching the restriction.
53    Count(Vec<Part>),
54    /// Every triplet matching the restriction, ordered by index.
55    Each(Vec<Part>),
56    /// Creates a triplet; `(0 0 0)` creates a point, its own type.
57    Create { type_id: u32, from: u32, to: u32 },
58    /// Makes an existing triplet `(index: type from to)`, keeping its address.
59    Update {
60        index: u32,
61        type_id: u32,
62        from: u32,
63        to: u32,
64    },
65    /// Deletes a triplet and every triplet that uses it.
66    Delete(u32),
67    /// Asks a [`LinksServer`](super::LinksServer) to push the changes other
68    /// connections make to the triplets matching the restriction; only the
69    /// server can run it, so [`execute`](Self::execute) on a store fails.
70    Subscribe(Vec<Part>),
71}
72
73/// A change a [`LinksServer`](super::LinksServer) in triplet mode pushed to a
74/// subscriber; a side that does not fit the restriction (or that the
75/// subscriber may not read) is `None`.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct TripletsNotification {
78    /// The number the `subscribe` reply gave.
79    pub subscription: u32,
80    /// The changes.
81    pub changes: Vec<TripletChange>,
82}
83
84impl TripletsOperation {
85    /// The request document for this operation.
86    pub fn to_document(&self) -> LinoDocument {
87        let (name, argument) = match self {
88            Self::Count(restriction) => ("count", restriction_lino(restriction)),
89            Self::Each(restriction) => ("each", restriction_lino(restriction)),
90            Self::Create { type_id, from, to } => ("create", numbers_lino(&[*type_id, *from, *to])),
91            Self::Update {
92                index,
93                type_id,
94                from,
95                to,
96            } => ("update", numbers_lino(&[*index, *type_id, *from, *to])),
97            Self::Delete(index) => ("delete", number(*index)),
98            Self::Subscribe(restriction) => ("subscribe", restriction_lino(restriction)),
99        };
100        vec![named(name, vec![argument])]
101    }
102
103    /// Recognises a triplet operation; `Ok(None)` for any other document, such
104    /// as a substitution query or a request about names.
105    pub fn from_document(document: &[LiNo<String>]) -> ProtocolResult<Option<Self>> {
106        let [LiNo::Link {
107            id: Some(name),
108            values,
109        }] = document
110        else {
111            return Ok(None);
112        };
113        let [argument] = values.as_slice() else {
114            return Ok(None);
115        };
116        let operation = match name.as_str() {
117            "count" => Self::Count(parse_restriction_of(argument, 4)?),
118            "each" => Self::Each(parse_restriction_of(argument, 4)?),
119            "create" => {
120                let [type_id, from, to] = parse_numbers::<3>(argument)?;
121                Self::Create { type_id, from, to }
122            }
123            "update" => {
124                let [index, type_id, from, to] = parse_numbers::<4>(argument)?;
125                Self::Update {
126                    index,
127                    type_id,
128                    from,
129                    to,
130                }
131            }
132            "delete" => Self::Delete(parse_number(argument)?),
133            "subscribe" => Self::Subscribe(parse_restriction_of(argument, 4)?),
134            _ => return Ok(None),
135        };
136        Ok(Some(operation))
137    }
138
139    /// Runs the operation against `triplets` and returns the reply document.
140    pub fn execute<T: Triplets + ?Sized>(&self, triplets: &mut T) -> anyhow::Result<LinoDocument> {
141        Ok(match self {
142            Self::Count(restriction) => {
143                let count = matching(triplets, restriction).len();
144                vec![named("count", vec![number(count as u32)])]
145            }
146            Self::Each(restriction) => matching(triplets, restriction)
147                .iter()
148                .map(triplet_lino)
149                .collect(),
150            Self::Create { type_id, from, to } => {
151                let created = if (*type_id, *from, *to) == (0, 0, 0) {
152                    let index = triplets.create_triplet_point()?;
153                    Triplet::new(index, index, 0, 0)
154                } else {
155                    let index = triplets.create_triplet(*type_id, *from, *to)?;
156                    Triplet::new(index, *type_id, *from, *to)
157                };
158                triplets.save()?;
159                triplet_changes_document(&[TripletChange {
160                    before: None,
161                    after: Some(created),
162                }])
163            }
164            Self::Update {
165                index,
166                type_id,
167                from,
168                to,
169            } => {
170                let before = triplets.update_triplet(*index, *type_id, *from, *to)?;
171                triplets.save()?;
172                triplet_changes_document(&[TripletChange {
173                    before: Some(before),
174                    after: Some(Triplet::new(*index, *type_id, *from, *to)),
175                }])
176            }
177            Self::Delete(index) => {
178                let deleted = triplets.delete_triplet(*index)?;
179                triplets.save()?;
180                let changes: Vec<TripletChange> = deleted
181                    .into_iter()
182                    .map(|triplet| TripletChange {
183                        before: Some(triplet),
184                        after: None,
185                    })
186                    .collect();
187                triplet_changes_document(&changes)
188            }
189            Self::Subscribe(_) => {
190                anyhow::bail!("subscriptions belong to a connection to a links server")
191            }
192        })
193    }
194}
195
196/// The query a restriction asks for; the parts it leaves out match anything.
197pub fn triplet_query(restriction: &[Part]) -> TripletQuery {
198    let part = |at: usize| restriction.get(at).copied().flatten();
199    TripletQuery::new(part(0), part(1), part(2), part(3))
200}
201
202/// The restriction of `query`, in the order of the wire.
203pub fn restriction_of_query(query: TripletQuery) -> Vec<Part> {
204    vec![query.index, query.type_id, query.from, query.to]
205}
206
207/// Whether `triplet` matches `restriction`, part by part.
208pub fn matches_triplet(triplet: &Triplet, restriction: &[Part]) -> bool {
209    restriction.len() <= 4 && triplet_query(restriction).matches(triplet)
210}
211
212fn matching<T: Triplets + ?Sized>(triplets: &mut T, restriction: &[Part]) -> Vec<Triplet> {
213    triplets.each_triplet(triplet_query(restriction))
214}
215
216/// Answers one request of a server in triplet mode against `triplets`;
217/// failures produce an [`error_document`].
218///
219/// The counterpart of [`execute_request`](super::execute_request); see the
220/// [module documentation](self).
221pub fn execute_triplets_request<T: Triplets + ?Sized>(
222    triplets: &mut T,
223    document: &[LiNo<String>],
224) -> LinoDocument {
225    execute_observed_triplets_request(triplets, document, &mut Vec::new())
226}
227
228/// Like [`execute_triplets_request`], adding every triplet the request
229/// changed to `changed`, with plain numbers.
230pub(super) fn execute_observed_triplets_request<T: Triplets + ?Sized>(
231    triplets: &mut T,
232    document: &[LiNo<String>],
233    changed: &mut Vec<TripletChange>,
234) -> LinoDocument {
235    match try_execute_triplets_request(triplets, document, changed) {
236        Ok(reply) => reply,
237        Err(error) => error_document(&format!("{error:#}")),
238    }
239}
240
241fn try_execute_triplets_request<T: Triplets + ?Sized>(
242    triplets: &mut T,
243    document: &[LiNo<String>],
244    changed: &mut Vec<TripletChange>,
245) -> anyhow::Result<LinoDocument> {
246    if let Some(operation) = TripletsOperation::from_document(document)? {
247        let reply = operation.execute(triplets)?;
248        if matches!(
249            operation,
250            TripletsOperation::Create { .. }
251                | TripletsOperation::Update { .. }
252                | TripletsOperation::Delete(_)
253        ) {
254            changed.extend(
255                parse_triplet_changes(&reply)?
256                    .into_iter()
257                    .filter(|change| change.before != change.after),
258            );
259        }
260        return Ok(reply);
261    }
262    if let Some(operation) = LinksOperation::from_document(document)? {
263        return operation.execute(triplets);
264    }
265    if document.is_empty() {
266        return triplets
267            .each_triplet(TripletQuery::any())
268            .iter()
269            .map(|triplet| named_triplet_lino(triplets, triplet))
270            .collect();
271    }
272    let changes = process_triplets_query(triplets, &format_document(document))?;
273    let writes = changes
274        .iter()
275        .filter(|change| change.before != change.after);
276    let before = changed.len();
277    changed.extend(writes.copied());
278    if changed.len() != before {
279        triplets.save()?;
280    }
281    changes
282        .iter()
283        .map(|change| {
284            Ok(group(vec![
285                named_side(triplets, change.before.as_ref())?,
286                named_side(triplets, change.after.as_ref())?,
287            ]))
288        })
289        .collect()
290}
291
292/// `(index: type from to)`, naming every reference that has a name.
293fn named_triplet_lino<T: Triplets + ?Sized>(
294    triplets: &mut T,
295    triplet: &Triplet,
296) -> anyhow::Result<LiNo<String>> {
297    let mut reference = |id: u32| -> anyhow::Result<String> { reference_name(triplets, id) };
298    Ok(LiNo::Link {
299        id: Some(reference(triplet.index)?),
300        values: vec![
301            LiNo::Ref(reference(triplet.type_id)?),
302            LiNo::Ref(reference(triplet.from)?),
303            LiNo::Ref(reference(triplet.to)?),
304        ],
305    })
306}
307
308fn named_side<T: Triplets + ?Sized>(
309    triplets: &mut T,
310    triplet: Option<&Triplet>,
311) -> anyhow::Result<LiNo<String>> {
312    Ok(group(match triplet {
313        Some(triplet) => vec![named_triplet_lino(triplets, triplet)?],
314        None => Vec::new(),
315    }))
316}
317
318/// `(index: type from to)` with plain numbers.
319pub fn triplet_lino(triplet: &Triplet) -> LiNo<String> {
320    named(
321        &triplet.index.to_string(),
322        vec![
323            number(triplet.type_id),
324            number(triplet.from),
325            number(triplet.to),
326        ],
327    )
328}
329
330fn side_lino(triplet: Option<&Triplet>) -> LiNo<String> {
331    group(triplet.map(triplet_lino).into_iter().collect())
332}
333
334/// A reply listing `changes`, one `(before) (after)` line each.
335pub fn triplet_changes_document(changes: &[TripletChange]) -> LinoDocument {
336    changes
337        .iter()
338        .map(|change| {
339            group(vec![
340                side_lino(change.before.as_ref()),
341                side_lino(change.after.as_ref()),
342            ])
343        })
344        .collect()
345}
346
347/// A push: `(notify: N)` followed by one `(before) (after)` line per change.
348pub fn triplet_notification_document(subscription: u32, changes: &[TripletChange]) -> LinoDocument {
349    let mut document = vec![named("notify", vec![number(subscription)])];
350    document.extend(triplet_changes_document(changes));
351    document
352}
353
354/// The subscription and the changes of a [`triplet_notification_document`].
355pub fn parse_triplet_notification(
356    document: &[LiNo<String>],
357) -> ProtocolResult<TripletsNotification> {
358    let subscription =
359        notification_number(document).ok_or_else(|| malformed_reply("notify", document))?;
360    Ok(TripletsNotification {
361        subscription,
362        changes: parse_triplet_changes(&document[1..])?,
363    })
364}
365
366/// The triplets of an `each` reply.
367pub fn parse_triplets(document: &[LiNo<String>]) -> ProtocolResult<Vec<Triplet>> {
368    document.iter().map(parse_triplet).collect()
369}
370
371/// The `(before) (after)` pairs of a `create`, `update` or `delete` reply.
372pub fn parse_triplet_changes(document: &[LiNo<String>]) -> ProtocolResult<Vec<TripletChange>> {
373    document
374        .iter()
375        .map(|change| match parts(change) {
376            [before, after] => Ok(TripletChange {
377                before: parse_side(before)?,
378                after: parse_side(after)?,
379            }),
380            _ => Err(malformed_reply("change", document)),
381        })
382        .collect()
383}
384
385fn parse_side(side: &LiNo<String>) -> ProtocolResult<Option<Triplet>> {
386    match side {
387        LiNo::Link { id: None, values } if values.is_empty() => Ok(None),
388        LiNo::Link { id: None, values } if values.len() == 1 => parse_triplet(&values[0]).map(Some),
389        // `((index: type from to))` loses its wrapper when the side is the
390        // single named link itself.
391        link @ LiNo::Link { id: Some(_), .. } => parse_triplet(link).map(Some),
392        _ => Err(malformed_argument("a change side", side)),
393    }
394}
395
396/// A triplet, as `(index: type from to)` or as [`pack_triplets`] writes it.
397pub fn parse_triplet(link: &LiNo<String>) -> ProtocolResult<Triplet> {
398    let malformed = || {
399        ProtocolError::malformed(format!(
400            "expected (index: type from to), found {}",
401            format_link(link)
402        ))
403    };
404    let LiNo::Link {
405        id: Some(index),
406        values,
407    } = link
408    else {
409        return Err(malformed());
410    };
411    let values: &[LiNo<String>] = match values.as_slice() {
412        [LiNo::Link { id: None, values }] => values,
413        values => values,
414    };
415    let [type_id, from, to] = values else {
416        return Err(malformed());
417    };
418    Ok(Triplet::new(
419        parse_text_number(index)?,
420        parse_number(type_id)?,
421        parse_number(from)?,
422        parse_number(to)?,
423    ))
424}
425
426/// Rewrites every triplet of `document` so it fits `format`: in a binary format
427/// whose arity holds three references but not five, `(index: type from to)`
428/// becomes `(index: (type from to))`, whose second part travels as one link of
429/// three references. Under any other format the document stays as it is.
430///
431/// `(index: type from to)` needs a link of five references, the marker of a
432/// named link and the index included, so under `2..3` the mapping would spell
433/// it as a chain of doublets: nothing would gain from the arity.
434pub fn pack_triplets(document: LinoDocument, format: MessageFormat) -> LinoDocument {
435    match format {
436        MessageFormat::Binary(options)
437            if options.arity.contains(3) && !options.arity.contains(5) =>
438        {
439            document.into_iter().map(pack_link).collect()
440        }
441        _ => document,
442    }
443}
444
445fn pack_link(link: LiNo<String>) -> LiNo<String> {
446    match link {
447        LiNo::Link { id: None, values } => group(values.into_iter().map(pack_link).collect()),
448        LiNo::Link {
449            id: Some(id),
450            values,
451        } if values.len() == 3 => LiNo::Link {
452            id: Some(id),
453            values: vec![group(values)],
454        },
455        link => link,
456    }
457}
458
459/// The inverse of [`pack_triplets`]: the canonical text of a triplet reply
460/// does not depend on the format that carried it.
461pub fn canonical_triplets(document: LinoDocument) -> LinoDocument {
462    document.into_iter().map(unpack_link).collect()
463}
464
465fn unpack_link(link: LiNo<String>) -> LiNo<String> {
466    match link {
467        LiNo::Link { id: None, values } => group(values.into_iter().map(unpack_link).collect()),
468        LiNo::Link {
469            id: Some(id),
470            mut values,
471        } if matches!(
472            values.as_slice(),
473            [LiNo::Link { id: None, values }] if values.len() == 3
474        ) =>
475        {
476            let Some(LiNo::Link { values, .. }) = values.pop() else {
477                unreachable!("the guard holds one unnamed link");
478            };
479            LiNo::Link {
480                id: Some(id),
481                values,
482            }
483        }
484        link => link,
485    }
486}