Skip to main content

link_cli/protocol/
remote_triplets.rs

1//! [`RemoteLinks`] as a [`Triplets`] store, behind a
2//! [`LinksServer`](super::LinksServer) in triplet mode (issue #152).
3//!
4//! Code written against [`Triplets`], [`process_triplets_query`](crate::process_triplets_query)
5//! included, switches from a local store to a server by swapping one value.
6//! Every call is one [`TripletsOperation`] round trip. The doublets that store
7//! the triplets stay behind the server: over a server in triplet mode, the
8//! doublet calls of [`RemoteLinks`] (`create`, `update`, `delete`, `get_link`,
9//! `all_links`, `search`) are refused or panic like a failed connection; only
10//! `exists`, which counts, and the names keep working.
11
12use super::error::{ProtocolError, ProtocolResult};
13use super::links_operations::{parse_count, parse_link_reply, parse_subscription, Part};
14use super::remote_links::{connected, RemoteLinks};
15use super::triplets_operations::{
16    parse_triplet_changes, parse_triplet_notification, parse_triplets, restriction_of_query,
17    TripletsNotification, TripletsOperation,
18};
19use super::LinksOperation;
20use crate::triplets::{
21    DoubletRole, Triplet, TripletChange, TripletMarkers, TripletQuery, Triplets,
22    NOTHING_MARKER_NAME, PAIR_MARKER_NAME,
23};
24use links_notation::binary::{parse_document, LinoDocument};
25use std::time::Duration;
26
27impl RemoteLinks {
28    /// Runs one triplet operation on the server and returns its reply.
29    pub fn execute_triplets(&self, operation: &TripletsOperation) -> ProtocolResult<LinoDocument> {
30        self.client().request(&operation.to_document())
31    }
32
33    /// Number of triplets matching `restriction`.
34    pub fn count_triplets_matching(&self, restriction: &[Part]) -> ProtocolResult<u32> {
35        parse_count(&self.execute_triplets(&TripletsOperation::Count(restriction.to_vec()))?)
36    }
37
38    /// Triplets matching `restriction`, ordered by index.
39    pub fn triplets_matching(&self, restriction: &[Part]) -> ProtocolResult<Vec<Triplet>> {
40        parse_triplets(&self.execute_triplets(&TripletsOperation::Each(restriction.to_vec()))?)
41    }
42
43    /// Runs a `create`, `update` or `delete` and returns its changes.
44    pub fn triplet_changes(
45        &self,
46        operation: &TripletsOperation,
47    ) -> ProtocolResult<Vec<TripletChange>> {
48        parse_triplet_changes(&self.execute_triplets(operation)?)
49    }
50
51    /// Asks the server to push the changes other connections make to the
52    /// triplets matching `restriction`; returns the subscription number that
53    /// [`receive_triplet_notification`](Self::receive_triplet_notification)
54    /// reports them with. [`unsubscribe`](Self::unsubscribe) stops it.
55    pub fn subscribe_triplets(&self, restriction: &[Part]) -> ProtocolResult<u32> {
56        parse_subscription(
57            &self.execute_triplets(&TripletsOperation::Subscribe(restriction.to_vec()))?,
58        )
59    }
60
61    /// The next change pushed to a subscription of this connection, waiting
62    /// up to `timeout` for one; `Ok(None)` when none arrived in time.
63    pub fn receive_triplet_notification(
64        &self,
65        timeout: Duration,
66    ) -> ProtocolResult<Option<TripletsNotification>> {
67        self.client()
68            .receive_notification(timeout)?
69            .map(|document| parse_triplet_notification(&document))
70            .transpose()
71    }
72
73    fn marker(&self, name: &str) -> u32 {
74        let reply = self.execute(&LinksOperation::GetByName(name.to_string()));
75        connected(reply.and_then(|document| parse_link_reply(&document))).unwrap_or(0)
76    }
77
78    fn created_triplet(&self, operation: &TripletsOperation) -> ProtocolResult<u32> {
79        self.triplet_changes(operation)?
80            .into_iter()
81            .find_map(|change| change.after.map(|triplet| triplet.index))
82            .ok_or_else(|| ProtocolError::malformed("the create reply holds no created triplet"))
83    }
84}
85
86impl Triplets for RemoteLinks {
87    /// The markers the server names; one the subject may not read is `0`.
88    /// Nothing else of this implementation depends on them: the server applies
89    /// the encoding.
90    fn triplet_markers(&self) -> TripletMarkers {
91        *self.triplet_markers.get_or_init(|| TripletMarkers {
92            pair: self.marker(PAIR_MARKER_NAME),
93            nothing: self.marker(NOTHING_MARKER_NAME),
94        })
95    }
96
97    /// A marker, a triplet, or `None`: the doublets that store the triplets
98    /// are not on the wire, so they read as missing.
99    fn role_of(&mut self, id: u32) -> Option<DoubletRole> {
100        if id == 0 {
101            return None;
102        }
103        if self.triplet_markers().contains(id) {
104            return Some(DoubletRole::Marker);
105        }
106        connected(self.triplets_matching(&[Some(id)]))
107            .pop()
108            .map(DoubletRole::Triplet)
109    }
110
111    fn create_triplet(&mut self, type_id: u32, from: u32, to: u32) -> anyhow::Result<u32> {
112        Ok(self.created_triplet(&TripletsOperation::Create { type_id, from, to })?)
113    }
114
115    fn create_triplet_point(&mut self) -> anyhow::Result<u32> {
116        Ok(self.created_triplet(&TripletsOperation::Create {
117            type_id: 0,
118            from: 0,
119            to: 0,
120        })?)
121    }
122
123    /// `create` has no way to name an address, a substitution query does.
124    fn create_triplet_point_at(&mut self, address: u32) -> anyhow::Result<()> {
125        let query = parse_document(&format!("() (({address}: {address} 0 0))"))
126            .map_err(|error| anyhow::anyhow!("{error}"))?;
127        self.client().request(&query)?;
128        Ok(())
129    }
130
131    fn update_triplet(
132        &mut self,
133        index: u32,
134        type_id: u32,
135        from: u32,
136        to: u32,
137    ) -> anyhow::Result<Triplet> {
138        self.triplet_changes(&TripletsOperation::Update {
139            index,
140            type_id,
141            from,
142            to,
143        })?
144        .into_iter()
145        .find_map(|change| change.before)
146        .ok_or_else(|| anyhow::anyhow!("the reply holds no change of {index}"))
147    }
148
149    fn delete_triplet(&mut self, index: u32) -> anyhow::Result<Vec<Triplet>> {
150        Ok(self
151            .triplet_changes(&TripletsOperation::Delete(index))?
152            .into_iter()
153            .filter_map(|change| change.before)
154            .collect())
155    }
156
157    fn each_triplet(&mut self, query: TripletQuery) -> Vec<Triplet> {
158        connected(self.triplets_matching(&restriction_of_query(query)))
159    }
160
161    fn count_triplets(&mut self, query: TripletQuery) -> usize {
162        connected(self.count_triplets_matching(&restriction_of_query(query))) as usize
163    }
164
165    /// How many other triplets use `id`: the doublets behind them are not on
166    /// the wire.
167    fn doublet_usages(&mut self, id: u32) -> usize {
168        let mut users = self.each_triplet(TripletQuery::by_type(id));
169        users.extend(self.each_triplet(TripletQuery::by_from(id)));
170        users.extend(self.each_triplet(TripletQuery::by_to(id)));
171        users.retain(|user| user.index != id);
172        users.sort_unstable();
173        users.dedup();
174        users.len()
175    }
176}