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::{BufRead, BufReader, Read, Write};
17
18pub trait LinoProtocol: Debug + Send + Sync {
20 fn write_document(
22 &self,
23 writer: &mut dyn Write,
24 document: &[LiNo<String>],
25 ) -> ProtocolResult<()>;
26
27 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>>;
29}
30
31impl<P: LinoProtocol + ?Sized> LinoProtocol for Box<P> {
32 fn write_document(
33 &self,
34 writer: &mut dyn Write,
35 document: &[LiNo<String>],
36 ) -> ProtocolResult<()> {
37 (**self).write_document(writer, document)
38 }
39
40 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
41 (**self).read_document(reader)
42 }
43}
44
45pub const DEFAULT_MAX_TEXT_BYTES: usize = 64 << 20;
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub struct ProtocolLimits {
55 pub binary: DecodeLimits,
57 pub max_text_bytes: usize,
59}
60
61impl Default for ProtocolLimits {
62 fn default() -> Self {
63 Self {
64 binary: DecodeLimits::default(),
65 max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
66 }
67 }
68}
69
70impl ProtocolLimits {
71 pub fn unlimited() -> Self {
73 Self {
74 binary: DecodeLimits::unlimited(),
75 max_text_bytes: usize::MAX,
76 }
77 }
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct TextLinoProtocol {
88 pub max_text_bytes: usize,
90}
91
92impl Default for TextLinoProtocol {
93 fn default() -> Self {
94 Self {
95 max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
96 }
97 }
98}
99
100impl TextLinoProtocol {
101 pub fn new() -> Self {
103 Self::default()
104 }
105
106 pub fn write_text(writer: &mut dyn Write, text: &str) -> ProtocolResult<()> {
108 let mut out = String::with_capacity(text.len() + 4);
109 if !text.is_empty() {
110 for line in text.split('\n') {
111 if line.starts_with('.') {
112 out.push('.');
113 }
114 out.push_str(line);
115 out.push('\n');
116 }
117 }
118 out.push_str(".\n");
119 writer.write_all(out.as_bytes())?;
120 writer.flush()?;
121 Ok(())
122 }
123
124 pub fn read_text(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<String>> {
126 let mut text = Vec::new();
127 let mut line = Vec::new();
128 let mut first = true;
129 loop {
130 line.clear();
131 let budget = self.max_text_bytes.saturating_sub(text.len()) as u64 + 2;
132 let read = reader.take(budget).read_until(b'\n', &mut line)?;
133 if read == 0 {
134 if first {
135 return Ok(None);
136 }
137 return Err(ProtocolError::malformed(
138 "stream ended before the '.' terminator line",
139 ));
140 }
141 if line.last() != Some(&b'\n') {
142 if read as u64 >= budget {
143 return Err(ProtocolError::LimitExceeded(format!(
144 "text message longer than {} bytes",
145 self.max_text_bytes
146 )));
147 }
148 return Err(ProtocolError::malformed(
149 "stream ended before the '.' terminator line",
150 ));
151 }
152 line.pop();
153 if line.last() == Some(&b'\r') {
155 line.pop();
156 }
157 if line == b"." {
158 break;
159 }
160 if !first {
161 text.push(b'\n');
162 }
163 first = false;
164 let content = line.strip_prefix(b".").unwrap_or(&line);
165 text.extend_from_slice(content);
166 }
167 String::from_utf8(text)
168 .map(Some)
169 .map_err(|_| ProtocolError::malformed("text message is not valid UTF-8"))
170 }
171}
172
173impl LinoProtocol for TextLinoProtocol {
174 fn write_document(
175 &self,
176 writer: &mut dyn Write,
177 document: &[LiNo<String>],
178 ) -> ProtocolResult<()> {
179 Self::write_text(writer, &format_document(document))
180 }
181
182 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
183 self.read_text(reader)?
184 .map(|text| parse_document(&text).map_err(ProtocolError::from))
185 .transpose()
186 }
187}
188
189#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
192pub struct BinaryLinoProtocol {
193 pub options: BinaryLinoOptions,
195 pub limits: DecodeLimits,
197}
198
199impl BinaryLinoProtocol {
200 pub fn new() -> Self {
202 Self::default()
203 }
204
205 pub fn with_options(options: BinaryLinoOptions) -> Self {
207 Self {
208 options,
209 ..Self::default()
210 }
211 }
212
213 pub fn encode(&self, document: &[LiNo<String>]) -> ProtocolResult<Vec<u8>> {
215 Ok(encode_document_with_limits(document, self.options, &self.limits)?.to_bytes()?)
216 }
217
218 pub fn decode(&self, bytes: &[u8]) -> ProtocolResult<LinoDocument> {
220 let packet = LinksPacket::from_bytes(bytes, &self.limits)?;
221 Ok(decode_document(&packet, &self.limits)?)
222 }
223}
224
225impl LinoProtocol for BinaryLinoProtocol {
226 fn write_document(
227 &self,
228 writer: &mut dyn Write,
229 document: &[LiNo<String>],
230 ) -> ProtocolResult<()> {
231 writer.write_all(&self.encode(document)?)?;
232 writer.flush()?;
233 Ok(())
234 }
235
236 fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
237 LinksPacket::read_from(reader, &self.limits)?
238 .map(|packet| Ok(decode_document(&packet, &self.limits)?))
239 .transpose()
240 }
241}
242
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
245pub enum MessageFormat {
246 Text,
248 Binary(BinaryLinoOptions),
250}
251
252impl MessageFormat {
253 pub fn protocol(self, limits: ProtocolLimits) -> Box<dyn LinoProtocol> {
255 match self {
256 MessageFormat::Text => Box::new(TextLinoProtocol {
257 max_text_bytes: limits.max_text_bytes,
258 }),
259 MessageFormat::Binary(options) => Box::new(BinaryLinoProtocol {
260 options,
261 limits: limits.binary,
262 }),
263 }
264 }
265}
266
267pub fn is_binary_start(byte: u8) -> bool {
269 byte & 0xF0 == BINARY_VERSION_1
270}
271
272pub fn read_any_document(
274 reader: &mut dyn BufRead,
275 limits: &ProtocolLimits,
276) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
277 let Some(&first) = reader.fill_buf()?.first() else {
278 return Ok(None);
279 };
280 if !is_binary_start(first) {
281 let text = TextLinoProtocol {
282 max_text_bytes: limits.max_text_bytes,
283 };
284 return Ok(text
285 .read_document(reader)?
286 .map(|document| (document, MessageFormat::Text)));
287 }
288 LinksPacket::read_from(reader, &limits.binary)?
289 .map(|packet| {
290 let document = decode_document(&packet, &limits.binary)?;
291 Ok((
292 document,
293 MessageFormat::Binary(BinaryLinoOptions::of_packet(&packet)),
294 ))
295 })
296 .transpose()
297}
298
299#[derive(Debug)]
301pub struct LinoConnection<S: Read + Write, P: LinoProtocol> {
302 stream: BufReader<S>,
303 protocol: P,
304}
305
306impl<S: Read + Write, P: LinoProtocol> LinoConnection<S, P> {
307 pub fn new(stream: S, protocol: P) -> Self {
309 Self {
310 stream: BufReader::new(stream),
311 protocol,
312 }
313 }
314
315 pub fn protocol(&self) -> &P {
317 &self.protocol
318 }
319
320 pub fn send(&mut self, document: &[LiNo<String>]) -> ProtocolResult<()> {
322 let mut buffer = Vec::new();
323 self.protocol.write_document(&mut buffer, document)?;
324 let stream = self.stream.get_mut();
325 stream.write_all(&buffer)?;
326 stream.flush()?;
327 Ok(())
328 }
329
330 pub fn receive(&mut self) -> ProtocolResult<Option<LinoDocument>> {
332 self.protocol.read_document(&mut self.stream)
333 }
334
335 pub fn request(&mut self, document: &[LiNo<String>]) -> ProtocolResult<LinoDocument> {
337 self.send(document)?;
338 self.receive()?
339 .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))
340 }
341
342 pub fn into_inner(self) -> S {
344 self.stream.into_inner()
345 }
346}