khive_wire_protocol/codec.rs
1//! The length-prefixed framing codec.
2//!
3//! One wire frame is a 4-byte big-endian `u32` length prefix followed by
4//! that many bytes of JSON, matching the existing Unix-domain-socket framing
5//! this crate remains base-compatible with (`crates/khive-runtime/src/daemon.rs`,
6//! `read_frame`/`write_frame`). This crate defines what the JSON payload
7//! inside that framing is; it performs no I/O itself — [`decode_frame`] and
8//! [`encode_frame`] operate on in-memory byte slices, and a transport crate
9//! is responsible for reading/writing those bytes from a socket and for
10//! buffering partial reads until a complete frame is available.
11
12use crate::frame::Frame;
13
14/// Length of the big-endian `u32` frame-length prefix, in bytes.
15pub const LENGTH_PREFIX_BYTES: usize = 4;
16
17/// The fixed wording every id/scope rejection carries, whichever decode
18/// path produced it: the serde visitor in [`crate::frame`] (which
19/// [`decode_payload`] drives, and which a direct
20/// `serde_json::from_str::<Frame>` reaches too) reports the rule through
21/// the deserializer's error type, and [`decode_payload`] re-classifies a
22/// message carrying this prefix into
23/// [`CodecError::InconsistentErrorScope`]. Keeping one wording lets both
24/// decode paths enforce the ADR-137 rule without duplicating its logic.
25pub(crate) const INCONSISTENT_SCOPE_ERROR_PREFIX: &str = "error frame violates the id/scope rule: ";
26
27/// Default maximum frame size: 8 MiB.
28///
29/// Chosen to match the existing Unix-domain-socket transport's
30/// `MAX_FRAME_BYTES` (`crates/khive-runtime/src/daemon.rs:38`) so that
31/// migrating a connection from that framing to this crate's codec does not
32/// silently tighten or loosen the limit. ADR-137 assigns the exact default
33/// to this crate as an implementation-phase deliverable ("Implementation-phase
34/// deliverables"); deployments that need a different bound configure
35/// [`FrameCodec::max_frame_bytes`] explicitly.
36pub const DEFAULT_MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
37
38/// A codec failure, distinguishing every frame-level case this crate can
39/// identify. Every variant maps onto the wire error taxonomy —
40/// [`crate::error::WireErrorCode::MalformedFrame`],
41/// [`crate::error::WireErrorCode::Internal`], or
42/// [`crate::error::WireErrorCode::FrameTooLarge`] — canonically via
43/// [`wire_code`](Self::wire_code) (and the `From<&CodecError>` impl), so
44/// servers need no hand-maintained mapping; this crate keeps the
45/// finer-grained variant so a caller (including a test) can assert the
46/// specific failure rather than only "decoding failed".
47#[derive(Debug, thiserror::Error, PartialEq, Eq)]
48pub enum CodecError {
49 /// Fewer than [`LENGTH_PREFIX_BYTES`] bytes were supplied — the 4-byte
50 /// length prefix itself is truncated.
51 #[error("truncated length prefix: got {available} of {LENGTH_PREFIX_BYTES} bytes")]
52 TruncatedLengthPrefix { available: usize },
53
54 /// The length prefix names a payload longer than what was supplied.
55 #[error("truncated payload: declared {declared} bytes, got {available}")]
56 TruncatedPayload { declared: usize, available: usize },
57
58 /// The declared frame length exceeds the configured maximum
59 /// (payload-only; the 4-byte prefix never counts against it). `max`
60 /// is always the configured bound that was exceeded.
61 #[error("frame of {declared} bytes exceeds the {max} byte maximum")]
62 FrameTooLarge { declared: usize, max: usize },
63
64 /// The serialized payload exceeds the 4-byte length prefix's inherent
65 /// `u32::MAX` byte capacity. Distinct from [`FrameTooLarge`](Self::FrameTooLarge): this arm
66 /// can only fire when the configured maximum is at least the payload
67 /// length (otherwise [`FrameTooLarge`](Self::FrameTooLarge) fires first), so the configured
68 /// maximum was NOT the binding limit — the prefix capacity was, and
69 /// the error names it.
70 #[error("frame of {declared} bytes exceeds the u32 length prefix's {max} byte capacity")]
71 U32PrefixLimitExceeded { declared: usize, max: usize },
72
73 /// Decode side: the payload bytes are not valid JSON at all. Encode
74 /// side: the frame failed to serialize (only reachable for opaque
75 /// payloads that cannot be represented, e.g. a map with non-string
76 /// keys smuggled into `response.result`).
77 #[error("payload is not valid JSON: {0}")]
78 InvalidJson(String),
79
80 /// The payload is valid JSON but not a JSON object, or has no `"kind"`
81 /// string field (absent or not a string).
82 #[error("payload has no string \"kind\" discriminant field")]
83 MissingKind,
84
85 /// The `"kind"` field names a value outside the closed
86 /// [`crate::frame::FRAME_KINDS`] set.
87 #[error("unknown frame kind: {0:?}")]
88 UnknownFrameKind(String),
89
90 /// The frame's `"kind"` was recognized but a field required by that
91 /// frame kind's shape is missing, has the wrong type, or is unknown to
92 /// the closed grammar (strict field rejection — see the crate
93 /// documentation's "Strict field rejection" section). Encode side: an
94 /// operation id field carries the empty string, which the wire grammar
95 /// forbids ([`crate::frame::OperationId`]).
96 #[error("frame kind {kind:?}: {detail}")]
97 InvalidFields { kind: String, detail: String },
98
99 /// An `error` frame whose operation-id presence contradicts its code's
100 /// terminal scope (ADR-137, "Operation correlation"): a
101 /// connection-terminal code carries no operation id, and a
102 /// request-terminal code echoes the one it terminates. Enforced at
103 /// decode — inside [`crate::frame::Frame`]'s serde visitor, so BOTH
104 /// the codec's `decode_payload` and a direct
105 /// `serde_json::from_str::<Frame>` reject it (the codec re-classifies
106 /// the visitor's message into this typed variant) — AND at encode
107 /// ([`encode_frame_with_max`]).
108 #[error("error frame violates the id/scope rule: {detail}")]
109 InconsistentErrorScope { detail: String },
110
111 /// Encode side: the frame is a decoded unknown-code fallback — a
112 /// [`crate::frame::Frame::Error`] carrying a `Some`
113 /// `unrecognized_code`, which only a decode path sets when the wire
114 /// carried a code outside the closed set. Re-encoding one would emit
115 /// the fallback code (`internal`) and silently discard the newer code
116 /// the peer sent, so the encode path rejects this local relay attempt;
117 /// the connection remains healthy, but this relay cannot re-encode the
118 /// decoded frame. If a relay must pass unknown codes through, it has to
119 /// operate on the raw frame bytes, not on a decoded-and-re-encoded frame.
120 #[error(
121 "fallback error frame (unrecognized code {code:?}) is not re-encodable: \
122 re-encoding would emit \"internal\" and discard the newer wire code"
123 )]
124 FallbackFrameNotEncodable { code: String },
125}
126
127impl CodecError {
128 /// The wire error code this failure maps to under ADR-137's taxonomy:
129 /// [`FrameTooLarge`](Self::FrameTooLarge) and
130 /// [`U32PrefixLimitExceeded`](Self::U32PrefixLimitExceeded) — the size
131 /// failures — map to [`WireErrorCode::FrameTooLarge`]. A decoded fallback
132 /// that this local relay cannot re-encode maps to
133 /// [`WireErrorCode::Internal`]; the connection is healthy and only the
134 /// relay attempt failed. Every other variant maps to
135 /// [`WireErrorCode::MalformedFrame`]. This is the canonical
136 /// codec→wire-error mapping: servers should use it (or the
137 /// `From<&CodecError>` impl) rather than hand-maintain their own.
138 ///
139 /// [`WireErrorCode::FrameTooLarge`]: crate::error::WireErrorCode::FrameTooLarge
140 /// [`WireErrorCode::MalformedFrame`]: crate::error::WireErrorCode::MalformedFrame
141 /// [`WireErrorCode::Internal`]: crate::error::WireErrorCode::Internal
142 pub const fn wire_code(&self) -> crate::error::WireErrorCode {
143 match self {
144 CodecError::FrameTooLarge { .. } | CodecError::U32PrefixLimitExceeded { .. } => {
145 crate::error::WireErrorCode::FrameTooLarge
146 }
147 CodecError::TruncatedLengthPrefix { .. }
148 | CodecError::TruncatedPayload { .. }
149 | CodecError::InvalidJson(_)
150 | CodecError::MissingKind
151 | CodecError::UnknownFrameKind(_)
152 | CodecError::InvalidFields { .. }
153 | CodecError::InconsistentErrorScope { .. } => {
154 crate::error::WireErrorCode::MalformedFrame
155 }
156 CodecError::FallbackFrameNotEncodable { .. } => crate::error::WireErrorCode::Internal,
157 }
158 }
159}
160
161impl From<&CodecError> for crate::error::WireErrorCode {
162 fn from(err: &CodecError) -> Self {
163 err.wire_code()
164 }
165}
166
167/// A configured framing codec.
168///
169/// Stateless beyond the configured [`max_frame_bytes`](Self::max_frame_bytes)
170/// bound: [`encode`](Self::encode) and [`decode`](Self::decode) operate on
171/// one frame at a time and hold no connection state (handshake sequencing
172/// is [`crate::handshake::HandshakeGate`]'s job, not the codec's).
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct FrameCodec {
175 max_frame_bytes: usize,
176}
177
178impl FrameCodec {
179 /// A codec with the given maximum frame size (the JSON payload length,
180 /// not counting the 4-byte prefix).
181 pub const fn new(max_frame_bytes: usize) -> Self {
182 Self { max_frame_bytes }
183 }
184
185 pub const fn max_frame_bytes(&self) -> usize {
186 self.max_frame_bytes
187 }
188
189 /// Encode one frame as a complete length-prefixed wire buffer: 4-byte
190 /// BE length followed by the JSON payload, guarded by this codec's own
191 /// configured maximum so encode and decode share one bound.
192 pub fn encode(&self, frame: &Frame) -> Result<Vec<u8>, CodecError> {
193 encode_frame_with_max(frame, self.max_frame_bytes)
194 }
195
196 /// Decode one complete length-prefixed frame from `buf`.
197 ///
198 /// `buf` must contain at least the full frame (prefix + payload); this
199 /// function does not support partial/streaming input. Bytes in `buf`
200 /// beyond the decoded frame, if any, are ignored — a transport that
201 /// reads a stream is responsible for slicing exactly one frame's bytes
202 /// (using the length prefix) before calling this, or for using
203 /// [`decode_with_consumed`](Self::decode_with_consumed) to learn where
204 /// the decoded frame ends.
205 pub fn decode(&self, buf: &[u8]) -> Result<Frame, CodecError> {
206 decode_frame(buf, self.max_frame_bytes)
207 }
208
209 /// Decode one complete length-prefixed frame from `buf` and report the
210 /// number of bytes consumed: the 4-byte length prefix plus the
211 /// declared payload length. The remainder `buf[consumed..]` — if any —
212 /// is the next frame's bytes, letting a transport split a buffered
213 /// stream into frames without re-parsing the length prefix itself.
214 /// The frame itself is decoded exactly as [`decode`](Self::decode).
215 pub fn decode_with_consumed(&self, buf: &[u8]) -> Result<(Frame, usize), CodecError> {
216 decode_frame_with_consumed(buf, self.max_frame_bytes)
217 }
218}
219
220impl Default for FrameCodec {
221 fn default() -> Self {
222 Self::new(DEFAULT_MAX_FRAME_BYTES)
223 }
224}
225
226/// Encode one frame as a complete length-prefixed wire buffer, using
227/// [`DEFAULT_MAX_FRAME_BYTES`] as the encode-side size guard.
228///
229/// Use [`encode_frame_with_max`] to encode against a different bound; a
230/// [`FrameCodec`] always encodes against its own configured maximum so that
231/// both directions of one codec share a single bound.
232pub fn encode_frame(frame: &Frame) -> Result<Vec<u8>, CodecError> {
233 encode_frame_with_max(frame, DEFAULT_MAX_FRAME_BYTES)
234}
235
236/// Encode one frame against an explicit `max_frame_bytes` bound.
237///
238/// `max_frame_bytes` is PAYLOAD-ONLY: the maximum JSON payload length, not
239/// counting the 4-byte length prefix — the same bound [`decode_frame`]
240/// checks against.
241///
242/// Before serializing, the frame is validated against the same wire rules
243/// the decode side enforces (`validate_frame_for_wire`, private): an empty
244/// operation id in any id field ([`CodecError::InvalidFields`]), a handshake
245/// or handshake acknowledgment naming version 0
246/// ([`CodecError::InvalidFields`]), an
247/// `error` frame whose id presence contradicts its code's terminal scope
248/// ([`CodecError::InconsistentErrorScope`]), and a decoded unknown-code
249/// fallback `error` frame ([`CodecError::FallbackFrameNotEncodable`]) are
250/// all rejected here, so a frame this function accepts is one any
251/// conforming decoder accepts. This keeps
252/// encode and decode symmetric: a locally constructed frame that violates
253/// the grammar can never leave this crate as wire bytes.
254///
255/// Cost note: the size guard runs on the SERIALIZED payload, so the frame
256/// is fully serialized (and its bytes allocated) before the bound is
257/// checked; an oversized frame therefore pays one full serialization before
258/// [`CodecError::FrameTooLarge`] is returned. This is the accepted cost of
259/// a local, non-I/O encode: no cheaper pre-estimate of the serialized size
260/// exists without serializing.
261pub fn encode_frame_with_max(frame: &Frame, max_frame_bytes: usize) -> Result<Vec<u8>, CodecError> {
262 validate_frame_for_wire(frame)?;
263 let payload = serde_json::to_vec(frame).map_err(|e| CodecError::InvalidJson(e.to_string()))?;
264 check_encode_payload_len(payload.len(), max_frame_bytes)?;
265 let mut buf = Vec::with_capacity(LENGTH_PREFIX_BYTES + payload.len());
266 buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
267 buf.extend_from_slice(&payload);
268 Ok(buf)
269}
270
271/// The encode-side mirror of the decode-side grammar checks: rejects a
272/// frame that [`decode_payload`] would reject, so encode and decode are
273/// symmetric and a locally constructed frame can never serialize into wire
274/// bytes no conforming decoder would accept.
275///
276/// Two rules are enforced here:
277///
278/// 1. No operation id field may carry the empty string — an empty string
279/// can never be a unique caller-generated id. Decode enforces this in
280/// `OperationId`'s `Deserialize` impl; the encode side checks the
281/// in-memory value directly, because [`crate::frame::OperationId`]
282/// construction is deliberately unrestricted.
283/// 2. An `error` frame's operation-id presence must agree with its code's
284/// terminal scope (ADR-137, "Operation correlation"), exactly as
285/// [`decode_payload`] enforces via [`CodecError::InconsistentErrorScope`].
286/// Every [`crate::error::WireErrorCode`] variant is in the closed set,
287/// so the decode side's unknown-code exemption never applies here.
288/// 3. A handshake or handshake acknowledgment may not name version 0;
289/// version 0 does not exist in this protocol.
290/// 4. An `error` frame carrying a `Some` `unrecognized_code` — the
291/// decoded unknown-code fallback marker, which only a decode path sets
292/// — is rejected with [`CodecError::FallbackFrameNotEncodable`].
293/// This relay cannot re-encode a fallback: doing so would emit the
294/// fallback code (`internal`) and silently discard the newer code the
295/// peer sent, so this crate refuses to corrupt it.
296fn validate_frame_for_wire(frame: &Frame) -> Result<(), CodecError> {
297 use crate::error::TerminalScope;
298
299 fn check_id(kind: &str, id: &crate::frame::OperationId) -> Result<(), CodecError> {
300 if id.0.is_empty() {
301 return Err(CodecError::InvalidFields {
302 kind: kind.to_string(),
303 detail: "operation id must be a non-empty string".to_string(),
304 });
305 }
306 Ok(())
307 }
308
309 match frame {
310 Frame::Handshake { version } => {
311 if version.get() == 0 {
312 return Err(CodecError::InvalidFields {
313 kind: "handshake".to_string(),
314 detail: "protocol version 0 does not exist".to_string(),
315 });
316 }
317 }
318 Frame::HandshakeAck { version } => {
319 if version.get() == 0 {
320 return Err(CodecError::InvalidFields {
321 kind: "handshake_ack".to_string(),
322 detail: "protocol version 0 does not exist".to_string(),
323 });
324 }
325 }
326 Frame::Event { .. } => {}
327 Frame::Request { id, .. } => check_id("request", id)?,
328 Frame::Response { id, .. } => check_id("response", id)?,
329 Frame::Cancel { id } => check_id("cancel", id)?,
330 Frame::Subscribe { id, .. } => check_id("subscribe", id)?,
331 Frame::SubscribeAck { id, .. } => check_id("subscribe_ack", id)?,
332 Frame::Unsubscribe { id, .. } => check_id("unsubscribe", id)?,
333 Frame::UnsubscribeAck { id, .. } => check_id("unsubscribe_ack", id)?,
334 Frame::Error {
335 id,
336 code,
337 unrecognized_code,
338 ..
339 } => {
340 // A decoded-fallback frame cannot be re-encoded by this relay;
341 // see rule 4.
342 if let Some(raw_code) = unrecognized_code {
343 return Err(CodecError::FallbackFrameNotEncodable {
344 code: raw_code.clone(),
345 });
346 }
347 if let Some(id) = id {
348 check_id("error", id)?;
349 }
350 match (code.terminal_scope(), id) {
351 (TerminalScope::Connection, Some(id)) => {
352 return Err(CodecError::InconsistentErrorScope {
353 detail: format!(
354 "connection-terminal code {code} must not carry an operation id, got {id}"
355 ),
356 });
357 }
358 (TerminalScope::Request, None) => {
359 return Err(CodecError::InconsistentErrorScope {
360 detail: format!(
361 "request-terminal code {code} must echo the operation id it terminates"
362 ),
363 });
364 }
365 (TerminalScope::Connection, None) | (TerminalScope::Request, Some(_)) => {}
366 }
367 }
368 }
369 Ok(())
370}
371
372/// The encode-side size decision, split out from
373/// [`encode_frame_with_max`] so both guards are testable without
374/// serializing a >4 GiB payload.
375fn check_encode_payload_len(payload_len: usize, max_frame_bytes: usize) -> Result<(), CodecError> {
376 if payload_len > max_frame_bytes {
377 return Err(CodecError::FrameTooLarge {
378 declared: payload_len,
379 max: max_frame_bytes,
380 });
381 }
382 // The 4-byte length prefix is a `u32`; without this guard a caller who
383 // configured `max_frame_bytes > u32::MAX` could admit a payload whose
384 // length would silently truncate in the cast to the prefix, writing a
385 // prefix that does not match the payload. This arm only fires when the
386 // configured maximum was NOT exceeded (that is the check above), so the
387 // error names the prefix capacity as the binding limit rather than the
388 // configured maximum.
389 if payload_len > u32::MAX as usize {
390 return Err(CodecError::U32PrefixLimitExceeded {
391 declared: payload_len,
392 max: u32::MAX as usize,
393 });
394 }
395 Ok(())
396}
397
398/// Decode one complete length-prefixed frame from `buf` against an explicit
399/// `max_frame_bytes` bound. See [`FrameCodec::decode`] for the contract.
400///
401/// `max_frame_bytes` is PAYLOAD-ONLY: the maximum JSON payload length, not
402/// counting the 4-byte prefix. Passing a total wire length here is a caller
403/// bug — it admits payloads 4 bytes over the intended bound.
404pub fn decode_frame(buf: &[u8], max_frame_bytes: usize) -> Result<Frame, CodecError> {
405 decode_frame_with_consumed(buf, max_frame_bytes).map(|(frame, _)| frame)
406}
407
408/// Decode one complete length-prefixed frame from `buf` and report the
409/// number of bytes consumed: [`LENGTH_PREFIX_BYTES`] plus the declared
410/// payload length. Bytes beyond the consumed prefix — if any — belong to
411/// the next frame, letting a transport split a buffered stream into frames
412/// without re-parsing the length prefix itself. [`decode_frame`] is this
413/// function with the consumed count discarded.
414///
415/// `max_frame_bytes` is PAYLOAD-ONLY, as in [`decode_frame`].
416///
417/// **Decode errors are connection-terminal.** An error from this function
418/// carries NO consumed count: once a frame fails to decode, this crate
419/// cannot say where the failed frame ends, so the stream position is
420/// unrecoverable. A transport must map the error through
421/// [`CodecError::wire_code`], send the corresponding wire error, and close
422/// the connection — never attempt to resynchronize and keep reading.
423pub fn decode_frame_with_consumed(
424 buf: &[u8],
425 max_frame_bytes: usize,
426) -> Result<(Frame, usize), CodecError> {
427 if buf.len() < LENGTH_PREFIX_BYTES {
428 return Err(CodecError::TruncatedLengthPrefix {
429 available: buf.len(),
430 });
431 }
432 let mut len_bytes = [0u8; LENGTH_PREFIX_BYTES];
433 len_bytes.copy_from_slice(&buf[..LENGTH_PREFIX_BYTES]);
434 let declared = u32::from_be_bytes(len_bytes) as usize;
435
436 if declared > max_frame_bytes {
437 return Err(CodecError::FrameTooLarge {
438 declared,
439 max: max_frame_bytes,
440 });
441 }
442
443 let available = buf.len() - LENGTH_PREFIX_BYTES;
444 if available < declared {
445 return Err(CodecError::TruncatedPayload {
446 declared,
447 available,
448 });
449 }
450
451 let payload = &buf[LENGTH_PREFIX_BYTES..LENGTH_PREFIX_BYTES + declared];
452 let frame = decode_payload(payload)?;
453 Ok((frame, LENGTH_PREFIX_BYTES + declared))
454}
455
456/// Decode one frame's JSON payload (without the length prefix).
457///
458/// Crate-internal split of [`decode_frame`]'s payload half; the public
459/// surface is the length-prefixed [`decode_frame`] / [`FrameCodec::decode`],
460/// which apply the `max_frame_bytes` size guard. Visible to unit tests in
461/// this module only. This function applies NO
462/// size check of its own: its only caller inside the crate is
463/// [`decode_frame_with_consumed`], which has already enforced the bound
464/// against the declared length before handing the payload over.
465///
466/// Enforces, beyond serde: the closed `"kind"` set
467/// ([`CodecError::UnknownFrameKind`]). The ADR-137 id/scope consistency
468/// rule for `error` frames and the unknown-code fallback diagnostic are
469/// enforced inside [`crate::frame::Frame`]'s serde visitor — the same
470/// visitor a direct serde decode drives — so both decode paths agree; this
471/// function re-classifies the visitor's id/scope rejection into the typed
472/// [`CodecError::InconsistentErrorScope`]. Strict field rejection (no
473/// unknown fields) is carried by the per-kind payload structs in
474/// [`crate::frame`]. For an `error` frame whose wire code is outside the
475/// closed set, the raw code string is preserved in
476/// [`Frame::Error`](crate::frame::Frame)'s `unrecognized_code` diagnostic
477/// field.
478pub(crate) fn decode_payload(payload: &[u8]) -> Result<Frame, CodecError> {
479 let value: serde_json::Value =
480 serde_json::from_slice(payload).map_err(|e| CodecError::InvalidJson(e.to_string()))?;
481
482 let kind = value
483 .as_object()
484 .and_then(|obj| obj.get("kind"))
485 .and_then(|k| k.as_str())
486 .ok_or(CodecError::MissingKind)?
487 .to_string();
488
489 if !crate::frame::FRAME_KINDS.contains(&kind.as_str()) {
490 return Err(CodecError::UnknownFrameKind(kind));
491 }
492
493 serde_json::from_value(value).map_err(|e| {
494 // The visitor reports an id/scope violation through the
495 // deserializer's error type; lift it back into the typed variant
496 // so callers can branch on the specific failure.
497 let detail = e.to_string();
498 match detail.strip_prefix(INCONSISTENT_SCOPE_ERROR_PREFIX) {
499 Some(scope_detail) => CodecError::InconsistentErrorScope {
500 detail: scope_detail.to_string(),
501 },
502 None => CodecError::InvalidFields { kind, detail },
503 }
504 })
505}
506
507#[cfg(test)]
508#[path = "codec_tests.rs"]
509mod tests;
510
511#[cfg(test)]
512#[path = "codec_configured_max_tests.rs"]
513mod configured_max_tests;