link_cli/protocol/
client.rs1use 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#[derive(Debug)]
21pub struct LinksClient {
22 connection: LinoConnection<TcpStream, Box<dyn LinoProtocol>>,
23 notifications: VecDeque<LinoDocument>,
24}
25
26impl LinksClient {
27 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 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 pub fn pending_notifications(&self) -> usize {
64 self.notifications.len()
65 }
66
67 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 pub fn query(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
100 self.request(&parse_document(query)?)
101 }
102
103 pub fn query_text(&mut self, query: &str) -> ProtocolResult<String> {
105 Ok(format_document(&self.query(query)?))
106 }
107}