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`]), or an Event payload is not
96 /// a JSON object (Amendment 1 Decision 10), or a Request deadline is zero.
97 #[error("frame kind {kind:?}: {detail}")]
98 InvalidFields { kind: String, detail: String },
99
100 /// An `error` frame whose operation-id presence contradicts its code's
101 /// terminal scope (ADR-137, "Operation correlation"): a
102 /// connection-terminal code carries no operation id, and a
103 /// request-terminal code echoes the one it terminates. Enforced at
104 /// decode — inside [`crate::frame::Frame`]'s serde visitor, so BOTH
105 /// the codec's `decode_payload` and a direct
106 /// `serde_json::from_str::<Frame>` reject it (the codec re-classifies
107 /// the visitor's message into this typed variant) — AND at encode
108 /// ([`encode_frame_with_max`]).
109 #[error("error frame violates the id/scope rule: {detail}")]
110 InconsistentErrorScope { detail: String },
111
112 /// Encode side: the frame is a decoded unknown-code fallback — a
113 /// [`crate::frame::Frame::Error`] carrying a `Some`
114 /// `unrecognized_code`, which only a decode path sets when the wire
115 /// carried a code outside the closed set. Re-encoding one would emit
116 /// the fallback code (`internal`) and silently discard the newer code
117 /// the peer sent, so the encode path rejects this local relay attempt;
118 /// the connection remains healthy, but this relay cannot re-encode the
119 /// decoded frame. If a relay must pass unknown codes through, it has to
120 /// operate on the raw frame bytes, not on a decoded-and-re-encoded frame.
121 #[error(
122 "fallback error frame (unrecognized code {code:?}) is not re-encodable: \
123 re-encoding would emit \"internal\" and discard the newer wire code"
124 )]
125 FallbackFrameNotEncodable { code: String },
126}
127
128impl CodecError {
129 /// The wire error code this failure maps to under ADR-137's taxonomy:
130 /// [`FrameTooLarge`](Self::FrameTooLarge) and
131 /// [`U32PrefixLimitExceeded`](Self::U32PrefixLimitExceeded) — the size
132 /// failures — map to [`WireErrorCode::FrameTooLarge`]. A decoded fallback
133 /// that this local relay cannot re-encode maps to
134 /// [`WireErrorCode::Internal`]; the connection is healthy and only the
135 /// relay attempt failed. Every other variant maps to
136 /// [`WireErrorCode::MalformedFrame`]. This is the canonical
137 /// codec→wire-error mapping: servers should use it (or the
138 /// `From<&CodecError>` impl) rather than hand-maintain their own.
139 ///
140 /// [`WireErrorCode::FrameTooLarge`]: crate::error::WireErrorCode::FrameTooLarge
141 /// [`WireErrorCode::MalformedFrame`]: crate::error::WireErrorCode::MalformedFrame
142 /// [`WireErrorCode::Internal`]: crate::error::WireErrorCode::Internal
143 pub const fn wire_code(&self) -> crate::error::WireErrorCode {
144 match self {
145 CodecError::FrameTooLarge { .. } | CodecError::U32PrefixLimitExceeded { .. } => {
146 crate::error::WireErrorCode::FrameTooLarge
147 }
148 CodecError::TruncatedLengthPrefix { .. }
149 | CodecError::TruncatedPayload { .. }
150 | CodecError::InvalidJson(_)
151 | CodecError::MissingKind
152 | CodecError::UnknownFrameKind(_)
153 | CodecError::InvalidFields { .. }
154 | CodecError::InconsistentErrorScope { .. } => {
155 crate::error::WireErrorCode::MalformedFrame
156 }
157 CodecError::FallbackFrameNotEncodable { .. } => crate::error::WireErrorCode::Internal,
158 }
159 }
160}
161
162impl From<&CodecError> for crate::error::WireErrorCode {
163 fn from(err: &CodecError) -> Self {
164 err.wire_code()
165 }
166}
167
168/// A configured framing codec.
169///
170/// Stateless beyond the configured [`max_frame_bytes`](Self::max_frame_bytes)
171/// bound: [`encode`](Self::encode) and [`decode`](Self::decode) operate on
172/// one frame at a time and hold no connection state (handshake sequencing
173/// is [`crate::handshake::HandshakeGate`]'s job, not the codec's).
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct FrameCodec {
176 max_frame_bytes: usize,
177}
178
179impl FrameCodec {
180 /// A codec with the given maximum frame size (the JSON payload length,
181 /// not counting the 4-byte prefix).
182 pub const fn new(max_frame_bytes: usize) -> Self {
183 Self { max_frame_bytes }
184 }
185
186 pub const fn max_frame_bytes(&self) -> usize {
187 self.max_frame_bytes
188 }
189
190 /// Encode one frame as a complete length-prefixed wire buffer: 4-byte
191 /// BE length followed by the JSON payload, guarded by this codec's own
192 /// configured maximum so encode and decode share one bound.
193 pub fn encode(&self, frame: &Frame) -> Result<Vec<u8>, CodecError> {
194 encode_frame_with_max(frame, self.max_frame_bytes)
195 }
196
197 /// Decode one complete length-prefixed frame from `buf`.
198 ///
199 /// `buf` must contain at least the full frame (prefix + payload); this
200 /// function does not support partial/streaming input. Bytes in `buf`
201 /// beyond the decoded frame, if any, are ignored — a transport that
202 /// reads a stream is responsible for slicing exactly one frame's bytes
203 /// (using the length prefix) before calling this, or for using
204 /// [`decode_with_consumed`](Self::decode_with_consumed) to learn where
205 /// the decoded frame ends.
206 pub fn decode(&self, buf: &[u8]) -> Result<Frame, CodecError> {
207 decode_frame(buf, self.max_frame_bytes)
208 }
209
210 /// Decode one complete length-prefixed frame from `buf` and report the
211 /// number of bytes consumed: the 4-byte length prefix plus the
212 /// declared payload length. The remainder `buf[consumed..]` — if any —
213 /// is the next frame's bytes, letting a transport split a buffered
214 /// stream into frames without re-parsing the length prefix itself.
215 /// The frame itself is decoded exactly as [`decode`](Self::decode).
216 pub fn decode_with_consumed(&self, buf: &[u8]) -> Result<(Frame, usize), CodecError> {
217 decode_frame_with_consumed(buf, self.max_frame_bytes)
218 }
219}
220
221impl Default for FrameCodec {
222 fn default() -> Self {
223 Self::new(DEFAULT_MAX_FRAME_BYTES)
224 }
225}
226
227/// Encode one frame as a complete length-prefixed wire buffer, using
228/// [`DEFAULT_MAX_FRAME_BYTES`] as the encode-side size guard.
229///
230/// Use [`encode_frame_with_max`] to encode against a different bound; a
231/// [`FrameCodec`] always encodes against its own configured maximum so that
232/// both directions of one codec share a single bound.
233pub fn encode_frame(frame: &Frame) -> Result<Vec<u8>, CodecError> {
234 encode_frame_with_max(frame, DEFAULT_MAX_FRAME_BYTES)
235}
236
237/// Encode one frame against an explicit `max_frame_bytes` bound.
238///
239/// `max_frame_bytes` is PAYLOAD-ONLY: the maximum JSON payload length, not
240/// counting the 4-byte length prefix — the same bound [`decode_frame`]
241/// checks against.
242///
243/// Before serializing, the frame is validated against the same wire rules
244/// the decode side enforces (`validate_frame_for_wire`, private): an empty
245/// operation id in any id field ([`CodecError::InvalidFields`]), a handshake
246/// or handshake acknowledgment naming version 0
247/// ([`CodecError::InvalidFields`]), an
248/// `error` frame whose id presence contradicts its code's terminal scope
249/// ([`CodecError::InconsistentErrorScope`]), a decoded unknown-code
250/// fallback `error` frame ([`CodecError::FallbackFrameNotEncodable`]), and
251/// a non-object Event payload or a zero Request deadline
252/// ([`CodecError::InvalidFields`]) are all rejected here, so a frame this
253/// function accepts is one any
254/// conforming decoder accepts. This keeps
255/// encode and decode symmetric: a locally constructed frame that violates
256/// the grammar can never leave this crate as wire bytes.
257///
258/// Cost note: the size guard runs on the SERIALIZED payload, so the frame
259/// is fully serialized (and its bytes allocated) before the bound is
260/// checked; an oversized frame therefore pays one full serialization before
261/// [`CodecError::FrameTooLarge`] is returned. This is the accepted cost of
262/// a local, non-I/O encode: no cheaper pre-estimate of the serialized size
263/// exists without serializing.
264pub fn encode_frame_with_max(frame: &Frame, max_frame_bytes: usize) -> Result<Vec<u8>, CodecError> {
265 validate_frame_for_wire(frame)?;
266 let payload = serde_json::to_vec(frame).map_err(|e| CodecError::InvalidJson(e.to_string()))?;
267 check_encode_payload_len(payload.len(), max_frame_bytes)?;
268 let mut buf = Vec::with_capacity(LENGTH_PREFIX_BYTES + payload.len());
269 buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
270 buf.extend_from_slice(&payload);
271 Ok(buf)
272}
273
274/// The encode-side mirror of the decode-side grammar checks: rejects a
275/// frame that [`decode_payload`] would reject, so encode and decode are
276/// symmetric and a locally constructed frame can never serialize into wire
277/// bytes no conforming decoder would accept.
278///
279/// These rules are enforced here:
280///
281/// 1. No operation id field may carry the empty string — an empty string
282/// can never be a unique caller-generated id. Decode enforces this in
283/// `OperationId`'s `Deserialize` impl; the encode side checks the
284/// in-memory value directly, because [`crate::frame::OperationId`]
285/// construction is deliberately unrestricted.
286/// 2. An `error` frame's operation-id presence must agree with its code's
287/// terminal scope (ADR-137, "Operation correlation"), exactly as
288/// [`decode_payload`] enforces via [`CodecError::InconsistentErrorScope`].
289/// Every [`crate::error::WireErrorCode`] variant is in the closed set,
290/// so the decode side's unknown-code exemption never applies here.
291/// 3. A handshake or handshake acknowledgment may not name version 0;
292/// version 0 does not exist in this protocol.
293/// 4. An `error` frame carrying a `Some` `unrecognized_code` — the
294/// decoded unknown-code fallback marker, which only a decode path sets
295/// — is rejected with [`CodecError::FallbackFrameNotEncodable`].
296/// This relay cannot re-encode a fallback: doing so would emit the
297/// fallback code (`internal`) and silently discard the newer code the
298/// peer sent, so this crate refuses to corrupt it.
299/// 5. An Event payload must be a JSON object (Amendment 1 Decision 10).
300/// Response results remain arbitrary JSON.
301/// 6. A present Request deadline_ms must be positive (ADR-137, "Deadlines
302/// and cancellation"); omission leaves no frame-supplied deadline.
303fn validate_frame_for_wire(frame: &Frame) -> Result<(), CodecError> {
304 use crate::error::TerminalScope;
305
306 fn check_id(kind: &str, id: &crate::frame::OperationId) -> Result<(), CodecError> {
307 if id.0.is_empty() {
308 return Err(CodecError::InvalidFields {
309 kind: kind.to_string(),
310 detail: "operation id must be a non-empty string".to_string(),
311 });
312 }
313 Ok(())
314 }
315
316 match frame {
317 Frame::Handshake { version } => {
318 if version.get() == 0 {
319 return Err(CodecError::InvalidFields {
320 kind: "handshake".to_string(),
321 detail: "protocol version 0 does not exist".to_string(),
322 });
323 }
324 }
325 Frame::HandshakeAck { version } => {
326 if version.get() == 0 {
327 return Err(CodecError::InvalidFields {
328 kind: "handshake_ack".to_string(),
329 detail: "protocol version 0 does not exist".to_string(),
330 });
331 }
332 }
333 Frame::Event { payload, .. } => {
334 if !payload.is_object() {
335 return Err(CodecError::InvalidFields {
336 kind: "event".to_string(),
337 detail: "payload must be a JSON object".to_string(),
338 });
339 }
340 }
341 Frame::Request {
342 id, deadline_ms, ..
343 } => {
344 check_id("request", id)?;
345 if *deadline_ms == Some(0) {
346 return Err(CodecError::InvalidFields {
347 kind: "request".to_string(),
348 detail: "deadline_ms must be a positive integer".to_string(),
349 });
350 }
351 }
352 Frame::Response { id, .. } => check_id("response", id)?,
353 Frame::Cancel { id } => check_id("cancel", id)?,
354 Frame::Subscribe { id, .. } => check_id("subscribe", id)?,
355 Frame::SubscribeAck { id, .. } => check_id("subscribe_ack", id)?,
356 Frame::Unsubscribe { id, .. } => check_id("unsubscribe", id)?,
357 Frame::UnsubscribeAck { id, .. } => check_id("unsubscribe_ack", id)?,
358 Frame::Error {
359 id,
360 code,
361 unrecognized_code,
362 ..
363 } => {
364 // A decoded-fallback frame cannot be re-encoded by this relay;
365 // see rule 4.
366 if let Some(raw_code) = unrecognized_code {
367 return Err(CodecError::FallbackFrameNotEncodable {
368 code: raw_code.clone(),
369 });
370 }
371 if let Some(id) = id {
372 check_id("error", id)?;
373 }
374 match (code.terminal_scope(), id) {
375 (TerminalScope::Connection, Some(id)) => {
376 return Err(CodecError::InconsistentErrorScope {
377 detail: format!(
378 "connection-terminal code {code} must not carry an operation id, got {id}"
379 ),
380 });
381 }
382 (TerminalScope::Request, None) => {
383 return Err(CodecError::InconsistentErrorScope {
384 detail: format!(
385 "request-terminal code {code} must echo the operation id it terminates"
386 ),
387 });
388 }
389 (TerminalScope::Connection, None) | (TerminalScope::Request, Some(_)) => {}
390 }
391 }
392 }
393 Ok(())
394}
395
396/// The encode-side size decision, split out from
397/// [`encode_frame_with_max`] so both guards are testable without
398/// serializing a >4 GiB payload.
399fn check_encode_payload_len(payload_len: usize, max_frame_bytes: usize) -> Result<(), CodecError> {
400 if payload_len > max_frame_bytes {
401 return Err(CodecError::FrameTooLarge {
402 declared: payload_len,
403 max: max_frame_bytes,
404 });
405 }
406 // The 4-byte length prefix is a `u32`; without this guard a caller who
407 // configured `max_frame_bytes > u32::MAX` could admit a payload whose
408 // length would silently truncate in the cast to the prefix, writing a
409 // prefix that does not match the payload. This arm only fires when the
410 // configured maximum was NOT exceeded (that is the check above), so the
411 // error names the prefix capacity as the binding limit rather than the
412 // configured maximum.
413 if payload_len > u32::MAX as usize {
414 return Err(CodecError::U32PrefixLimitExceeded {
415 declared: payload_len,
416 max: u32::MAX as usize,
417 });
418 }
419 Ok(())
420}
421
422/// Decode one complete length-prefixed frame from `buf` against an explicit
423/// `max_frame_bytes` bound. See [`FrameCodec::decode`] for the contract.
424///
425/// `max_frame_bytes` is PAYLOAD-ONLY: the maximum JSON payload length, not
426/// counting the 4-byte prefix. Passing a total wire length here is a caller
427/// bug — it admits payloads 4 bytes over the intended bound.
428pub fn decode_frame(buf: &[u8], max_frame_bytes: usize) -> Result<Frame, CodecError> {
429 decode_frame_with_consumed(buf, max_frame_bytes).map(|(frame, _)| frame)
430}
431
432/// Decode one complete length-prefixed frame from `buf` and report the
433/// number of bytes consumed: [`LENGTH_PREFIX_BYTES`] plus the declared
434/// payload length. Bytes beyond the consumed prefix — if any — belong to
435/// the next frame, letting a transport split a buffered stream into frames
436/// without re-parsing the length prefix itself. [`decode_frame`] is this
437/// function with the consumed count discarded.
438///
439/// `max_frame_bytes` is PAYLOAD-ONLY, as in [`decode_frame`].
440///
441/// **Decode errors are connection-terminal.** An error from this function
442/// carries NO consumed count: once a frame fails to decode, this crate
443/// cannot say where the failed frame ends, so the stream position is
444/// unrecoverable. A transport must map the error through
445/// [`CodecError::wire_code`], send the corresponding wire error, and close
446/// the connection — never attempt to resynchronize and keep reading.
447pub fn decode_frame_with_consumed(
448 buf: &[u8],
449 max_frame_bytes: usize,
450) -> Result<(Frame, usize), CodecError> {
451 if buf.len() < LENGTH_PREFIX_BYTES {
452 return Err(CodecError::TruncatedLengthPrefix {
453 available: buf.len(),
454 });
455 }
456 let mut len_bytes = [0u8; LENGTH_PREFIX_BYTES];
457 len_bytes.copy_from_slice(&buf[..LENGTH_PREFIX_BYTES]);
458 let declared = u32::from_be_bytes(len_bytes) as usize;
459
460 if declared > max_frame_bytes {
461 return Err(CodecError::FrameTooLarge {
462 declared,
463 max: max_frame_bytes,
464 });
465 }
466
467 let available = buf.len() - LENGTH_PREFIX_BYTES;
468 if available < declared {
469 return Err(CodecError::TruncatedPayload {
470 declared,
471 available,
472 });
473 }
474
475 let payload = &buf[LENGTH_PREFIX_BYTES..LENGTH_PREFIX_BYTES + declared];
476 let frame = decode_payload(payload)?;
477 Ok((frame, LENGTH_PREFIX_BYTES + declared))
478}
479
480/// Decode one frame's JSON payload (without the length prefix).
481///
482/// Crate-internal split of [`decode_frame`]'s payload half; the public
483/// surface is the length-prefixed [`decode_frame`] / [`FrameCodec::decode`],
484/// which apply the `max_frame_bytes` size guard. Visible to unit tests in
485/// this module only. This function applies NO
486/// size check of its own: its only caller inside the crate is
487/// [`decode_frame_with_consumed`], which has already enforced the bound
488/// against the declared length before handing the payload over.
489///
490/// Enforces, beyond serde: the closed `"kind"` set
491/// ([`CodecError::UnknownFrameKind`]). The ADR-137 id/scope consistency
492/// rule for `error` frames and the unknown-code fallback diagnostic are
493/// enforced inside [`crate::frame::Frame`]'s serde visitor — the same
494/// visitor a direct serde decode drives — so both decode paths agree; this
495/// function re-classifies the visitor's id/scope rejection into the typed
496/// [`CodecError::InconsistentErrorScope`]. Strict field rejection (no
497/// unknown fields) is carried by the per-kind payload structs in
498/// [`crate::frame`]. For an `error` frame whose wire code is outside the
499/// closed set, the raw code string is preserved in
500/// [`Frame::Error`](crate::frame::Frame)'s `unrecognized_code` diagnostic
501/// field.
502pub(crate) fn decode_payload(payload: &[u8]) -> Result<Frame, CodecError> {
503 // Decision 4 requires the Frame visitor to see raw envelope members.
504 // A Value-first success path would erase duplicate keys before it runs.
505 let error = match serde_json::from_slice::<Frame>(payload) {
506 Ok(frame) => return Ok(frame),
507 Err(error) => error,
508 };
509
510 // This second parse classifies an already-refused payload only. It
511 // must never deserialize the Value back into an accepted Frame.
512 let value: serde_json::Value =
513 serde_json::from_slice(payload).map_err(|e| CodecError::InvalidJson(e.to_string()))?;
514
515 let kind = value
516 .as_object()
517 .and_then(|obj| obj.get("kind"))
518 .and_then(|k| k.as_str())
519 .ok_or(CodecError::MissingKind)?
520 .to_string();
521
522 if !crate::frame::FRAME_KINDS.contains(&kind.as_str()) {
523 return Err(CodecError::UnknownFrameKind(kind));
524 }
525
526 // Preserve the visitor's original refusal, including duplicate keys
527 // and present-null fields, while retaining typed id/scope diagnostics.
528 let detail = error.to_string();
529 Err(match detail.strip_prefix(INCONSISTENT_SCOPE_ERROR_PREFIX) {
530 Some(scope_detail) => CodecError::InconsistentErrorScope {
531 detail: scope_detail.to_string(),
532 },
533 None => CodecError::InvalidFields { kind, detail },
534 })
535}
536
537#[cfg(test)]
538#[path = "codec_tests.rs"]
539mod tests;
540
541#[cfg(test)]
542#[path = "codec_configured_max_tests.rs"]
543mod configured_max_tests;