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 links_notation::LiNo;
9use std::collections::VecDeque;
10use std::io;
11use std::net::{TcpStream, ToSocketAddrs};
12use std::time::Duration;
13
14#[derive(Debug)]
22pub struct LinksClient {
23 connection: LinoConnection<TcpStream, Box<dyn LinoProtocol>>,
24 notifications: VecDeque<LinoDocument>,
25}
26
27impl LinksClient {
28 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 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 pub fn pending_notifications(&self) -> usize {
65 self.notifications.len()
66 }
67
68 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 pub fn query(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
101 self.request(&parse_document(query)?)
102 }
103
104 pub fn query_text(&mut self, query: &str) -> ProtocolResult<String> {
106 Ok(format_document(&self.query(query)?))
107 }
108
109 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}