Skip to main content

kian_plugin/hooks/sidecar/
line.rs

1//! The newline-delimited carrier with §7.6's byte bounds.
2//!
3//! A line is at most `max_payload_kib` **wire bytes in either
4//! direction**, enforced **while scanning for `\n` and before any
5//! unbounded buffering or JSON parse** (§7.6). The reader consumes the
6//! stream in fixed chunks and keeps only what fits, so a hostile child
7//! streaming an endless line without a newline can never grow memory
8//! past one chunk plus one bound.
9
10use std::io::{Read, Write};
11
12/// Why a line could not be read within bounds.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum LineError {
15    /// Over the byte bound while scanning for `\n` — `frame_overflow`
16    /// (§7.6: immediate quarantine, never a window increment).
17    Overflow { scanned: usize, max: usize },
18    /// The stream ended without a newline after it (EOF without the
19    /// expected reply is a crash, §7.5) or the read failed.
20    Io(String),
21}
22
23/// Bounded line writer (S→P direction).
24pub fn write_line<W: Write>(out: &mut W, line: &str, max: usize) -> Result<(), LineError> {
25    if line.len() > max {
26        return Err(LineError::Overflow {
27            scanned: line.len(),
28            max,
29        });
30    }
31    out.write_all(line.as_bytes())
32        .and_then(|_| out.write_all(b"\n"))
33        .and_then(|_| out.flush())
34        .map_err(|e| LineError::Io(e.to_string()))
35}
36
37/// Bounded line reader (P→S direction): scans for `\n` in fixed-size
38/// chunks, refusing to buffer past `max` bytes without one.
39pub struct BoundedLineReader<R: Read> {
40    inner: R,
41    /// Bytes read past the last newline, not yet returned.
42    pending: Vec<u8>,
43    /// Fixed chunk buffer for the current scan.
44    chunk: Vec<u8>,
45}
46
47const CHUNK: usize = 8 * 1024;
48
49impl<R: Read> BoundedLineReader<R> {
50    pub fn new(inner: R) -> Self {
51        Self {
52            inner,
53            pending: Vec::new(),
54            chunk: vec![0; CHUNK],
55        }
56    }
57
58    /// Reads one `\n`-terminated line (returned without the newline,
59    /// as a lossy UTF-8 string — the carrier is UTF-8 JSON, §7.1).
60    /// `Err(Overflow)` leaves the stream position undefined; the
61    /// runner quarantines and kills the child rather than resyncing.
62    pub fn read_line(&mut self, max: usize) -> Result<String, LineError> {
63        loop {
64            if let Some(pos) = self.pending.iter().position(|b| *b == b'\n') {
65                // The bound is on the *line* (§7.6): a newline that
66                // arrives in the same chunk that crosses the limit is
67                // still an overflow — the check is on the line length,
68                // not on what happened to be buffered so far.
69                if pos > max {
70                    return Err(LineError::Overflow { scanned: pos, max });
71                }
72                let line: Vec<u8> = self.pending.drain(..=pos).collect();
73                let mut line = line;
74                line.pop(); // the newline itself
75                return String::from_utf8(line)
76                    .map_err(|_| LineError::Io("line is not UTF-8".to_string()));
77            }
78            if self.pending.len() > max {
79                return Err(LineError::Overflow {
80                    scanned: self.pending.len(),
81                    max,
82                });
83            }
84            let read = self
85                .inner
86                .read(&mut self.chunk)
87                .map_err(|e| LineError::Io(e.to_string()))?;
88            if read == 0 {
89                return Err(LineError::Io("eof".to_string()));
90            }
91            self.pending.extend_from_slice(&self.chunk[..read]);
92        }
93    }
94
95    /// Discards through the next `\n` (or EOF), memory-bounded — the
96    /// stderr drainer's resync after an oversized line: bytes are
97    /// dropped, never buffered (§10.5).
98    pub fn discard_line(&mut self) -> bool {
99        loop {
100            if let Some(pos) = self.pending.iter().position(|b| *b == b'\n') {
101                self.pending.drain(..=pos);
102                return true;
103            }
104            self.pending.clear();
105            match self.inner.read(&mut self.chunk) {
106                Ok(0) => return false,
107                Ok(read) => {
108                    if let Some(pos) = self.chunk[..read].iter().position(|b| *b == b'\n') {
109                        self.pending.extend_from_slice(&self.chunk[pos + 1..read]);
110                        return true;
111                    }
112                }
113                Err(_) => return false,
114            }
115        }
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn reads_lines_and_keeps_remainder() {
125        let mut reader = BoundedLineReader::new(&b"one\ntwo\nthree\n"[..]);
126        assert_eq!(reader.read_line(64).unwrap(), "one");
127        assert_eq!(reader.read_line(64).unwrap(), "two");
128        assert_eq!(reader.read_line(64).unwrap(), "three");
129        assert_eq!(
130            reader.read_line(64).unwrap_err(),
131            LineError::Io("eof".to_string())
132        );
133    }
134
135    #[test]
136    fn refuses_to_buffer_past_the_bound() {
137        // A line over the bound, delivered in small chunks (a slow
138        // hostile child): the refusal fires at the bound, not at EOF.
139        let stream: &[u8] = &vec![b'x'; 5 * CHUNK];
140        let mut reader = BoundedLineReader::new(stream);
141        let err = reader.read_line(1024).unwrap_err();
142        assert!(matches!(err, LineError::Overflow { scanned: _, max } if max == 1024));
143    }
144
145    #[test]
146    fn a_line_exactly_at_the_bound_is_legal() {
147        let payload = format!("{}\n", "x".repeat(1024));
148        let mut reader = BoundedLineReader::new(payload.as_bytes());
149        assert_eq!(reader.read_line(1024).unwrap().len(), 1024);
150        // One over: overflow, even when the newline arrives in the
151        // same chunk that crosses the limit.
152        let payload = format!("{}\nnext\n", "x".repeat(1025));
153        let mut reader = BoundedLineReader::new(payload.as_bytes());
154        assert!(matches!(
155            reader.read_line(1024).unwrap_err(),
156            LineError::Overflow { .. }
157        ));
158    }
159
160    #[test]
161    fn write_line_checks_the_bound_before_writing() {
162        let mut sink: Vec<u8> = Vec::new();
163        assert!(write_line(&mut sink, "ok", 64).is_ok());
164        assert_eq!(sink, b"ok\n");
165        let long = "x".repeat(65);
166        assert_eq!(
167            write_line(&mut sink, &long, 64).unwrap_err(),
168            LineError::Overflow {
169                scanned: 65,
170                max: 64
171            }
172        );
173    }
174}