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 std::collections::VecDeque;
9use std::io;
10use std::net::{TcpStream, ToSocketAddrs};
11use std::time::Duration;
12
13/// Sends substitution queries to a LiNo server over any [`LinoProtocol`].
14///
15/// A server pushes the changes a connection subscribed to between its
16/// replies; a pushed document starts with `(notify: N)`.
17/// [`request`](Self::request) sets the pushes it meets aside for
18/// [`receive_notification`](Self::receive_notification), so replies and
19/// pushes never get mixed up.
20#[derive(Debug)]
21pub struct LinksClient {
22    connection: LinoConnection<TcpStream, Box<dyn LinoProtocol>>,
23    notifications: VecDeque<LinoDocument>,
24}
25
26impl LinksClient {
27    /// Connects to `address` using `protocol` for every message.
28    pub fn connect(
29        address: impl ToSocketAddrs,
30        protocol: impl LinoProtocol + 'static,
31    ) -> ProtocolResult<Self> {
32        let stream = TcpStream::connect(address)?;
33        let _ = stream.set_nodelay(true);
34        Ok(Self {
35            connection: LinoConnection::new(stream, Box::new(protocol)),
36            notifications: VecDeque::new(),
37        })
38    }
39
40    /// Sends a parsed document and returns the reply document.
41    ///
42    /// An `(error: 'message')` reply becomes [`ProtocolError::Remote`].
43    pub fn request(&mut self, document: &LinoDocument) -> ProtocolResult<LinoDocument> {
44        self.connection.send(document)?;
45        loop {
46            let reply = self
47                .connection
48                .receive()?
49                .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))?;
50            if is_notification(&reply) {
51                self.notifications.push_back(reply);
52                continue;
53            }
54            if let Some(message) = error_message(&reply) {
55                return Err(ProtocolError::Remote(message.to_string()));
56            }
57            return Ok(reply);
58        }
59    }
60
61    /// The number of pushes received and not yet taken by
62    /// [`receive_notification`](Self::receive_notification).
63    pub fn pending_notifications(&self) -> usize {
64        self.notifications.len()
65    }
66
67    /// The next document the server pushed, `(notify: N)` and its changes,
68    /// waiting up to `timeout` for one; `Ok(None)` when none arrived in time.
69    ///
70    /// Fails when the connection closed, or when the server sent something
71    /// other than a push while no request was waiting.
72    pub fn receive_notification(
73        &mut self,
74        timeout: Duration,
75    ) -> ProtocolResult<Option<LinoDocument>> {
76        if let Some(queued) = self.notifications.pop_front() {
77            return Ok(Some(queued));
78        }
79        if !self.connection.wait_for_message(timeout)? {
80            return Ok(None);
81        }
82        let document = self.connection.receive()?.ok_or_else(|| {
83            ProtocolError::Io(io::Error::new(
84                io::ErrorKind::UnexpectedEof,
85                "connection closed",
86            ))
87        })?;
88        if is_notification(&document) {
89            Ok(Some(document))
90        } else {
91            Err(ProtocolError::malformed(format!(
92                "the server sent a reply nobody asked for: {}",
93                format_document(&document)
94            )))
95        }
96    }
97
98    /// Runs a LiNo substitution query; the empty query reads every link.
99    pub fn query(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
100        self.request(&parse_document(query)?)
101    }
102
103    /// Like [`query`](Self::query), returning the reply as canonical text.
104    pub fn query_text(&mut self, query: &str) -> ProtocolResult<String> {
105        Ok(format_document(&self.query(query)?))
106    }
107}