From 1af016f7f2761fb348816df33e4a2c0d2ea9fa6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:41:20 -0800 Subject: [PATCH] craft-jsonrpc: add skip_line to resume after an over-long line After read_line returns LineError::TooLong, skip_line discards the rest of that line without buffering it and leaves the reader at the next message, so a server can answer the oversized message and keep the session open. It returns false at EOF and retries interrupted reads. --- crates/jsonrpc/README.md | 3 ++- crates/jsonrpc/src/lib.rs | 22 ++++++++++++++++++++++ crates/jsonrpc/tests/server.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/jsonrpc/README.md b/crates/jsonrpc/README.md index 8711c25ff4..88f9860275 100644 --- a/crates/jsonrpc/README.md +++ b/crates/jsonrpc/README.md @@ -9,7 +9,8 @@ names and arguments. `Limits` defaults to 64 MiB per message and 4096 batch entries. `parse_json` checks the byte limit before deserialization, and `process` rejects an oversized batch before calling any handler. For newline-delimited transports, `read_line` bounds memory while reading; after an over-limit -line, the caller must close the stream or discard the rest of that line. +line, the caller must close the stream or call `skip_line`, which discards the rest of that line +without buffering it, before reading the next message. `serde_json`'s nesting limit remains in effect. Response sizes are the caller's responsibility. A valid request receives the handler's result or error with its original string, numeric, or null diff --git a/crates/jsonrpc/src/lib.rs b/crates/jsonrpc/src/lib.rs index 97105b4531..d6c5025f56 100644 --- a/crates/jsonrpc/src/lib.rs +++ b/crates/jsonrpc/src/lib.rs @@ -99,6 +99,28 @@ pub fn read_line(reader: &mut R, max_bytes: usize) -> Result(reader: &mut R) -> std::io::Result { + loop { + let bytes = match reader.fill_buf() { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + }; + if bytes.is_empty() { + return Ok(false); + } + let newline = bytes.iter().position(|&byte| byte == b'\n'); + let len = newline.map_or(bytes.len(), |index| index + 1); + reader.consume(len); + if newline.is_some() { + return Ok(true); + } + } +} + /// Parse JSON after checking its byte length. `serde_json` also bounds nesting depth. pub fn parse_json(bytes: &[u8], limits: Limits) -> Result { if bytes.len() > limits.max_message_bytes { diff --git a/crates/jsonrpc/tests/server.rs b/crates/jsonrpc/tests/server.rs index a9186f4ae8..c2e7b3e57e 100644 --- a/crates/jsonrpc/tests/server.rs +++ b/crates/jsonrpc/tests/server.rs @@ -132,6 +132,39 @@ fn bounded_line_read_handles_chunks_empty_lines_and_eof() { assert!(matches!(craft_jsonrpc::read_line(&mut too_long, 3), Err(craft_jsonrpc::LineError::TooLong))); } +#[test] +fn skipping_an_over_long_line_resumes_at_the_next_message() { + use std::io::{BufReader, Cursor}; + let mut reader = BufReader::with_capacity(2, Cursor::new(b"abcdefgh\nok\nxyzxyz")); + assert!(matches!(craft_jsonrpc::read_line(&mut reader, 3), Err(craft_jsonrpc::LineError::TooLong))); + assert!(craft_jsonrpc::skip_line(&mut reader).unwrap()); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"ok".to_vec())); + assert!(matches!(craft_jsonrpc::read_line(&mut reader, 3), Err(craft_jsonrpc::LineError::TooLong))); + assert!(!craft_jsonrpc::skip_line(&mut reader).unwrap()); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), None); +} + +#[test] +fn skipping_a_line_retries_interrupted_reads_and_reports_other_errors() { + struct Flaky(Vec>); + impl std::io::Read for Flaky { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0.is_empty() { + return Ok(0); + } + let bytes = self.0.remove(0)?; + buf[..bytes.len()].copy_from_slice(bytes); + Ok(bytes.len()) + } + } + let interrupted = || Err(std::io::Error::from(std::io::ErrorKind::Interrupted)); + let mut reader = std::io::BufReader::new(Flaky(vec![Ok(b"ab"), interrupted(), Ok(b"c\nok\n")])); + assert!(craft_jsonrpc::skip_line(&mut reader).unwrap()); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"ok".to_vec())); + let mut broken = std::io::BufReader::new(Flaky(vec![Err(std::io::Error::other("broken"))])); + assert!(craft_jsonrpc::skip_line(&mut broken).is_err()); +} + #[test] fn bounded_line_read_propagates_io_errors() { struct Broken;