Skip to main content

khive_wire_protocol/
frame.rs

1//! The closed set of application frame kinds (ADR-137, "Decision" and
2//! "Protocol contract completeness").
3
4use serde::de::{Error as DeError, MapAccess, Visitor};
5use serde::ser::{Error as SerError, SerializeMap};
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use crate::version::ProtocolVersion;
9use crate::OpaqueValue;
10
11/// A caller-generated operation id.
12///
13/// Unique across `request`, `subscribe`, and `unsubscribe` frames for the
14/// lifetime of one connection. The server echoes it on the operation's
15/// single terminal frame.
16///
17/// The codec rejects an EMPTY operation id in BOTH directions: an empty
18/// string can never be a unique caller-generated id, so it is a
19/// frame-grammar violation rather than a value the protocol has to give
20/// meaning to. Decode rejects it in `OperationId`'s [`Deserialize`] impl;
21/// encode rejects it in [`crate::codec::encode_frame_with_max`], so a
22/// locally constructed frame carrying one can never leave this crate.
23/// In-memory construction (`From<String>`, `From<&str>`) remains
24/// unrestricted; only the wire form is validated.
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub struct OperationId(pub String);
27
28impl From<String> for OperationId {
29    fn from(value: String) -> Self {
30        Self(value)
31    }
32}
33
34impl From<&str> for OperationId {
35    fn from(value: &str) -> Self {
36        Self(value.to_string())
37    }
38}
39
40impl std::fmt::Display for OperationId {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.write_str(&self.0)
43    }
44}
45
46impl Serialize for OperationId {
47    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
48        serializer.serialize_str(&self.0)
49    }
50}
51
52impl<'de> Deserialize<'de> for OperationId {
53    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
54        let value = String::deserialize(deserializer)?;
55        if value.is_empty() {
56            return Err(D::Error::custom("operation id must be a non-empty string"));
57        }
58        Ok(Self(value))
59    }
60}
61
62/// A per-topic, server-assigned, strictly increasing resumption cursor.
63pub type Cursor = u64;
64
65/// The names of every frame kind, in the order ADR-137 lists them. Used to
66/// drive the closed-set unknown-kind check in the codec, and exposed so a
67/// caller can enumerate the protocol's frame vocabulary without matching on
68/// [`Frame`] itself.
69pub const FRAME_KINDS: &[&str] = &[
70    "handshake",
71    "handshake_ack",
72    "request",
73    "response",
74    "error",
75    "cancel",
76    "subscribe",
77    "subscribe_ack",
78    "unsubscribe",
79    "unsubscribe_ack",
80    "event",
81];
82
83/// The frame kinds a client may send to the server, in the direction each
84/// is legal. The complement of this set within [`FRAME_KINDS`] —
85/// `handshake_ack`, `response`, `error`, `subscribe_ack`, `unsubscribe_ack`,
86/// and `event` — is server→client only; a server-side inbound gate rejects
87/// them as grammar violations ([`crate::handshake::HandshakeGate`]).
88pub const CLIENT_TO_SERVER_KINDS: &[&str] =
89    &["handshake", "request", "cancel", "subscribe", "unsubscribe"];
90
91/// The field set of a [`Frame::Handshake`] payload.
92///
93/// Strict within a protocol version: [`deny_unknown_fields`](serde) — a
94/// payload carrying any field this struct does not declare is rejected at
95/// decode (ADR-137's closed grammar; see the crate documentation's "Strict
96/// field rejection" section).
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98#[serde(deny_unknown_fields)]
99pub struct HandshakePayload {
100    /// The protocol version the client wants to speak.
101    pub version: ProtocolVersion,
102}
103
104/// The field set of a [`Frame::HandshakeAck`] payload.
105#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct HandshakeAckPayload {
108    /// The protocol version the connection now speaks.
109    pub version: ProtocolVersion,
110}
111
112// Optional envelope fields distinguish omission from an explicit null under
113// ADR-137 Amendment 1 Decision 4. The field default handles omission; a
114// present field must deserialize as T itself, rather than Option<T>.
115fn deserialize_present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
116where
117    D: Deserializer<'de>,
118    T: Deserialize<'de>,
119{
120    T::deserialize(deserializer).map(Some)
121}
122
123/// The field set of a [`Frame::Request`] payload.
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125#[serde(deny_unknown_fields)]
126pub struct RequestPayload {
127    /// Caller-generated, connection-unique operation id.
128    pub id: OperationId,
129    /// The request DSL string (ADR-016's function-call or JSON form).
130    pub ops: String,
131    /// Optional positive deadline in milliseconds, measured from server receipt
132    /// of this frame against the server's monotonic clock. Scopes the
133    /// entire request frame (the whole DSL batch or chain).
134    #[serde(
135        default,
136        skip_serializing_if = "Option::is_none",
137        deserialize_with = "deserialize_present"
138    )]
139    pub deadline_ms: Option<u64>,
140    /// Frame-level namespace override. Legal only on transports that
141    /// accept caller-supplied identity context; a mapped transport
142    /// (ADR-137's TCP transport) rejects any request carrying this with
143    /// [`crate::error::WireErrorCode::ContextRejected`].
144    #[serde(
145        default,
146        skip_serializing_if = "Option::is_none",
147        deserialize_with = "deserialize_present"
148    )]
149    pub namespace: Option<String>,
150    /// Frame-level actor override; see `namespace` above.
151    #[serde(
152        default,
153        skip_serializing_if = "Option::is_none",
154        deserialize_with = "deserialize_present"
155    )]
156    pub actor_id: Option<String>,
157    /// Frame-level visible-namespace-set override; see `namespace`
158    /// above.
159    #[serde(
160        default,
161        skip_serializing_if = "Option::is_none",
162        deserialize_with = "deserialize_present"
163    )]
164    pub visible_namespaces: Option<Vec<String>>,
165}
166
167/// The field set of a [`Frame::Response`] payload.
168#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
169#[serde(deny_unknown_fields)]
170pub struct ResponsePayload {
171    /// Echoes the originating `request`'s operation id.
172    pub id: OperationId,
173    /// The verb-dispatch result, exactly as ADR-016's `request` verb
174    /// surface returns it (an aggregate `{ok, tool, result}` /
175    /// `{ok, summary, ...}` payload). Opaque to this crate.
176    pub result: OpaqueValue,
177}
178
179/// The field set of a [`Frame::Error`] payload.
180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181#[serde(deny_unknown_fields)]
182pub struct ErrorPayload {
183    /// The operation id this error terminates, for a request-scoped
184    /// error. `None` for a connection-terminal error, which carries no
185    /// operation id (ADR-137, "Operation correlation").
186    #[serde(
187        default,
188        skip_serializing_if = "Option::is_none",
189        deserialize_with = "deserialize_present"
190    )]
191    pub id: Option<OperationId>,
192    /// The wire error code.
193    pub code: crate::error::WireErrorCode,
194    /// A human-readable detail message. Not part of the closed
195    /// contract — callers must branch on `code`, never on this string.
196    pub message: String,
197}
198
199/// The field set of a [`Frame::Cancel`] payload.
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
201#[serde(deny_unknown_fields)]
202pub struct CancelPayload {
203    /// The `request` operation id to cancel. A `cancel` naming a
204    /// subscribe/unsubscribe id, or an unknown or already-terminal
205    /// request id, is a no-op.
206    pub id: OperationId,
207}
208
209/// The field set of a [`Frame::Subscribe`] payload.
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211#[serde(deny_unknown_fields)]
212pub struct SubscribePayload {
213    /// Caller-generated, connection-unique operation id.
214    pub id: OperationId,
215    /// The topic to subscribe to, `<domain>.<event>`.
216    pub topic: String,
217    /// Resume position. Absent starts delivery at new events only;
218    /// present replays every retained event with a cursor greater than
219    /// this value before delivering new events.
220    #[serde(
221        default,
222        skip_serializing_if = "Option::is_none",
223        deserialize_with = "deserialize_present"
224    )]
225    pub resume_cursor: Option<Cursor>,
226}
227
228/// The field set of a [`Frame::SubscribeAck`] payload.
229#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
230#[serde(deny_unknown_fields)]
231pub struct SubscribeAckPayload {
232    /// Echoes the originating `subscribe`'s operation id.
233    pub id: OperationId,
234    /// The subscribed topic.
235    pub topic: String,
236    /// The cursor position delivery begins after.
237    pub start_cursor: Cursor,
238}
239
240/// The field set of a [`Frame::Unsubscribe`] payload.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242#[serde(deny_unknown_fields)]
243pub struct UnsubscribePayload {
244    /// Caller-generated, connection-unique operation id.
245    pub id: OperationId,
246    /// The topic to unsubscribe from. Naming a topic with no active
247    /// subscription is an idempotent no-op.
248    pub topic: String,
249}
250
251/// The field set of a [`Frame::UnsubscribeAck`] payload.
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253#[serde(deny_unknown_fields)]
254pub struct UnsubscribeAckPayload {
255    /// Echoes the originating `unsubscribe`'s operation id.
256    pub id: OperationId,
257    /// The unsubscribed topic.
258    pub topic: String,
259}
260
261/// The field set of a [`Frame::Event`] payload.
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
263#[serde(deny_unknown_fields)]
264pub struct EventPayload {
265    /// The topic this event belongs to.
266    pub topic: String,
267    /// Server-assigned, per-topic, strictly increasing resumption
268    /// cursor.
269    pub cursor: Cursor,
270    /// Server-assigned event time, RFC 3339.
271    pub occurred_at: String,
272    /// Topic-specific JSON object. Its field-by-field shape is owned by
273    /// the per-topic catalog (ADR-137, "Implementation-phase deliverables").
274    /// Amendment 1 Decision 10 requires the outer object shape on the wire.
275    pub payload: OpaqueValue,
276}
277
278/// One application frame.
279///
280/// Every variant corresponds to exactly one entry in [`FRAME_KINDS`] and is
281/// carried on the wire as a JSON object with a `"kind"` discriminant field
282/// holding that variant's `snake_case` name, followed by the variant's own
283/// fields flattened into the same object. This is the wire framing's
284/// internally tagged encoding; see the crate documentation for a worked
285/// example of the exact bytes.
286///
287/// The set is closed within a protocol version (ADR-137, "Decision"): a
288/// decoder that encounters a `"kind"` value outside [`FRAME_KINDS`] must
289/// reject the frame ([`crate::codec::CodecError::UnknownFrameKind`]), never
290/// skip or ignore it.
291///
292/// Serde is implemented by hand (rather than `#[serde(tag = "kind")]`) so
293/// the decode path can enforce the closed grammar ADR-137 requires: the
294/// codec checks the `"kind"` discriminant against [`FRAME_KINDS`] itself,
295/// then hands the payload to the matching kind's payload struct
296/// ([`HandshakePayload`], [`RequestPayload`], ...), every one of which
297/// carries `#[serde(deny_unknown_fields)]`. A payload with any field its
298/// kind does not declare is therefore rejected — never silently ignored —
299/// and a missing or non-string `"kind"` is rejected before any kind is
300/// matched. The visitor likewise enforces the ADR-137 id/scope rule for
301/// `error` frames and captures the unknown-code fallback's raw string
302/// ([`Frame::Error`](Frame)'s `unrecognized_code`), so a DIRECT serde
303/// decode of `Frame` — not just the codec — can never represent an
304/// inconsistent error frame. Encoding writes `"kind"` first, then the
305/// kind's fields in
306/// declaration order, skipping absent optional fields; this is the exact
307/// byte layout the golden fixtures pin.
308#[derive(Debug, Clone, PartialEq)]
309pub enum Frame {
310    /// The first application frame on every connection. Names the protocol
311    /// version the client supports.
312    Handshake {
313        /// The protocol version the client wants to speak.
314        version: ProtocolVersion,
315    },
316
317    /// The server's acceptance of a [`Frame::Handshake`], naming the
318    /// accepted protocol version.
319    HandshakeAck {
320        /// The protocol version the connection now speaks.
321        version: ProtocolVersion,
322    },
323
324    /// A caller-issued operation: a DSL batch or chain (ADR-016) to execute.
325    Request {
326        /// Caller-generated, connection-unique operation id.
327        id: OperationId,
328        /// The request DSL string (ADR-016's function-call or JSON form).
329        ops: String,
330        /// Optional positive deadline in milliseconds, measured from server receipt
331        /// of this frame against the server's monotonic clock. Scopes the
332        /// entire request frame (the whole DSL batch or chain).
333        deadline_ms: Option<u64>,
334        /// Frame-level namespace override. Legal only on transports that
335        /// accept caller-supplied identity context; a mapped transport
336        /// (ADR-137's TCP transport) rejects any request carrying this with
337        /// [`crate::error::WireErrorCode::ContextRejected`].
338        namespace: Option<String>,
339        /// Frame-level actor override; see `namespace` above.
340        actor_id: Option<String>,
341        /// Frame-level visible-namespace-set override; see `namespace`
342        /// above.
343        visible_namespaces: Option<Vec<String>>,
344    },
345
346    /// The successful terminal frame for a `request`.
347    Response {
348        /// Echoes the originating `request`'s operation id.
349        id: OperationId,
350        /// The verb-dispatch result, exactly as ADR-016's `request` verb
351        /// surface returns it (an aggregate `{ok, tool, result}` /
352        /// `{ok, summary, ...}` payload). Opaque to this crate.
353        result: OpaqueValue,
354    },
355
356    /// A wire-level failure terminal frame.
357    Error {
358        /// The operation id this error terminates, for a request-scoped
359        /// error. `None` for a connection-terminal error, which carries no
360        /// operation id (ADR-137, "Operation correlation").
361        id: Option<OperationId>,
362        /// The wire error code.
363        code: crate::error::WireErrorCode,
364        /// A human-readable detail message. Not part of the closed
365        /// contract — callers must branch on `code`, never on this string.
366        message: String,
367        /// The raw code string when the wire carried a code OUTSIDE the
368        /// closed set ([`crate::error::WIRE_ERROR_CODES`]) and serde's
369        /// `#[serde(other)]` fallback mapped it to
370        /// [`crate::error::WireErrorCode::Internal`]; `None` for every
371        /// recognized code, and for every frame this crate produced by
372        /// encoding or by in-memory construction. Diagnostic only: it is
373        /// never serialized, and only DECODE paths fill it — this type's
374        /// serde visitor, whether driven by the codec's `decode_payload`
375        /// or by a direct serde decode. A frame carrying it is a decoded
376        /// fallback and cannot be re-encoded by this relay: the encode path
377        /// rejects it ([`crate::codec::CodecError::FallbackFrameNotEncodable`])
378        /// rather than emit `internal` and silently discard the newer code.
379        /// The connection remains healthy; only this relay attempt failed.
380        /// Under ADR-137 Amendment 1 Decision 5, only an unknown code with
381        /// an operation id can decode to this fallback. An id-less unknown
382        /// code is rejected as malformed at the decode boundary.
383        unrecognized_code: Option<String>,
384    },
385
386    /// Asks the server to terminate an in-flight `request`.
387    Cancel {
388        /// The `request` operation id to cancel. A `cancel` naming a
389        /// subscribe/unsubscribe id, or an unknown or already-terminal
390        /// request id, is a no-op.
391        id: OperationId,
392    },
393
394    /// Opens delivery for one topic on the connection.
395    Subscribe {
396        /// Caller-generated, connection-unique operation id.
397        id: OperationId,
398        /// The topic to subscribe to, `<domain>.<event>`.
399        topic: String,
400        /// Resume position. Absent starts delivery at new events only;
401        /// present replays every retained event with a cursor greater than
402        /// this value before delivering new events.
403        resume_cursor: Option<Cursor>,
404    },
405
406    /// The successful terminal frame for a `subscribe`.
407    SubscribeAck {
408        /// Echoes the originating `subscribe`'s operation id.
409        id: OperationId,
410        /// The subscribed topic.
411        topic: String,
412        /// The cursor position delivery begins after.
413        start_cursor: Cursor,
414    },
415
416    /// Ends delivery for one topic on the connection.
417    Unsubscribe {
418        /// Caller-generated, connection-unique operation id.
419        id: OperationId,
420        /// The topic to unsubscribe from. Naming a topic with no active
421        /// subscription is an idempotent no-op.
422        topic: String,
423    },
424
425    /// The terminal frame for an `unsubscribe`.
426    UnsubscribeAck {
427        /// Echoes the originating `unsubscribe`'s operation id.
428        id: OperationId,
429        /// The unsubscribed topic.
430        topic: String,
431    },
432
433    /// A server-pushed state-change delivery for a subscribed topic.
434    ///
435    /// Carries no operation id; correlated by topic and ordered by cursor
436    /// instead.
437    Event {
438        /// The topic this event belongs to.
439        topic: String,
440        /// Server-assigned, per-topic, strictly increasing resumption
441        /// cursor.
442        cursor: Cursor,
443        /// Server-assigned event time, RFC 3339.
444        occurred_at: String,
445        /// Topic-specific JSON object on the wire (Amendment 1 Decision 10).
446        /// Its members are opaque to this crate and owned by the per-topic
447        /// catalog; local Value construction uses `OpaqueValue::from`.
448        payload: OpaqueValue,
449    },
450}
451
452impl Frame {
453    /// The `snake_case` frame-kind name of this frame, matching its `"kind"`
454    /// discriminant on the wire.
455    pub const fn kind(&self) -> &'static str {
456        match self {
457            Frame::Handshake { .. } => "handshake",
458            Frame::HandshakeAck { .. } => "handshake_ack",
459            Frame::Request { .. } => "request",
460            Frame::Response { .. } => "response",
461            Frame::Error { .. } => "error",
462            Frame::Cancel { .. } => "cancel",
463            Frame::Subscribe { .. } => "subscribe",
464            Frame::SubscribeAck { .. } => "subscribe_ack",
465            Frame::Unsubscribe { .. } => "unsubscribe",
466            Frame::UnsubscribeAck { .. } => "unsubscribe_ack",
467            Frame::Event { .. } => "event",
468        }
469    }
470}
471
472/// Validate the invariants shared by the codec and direct serde encoding.
473fn validate_frame_for_serialize(frame: &Frame) -> Result<(), String> {
474    use crate::error::TerminalScope;
475
476    fn check_id(kind: &str, id: &OperationId) -> Result<(), String> {
477        if id.0.is_empty() {
478            return Err(format!(
479                "frame kind {kind:?}: operation id must be a non-empty string"
480            ));
481        }
482        Ok(())
483    }
484
485    fn check_version(kind: &str, version: ProtocolVersion) -> Result<(), String> {
486        if version.get() == 0 {
487            return Err(format!(
488                "frame kind {kind:?}: protocol version 0 does not exist"
489            ));
490        }
491        Ok(())
492    }
493
494    match frame {
495        Frame::Handshake { version } => check_version("handshake", *version)?,
496        Frame::HandshakeAck { version } => check_version("handshake_ack", *version)?,
497        Frame::Request {
498            id, deadline_ms, ..
499        } => {
500            check_id("request", id)?;
501            if *deadline_ms == Some(0) {
502                return Err(
503                    "frame kind \"request\": deadline_ms must be a positive integer".to_string(),
504                );
505            }
506        }
507        Frame::Response { id, .. } => check_id("response", id)?,
508        Frame::Cancel { id } => check_id("cancel", id)?,
509        Frame::Subscribe { id, .. } => check_id("subscribe", id)?,
510        Frame::SubscribeAck { id, .. } => check_id("subscribe_ack", id)?,
511        Frame::Unsubscribe { id, .. } => check_id("unsubscribe", id)?,
512        Frame::UnsubscribeAck { id, .. } => check_id("unsubscribe_ack", id)?,
513        Frame::Event { payload, .. } => {
514            if !payload.is_object() {
515                return Err("frame kind \"event\": payload must be a JSON object".to_string());
516            }
517        }
518        Frame::Error {
519            id,
520            code,
521            unrecognized_code,
522            ..
523        } => {
524            if let Some(raw_code) = unrecognized_code {
525                return Err(format!(
526                    "fallback error frame (unrecognized code {raw_code:?}) is not re-encodable: \
527                     re-encoding would emit \"internal\" and discard the newer wire code"
528                ));
529            }
530            if let Some(id) = id {
531                check_id("error", id)?;
532            }
533            match (code.terminal_scope(), id) {
534                (TerminalScope::Connection, Some(id)) => {
535                    return Err(format!(
536                        "error frame violates the id/scope rule: connection-terminal code {code} \
537                         must not carry an operation id, got {id}"
538                    ));
539                }
540                (TerminalScope::Request, None) => {
541                    return Err(format!(
542                        "error frame violates the id/scope rule: request-terminal code {code} \
543                         must echo the operation id it terminates"
544                    ));
545                }
546                (TerminalScope::Connection, None) | (TerminalScope::Request, Some(_)) => {}
547            }
548        }
549    }
550    Ok(())
551}
552
553/// Serialize one frame as its wire object: `"kind"` first, then the kind's
554/// fields in declaration order, absent optional fields skipped. The byte
555/// layout is pinned by the golden fixtures in `tests/fixtures/*.hex`.
556impl Serialize for Frame {
557    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
558        if let Err(detail) = validate_frame_for_serialize(self) {
559            return Err(S::Error::custom(detail));
560        }
561        let size_hint = match self {
562            Frame::Handshake { .. } | Frame::HandshakeAck { .. } | Frame::Cancel { .. } => 2,
563            Frame::Subscribe { resume_cursor, .. } => {
564                if resume_cursor.is_some() {
565                    4
566                } else {
567                    3
568                }
569            }
570            Frame::Request {
571                deadline_ms,
572                namespace,
573                actor_id,
574                visible_namespaces,
575                ..
576            } => {
577                3 + usize::from(deadline_ms.is_some())
578                    + usize::from(namespace.is_some())
579                    + usize::from(actor_id.is_some())
580                    + usize::from(visible_namespaces.is_some())
581            }
582            Frame::Error { id, .. } => 3 + usize::from(id.is_some()),
583            Frame::Response { .. } | Frame::Unsubscribe { .. } | Frame::UnsubscribeAck { .. } => 3,
584            Frame::SubscribeAck { .. } => 4,
585            Frame::Event { .. } => 5,
586        };
587        let mut map = serializer.serialize_map(Some(size_hint))?;
588        map.serialize_entry("kind", self.kind())?;
589        match self {
590            Frame::Handshake { version } => {
591                map.serialize_entry("version", version)?;
592            }
593            Frame::HandshakeAck { version } => {
594                map.serialize_entry("version", version)?;
595            }
596            Frame::Request {
597                id,
598                ops,
599                deadline_ms,
600                namespace,
601                actor_id,
602                visible_namespaces,
603            } => {
604                map.serialize_entry("id", id)?;
605                map.serialize_entry("ops", ops)?;
606                if let Some(deadline_ms) = deadline_ms {
607                    map.serialize_entry("deadline_ms", deadline_ms)?;
608                }
609                if let Some(namespace) = namespace {
610                    map.serialize_entry("namespace", namespace)?;
611                }
612                if let Some(actor_id) = actor_id {
613                    map.serialize_entry("actor_id", actor_id)?;
614                }
615                if let Some(visible_namespaces) = visible_namespaces {
616                    map.serialize_entry("visible_namespaces", visible_namespaces)?;
617                }
618            }
619            Frame::Response { id, result } => {
620                map.serialize_entry("id", id)?;
621                map.serialize_entry("result", result)?;
622            }
623            // `unrecognized_code` is a decode-only diagnostic; validation
624            // above rejects it rather than silently dropping the wire code.
625            Frame::Error {
626                id, code, message, ..
627            } => {
628                if let Some(id) = id {
629                    map.serialize_entry("id", id)?;
630                }
631                map.serialize_entry("code", code)?;
632                map.serialize_entry("message", message)?;
633            }
634            Frame::Cancel { id } => {
635                map.serialize_entry("id", id)?;
636            }
637            Frame::Subscribe {
638                id,
639                topic,
640                resume_cursor,
641            } => {
642                map.serialize_entry("id", id)?;
643                map.serialize_entry("topic", topic)?;
644                if let Some(resume_cursor) = resume_cursor {
645                    map.serialize_entry("resume_cursor", resume_cursor)?;
646                }
647            }
648            Frame::SubscribeAck {
649                id,
650                topic,
651                start_cursor,
652            } => {
653                map.serialize_entry("id", id)?;
654                map.serialize_entry("topic", topic)?;
655                map.serialize_entry("start_cursor", start_cursor)?;
656            }
657            Frame::Unsubscribe { id, topic } => {
658                map.serialize_entry("id", id)?;
659                map.serialize_entry("topic", topic)?;
660            }
661            Frame::UnsubscribeAck { id, topic } => {
662                map.serialize_entry("id", id)?;
663                map.serialize_entry("topic", topic)?;
664            }
665            Frame::Event {
666                topic,
667                cursor,
668                occurred_at,
669                payload,
670            } => {
671                map.serialize_entry("topic", topic)?;
672                map.serialize_entry("cursor", cursor)?;
673                map.serialize_entry("occurred_at", occurred_at)?;
674                map.serialize_entry("payload", payload)?;
675            }
676        }
677        map.end()
678    }
679}
680
681/// The decode half of the closed grammar; see the type-level docs and the
682/// crate documentation's "Strict field rejection" section. The codec's
683/// `decode_payload` drives this directly from the raw JSON bytes, before
684/// any diagnostic parsing into a Value can discard duplicate members.
685/// It re-classifies refusals into the codec's finer-grained error types.
686///
687/// The visitor enforces every decode-time rule that only needs the fields
688/// of one frame, so a DIRECT serde decode of `Frame` (e.g.
689/// `serde_json::from_str::<Frame>`) agrees with the codec path:
690///
691/// - the ADR-137 id/scope pairing for `error` frames — a
692///   connection-terminal code must carry no operation id, and a
693///   request-terminal code must echo the one it terminates
694///   ([`crate::codec::CodecError::InconsistentErrorScope`] is the codec's
695///   typed form of this rejection; a direct serde decode reports the same
696///   rule through its deserializer's error type); and
697/// - the unknown-code fallback diagnostic: an `error` frame whose wire
698///   code is outside the closed set ([`crate::error::WIRE_ERROR_CODES`])
699///   carries the raw string in `unrecognized_code`.
700///
701/// The one guarantee only the codec path provides is the finer-grained
702/// [`crate::codec::CodecError::UnknownFrameKind`] classification for a
703/// `"kind"` outside [`FRAME_KINDS`]; this visitor rejects unknown kinds
704/// too, with the deserializer's own error type.
705impl<'de> Deserialize<'de> for Frame {
706    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
707        struct FrameVisitor;
708
709        impl<'de> Visitor<'de> for FrameVisitor {
710            type Value = Frame;
711
712            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713                formatter.write_str("a JSON object with a string \"kind\" discriminant field")
714            }
715
716            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Frame, A::Error> {
717                // Decision 4: reject every repeated decoded envelope key
718                // before kind or per-kind field validation. Values inside
719                // result/payload remain opaque JSON, not envelope grammar.
720                let mut object = std::collections::BTreeMap::new();
721                while let Some(key) = map.next_key::<String>()? {
722                    if object.contains_key(&key) {
723                        return Err(A::Error::custom(format!(
724                            "duplicate envelope field `{key}`"
725                        )));
726                    }
727                    let value = map.next_value::<Box<serde_json::value::RawValue>>()?;
728                    object.insert(key, value);
729                }
730                let kind_value = object
731                    .get("kind")
732                    .ok_or_else(|| A::Error::custom("missing field `kind`"))?;
733                let kind: String = serde_json::from_str(kind_value.get())
734                    .map_err(|_| A::Error::custom("field `kind` must be a string"))?;
735                object.remove("kind");
736
737                fn parse<T: serde::de::DeserializeOwned>(
738                    object: &std::collections::BTreeMap<String, Box<serde_json::value::RawValue>>,
739                ) -> Result<T, serde_json::Error> {
740                    // Decision 9: serialize raw root members without projecting them
741                    // through Value, then deserialize a plain payload struct. A
742                    // tagged/untagged Content intermediary would lose raw tokens.
743                    // This functional-first path makes a transient JSON byte copy.
744                    let bytes = serde_json::to_vec(object)?;
745                    serde_json::from_slice(&bytes)
746                }
747
748                match kind.as_str() {
749                    "handshake" => {
750                        let payload: HandshakePayload = parse(&object).map_err(A::Error::custom)?;
751                        Ok(Frame::Handshake {
752                            version: payload.version,
753                        })
754                    }
755                    "handshake_ack" => {
756                        let payload: HandshakeAckPayload =
757                            parse(&object).map_err(A::Error::custom)?;
758                        Ok(Frame::HandshakeAck {
759                            version: payload.version,
760                        })
761                    }
762                    "request" => {
763                        let payload: RequestPayload = parse(&object).map_err(A::Error::custom)?;
764                        if payload.deadline_ms == Some(0) {
765                            return Err(A::Error::custom("deadline_ms must be a positive integer"));
766                        }
767                        Ok(Frame::Request {
768                            id: payload.id,
769                            ops: payload.ops,
770                            deadline_ms: payload.deadline_ms,
771                            namespace: payload.namespace,
772                            actor_id: payload.actor_id,
773                            visible_namespaces: payload.visible_namespaces,
774                        })
775                    }
776                    "response" => {
777                        let payload: ResponsePayload = parse(&object).map_err(A::Error::custom)?;
778                        Ok(Frame::Response {
779                            id: payload.id,
780                            result: payload.result,
781                        })
782                    }
783                    "error" => {
784                        // Capture the raw code string BEFORE payload
785                        // parsing: serde's `#[serde(other)]` fallback maps
786                        // every code outside the closed set
787                        // ([`crate::error::WIRE_ERROR_CODES`]) to
788                        // [`crate::error::WireErrorCode::Internal`] and
789                        // erases which of the two the wire carried. Both
790                        // the id/scope check and the fallback diagnostic
791                        // below need the pre-fallback string.
792                        let raw_code = object
793                            .get("code")
794                            .and_then(|c| serde_json::from_str::<String>(c.get()).ok());
795                        let payload: ErrorPayload = parse(&object).map_err(A::Error::custom)?;
796
797                        // ADR-137, "Operation correlation": a
798                        // connection-terminal code carries no operation id,
799                        // and a request-terminal code echoes the one it
800                        // terminates. Enforced HERE — inside the visitor —
801                        // so every decode path agrees: a direct
802                        // `serde_json::from_str::<Frame>` can never
803                        // represent an inconsistent error frame, and
804                        // [`crate::codec::decode_payload`] (which drives
805                        // this same visitor) re-classifies the rejection
806                        // into its typed
807                        // [`crate::codec::CodecError::InconsistentErrorScope`].
808                        // ADR-137 Amendment 1 Decision 5: an unknown code
809                        // falls back to request-terminal `internal` only
810                        // when it carries an operation id. Without one it
811                        // is malformed at this role-agnostic decode boundary.
812                        let code_in_closed_set = raw_code
813                            .as_deref()
814                            .is_some_and(|c| crate::error::WIRE_ERROR_CODES.contains(&c));
815                        if !code_in_closed_set && payload.id.is_none() {
816                            return Err(A::Error::custom(format!(
817                                "{}unknown error code requires an operation id",
818                                crate::codec::INCONSISTENT_SCOPE_ERROR_PREFIX,
819                            )));
820                        }
821                        if code_in_closed_set {
822                            match (payload.code.terminal_scope(), payload.id.as_ref()) {
823                                (crate::error::TerminalScope::Connection, Some(id)) => {
824                                    return Err(A::Error::custom(format!(
825                                        "{}connection-terminal code {code} must not carry an operation id, got {id}",
826                                        crate::codec::INCONSISTENT_SCOPE_ERROR_PREFIX,
827                                        code = payload.code
828                                    )));
829                                }
830                                (crate::error::TerminalScope::Request, None) => {
831                                    return Err(A::Error::custom(format!(
832                                        "{}request-terminal code {code} must echo the operation id it terminates",
833                                        crate::codec::INCONSISTENT_SCOPE_ERROR_PREFIX,
834                                        code = payload.code
835                                    )));
836                                }
837                                (crate::error::TerminalScope::Connection, None)
838                                | (crate::error::TerminalScope::Request, Some(_)) => {}
839                            }
840                        }
841
842                        Ok(Frame::Error {
843                            id: payload.id,
844                            code: payload.code,
845                            message: payload.message,
846                            // The decoded-fallback marker, filled on EVERY
847                            // decode path (codec or direct serde): the raw
848                            // string when the code fell back to `Internal`,
849                            // `None` for every closed-set code — including a
850                            // literal `"internal"`, which is a closed-set
851                            // member, not a fallback.
852                            unrecognized_code: if code_in_closed_set { None } else { raw_code },
853                        })
854                    }
855                    "cancel" => {
856                        let payload: CancelPayload = parse(&object).map_err(A::Error::custom)?;
857                        Ok(Frame::Cancel { id: payload.id })
858                    }
859                    "subscribe" => {
860                        let payload: SubscribePayload = parse(&object).map_err(A::Error::custom)?;
861                        Ok(Frame::Subscribe {
862                            id: payload.id,
863                            topic: payload.topic,
864                            resume_cursor: payload.resume_cursor,
865                        })
866                    }
867                    "subscribe_ack" => {
868                        let payload: SubscribeAckPayload =
869                            parse(&object).map_err(A::Error::custom)?;
870                        Ok(Frame::SubscribeAck {
871                            id: payload.id,
872                            topic: payload.topic,
873                            start_cursor: payload.start_cursor,
874                        })
875                    }
876                    "unsubscribe" => {
877                        let payload: UnsubscribePayload =
878                            parse(&object).map_err(A::Error::custom)?;
879                        Ok(Frame::Unsubscribe {
880                            id: payload.id,
881                            topic: payload.topic,
882                        })
883                    }
884                    "unsubscribe_ack" => {
885                        let payload: UnsubscribeAckPayload =
886                            parse(&object).map_err(A::Error::custom)?;
887                        Ok(Frame::UnsubscribeAck {
888                            id: payload.id,
889                            topic: payload.topic,
890                        })
891                    }
892                    "event" => {
893                        let payload: EventPayload = parse(&object).map_err(A::Error::custom)?;
894                        if !payload.payload.is_object() {
895                            return Err(A::Error::custom("event payload must be a JSON object"));
896                        }
897                        Ok(Frame::Event {
898                            topic: payload.topic,
899                            cursor: payload.cursor,
900                            occurred_at: payload.occurred_at,
901                            payload: payload.payload,
902                        })
903                    }
904                    // The codec re-classifies this refusal as
905                    // UnknownFrameKind. Direct serde retains its own
906                    // deserializer error type.
907                    other => Err(A::Error::custom(format!("unknown frame kind: {other:?}"))),
908                }
909            }
910        }
911
912        deserializer.deserialize_map(FrameVisitor)
913    }
914}
915
916#[cfg(test)]
917#[path = "frame_tests.rs"]
918mod tests;