Expand description
§weavatrix-lsp-wire
weavatrix-lsp-wire is a small, runtime-independent codec for the
Content-Length transport and JSON-RPC 2.0 envelopes used by the Language
Server Protocol. It has no Tokio, futures, I/O runtime, subprocess, or concrete
LSP method-type dependency. The byte framing remains dependency-free; the
explicit JSON-RPC layer uses serde and serde_json only for JSON syntax and
arbitrary JSON values.
The decoder is incremental: reads may split at any byte, contain several
frames, or stop immediately after a frame. Memory stays bounded by an explicit
Limits configuration. Headers must be seven-bit ASCII with exact CRLF line
endings and exactly one case-insensitive Content-Length. An optional
Content-Type must use application/vscode-jsonrpc; utf-8 and the legacy
utf8 spelling are accepted as charsets.
use weavatrix_lsp_wire::{Decoder, Encoder};
let wire = Encoder::default().encode(br#"{"jsonrpc":"2.0"}"#)?;
let mut decoder = Decoder::default();
let mut payloads = Vec::new();
// Any read boundaries are valid.
for chunk in wire.chunks(3) {
decoder.push(chunk, |payload| payloads.push(payload.to_vec()))?;
}
decoder.finish()?;
assert_eq!(payloads, [br#"{"jsonrpc":"2.0"}"#.to_vec()]);§Safety and failure contract
- Header bytes, line length, field count, inbound body length, and outbound body length have independently configurable bounds.
- Decimal
Content-Lengthparsing uses checked arithmetic. - A complete canonical
Content-Lengthframe passed contiguously toDecoder::pushdispatches its body directly from the caller’s input slice; fragmented and noncanonical input uses the same bounded state-machine fallback and preserves the documented error semantics. - Bodies remain opaque bytes to
Decoder.JsonRpcCodecis a separate, caller-selected layer that validates UTF-8, JSON, a fixed nesting bound, and the complete base envelope before returning an owned typed message. - Any decoding or EOF error poisons the decoder. Call
Decoder::resetonly after the underlying stream has been replaced or deliberately resynchronized. - A successful
Decoder::finishseals the stream; reset is required before feeding bytes from a new stream. - A callback panic poisons the decoder before the panic resumes; unread bytes from that input chunk cannot be continued safely.
Encoder::write_frameusesWrite::write_allfor the header and body and flushes the writer, so short writes are handled without assuming pipe behavior. After an I/O error, discard the stream because a partial frame may have been written.Encoder::encode_ownedprepends a frame header to an owned payload and reuses its allocation when capacity permits; it applies the same framing limits as the borrowedEncoder::encodepath.- The crate contains no
unsafecode and supports Rust 1.88 or newer.
The JSON-RPC layer rejects batch messages, duplicate or unknown base-envelope
fields, ambiguous request/response shapes, non-structured params, fractional
or out-of-range LSP IDs, and malformed error objects. It preserves arbitrary
method payloads as owned validated raw JsonValue segments rather than a
serde_json::Value tree; concrete LSP method schemas remain a higher-layer
concern. JsonRpcCodec::decode_borrowed applies the same strict envelope
contract while borrowing method names, string identifiers, and raw
params/result/error.data segments directly from the caller’s frame:
identifiers and methods allocate only when JSON escapes require it, raw
segments are never copied or reparsed until the caller either deserializes the
selected type or converts the message to the owned model with one copy. Unknown field errors retain only a UTF-8-safe 64-byte preview and the
complete decoded field-name byte length, so diagnostics cannot clone or print
an attacker-sized name.
Outbound JSON serialization is capped while bytes are written with bounded
geometric buffer growth and an incremental string-aware nesting scanner, not
checked only after an unbounded temporary allocation or deep serializer
recursion. Use JsonRpcCodec::value_from_serializable to turn a typed LSP
value into raw JSON without an unbounded intermediate string, or
JsonRpcCodec::value_from_string when an owned JSON string already exists.
Both paths validate the raw value and its nesting before it can enter a
message. The public message, parameter, ID, and raw-value types intentionally
do not implement serde::Serialize; JsonRpcCodec::encode is the only
supported message-to-wire serialization path and reapplies the complete
message byte and nesting bounds.
Normal top-level JSON-RPC objects are classified in one JSON parse. Non-object
inputs still complete one syntax parse before the codec distinguishes a valid
unsupported batch from malformed JSON. Typed values are syntax-validated after
bounded serialization as well as checked by the writer’s size/depth guards, so
even a custom Serialize implementation cannot inject malformed raw JSON.
Decoded messages do not retain the original framed body. The sum reported by
JsonRpcMessage::retained_payload_bytes is at most that body’s length for a
codec-produced message. While decoding synchronously from a Decoder
callback, frame-body plus decoded-message payload text is at most twice the
inbound body limit. A message retains at most three payload allocations. These
figures exclude fixed structs, allocator metadata/capacity rounding, and
short-lived parser scratch. Client queues should enforce both an item count and
the exact logical retained-byte count.
§Competitor benchmark
The recorded 2026-08-03 Windows x86-64 MSVC snapshot compares output-equivalent
paths against lsp-server 0.10.0 and a direct serde_json + lsp-types 0.97.0
baseline. It is a pre-freeze, dirty-worktree signal for the borrowed decoder;
release-grade numbers will be re-measured on a clean committed tree. At p50,
Weavatrix was 3.05x faster than the disclosed non-public, source-inspired
reproduction of lsp-server’s private framing reader, 1.37x on raw envelope
decode, 1.77-1.82x on prebuilt envelope encode, 1.36x on the public full-frame
decode path, and 3.66x on the public full-frame encode path. The framing-only
row is not a measurement of crate code or a public API.
The 0.1.0 release disclosed that the direct permissive typed decoder was 1.78x
faster than the strict envelope-validation-then-typed path. The borrowed
decoder replaces that comparison: on the recorded snapshot,
JsonRpcCodec::decode_borrowed plus a typed parse from the borrowed frame
was faster than the direct permissive parse on every measured payload — a
workspace/symbol request (1.40x), an initialize response (1.11x), a
textDocument/definition request (1.14x), a publishDiagnostics notification
(1.02x), and a $/cancelRequest notification (1.39x) — while still enforcing
the full strict wire contract. One variance note is recorded rather than
hidden: across repeated runs on that loaded workstation the definition and
publishDiagnostics comparisons oscillate around parity, because the strict
contract syntax-validates the params segment before the caller’s typed parse
reads it again; single-run results on those two payloads are inside the
machine’s noise band. The repository still does not claim blanket superiority
across unlike contracts.
The raw 26-row, nine-sample report and full methodology
identify the measured source as
sha1:8550c852616a6ac1685b5d3cb16b2e8c46dd6115. Canonical decode timing uses
one complete frame in one call; fragmented and noncanonical fallback behavior
is correctness-tested but not included in that latency row.
This crate does not start processes, schedule requests, assign JSON-RPC IDs, implement cancellation, or validate concrete LSP method params/results.
Structs§
- Borrowed
Error Object - A JSON-RPC error body borrowed from the inbound frame.
- Borrowed
Error Response - A failed response borrowed from the inbound frame.
- Borrowed
Json Value - A validated raw JSON segment borrowed from the inbound frame.
- Borrowed
Notification - A notification whose method and parameters borrow the inbound frame.
- Borrowed
Params - Structured request parameters borrowed from the inbound frame.
- Borrowed
Request - A request whose strings and parameters borrow the inbound frame.
- Borrowed
Success Response - A successful response borrowed from the inbound frame.
- Decoder
- Incremental, bounded decoder for LSP
Content-Lengthframes. - Encoder
- Bounded encoder for outbound LSP frames.
- Error
Object - The required body of a failed JSON-RPC response.
- Error
Response - A failed JSON-RPC response.
- Json
RpcCodec - Bounded JSON-RPC 2.0/LSP payload codec layered above
crate::Decoderand belowcrate::Encoder. - Json
Value - An owned, validated raw JSON segment carried by
params,result, orerror.data. - Limits
- Resource limits enforced by both sides of the wire codec.
- Notification
- A JSON-RPC notification that must not receive a response.
- Params
- Structured JSON-RPC request or notification parameters.
- Request
- A JSON-RPC request that requires a response.
- Success
Response - A successful JSON-RPC response.
Enums§
- Borrowed
Json RpcMessage - One strictly classified JSON-RPC message borrowing its inbound frame.
- Borrowed
Request Id - An LSP request identifier that borrows an unescaped string from the frame.
- Borrowed
Response Id - An LSP response identifier borrowed from the frame.
- Decode
Error - A fatal inbound framing error.
- Encode
Error - An outbound payload could not be encoded.
- IdError
- Why an LSP request or response identifier was rejected.
- Json
RpcDecode Error - A bounded JSON-RPC payload could not be decoded or classified.
- Json
RpcEncode Error - A typed JSON-RPC message could not be serialized within its bound.
- Json
RpcMessage - One strictly classified JSON-RPC 2.0/LSP base message.
- Json
RpcObject - The JSON object whose base-envelope fields were invalid.
- Json
Value Error - An owned arbitrary JSON segment was not valid or safely bounded.
- Limits
Error - An invalid resource-limit configuration.
- Params
Kind - The structured shape of JSON-RPC request or notification parameters.
- Request
Id - An LSP request identifier.
- Response
Id - An LSP response identifier.
- Write
Frame Error - Encoding or writing an outbound frame failed.
Constants§
- MAX_
FIELD_ PREVIEW_ BYTES - Maximum UTF-8 bytes retained from an unknown JSON-RPC field name.
- MAX_
JSON_ NESTING_ DEPTH - Maximum top-level-inclusive JSON array/object nesting accepted by the JSON-RPC codec.