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