mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 13:17:41 +00:00
Merge pull request #2609 from dotCooCoo/fix/jsonrpc-skip-long-line
craft-jsonrpc: skip_line discards the rest of an over-long line
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -127,6 +127,28 @@ pub fn read_line<R: BufRead>(reader: &mut R, max_bytes: usize) -> Result<Option<
|
||||
}
|
||||
}
|
||||
|
||||
/// Discard input through the next newline without buffering it, as after [`LineError::TooLong`].
|
||||
/// Returns `true` when a newline was consumed, so the next read starts a new message, and `false`
|
||||
/// at EOF. An interrupted read is retried.
|
||||
pub fn skip_line<R: BufRead>(reader: &mut R) -> std::io::Result<bool> {
|
||||
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<Value, ParseError> {
|
||||
if bytes.len() > limits.max_message_bytes {
|
||||
|
||||
@@ -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<std::io::Result<&'static [u8]>>);
|
||||
impl std::io::Read for Flaky {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user