link_cli/protocol/
client.rs1use super::error::{ProtocolError, ProtocolResult};
5use super::ipc::{self, IpcStream};
6use super::links_operations::is_notification;
7use super::protocols::{LinoConnection, LinoProtocol};
8use super::server::error_message;
9use links_notation::binary::{format_document, parse_document, LinoDocument};
10use links_notation::LiNo;
11use std::collections::VecDeque;
12use std::io;
13use std::net::{TcpStream, ToSocketAddrs};
14use std::time::Duration;
15
16#[derive(Debug)]
24pub struct LinksClient {
25 connection: LinoConnection<IpcStream, Box<dyn LinoProtocol>>,
26 notifications: VecDeque<LinoDocument>,
27}
28
29impl LinksClient {
30 pub fn connect(
32 address: impl ToSocketAddrs,
33 protocol: impl LinoProtocol + 'static,
34 ) -> ProtocolResult<Self> {
35 let stream = TcpStream::connect(address)?;
36 Ok(Self::from_stream(ipc::from_tcp_stream(stream), protocol))
37 }
38
39 pub fn connect_endpoint(
42 endpoint: &str,
43 protocol: impl LinoProtocol + 'static,
44 ) -> ProtocolResult<Self> {
45 Ok(Self::from_stream(ipc::connect(endpoint)?, protocol))
46 }
47
48 pub fn from_stream(stream: IpcStream, protocol: impl LinoProtocol + 'static) -> Self {
50 Self {
51 connection: LinoConnection::new(stream, Box::new(protocol)),
52 notifications: VecDeque::new(),
53 }
54 }
55
56 pub fn kind(&self) -> &'static str {
58 self.connection.stream().kind()
59 }
60
61 pub fn request(&mut self, document: &LinoDocument) -> ProtocolResult<LinoDocument> {
65 self.connection.send(document)?;
66 loop {
67 let reply = self
68 .connection
69 .receive()?
70 .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))?;
71 if is_notification(&reply) {
72 self.notifications.push_back(reply);
73 continue;
74 }
75 if let Some(message) = error_message(&reply) {
76 return Err(ProtocolError::Remote(message.to_string()));
77 }
78 return Ok(reply);
79 }
80 }
81
82 pub fn pending_notifications(&self) -> usize {
85 self.notifications.len()
86 }
87
88 pub fn receive_notification(
94 &mut self,
95 timeout: Duration,
96 ) -> ProtocolResult<Option<LinoDocument>> {
97 if let Some(queued) = self.notifications.pop_front() {
98 return Ok(Some(queued));
99 }
100 if !self.connection.wait_for_message(timeout)? {
101 return Ok(None);
102 }
103 let document = self.connection.receive()?.ok_or_else(|| {
104 ProtocolError::Io(io::Error::new(
105 io::ErrorKind::UnexpectedEof,
106 "connection closed",
107 ))
108 })?;
109 if is_notification(&document) {
110 Ok(Some(document))
111 } else {
112 Err(ProtocolError::malformed(format!(
113 "the server sent a reply nobody asked for: {}",
114 format_document(&document)
115 )))
116 }
117 }
118
119 pub fn query(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
121 self.request(&parse_document(query)?)
122 }
123
124 pub fn query_lossless(&mut self, query: &str) -> ProtocolResult<LinoDocument> {
129 self.request(&super::server::query_document(query))
130 }
131
132 pub fn query_text(&mut self, query: &str) -> ProtocolResult<String> {
134 Ok(format_document(&self.query(query)?))
135 }
136
137 pub fn authenticate(&mut self, token: &str) -> ProtocolResult<u32> {
141 let reply = self.request(&vec![LiNo::Link {
142 id: Some("auth".to_string()),
143 values: vec![LiNo::Ref(token.to_string())],
144 }])?;
145 if let [LiNo::Link {
146 id: Some(id),
147 values,
148 }] = reply.as_slice()
149 {
150 if let [LiNo::Ref(subject)] = values.as_slice() {
151 if id == "subject" && subject.bytes().all(|byte| byte.is_ascii_digit()) {
152 if let Ok(subject) = subject.parse() {
153 return Ok(subject);
154 }
155 }
156 }
157 }
158 Err(ProtocolError::Malformed(format!(
159 "expected a subject reply, found {}",
160 format_document(&reply)
161 )))
162 }
163}