Skip to main content

link_cli/protocol/
client.rs

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