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    /// Connects to the server at an [IPC endpoint](super::ipc::Endpoint)
70    /// such as `unix:/tmp/links.sock` or `shm:/tmp/links`.
71    pub fn connect_endpoint(
72        endpoint: &str,
73        protocol: impl LinoProtocol + 'static,
74    ) -> ProtocolResult<Self> {
75        Ok(Self::new(LinksClient::connect_endpoint(
76            endpoint, protocol,
77        )?))
78    }
79
80    /// Uses an existing connection.
81    pub fn new(client: LinksClient) -> Self {
82        Self {
83            client: Mutex::new(client),
84            triplet_markers: OnceLock::new(),
85        }
86    }
87
88    /// Runs one operation on the server and returns its reply.
89    pub fn execute(&self, operation: &LinksOperation) -> ProtocolResult<LinoDocument> {
90        self.client().request(&operation.to_document())
91    }
92
93    /// Asks the server to push the changes other connections make to the
94    /// links matching `restriction`; returns the subscription number that
95    /// [`receive_notification`](Self::receive_notification) reports them with.
96    pub fn subscribe(&self, restriction: &[Part]) -> ProtocolResult<u32> {
97        parse_subscription(&self.execute(&LinksOperation::Subscribe(restriction.to_vec()))?)
98    }
99
100    /// Stops a subscription; an unknown number is ignored.
101    pub fn unsubscribe(&self, subscription: u32) -> ProtocolResult<()> {
102        self.execute(&LinksOperation::Unsubscribe(subscription))?;
103        Ok(())
104    }
105
106    /// The next change pushed to a subscription of this connection, waiting
107    /// up to `timeout` for one; `Ok(None)` when none arrived in time.
108    pub fn receive_notification(
109        &self,
110        timeout: Duration,
111    ) -> ProtocolResult<Option<LinksNotification>> {
112        self.client()
113            .receive_notification(timeout)?
114            .map(|document| parse_notification(&document))
115            .transpose()
116    }
117
118    pub(super) fn client(&self) -> MutexGuard<'_, LinksClient> {
119        self.client.lock().unwrap_or_else(PoisonError::into_inner)
120    }
121
122    /// Number of links matching `restriction`.
123    pub fn count_matching(&self, restriction: &[Part]) -> ProtocolResult<u32> {
124        parse_count(&self.execute(&LinksOperation::Count(restriction.to_vec()))?)
125    }
126
127    /// Links matching `restriction`, ordered by index.
128    pub fn links_matching(&self, restriction: &[Part]) -> ProtocolResult<Vec<Link>> {
129        parse_links(&self.execute(&LinksOperation::Each(restriction.to_vec()))?)
130    }
131
132    /// Runs a `create`, `update` or `delete` and returns its changes.
133    pub fn changes(&self, operation: &LinksOperation) -> ProtocolResult<Vec<Change>> {
134        parse_changes(&self.execute(operation)?)
135    }
136
137    /// The link stored at `index`.
138    pub fn link(&self, index: u32) -> ProtocolResult<Option<Link>> {
139        Ok(self.links_matching(&[Some(index)])?.pop())
140    }
141
142    fn create_remote(&self, source: u32, target: u32) -> ProtocolResult<Link> {
143        self.changes(&LinksOperation::Create { source, target })?
144            .into_iter()
145            .find_map(|(before, after)| (before.is_null() && !after.is_null()).then_some(after))
146            .ok_or_else(|| ProtocolError::malformed("the create reply holds no created link"))
147    }
148
149    /// Runs an `update` or `delete` of `index`, reports its changes to
150    /// `observer` and returns the state `index` was in before.
151    fn observed(
152        &self,
153        operation: &LinksOperation,
154        index: u32,
155        observer: ChangeObserver<'_>,
156    ) -> ProtocolResult<Link> {
157        let changes = self.changes(operation)?;
158        for (before, after) in &changes {
159            observer(*before, *after);
160        }
161        changes
162            .iter()
163            .find(|(before, _)| before.index == index)
164            .map(|(before, _)| *before)
165            .ok_or_else(|| {
166                ProtocolError::malformed(format!("the reply holds no change of {index}"))
167            })
168    }
169
170    fn parts(&self, query: &[u32]) -> Vec<Part> {
171        let any = self.constants().any;
172        query
173            .iter()
174            .map(|&part| (part != any).then_some(part))
175            .collect()
176    }
177}
178
179/// Unwraps the result of a call whose interface has no way to report a
180/// failure.
181pub(super) fn connected<T>(result: ProtocolResult<T>) -> T {
182    result.unwrap_or_else(|error| panic!("remote links store failed: {error}"))
183}
184
185fn doublets_link(link: &Link) -> DoubletsLink<u32> {
186    DoubletsLink::new(link.index, link.source, link.target)
187}
188
189fn doublets_error(error: ProtocolError) -> Error<u32> {
190    Error::Other(Box::new(error))
191}
192
193/// Feeds `changes` to `handler` until it asks to stop.
194fn replay(changes: &[Change], handler: WriteHandler<'_, u32>) -> Flow {
195    for (before, after) in changes {
196        if handler(doublets_link(before), doublets_link(after)) == Flow::Break {
197            return Flow::Break;
198        }
199    }
200    Flow::Continue
201}
202
203fn part(query: &[u32], index: usize) -> u32 {
204    query.get(index).copied().unwrap_or(0)
205}
206
207impl Links<u32> for RemoteLinks {
208    fn constants(&self) -> &LinksConstants<u32> {
209        link_storage_constants()
210    }
211
212    fn count_links(&self, query: &[u32]) -> u32 {
213        connected(self.count_matching(&self.parts(query)))
214    }
215
216    /// Creates an empty `(index: 0 0)` link, like every `doublets` store.
217    fn create_links(
218        &mut self,
219        _query: &[u32],
220        handler: WriteHandler<'_, u32>,
221    ) -> Result<Flow, Error<u32>> {
222        let changes = self
223            .changes(&LinksOperation::Create {
224                source: 0,
225                target: 0,
226            })
227            .map_err(doublets_error)?;
228        Ok(replay(&changes, handler))
229    }
230
231    fn each_links(&self, query: &[u32], handler: ReadHandler<'_, u32>) -> Flow {
232        for link in connected(self.links_matching(&self.parts(query))) {
233            if handler(doublets_link(&link)) == Flow::Break {
234                return Flow::Break;
235            }
236        }
237        Flow::Continue
238    }
239
240    fn update_links(
241        &mut self,
242        query: &[u32],
243        change: &[u32],
244        handler: WriteHandler<'_, u32>,
245    ) -> Result<Flow, Error<u32>> {
246        let changes = self
247            .changes(&LinksOperation::Update {
248                index: part(query, 0),
249                source: part(change, 1),
250                target: part(change, 2),
251            })
252            .map_err(doublets_error)?;
253        Ok(replay(&changes, handler))
254    }
255
256    fn delete_links(
257        &mut self,
258        query: &[u32],
259        handler: WriteHandler<'_, u32>,
260    ) -> Result<Flow, Error<u32>> {
261        let changes = self
262            .changes(&LinksOperation::Delete(part(query, 0)))
263            .map_err(doublets_error)?;
264        Ok(replay(&changes, handler))
265    }
266}
267
268impl Doublets<u32> for RemoteLinks {
269    fn get_link(&self, index: u32) -> Option<DoubletsLink<u32>> {
270        connected(self.link(index)).as_ref().map(doublets_link)
271    }
272}
273
274impl NamedTypeLinks for RemoteLinks {
275    fn create(&mut self, source: u32, target: u32) -> u32 {
276        connected(self.create_remote(source, target)).index
277    }
278
279    /// Asks for links until the server hands out `id`, then deletes the ones
280    /// handed out on the way, exactly like [`LinkStorage::ensure_created`](crate::LinkStorage::ensure_created).
281    fn ensure_created(&mut self, id: u32) -> u32 {
282        if id == 0 || self.exists(id) {
283            return id;
284        }
285        let mut passed_over = Vec::new();
286        loop {
287            let created = NamedTypeLinks::create(self, 0, 0);
288            if created == id {
289                break;
290            }
291            passed_over.push(created);
292        }
293        for address in passed_over {
294            connected(self.changes(&LinksOperation::Delete(address)));
295        }
296        id
297    }
298
299    fn get_link(&mut self, id: u32) -> Option<Link> {
300        connected(self.link(id))
301    }
302
303    /// Counts, so it also holds on a server in triplet mode, where a link
304    /// does not read as a doublet.
305    fn exists(&mut self, id: u32) -> bool {
306        connected(self.count_matching(&[Some(id)])) > 0
307    }
308
309    fn update_observed(
310        &mut self,
311        id: u32,
312        source: u32,
313        target: u32,
314        observer: ChangeObserver<'_>,
315    ) -> anyhow::Result<Link> {
316        let operation = LinksOperation::Update {
317            index: id,
318            source,
319            target,
320        };
321        Ok(self.observed(&operation, id, observer)?)
322    }
323
324    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> anyhow::Result<Link> {
325        Ok(self.observed(&LinksOperation::Delete(id), id, observer)?)
326    }
327
328    fn all_links(&mut self) -> Vec<Link> {
329        connected(self.links_matching(&[]))
330    }
331
332    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
333        connected(self.links_matching(&[None, Some(source), Some(target)]))
334            .first()
335            .map(|link| link.index)
336    }
337
338    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
339        match self.search(source, target) {
340            Some(index) => index,
341            None => NamedTypeLinks::create(self, source, target),
342        }
343    }
344
345    fn get_name(&mut self, id: u32) -> anyhow::Result<Option<String>> {
346        Ok(parse_name(&self.execute(&LinksOperation::GetName(id))?)?)
347    }
348
349    fn set_name(&mut self, id: u32, name: &str) -> anyhow::Result<u32> {
350        parse_link_reply(&self.execute(&LinksOperation::SetName(id, name.to_string()))?)?
351            .ok_or_else(|| anyhow::anyhow!("the set-name reply holds no link"))
352    }
353
354    fn get_by_name(&mut self, name: &str) -> anyhow::Result<Option<u32>> {
355        Ok(parse_link_reply(
356            &self.execute(&LinksOperation::GetByName(name.to_string()))?,
357        )?)
358    }
359
360    fn remove_name(&mut self, id: u32) -> anyhow::Result<()> {
361        self.execute(&LinksOperation::RemoveName(id))?;
362        Ok(())
363    }
364
365    /// The server saves after every change, so there is nothing to flush.
366    fn save(&mut self) -> anyhow::Result<()> {
367        Ok(())
368    }
369}