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::protocols::{LinoConnection, LinoProtocol};
5use super::server::error_message;
6use links_notation::binary::{format_document, parse_document, LinoDocument};
7use std::net::{TcpStream, ToSocketAddrs};
8
9/// Sends substitution queries to a LiNo server over any [`LinoProtocol`].
10#[derive(Debug)]
11pub struct LinksClient {
12    connection: LinoConnection<TcpStream, Box<dyn LinoProtocol>>,
13}
14
15impl LinksClient {
16    /// Connects to `address` using `protocol` for every message.
17    pub fn connect(
18        address: impl ToSocketAddrs,
19        protocol: impl LinoProtocol + 'static,
20    ) -> ProtocolResult<Self> {
21        let stream = TcpStream::connect(address)?;
22        let _ = stream.set_nodelay(true);
23        Ok(Self {
24            connection: LinoConnection::new(stream, Box::new(protocol)),
25        })
26    }
27
28    /// Sends a parsed document and returns the reply document.
29    ///
30    /// An `(error: 'message')` reply becomes [`ProtocolError::Remote`].
31    pub fn request(&mut self, document: &LinoDocument) -> ProtocolResult<LinoDocument> {
32        let reply = self.connection.request(document)?;
33        if let Some(message) = error_message(&reply) {
34            return Err(ProtocolError::Remote(message.to_string()));
35        }
36        Ok(reply)
37    }
38
39    /// Runs a LiNo substitution query; the empty query reads every link.
40    pub fn query(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
41        self.request(&parse_document(query)?)
42    }
43
44    /// Like [`query`](Self::query), returning the reply as canonical text.
45    pub fn query_text(&mut self, query: &str) -> ProtocolResult<String> {
46        Ok(format_document(&self.query(query)?))
47    }
48}