Skip to main content

link_cli/protocol/
client.rs

1//! A client for [`LinksServer`](super::LinksServer) over TCP or any other
2//! [inter-process communication transport](super::ipc).
3
4use super::error::{ProtocolError, ProtocolResult};
5use super::ipc::{self, IpcStream};
6use super::links_operations::is_notification;
7use super::protocols::{LinoConnection, LinoProtocol};
8use super::server::error_message;
9use links_notation::binary::{format_document, parse_document, LinoDocument};
10use links_notation::LiNo;
11use std::collections::VecDeque;
12use std::io;
13use std::net::{TcpStream, ToSocketAddrs};
14use std::time::Duration;
15
16/// Sends substitution queries to a LiNo server over any [`LinoProtocol`].
17///
18/// A server pushes the changes a connection subscribed to between its
19/// replies; a pushed document starts with `(notify: N)`.
20/// [`request`](Self::request) sets the pushes it meets aside for
21/// [`receive_notification`](Self::receive_notification), so replies and
22/// pushes never get mixed up.
23#[derive(Debug)]
24pub struct LinksClient {
25    connection: LinoConnection<IpcStream, Box<dyn LinoProtocol>>,
26    notifications: VecDeque<LinoDocument>,
27}
28
29impl LinksClient {
30    /// Connects to the TCP `address` using `protocol` for every message.
31    pub fn connect(
32        address: impl ToSocketAddrs,
33        protocol: impl LinoProtocol + 'static,
34    ) -> ProtocolResult<Self> {
35        let stream = TcpStream::connect(address)?;
36        Ok(Self::from_stream(ipc::from_tcp_stream(stream), protocol))
37    }
38
39    /// Connects to an [IPC endpoint](ipc::Endpoint) such as `127.0.0.1:8080`,
40    /// `unix:/tmp/links.sock`, `pipe:links` or `shm:/tmp/links`.
41    pub fn connect_endpoint(
42        endpoint: &str,
43        protocol: impl LinoProtocol + 'static,
44    ) -> ProtocolResult<Self> {
45        Ok(Self::from_stream(ipc::connect(endpoint)?, protocol))
46    }
47
48    /// Talks over an already connected stream of any transport.
49    pub fn from_stream(stream: IpcStream, protocol: impl LinoProtocol + 'static) -> Self {
50        Self {
51            connection: LinoConnection::new(stream, Box::new(protocol)),
52            notifications: VecDeque::new(),
53        }
54    }
55
56    /// The endpoint kind of the connection, such as `tcp` or `shm`.
57    pub fn kind(&self) -> &'static str {
58        self.connection.stream().kind()
59    }
60
61    /// Sends a parsed document and returns the reply document.
62    ///
63    /// An `(error: 'message')` reply becomes [`ProtocolError::Remote`].
64    pub fn request(&mut self, document: &LinoDocument) -> ProtocolResult<LinoDocument> {
65        self.connection.send(document)?;
66        loop {
67            let reply = self
68                .connection
69                .receive()?
70                .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))?;
71            if is_notification(&reply) {
72                self.notifications.push_back(reply);
73                continue;
74            }
75            if let Some(message) = error_message(&reply) {
76                return Err(ProtocolError::Remote(message.to_string()));
77            }
78            return Ok(reply);
79        }
80    }
81
82    /// The number of pushes received and not yet taken by
83    /// [`receive_notification`](Self::receive_notification).
84    pub fn pending_notifications(&self) -> usize {
85        self.notifications.len()
86    }
87
88    /// The next document the server pushed, `(notify: N)` and its changes,
89    /// waiting up to `timeout` for one; `Ok(None)` when none arrived in time.
90    ///
91    /// Fails when the connection closed, or when the server sent something
92    /// other than a push while no request was waiting.
93    pub fn receive_notification(
94        &mut self,
95        timeout: Duration,
96    ) -> ProtocolResult<Option<LinoDocument>> {
97        if let Some(queued) = self.notifications.pop_front() {
98            return Ok(Some(queued));
99        }
100        if !self.connection.wait_for_message(timeout)? {
101            return Ok(None);
102        }
103        let document = self.connection.receive()?.ok_or_else(|| {
104            ProtocolError::Io(io::Error::new(
105                io::ErrorKind::UnexpectedEof,
106                "connection closed",
107            ))
108        })?;
109        if is_notification(&document) {
110            Ok(Some(document))
111        } else {
112            Err(ProtocolError::malformed(format!(
113                "the server sent a reply nobody asked for: {}",
114                format_document(&document)
115            )))
116        }
117    }
118
119    /// Runs a LiNo substitution query; the empty query reads every link.
120    pub fn query(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
121        self.request(&parse_document(query)?)
122    }
123
124    /// Sends original query text without losing quoted-reference kinds.
125    /// The peer must support [`super::query_document`]; legacy query behavior
126    /// remains available through [`Self::query`]. No mutation is retried using
127    /// a different wire representation after an error or unknown reply.
128    pub fn query_lossless(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
129        self.request(&super::server::query_document(query))
130    }
131
132    /// Like [`query`](Self::query), returning the reply as canonical text.
133    pub fn query_text(&mut self, query: &str) -> ProtocolResult<String> {
134        Ok(format_document(&self.query(query)?))
135    }
136
137    /// Sends `(auth: token)`: every later request of the connection runs as
138    /// the subject the server gives the token, which this returns (issue
139    /// #149). A token the server does not know is a [`ProtocolError::Remote`].
140    pub fn authenticate(&mut self, token: &str) -> ProtocolResult<u32> {
141        let reply = self.request(&vec![LiNo::Link {
142            id: Some("auth".to_string()),
143            values: vec![LiNo::Ref(token.to_string())],
144        }])?;
145        if let [LiNo::Link {
146            id: Some(id),
147            values,
148        }] = reply.as_slice()
149        {
150            if let [LiNo::Ref(subject)] = values.as_slice() {
151                if id == "subject" && subject.bytes().all(|byte| byte.is_ascii_digit()) {
152                    if let Ok(subject) = subject.parse() {
153                        return Ok(subject);
154                    }
155                }
156            }
157        }
158        Err(ProtocolError::Malformed(format!(
159            "expected a subject reply, found {}",
160            format_document(&reply)
161        )))
162    }
163}