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