Lutra/crates/lsp/tests/framing.rs
danny 81831c90e0 M3.2: LSP client core (framing, supervision, requests, document sync)
crates/lsp is now a library: Content-Length JSON-RPC framing over stdio
(32 MiB cap, malformed frames dropped and reported, fuzzed), Server::spawn
with initialize/initialized (utf-16, incremental sync, completion, hover,
signatureHelp, definition, references, rename, publishDiagnostics),
typed requests with timeouts and $/cancelRequest, answers to server
requests (configuration nulls, MethodNotFound), events on a bounded
channel, supervision with backoff restarts that reopen documents and
give up after 5 crashes in 2 min, shutdown/exit, and incremental
document sync from lutra_text edits. Tested against a scripted fake
server binary; docs: architecture, G6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 00:57:10 +02:00

139 lines
4.5 KiB
Rust

//! Framing round trips and fuzzing of the frame reader and message parser.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic
)]
use std::io::BufReader;
use lutra_lsp::jsonrpc::{Frame, Message, encode, read_frame};
use proptest::prelude::*;
use serde_json::{Value, json};
/// Reads every frame of `input` with a cap of `max` bytes.
fn frames(input: &[u8], max: usize) -> Vec<Frame> {
let mut reader = BufReader::with_capacity(7, input);
let mut out = Vec::new();
while let Some(frame) = read_frame(&mut reader, max).unwrap() {
out.push(frame);
assert!(out.len() <= input.len() + 1, "reader does not advance");
}
out
}
fn json_value() -> impl Strategy<Value = Value> {
let leaf = prop_oneof![
Just(Value::Null),
any::<bool>().prop_map(Value::Bool),
any::<i64>().prop_map(|n| json!(n)),
".{0,12}".prop_map(Value::String),
];
leaf.prop_recursive(3, 24, 4, |inner| {
prop_oneof![
proptest::collection::vec(inner.clone(), 0..4).prop_map(Value::Array),
proptest::collection::btree_map("[a-z]{1,4}", inner, 0..4)
.prop_map(|m| Value::Object(m.into_iter().collect())),
]
})
}
fn message() -> impl Strategy<Value = Message> {
prop_oneof![
(any::<i32>(), "[a-z/$]{1,12}", json_value()).prop_map(|(id, method, params)| {
Message::Request {
id: json!(id),
method,
params,
}
}),
("[a-z/$]{1,12}", json_value())
.prop_map(|(method, params)| Message::Notification { method, params }),
(any::<i32>(), json_value()).prop_map(|(id, result)| Message::Response {
id: json!(id),
result: Ok(result),
}),
]
}
proptest! {
#[test]
fn messages_round_trip(messages in proptest::collection::vec(message(), 0..6)) {
let mut stream = Vec::new();
for message in &messages {
stream.extend(encode(&message.to_json()));
}
let read: Vec<Message> = frames(&stream, 1 << 20)
.into_iter()
.map(|frame| match frame {
Frame::Body(body) => Message::parse(&body).unwrap(),
Frame::Dropped(reason) => panic!("dropped: {reason}"),
})
.collect();
prop_assert_eq!(read, messages);
}
#[test]
fn random_bytes_never_panic(input in proptest::collection::vec(any::<u8>(), 0..512)) {
for frame in frames(&input, 64) {
if let Frame::Body(body) = frame {
prop_assert!(body.len() <= 64);
let _ = Message::parse(&body);
}
}
}
#[test]
fn header_like_noise_never_panics(
parts in proptest::collection::vec(
prop_oneof![
Just(b"Content-Length: ".to_vec()),
Just(b"\r\n".to_vec()),
Just(b"\n".to_vec()),
Just(b":".to_vec()),
"[0-9]{1,3}".prop_map(String::into_bytes),
"[ -~]{0,5}".prop_map(String::into_bytes),
],
0..40,
)
) {
let input: Vec<u8> = parts.concat();
let _ = frames(&input, 32);
}
#[test]
fn random_json_bodies_never_panic(value in json_value()) {
let _ = Message::parse(value.to_string().as_bytes());
}
#[test]
fn recovers_after_bad_frames(bad in prop_oneof![
Just(b"Content-Length: 99999\r\n\r\n".to_vec()),
Just(b"no colon\r\n\r\n".to_vec()),
Just(b"X: y\r\n\r\n".to_vec()),
Just(b"Content-Length: -1\r\n\r\n".to_vec()),
]) {
let good = encode(&json!({"jsonrpc": "2.0", "method": "ok"}));
let mut input = bad.clone();
if bad.starts_with(b"Content-Length: 99999") {
input.extend(std::iter::repeat_n(b' ', 99_999));
}
input.extend(&good);
let out = frames(&input, 1024);
prop_assert!(matches!(out.first(), Some(Frame::Dropped(_))));
prop_assert!(matches!(out.last(), Some(Frame::Body(_))));
}
}
#[test]
fn overlong_header_line_is_dropped_without_buffering() {
let mut input = b"Content-Length: 2".to_vec();
input.extend(std::iter::repeat_n(b'x', 100_000));
input.extend(b"\r\n\r\n");
input.extend(encode(&json!({"method": "ok"})));
let out = frames(&input, 1024);
assert!(matches!(out.first(), Some(Frame::Dropped(_))));
assert!(matches!(out.last(), Some(Frame::Body(_))));
}