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 let Some(&first) = reader.fill_buf()?.first() else {
280 return Ok(None);
281 };
282 if !is_binary_start(first) {
283 let text = TextLinoProtocol {
284 max_text_bytes: limits.max_text_bytes,
285 };
286 return Ok(text
287 .read_document(reader)?
288 .map(|document| (document, MessageFormat::Text)));
289 }
290 LinksPacket::read_from(reader, &limits.binary)?
291 .map(|packet| {
292 let document = decode_document(&packet, &limits.binary)?;
293 Ok((
294 document,
295 MessageFormat::Binary(BinaryLinoOptions::of_packet(&packet)),
296 ))
297 })
298 .transpose()
299}
300
301#[derive(Debug)]
303pub struct LinoConnection<S: Read + Write, P: LinoProtocol> {
304 stream: BufReader<S>,
305 protocol: P,
306}
307
308impl<S: Read + Write, P: LinoProtocol> LinoConnection<S, P> {
309 pub fn new(stream: S, protocol: P) -> Self {
311 Self {
312 stream: BufReader::new(stream),
313 protocol,
314 }
315 }
316
317 pub fn protocol(&self) -> &P {
319 &self.protocol
320 }
321
322 pub fn send(&mut self, document: &[LiNo<String>]) -> ProtocolResult<()> {
324 let mut buffer = Vec::new();
325 self.protocol.write_document(&mut buffer, document)?;
326 let stream = self.stream.get_mut();
327 stream.write_all(&buffer)?;
328 stream.flush()?;
329 Ok(())
330 }
331
332 pub fn receive(&mut self) -> ProtocolResult<Option<LinoDocument>> {
334 self.protocol.read_document(&mut self.stream)
335 }
336
337 pub fn request(&mut self, document: &[LiNo<String>]) -> ProtocolResult<LinoDocument> {
339 self.send(document)?;
340 self.receive()?
341 .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))
342 }
343
344 pub fn into_inner(self) -> S {
346 self.stream.into_inner()
347 }
348}
349
350impl<P: LinoProtocol> LinoConnection<TcpStream, P> {
351 pub fn wait_for_message(&mut self, timeout: Duration) -> ProtocolResult<bool> {
355 if !self.stream.buffer().is_empty() {
356 return Ok(true);
357 }
358 let stream = self.stream.get_ref();
359 let previous = stream.read_timeout()?;
360 stream.set_read_timeout(Some(timeout.max(Duration::from_millis(1))))?;
362 let arrived = self.stream.fill_buf().map(|_| ());
363 self.stream.get_ref().set_read_timeout(previous)?;
364 match arrived {
365 Ok(()) => Ok(true),
366 Err(error)
367 if matches!(
368 error.kind(),
369 io::ErrorKind::WouldBlock
370 | io::ErrorKind::TimedOut
371 | io::ErrorKind::Interrupted
372 ) =>
373 {
374 Ok(false)
375 }
376 Err(error) => Err(error.into()),
377 }
378 }
379}