Skip to main content

link_cli/protocol/
remote_links.rs

1//! [`RemoteLinks`]: a links store that lives behind a [`LinksServer`](super::LinksServer).
2//!
3//! It implements the same interfaces as a local store — [`doublets::Links`],
4//! [`doublets::Doublets`] and [`NamedTypeLinks`] — so code written against
5//! them, the [`QueryProcessor`](crate::QueryProcessor) included, switches
6//! from a local file to a server by swapping one value:
7//!
8//! ```no_run
9//! use link_cli::protocol::{RemoteLinks, TextLinoProtocol};
10//! use link_cli::{NamedTypeLinks, NamedTypesDecorator, QueryProcessor};
11//!
12//! fn run(store: &mut impl NamedTypeLinks) -> anyhow::Result<()> {
13//!     QueryProcessor::new(false).process_query(store, "() ((1 1))")?;
14//!     Ok(())
15//! }
16//!
17//! run(&mut NamedTypesDecorator::new("db.links", false)?)?;
18//! run(&mut RemoteLinks::connect("127.0.0.1:8080", TextLinoProtocol::new())?)?;
19//! # Ok::<(), anyhow::Error>(())
20//! ```
21//!
22//! Every call is one [`LinksOperation`] round trip. An observer of a write
23//! sees the net change of every link it touched, not the steps the store
24//! behind the server took. The methods of the upstream and CLI traits that
25//! cannot return an error panic when the connection fails, the way a local
26//! store panics when its file does; the inherent methods return every failure
27//! as a [`ProtocolError`].
28//!
29//! Over a server in triplet mode it is a [`Triplets`](crate::Triplets) store;
30//! see `remote_triplets.rs`.
31
32use super::client::LinksClient;
33use super::error::{ProtocolError, ProtocolResult};
34use super::links_operations::{
35    parse_changes, parse_count, parse_link_reply, parse_links, parse_name, parse_notification,
36    parse_subscription, Change, LinksNotification, LinksOperation, Part,
37};
38use super::protocols::LinoProtocol;
39use crate::link::Link;
40use crate::link_storage::ChangeObserver;
41use crate::link_storage_doublets::link_storage_constants;
42use crate::named_type_links::NamedTypeLinks;
43use crate::triplets::TripletMarkers;
44use doublets::data::{Flow, LinksConstants, ReadHandler, WriteHandler};
45use doublets::{Doublets, Error, Link as DoubletsLink, Links};
46use links_notation::binary::LinoDocument;
47use std::net::ToSocketAddrs;
48use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
49use std::time::Duration;
50
51/// A links store served by a [`LinksServer`](super::LinksServer), usable
52/// wherever a local store is.
53#[derive(Debug)]
54pub struct RemoteLinks {
55    client: Mutex<LinksClient>,
56    /// What the server names `Pair` and `Nothing`, once asked.
57    pub(super) triplet_markers: OnceLock<TripletMarkers>,
58}
59
60impl RemoteLinks {
61    /// Connects to the server at `address`.
62    pub fn connect(
63        address: impl ToSocketAddrs,
64        protocol: impl LinoProtocol + 'static,
65    ) -> ProtocolResult<Self> {
66        Ok(Self::new(LinksClient::connect(address, protocol)?))
67    }
68
69    /// Uses an existing connection.
70    pub fn new(client: LinksClient) -> Self {
71        Self {
72            client: Mutex::new(client),
73            triplet_markers: OnceLock::new(),
74        }
75    }
76
77    /// Runs one operation on the server and returns its reply.
78    pub fn execute(&self, operation: &LinksOperation) -> ProtocolResult<LinoDocument> {
79        self.client().request(&operation.to_document())
80    }
81
82    /// Asks the server to push the changes other connections make to the
83    /// links matching `restriction`; returns the subscription number that
84    /// [`receive_notification`](Self::receive_notification) reports them with.
85    pub fn subscribe(&self, restriction: &[Part]) -> ProtocolResult<u32> {
86        parse_subscription(&self.execute(&LinksOperation::Subscribe(restriction.to_vec()))?)
87    }
88
89    /// Stops a subscription; an unknown number is ignored.
90    pub fn unsubscribe(&self, subscription: u32) -> ProtocolResult<()> {
91        self.execute(&LinksOperation::Unsubscribe(subscription))?;
92        Ok(())
93    }
94
95    /// The next change pushed to a subscription of this connection, waiting
96    /// up to `timeout` for one; `Ok(None)` when none arrived in time.
97    pub fn receive_notification(
98        &self,
99        timeout: Duration,
100    ) -> ProtocolResult<Option<LinksNotification>> {
101        self.client()
102            .receive_notification(timeout)?
103            .map(|document| parse_notification(&document))
104            .transpose()
105    }
106
107    pub(super) fn client(&self) -> MutexGuard<'_, LinksClient> {
108        self.client.lock().unwrap_or_else(PoisonError::into_inner)
109    }
110
111    /// Number of links matching `restriction`.
112    pub fn count_matching(&self, restriction: &[Part]) -> ProtocolResult<u32> {
113        parse_count(&self.execute(&LinksOperation::Count(restriction.to_vec()))?)
114    }
115
116    /// Links matching `restriction`, ordered by index.
117    pub fn links_matching(&self, restriction: &[Part]) -> ProtocolResult<Vec<Link>> {
118        parse_links(&self.execute(&LinksOperation::Each(restriction.to_vec()))?)
119    }
120
121    /// Runs a `create`, `update` or `delete` and returns its changes.
122    pub fn changes(&self, operation: &LinksOperation) -> ProtocolResult<Vec<Change>> {
123        parse_changes(&self.execute(operation)?)
124    }
125
126    /// The link stored at `index`.
127    pub fn link(&self, index: u32) -> ProtocolResult<Option<Link>> {
128        Ok(self.links_matching(&[Some(index)])?.pop())
129    }
130
131    fn create_remote(&self, source: u32, target: u32) -> ProtocolResult<Link> {
132        self.changes(&LinksOperation::Create { source, target })?
133            .into_iter()
134            .find_map(|(before, after)| (before.is_null() && !after.is_null()).then_some(after))
135            .ok_or_else(|| ProtocolError::malformed("the create reply holds no created link"))
136    }
137
138    /// Runs an `update` or `delete` of `index`, reports its changes to
139    /// `observer` and returns the state `index` was in before.
140    fn observed(
141        &self,
142        operation: &LinksOperation,
143        index: u32,
144        observer: ChangeObserver<'_>,
145    ) -> ProtocolResult<Link> {
146        let changes = self.changes(operation)?;
147        for (before, after) in &changes {
148            observer(*before, *after);
149        }
150        changes
151            .iter()
152            .find(|(before, _)| before.index == index)
153            .map(|(before, _)| *before)
154            .ok_or_else(|| {
155                ProtocolError::malformed(format!("the reply holds no change of {index}"))
156            })
157    }
158
159    fn parts(&self, query: &[u32]) -> Vec<Part> {
160        let any = self.constants().any;
161        query
162            .iter()
163            .map(|&part| (part != any).then_some(part))
164            .collect()
165    }
166}
167
168/// Unwraps the result of a call whose interface has no way to report a
169/// failure.
170pub(super) fn connected<T>(result: ProtocolResult<T>) -> T {
171    result.unwrap_or_else(|error| panic!("remote links store failed: {error}"))
172}
173
174fn doublets_link(link: &Link) -> DoubletsLink<u32> {
175    DoubletsLink::new(link.index, link.source, link.target)
176}
177
178fn doublets_error(error: ProtocolError) -> Error<u32> {
179    Error::Other(Box::new(error))
180}
181
182/// Feeds `changes` to `handler` until it asks to stop.
183fn replay(changes: &[Change], handler: WriteHandler<'_, u32>) -> Flow {
184    for (before, after) in changes {
185        if handler(doublets_link(before), doublets_link(after)) == Flow::Break {
186            return Flow::Break;
187        }
188    }
189    Flow::Continue
190}
191
192fn part(query: &[u32], index: usize) -> u32 {
193    query.get(index).copied().unwrap_or(0)
194}
195
196impl Links<u32> for RemoteLinks {
197    fn constants(&self) -> &LinksConstants<u32> {
198        link_storage_constants()
199    }
200
201    fn count_links(&self, query: &[u32]) -> u32 {
202        connected(self.count_matching(&self.parts(query)))
203    }
204
205    /// Creates an empty `(index: 0 0)` link, like every `doublets` store.
206    fn create_links(
207        &mut self,
208        _query: &[u32],
209        handler: WriteHandler<'_, u32>,
210    ) -> Result<Flow, Error<u32>> {
211        let changes = self
212            .changes(&LinksOperation::Create {
213                source: 0,
214                target: 0,
215            })
216            .map_err(doublets_error)?;
217        Ok(replay(&changes, handler))
218    }
219
220    fn each_links(&self, query: &[u32], handler: ReadHandler<'_, u32>) -> Flow {
221        for link in connected(self.links_matching(&self.parts(query))) {
222            if handler(doublets_link(&link)) == Flow::Break {
223                return Flow::Break;
224            }
225        }
226        Flow::Continue
227    }
228
229    fn update_links(
230        &mut self,
231        query: &[u32],
232        change: &[u32],
233        handler: WriteHandler<'_, u32>,
234    ) -> Result<Flow, Error<u32>> {
235        let changes = self
236            .changes(&LinksOperation::Update {
237                index: part(query, 0),
238                source: part(change, 1),
239                target: part(change, 2),
240            })
241            .map_err(doublets_error)?;
242        Ok(replay(&changes, handler))
243    }
244
245    fn delete_links(
246        &mut self,
247        query: &[u32],
248        handler: WriteHandler<'_, u32>,
249    ) -> Result<Flow, Error<u32>> {
250        let changes = self
251            .changes(&LinksOperation::Delete(part(query, 0)))
252            .map_err(doublets_error)?;
253        Ok(replay(&changes, handler))
254    }
255}
256
257impl Doublets<u32> for RemoteLinks {
258    fn get_link(&self, index: u32) -> Option<DoubletsLink<u32>> {
259        connected(self.link(index)).as_ref().map(doublets_link)
260    }
261}
262
263impl NamedTypeLinks for RemoteLinks {
264    fn create(&mut self, source: u32, target: u32) -> u32 {
265        connected(self.create_remote(source, target)).index
266    }
267
268    /// Asks for links until the server hands out `id`, then deletes the ones
269    /// handed out on the way, exactly like [`LinkStorage::ensure_created`](crate::LinkStorage::ensure_created).
270    fn ensure_created(&mut self, id: u32) -> u32 {
271        if id == 0 || self.exists(id) {
272            return id;
273        }
274        let mut passed_over = Vec::new();
275        loop {
276            let created = NamedTypeLinks::create(self, 0, 0);
277            if created == id {
278                break;
279            }
280            passed_over.push(created);
281        }
282        for address in passed_over {
283            connected(self.changes(&LinksOperation::Delete(address)));
284        }
285        id
286    }
287
288    fn get_link(&mut self, id: u32) -> Option<Link> {
289        connected(self.link(id))
290    }
291
292    /// Counts, so it also holds on a server in triplet mode, where a link
293    /// does not read as a doublet.
294    fn exists(&mut self, id: u32) -> bool {
295        connected(self.count_matching(&[Some(id)])) > 0
296    }
297
298    fn update_observed(
299        &mut self,
300        id: u32,
301        source: u32,
302        target: u32,
303        observer: ChangeObserver<'_>,
304    ) -> anyhow::Result<Link> {
305        let operation = LinksOperation::Update {
306            index: id,
307            source,
308            target,
309        };
310        Ok(self.observed(&operation, id, observer)?)
311    }
312
313    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> anyhow::Result<Link> {
314        Ok(self.observed(&LinksOperation::Delete(id), id, observer)?)
315    }
316
317    fn all_links(&mut self) -> Vec<Link> {
318        connected(self.links_matching(&[]))
319    }
320
321    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
322        connected(self.links_matching(&[None, Some(source), Some(target)]))
323            .first()
324            .map(|link| link.index)
325    }
326
327    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
328        match self.search(source, target) {
329            Some(index) => index,
330            None => NamedTypeLinks::create(self, source, target),
331        }
332    }
333
334    fn get_name(&mut self, id: u32) -> anyhow::Result<Option<String>> {
335        Ok(parse_name(&self.execute(&LinksOperation::GetName(id))?)?)
336    }
337
338    fn set_name(&mut self, id: u32, name: &str) -> anyhow::Result<u32> {
339        parse_link_reply(&self.execute(&LinksOperation::SetName(id, name.to_string()))?)?
340            .ok_or_else(|| anyhow::anyhow!("the set-name reply holds no link"))
341    }
342
343    fn get_by_name(&mut self, name: &str) -> anyhow::Result<Option<u32>> {
344        Ok(parse_link_reply(
345            &self.execute(&LinksOperation::GetByName(name.to_string()))?,
346        )?)
347    }
348
349    fn remove_name(&mut self, id: u32) -> anyhow::Result<()> {
350        self.execute(&LinksOperation::RemoveName(id))?;
351        Ok(())
352    }
353
354    /// The server saves after every change, so there is nothing to flush.
355    fn save(&mut self) -> anyhow::Result<()> {
356        Ok(())
357    }
358}