1use super::error::{ProtocolError, ProtocolResult};
9use super::ipc::IpcStream;
10use links_notation::binary::packet::BINARY_VERSION_1;
11use links_notation::binary::{
12 decode_document, encode_document_with_limits, format_document, parse_document,
13 BinaryLinoOptions, DecodeLimits, LinksPacket, LinoDocument,
14};
15use links_notation::LiNo;
16use std::fmt::Debug;
17use std::io::{self, BufRead, BufReader, Read, Write};
18use std::net::TcpStream;
19use std::time::Duration;
20
21pub trait LinoProtocol: Debug + Send + Sync {
23 fn write_document(
25 &self,
26 writer: &mut dyn Write,
27 document: &[LiNo<String>],
28 ) -> ProtocolResult<()>;
29
30 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>>;
32}
33
34impl<P: LinoProtocol + ?Sized> LinoProtocol for Box<P> {
35 fn write_document(
36 &self,
37 writer: &mut dyn Write,
38 document: &[LiNo<String>],
39 ) -> ProtocolResult<()> {
40 (**self).write_document(writer, document)
41 }
42
43 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
44 (**self).read_document(reader)
45 }
46}
47
48pub const DEFAULT_MAX_TEXT_BYTES: usize = 64 << 20;
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct ProtocolLimits {
58 pub binary: DecodeLimits,
60 pub max_text_bytes: usize,
62}
63
64impl Default for ProtocolLimits {
65 fn default() -> Self {
66 Self {
67 binary: DecodeLimits::default(),
68 max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
69 }
70 }
71}
72
73impl ProtocolLimits {
74 pub fn unlimited() -> Self {
76 Self {
77 binary: DecodeLimits::unlimited(),
78 max_text_bytes: usize::MAX,
79 }
80 }
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct TextLinoProtocol {
91 pub max_text_bytes: usize,
93}
94
95impl Default for TextLinoProtocol {
96 fn default() -> Self {
97 Self {
98 max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
99 }
100 }
101}
102
103impl TextLinoProtocol {
104 pub fn new() -> Self {
106 Self::default()
107 }
108
109 pub fn write_text(writer: &mut dyn Write, text: &str) -> ProtocolResult<()> {
111 let mut out = String::with_capacity(text.len() + 4);
112 if !text.is_empty() {
113 for line in text.split('\n') {
114 if line.starts_with('.') {
115 out.push('.');
116 }
117 out.push_str(line);
118 out.push('\n');
119 }
120 }
121 out.push_str(".\n");
122 writer.write_all(out.as_bytes())?;
123 writer.flush()?;
124 Ok(())
125 }
126
127 pub fn read_text(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<String>> {
129 let mut text = Vec::new();
130 let mut line = Vec::new();
131 let mut first = true;
132 loop {
133 line.clear();
134 let budget = self.max_text_bytes.saturating_sub(text.len()) as u64 + 2;
135 let read = reader.take(budget).read_until(b'\n', &mut line)?;
136 if read == 0 {
137 if first {
138 return Ok(None);
139 }
140 return Err(ProtocolError::malformed(
141 "stream ended before the '.' terminator line",
142 ));
143 }
144 if line.last() != Some(&b'\n') {
145 if read as u64 >= budget {
146 return Err(ProtocolError::LimitExceeded(format!(
147 "text message longer than {} bytes",
148 self.max_text_bytes
149 )));
150 }
151 return Err(ProtocolError::malformed(
152 "stream ended before the '.' terminator line",
153 ));
154 }
155 line.pop();
156 if line.last() == Some(&b'\r') {
158 line.pop();
159 }
160 if line == b"." {
161 break;
162 }
163 if !first {
164 text.push(b'\n');
165 }
166 first = false;
167 let content = line.strip_prefix(b".").unwrap_or(&line);
168 text.extend_from_slice(content);
169 }
170 String::from_utf8(text)
171 .map(Some)
172 .map_err(|_| ProtocolError::malformed("text message is not valid UTF-8"))
173 }
174}
175
176impl LinoProtocol for TextLinoProtocol {
177 fn write_document(
178 &self,
179 writer: &mut dyn Write,
180 document: &[LiNo<String>],
181 ) -> ProtocolResult<()> {
182 Self::write_text(writer, &format_document(document))
183 }
184
185 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
186 self.read_text(reader)?
187 .map(|text| parse_document(&text).map_err(ProtocolError::from))
188 .transpose()
189 }
190}
191
192#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
195pub struct BinaryLinoProtocol {
196 pub options: BinaryLinoOptions,
198 pub limits: DecodeLimits,
200}
201
202impl BinaryLinoProtocol {
203 pub fn new() -> Self {
205 Self::default()
206 }
207
208 pub fn with_options(options: BinaryLinoOptions) -> Self {
210 Self {
211 options,
212 ..Self::default()
213 }
214 }
215
216 pub fn encode(&self, document: &[LiNo<String>]) -> ProtocolResult<Vec<u8>> {
218 Ok(encode_document_with_limits(document, self.options, &self.limits)?.to_bytes()?)
219 }
220
221 pub fn decode(&self, bytes: &[u8]) -> ProtocolResult<LinoDocument> {
223 let packet = LinksPacket::from_bytes(bytes, &self.limits)?;
224 Ok(decode_document(&packet, &self.limits)?)
225 }
226}
227
228impl LinoProtocol for BinaryLinoProtocol {
229 fn write_document(
230 &self,
231 writer: &mut dyn Write,
232 document: &[LiNo<String>],
233 ) -> ProtocolResult<()> {
234 writer.write_all(&self.encode(document)?)?;
235 writer.flush()?;
236 Ok(())
237 }
238
239 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
240 LinksPacket::read_from(reader, &self.limits)?
241 .map(|packet| Ok(decode_document(&packet, &self.limits)?))
242 .transpose()
243 }
244}
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248pub enum MessageFormat {
249 Text,
251 Binary(BinaryLinoOptions),
253}
254
255impl MessageFormat {
256 pub fn protocol(self, limits: ProtocolLimits) -> Box<dyn LinoProtocol> {
258 match self {
259 MessageFormat::Text => Box::new(TextLinoProtocol {
260 max_text_bytes: limits.max_text_bytes,
261 }),
262 MessageFormat::Binary(options) => Box::new(BinaryLinoProtocol {
263 options,
264 limits: limits.binary,
265 }),
266 }
267 }
268}
269
270pub fn is_binary_start(byte: u8) -> bool {
272 byte & 0xF0 == BINARY_VERSION_1
273}
274
275pub fn read_any_document(
277 reader: &mut dyn BufRead,
278 limits: &ProtocolLimits,
279) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
280 read_any_document_with_query_limits(reader, limits, None)
281}
282
283pub(crate) fn read_any_document_with_query_limits(
286 reader: &mut dyn BufRead,
287 limits: &ProtocolLimits,
288 query_limits: Option<crate::query_options::QueryLimits>,
289) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
290 let mut limits = *limits;
291 if let Some(query) = query_limits {
292 limits.max_text_bytes = limits.max_text_bytes.min(query.max_bytes);
293 limits.binary.max_depth = limits.binary.max_depth.min(query.max_depth);
294 limits.binary.max_nodes = limits.binary.max_nodes.min(query.max_nodes);
295 limits.binary.max_string_bytes = limits.binary.max_string_bytes.min(query.max_bytes);
296 let max_nodes = u64::try_from(query.max_nodes).unwrap_or(u64::MAX);
297 limits.binary.max_links = limits.binary.max_links.min(max_nodes);
298 limits.binary.max_references = limits.binary.max_references.min(max_nodes);
299 }
300 let Some(&first) = reader.fill_buf()?.first() else {
301 return Ok(None);
302 };
303 if !is_binary_start(first) {
304 let text = TextLinoProtocol {
305 max_text_bytes: limits.max_text_bytes,
306 };
307 return Ok(text
308 .read_text(reader)?
309 .map(|text| match query_limits {
310 Some(query) => super::server::parse_document_with_limits(&text, query),
311 None => parse_document(&text).map_err(ProtocolError::from),
312 })
313 .transpose()?
314 .map(|document| (document, MessageFormat::Text)));
315 }
316 LinksPacket::read_from(reader, &limits.binary)?
317 .map(|packet| {
318 let document = decode_document(&packet, &limits.binary)?;
319 Ok((
320 document,
321 MessageFormat::Binary(BinaryLinoOptions::of_packet(&packet)),
322 ))
323 })
324 .transpose()
325}
326
327#[derive(Debug)]
329pub struct LinoConnection<S: Read + Write, P: LinoProtocol> {
330 stream: BufReader<S>,
331 protocol: P,
332}
333
334impl<S: Read + Write, P: LinoProtocol> LinoConnection<S, P> {
335 pub fn new(stream: S, protocol: P) -> Self {
337 Self {
338 stream: BufReader::new(stream),
339 protocol,
340 }
341 }
342
343 pub fn protocol(&self) -> &P {
345 &self.protocol
346 }
347
348 pub fn send(&mut self, document: &[LiNo<String>]) -> ProtocolResult<()> {
350 let mut buffer = Vec::new();
351 self.protocol.write_document(&mut buffer, document)?;
352 let stream = self.stream.get_mut();
353 stream.write_all(&buffer)?;
354 stream.flush()?;
355 Ok(())
356 }
357
358 pub fn receive(&mut self) -> ProtocolResult<Option<LinoDocument>> {
360 self.protocol.read_document(&mut self.stream)
361 }
362
363 pub fn request(&mut self, document: &[LiNo<String>]) -> ProtocolResult<LinoDocument> {
365 self.send(document)?;
366 self.receive()?
367 .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))
368 }
369
370 pub fn stream(&self) -> &S {
372 self.stream.get_ref()
373 }
374
375 pub fn into_inner(self) -> S {
377 self.stream.into_inner()
378 }
379}
380
381pub trait TimedStream: Read + Write {
384 fn current_read_timeout(&self) -> io::Result<Option<Duration>>;
386 fn change_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()>;
388}
389
390impl TimedStream for TcpStream {
391 fn current_read_timeout(&self) -> io::Result<Option<Duration>> {
392 self.read_timeout()
393 }
394
395 fn change_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
396 self.set_read_timeout(timeout)
397 }
398}
399
400impl TimedStream for IpcStream {
401 fn current_read_timeout(&self) -> io::Result<Option<Duration>> {
402 Ok(self.read_timeout())
403 }
404
405 fn change_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
406 self.set_read_timeout(timeout);
407 Ok(())
408 }
409}
410
411impl<S: TimedStream, P: LinoProtocol> LinoConnection<S, P> {
412 pub fn wait_for_message(&mut self, timeout: Duration) -> ProtocolResult<bool> {
416 if !self.stream.buffer().is_empty() {
417 return Ok(true);
418 }
419 let previous = self.stream.get_ref().current_read_timeout()?;
420 self.stream
422 .get_mut()
423 .change_read_timeout(Some(timeout.max(Duration::from_millis(1))))?;
424 let arrived = self.stream.fill_buf().map(|_| ());
425 self.stream.get_mut().change_read_timeout(previous)?;
426 match arrived {
427 Ok(()) => Ok(true),
428 Err(error)
429 if matches!(
430 error.kind(),
431 io::ErrorKind::WouldBlock
432 | io::ErrorKind::TimedOut
433 | io::ErrorKind::Interrupted
434 ) =>
435 {
436 Ok(false)
437 }
438 Err(error) => Err(error.into()),
439 }
440 }
441}