link-cli 3.3.3

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Interchangeable message protocols for LiNo documents.
//!
//! Both [`TextLinoProtocol`] and [`BinaryLinoProtocol`] implement
//! [`LinoProtocol`], so code written against the trait switches between them
//! by swapping one value. [`LinoConnection`] decorates any byte stream (a
//! `TcpStream`, a pipe, an in-memory buffer) with a protocol.

use super::error::{ProtocolError, ProtocolResult};
use super::ipc::IpcStream;
use links_notation::binary::packet::BINARY_VERSION_1;
use links_notation::binary::{
    decode_document, encode_document_with_limits, format_document, parse_document,
    BinaryLinoOptions, DecodeLimits, LinksPacket, LinoDocument,
};
use links_notation::LiNo;
use std::fmt::Debug;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::time::Duration;

/// Reads and writes whole LiNo documents on a byte stream.
pub trait LinoProtocol: Debug + Send + Sync {
    /// Writes one message carrying `document`.
    fn write_document(
        &self,
        writer: &mut dyn Write,
        document: &[LiNo<String>],
    ) -> ProtocolResult<()>;

    /// Reads one message; `Ok(None)` when the stream ended cleanly.
    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>>;
}

impl<P: LinoProtocol + ?Sized> LinoProtocol for Box<P> {
    fn write_document(
        &self,
        writer: &mut dyn Write,
        document: &[LiNo<String>],
    ) -> ProtocolResult<()> {
        (**self).write_document(writer, document)
    }

    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
        (**self).read_document(reader)
    }
}

/// The default limit of a text message: 64 MiB.
pub const DEFAULT_MAX_TEXT_BYTES: usize = 64 << 20;

/// Limits applied to incoming messages of either protocol.
///
/// The binary limits belong to links-notation; the text limit is link-cli's
/// own, because framing text messages is part of the transport, not of the
/// notation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProtocolLimits {
    /// Limits of [`BinaryLinoProtocol`] messages.
    pub binary: DecodeLimits,
    /// Maximum size of a [`TextLinoProtocol`] message in bytes.
    pub max_text_bytes: usize,
}

impl Default for ProtocolLimits {
    fn default() -> Self {
        Self {
            binary: DecodeLimits::default(),
            max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
        }
    }
}

impl ProtocolLimits {
    /// Limits for trusted input: only the address space bounds a message.
    pub fn unlimited() -> Self {
        Self {
            binary: DecodeLimits::unlimited(),
            max_text_bytes: usize::MAX,
        }
    }
}

/// UTF-8 LiNo text, one message per block of lines ended by a line holding
/// only `.`. Lines starting with `.` get one extra `.` (SMTP dot-stuffing).
///
/// Lines may end with `\n` or `\r\n`; a carriage return right before a line
/// feed is dropped in legacy quoted input. The formatter uses lossless `~1{hex}`
/// literals for control characters, preserving `\r\n` inside references.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TextLinoProtocol {
    /// Maximum size of a message read, in bytes.
    pub max_text_bytes: usize,
}

impl Default for TextLinoProtocol {
    fn default() -> Self {
        Self {
            max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
        }
    }
}

impl TextLinoProtocol {
    /// A text protocol with default limits.
    pub fn new() -> Self {
        Self::default()
    }

    /// Frames already formatted LiNo text as one message.
    pub fn write_text(writer: &mut dyn Write, text: &str) -> ProtocolResult<()> {
        let mut out = String::with_capacity(text.len() + 4);
        if !text.is_empty() {
            for line in text.split('\n') {
                if line.starts_with('.') {
                    out.push('.');
                }
                out.push_str(line);
                out.push('\n');
            }
        }
        out.push_str(".\n");
        writer.write_all(out.as_bytes())?;
        writer.flush()?;
        Ok(())
    }

    /// Reads one framed message as raw text, without parsing it.
    pub fn read_text(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<String>> {
        let mut text = Vec::new();
        let mut line = Vec::new();
        let mut first = true;
        loop {
            line.clear();
            let budget = self.max_text_bytes.saturating_sub(text.len()) as u64 + 2;
            let read = reader.take(budget).read_until(b'\n', &mut line)?;
            if read == 0 {
                if first {
                    return Ok(None);
                }
                return Err(ProtocolError::malformed(
                    "stream ended before the '.' terminator line",
                ));
            }
            if line.last() != Some(&b'\n') {
                if read as u64 >= budget {
                    return Err(ProtocolError::LimitExceeded(format!(
                        "text message longer than {} bytes",
                        self.max_text_bytes
                    )));
                }
                return Err(ProtocolError::malformed(
                    "stream ended before the '.' terminator line",
                ));
            }
            line.pop();
            // CRLF line endings (telnet, netcat on Windows) are accepted.
            if line.last() == Some(&b'\r') {
                line.pop();
            }
            if line == b"." {
                break;
            }
            if !first {
                text.push(b'\n');
            }
            first = false;
            let content = line.strip_prefix(b".").unwrap_or(&line);
            text.extend_from_slice(content);
        }
        String::from_utf8(text)
            .map(Some)
            .map_err(|_| ProtocolError::malformed("text message is not valid UTF-8"))
    }
}

impl LinoProtocol for TextLinoProtocol {
    fn write_document(
        &self,
        writer: &mut dyn Write,
        document: &[LiNo<String>],
    ) -> ProtocolResult<()> {
        Self::write_text(writer, &format_document(document))
    }

    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
        self.read_text(reader)?
            .map(|text| parse_document(&text).map_err(ProtocolError::from))
            .transpose()
    }
}

/// Binary links packets of [`links_notation::binary`]; every message is
/// self-delimiting, so no extra framing is needed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BinaryLinoProtocol {
    /// Optional features used when writing.
    pub options: BinaryLinoOptions,
    /// Limits applied when reading, and checked when writing.
    pub limits: DecodeLimits,
}

impl BinaryLinoProtocol {
    /// A binary protocol with every optional feature off.
    pub fn new() -> Self {
        Self::default()
    }

    /// A binary protocol with the given optional features.
    pub fn with_options(options: BinaryLinoOptions) -> Self {
        Self {
            options,
            ..Self::default()
        }
    }

    /// Encodes a document into packet bytes.
    pub fn encode(&self, document: &[LiNo<String>]) -> ProtocolResult<Vec<u8>> {
        Ok(encode_document_with_limits(document, self.options, &self.limits)?.to_bytes()?)
    }

    /// Decodes packet bytes into a document.
    pub fn decode(&self, bytes: &[u8]) -> ProtocolResult<LinoDocument> {
        let packet = LinksPacket::from_bytes(bytes, &self.limits)?;
        Ok(decode_document(&packet, &self.limits)?)
    }
}

impl LinoProtocol for BinaryLinoProtocol {
    fn write_document(
        &self,
        writer: &mut dyn Write,
        document: &[LiNo<String>],
    ) -> ProtocolResult<()> {
        writer.write_all(&self.encode(document)?)?;
        writer.flush()?;
        Ok(())
    }

    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
        LinksPacket::read_from(reader, &self.limits)?
            .map(|packet| Ok(decode_document(&packet, &self.limits)?))
            .transpose()
    }
}

/// The wire format a message arrived in, so a reply can use the same one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MessageFormat {
    /// [`TextLinoProtocol`].
    Text,
    /// [`BinaryLinoProtocol`] with the options read from the packet header.
    Binary(BinaryLinoOptions),
}

impl MessageFormat {
    /// A protocol that writes messages in this format.
    pub fn protocol(self, limits: ProtocolLimits) -> Box<dyn LinoProtocol> {
        match self {
            MessageFormat::Text => Box::new(TextLinoProtocol {
                max_text_bytes: limits.max_text_bytes,
            }),
            MessageFormat::Binary(options) => Box::new(BinaryLinoProtocol {
                options,
                limits: limits.binary,
            }),
        }
    }
}

/// True when `byte` starts a binary message rather than a text one.
pub fn is_binary_start(byte: u8) -> bool {
    byte & 0xF0 == BINARY_VERSION_1
}

/// Reads one message in whichever protocol the peer used.
pub fn read_any_document(
    reader: &mut dyn BufRead,
    limits: &ProtocolLimits,
) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
    read_any_document_with_query_limits(reader, limits, None)
}

/// Checked workspaces bound framing and decoding before constructing the AST.
/// The original public transport API retains its configured limits.
pub(crate) fn read_any_document_with_query_limits(
    reader: &mut dyn BufRead,
    limits: &ProtocolLimits,
    query_limits: Option<crate::query_options::QueryLimits>,
) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
    let mut limits = *limits;
    if let Some(query) = query_limits {
        limits.max_text_bytes = limits.max_text_bytes.min(query.max_bytes);
        limits.binary.max_depth = limits.binary.max_depth.min(query.max_depth);
        limits.binary.max_nodes = limits.binary.max_nodes.min(query.max_nodes);
        limits.binary.max_string_bytes = limits.binary.max_string_bytes.min(query.max_bytes);
        let max_nodes = u64::try_from(query.max_nodes).unwrap_or(u64::MAX);
        limits.binary.max_links = limits.binary.max_links.min(max_nodes);
        limits.binary.max_references = limits.binary.max_references.min(max_nodes);
    }
    let Some(&first) = reader.fill_buf()?.first() else {
        return Ok(None);
    };
    if !is_binary_start(first) {
        let text = TextLinoProtocol {
            max_text_bytes: limits.max_text_bytes,
        };
        return Ok(text
            .read_text(reader)?
            .map(|text| match query_limits {
                Some(query) => super::server::parse_document_with_limits(&text, query),
                None => parse_document(&text).map_err(ProtocolError::from),
            })
            .transpose()?
            .map(|document| (document, MessageFormat::Text)));
    }
    LinksPacket::read_from(reader, &limits.binary)?
        .map(|packet| {
            let document = decode_document(&packet, &limits.binary)?;
            Ok((
                document,
                MessageFormat::Binary(BinaryLinoOptions::of_packet(&packet)),
            ))
        })
        .transpose()
}

/// A byte stream decorated with a [`LinoProtocol`].
#[derive(Debug)]
pub struct LinoConnection<S: Read + Write, P: LinoProtocol> {
    stream: BufReader<S>,
    protocol: P,
}

impl<S: Read + Write, P: LinoProtocol> LinoConnection<S, P> {
    /// Wraps `stream`.
    pub fn new(stream: S, protocol: P) -> Self {
        Self {
            stream: BufReader::new(stream),
            protocol,
        }
    }

    /// The protocol in use.
    pub fn protocol(&self) -> &P {
        &self.protocol
    }

    /// Sends one document.
    pub fn send(&mut self, document: &[LiNo<String>]) -> ProtocolResult<()> {
        let mut buffer = Vec::new();
        self.protocol.write_document(&mut buffer, document)?;
        let stream = self.stream.get_mut();
        stream.write_all(&buffer)?;
        stream.flush()?;
        Ok(())
    }

    /// Receives one document; `Ok(None)` when the peer closed the stream.
    pub fn receive(&mut self) -> ProtocolResult<Option<LinoDocument>> {
        self.protocol.read_document(&mut self.stream)
    }

    /// Sends `document` and waits for the reply.
    pub fn request(&mut self, document: &[LiNo<String>]) -> ProtocolResult<LinoDocument> {
        self.send(document)?;
        self.receive()?
            .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))
    }

    /// The underlying stream.
    pub fn stream(&self) -> &S {
        self.stream.get_ref()
    }

    /// Unwraps the underlying stream.
    pub fn into_inner(self) -> S {
        self.stream.into_inner()
    }
}

/// A stream whose reads can time out, so a [`LinoConnection`] over it can
/// [wait](LinoConnection::wait_for_message) for a message.
pub trait TimedStream: Read + Write {
    /// The current read timeout; `None` waits forever.
    fn current_read_timeout(&self) -> io::Result<Option<Duration>>;
    /// Makes reads fail with a timeout after `timeout`.
    fn change_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()>;
}

impl TimedStream for TcpStream {
    fn current_read_timeout(&self) -> io::Result<Option<Duration>> {
        self.read_timeout()
    }

    fn change_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
        self.set_read_timeout(timeout)
    }
}

impl TimedStream for IpcStream {
    fn current_read_timeout(&self) -> io::Result<Option<Duration>> {
        Ok(self.read_timeout())
    }

    fn change_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
        self.set_read_timeout(timeout);
        Ok(())
    }
}

impl<S: TimedStream, P: LinoProtocol> LinoConnection<S, P> {
    /// Waits up to `timeout` for the next message to start arriving; false
    /// when none did in time. True as well when the peer closed the stream,
    /// which the next [`receive`](Self::receive) reports.
    pub fn wait_for_message(&mut self, timeout: Duration) -> ProtocolResult<bool> {
        if !self.stream.buffer().is_empty() {
            return Ok(true);
        }
        let previous = self.stream.get_ref().current_read_timeout()?;
        // A zero timeout is refused by a socket; the shortest one waits 1 ms.
        self.stream
            .get_mut()
            .change_read_timeout(Some(timeout.max(Duration::from_millis(1))))?;
        let arrived = self.stream.fill_buf().map(|_| ());
        self.stream.get_mut().change_read_timeout(previous)?;
        match arrived {
            Ok(()) => Ok(true),
            Err(error)
                if matches!(
                    error.kind(),
                    io::ErrorKind::WouldBlock
                        | io::ErrorKind::TimedOut
                        | io::ErrorKind::Interrupted
                ) =>
            {
                Ok(false)
            }
            Err(error) => Err(error.into()),
        }
    }
}