diff --git a/crates/jsonrpc/README.md b/crates/jsonrpc/README.md index 445d1ea79b..d2886673e8 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 5b9622f854..e345f59179 100644 --- a/crates/jsonrpc/src/lib.rs +++ b/crates/jsonrpc/src/lib.rs @@ -127,6 +127,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 824ad5e355..5eb1f52e51 100644 --- a/crates/jsonrpc/tests/server.rs +++ b/crates/jsonrpc/tests/server.rs @@ -208,6 +208,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;