Skip to main content

tea_cli/rpc/
reader.rs

1use std::io;
2
3use tokio::io::{AsyncRead, AsyncReadExt as _};
4
5/// Maximum bytes accepted before one LF delimiter.
6pub const MAX_RPC_FRAME_BYTES: usize = 1024 * 1024;
7const READ_CHUNK_BYTES: usize = 8192;
8
9/// Terminal strict-framing or input failure.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
11pub enum RpcReadError {
12    /// A frame exceeded the configured bound before its LF delimiter.
13    #[error("RPC frame exceeds the size limit")]
14    Oversize,
15    /// EOF arrived after bytes that were not terminated by LF.
16    #[error("RPC input ended inside a frame")]
17    Unterminated,
18    /// The underlying input failed.
19    #[error("RPC input is unavailable")]
20    Io,
21}
22
23/// Strict byte-oriented LF frame reader with a fixed memory bound.
24#[derive(Debug)]
25pub struct RpcFrameReader<R> {
26    input: R,
27    buffered: Vec<u8>,
28    eof: bool,
29}
30
31impl<R: AsyncRead + Unpin> RpcFrameReader<R> {
32    /// Wraps one async byte stream.
33    #[must_use]
34    pub const fn new(input: R) -> Self {
35        Self {
36            input,
37            buffered: Vec::new(),
38            eof: false,
39        }
40    }
41
42    /// Reads one complete frame, excluding LF and an optional preceding CR.
43    ///
44    /// # Errors
45    ///
46    /// Returns a terminal error for oversized, unterminated, or failed input.
47    pub async fn read_frame(&mut self) -> Result<Option<Vec<u8>>, RpcReadError> {
48        loop {
49            if let Some(index) = self.buffered.iter().position(|byte| *byte == b'\n') {
50                if index > MAX_RPC_FRAME_BYTES {
51                    return Err(RpcReadError::Oversize);
52                }
53                let mut frame = self.buffered.drain(..=index).collect::<Vec<_>>();
54                frame.pop();
55                if frame.last() == Some(&b'\r') {
56                    frame.pop();
57                }
58                return Ok(Some(frame));
59            }
60            if self.buffered.len() > MAX_RPC_FRAME_BYTES {
61                return Err(RpcReadError::Oversize);
62            }
63            if self.eof {
64                return if self.buffered.is_empty() {
65                    Ok(None)
66                } else {
67                    Err(RpcReadError::Unterminated)
68                };
69            }
70
71            let mut chunk = [0_u8; READ_CHUNK_BYTES];
72            let read = self.input.read(&mut chunk).await.map_err(map_io_error)?;
73            if read == 0 {
74                self.eof = true;
75            } else {
76                self.buffered.extend_from_slice(&chunk[..read]);
77            }
78        }
79    }
80}
81
82fn map_io_error(_error: io::Error) -> RpcReadError {
83    RpcReadError::Io
84}