Skip to main content

khive_wire_protocol/
lib.rs

1//! # khive wire protocol
2//!
3//! This crate is the normative specification of khive's frame protocol
4//! (ADR-137: "Tailnet Wire Transport for the khive Frame Protocol"). It
5//! defines framing, the handshake sequence, every frame kind and its
6//! fields, the closed wire error taxonomy, and protocol versioning. A
7//! non-Rust client can implement this protocol from this documentation
8//! alone — that is the ADR's stated bar for this crate, and the sections
9//! below are written to meet it.
10//!
11//! This crate does no I/O and depends on no async runtime. It is types, a
12//! byte-buffer codec, and handshake state machines; a transport crate
13//! (Unix-domain socket, tailnet TCP, or any other carrier of the same
14//! framing) drives it.
15//!
16//! ## Framing
17//!
18//! One wire frame is:
19//!
20//! ```text
21//! +----------------------------+----------------------------------+
22//! | length: u32, big-endian    | payload: `length` bytes of JSON  |
23//! | (4 bytes)                  |                                  |
24//! +----------------------------+----------------------------------+
25//! ```
26//!
27//! `length` is the byte length of the JSON payload only — it does not
28//! include itself. This is the same framing the existing Unix-domain-socket
29//! transport uses (`crates/khive-runtime/src/daemon.rs`, `read_frame` /
30//! `write_frame`): a 4-byte big-endian `u32` length prefix followed by JSON
31//! bytes. This crate defines what that JSON is; it does not change the
32//! outer framing.
33//!
34//! The default maximum frame size is **8 MiB**
35//! ([`codec::DEFAULT_MAX_FRAME_BYTES`]), matching the existing transport's
36//! configured limit. A deployment may configure a different maximum via
37//! [`codec::FrameCodec::new`]. A frame whose declared length exceeds the
38//! configured maximum is rejected at decode with
39//! [`codec::CodecError::FrameTooLarge`], which a server maps to the wire
40//! error [`error::WireErrorCode::FrameTooLarge`] and closes the connection
41//! — the frame is never partially buffered.
42//!
43//! [`codec::decode_frame`] and [`codec::encode_frame`] (or the
44//! [`codec::FrameCodec`] wrapper) operate on one complete frame's bytes at a
45//! time. They do not support partial/streaming reads: a transport reading
46//! from a socket is responsible for buffering until it has the 4-byte
47//! prefix and then the declared number of payload bytes before calling
48//! into this crate.
49//!
50//! **Decode errors are connection-terminal.** A decode error carries NO
51//! consumed byte count: once a frame fails to decode, the stream position
52//! is unrecoverable and the transport cannot find the next frame's start.
53//! A transport must map the error through [`codec::CodecError::wire_code`],
54//! send the corresponding wire error, and close the connection — never
55//! attempt to resynchronize and keep reading.
56//!
57//! ## The JSON payload: frame kind and fields
58//!
59//! Every payload is a JSON object with a `"kind"` string field naming one
60//! of the eleven closed frame kinds, plus that kind's own fields flattened
61//! into the same object (an internally tagged encoding). For example, a
62//! `cancel` frame referencing operation id `"op-42"`:
63//!
64//! ```json
65//! {"kind":"cancel","id":"op-42"}
66//! ```
67//!
68//! The eleven frame kinds ([`frame::FRAME_KINDS`]), grouped by role:
69//!
70//! | Kind               | Direction       | Fields                                                        | Role |
71//! | ------------------ | --------------- | -------------------------------------------------------------- | ---- |
72//! | `handshake`        | client → server | `version: u32`                                                 | First frame on every connection; names the client's protocol version. |
73//! | `handshake_ack`    | server → client | `version: u32`                                                 | Accepts a `handshake`; names the version the connection now speaks. |
74//! | `request`          | client → server | `id: string`, `ops: string`, `deadline_ms?: u64`, `namespace?: string`, `actor_id?: string`, `visible_namespaces?: string[]` | One DSL batch/chain (ADR-016) to execute. `deadline_ms`, when present, must be positive (ADR-137, "Deadlines and cancellation"). The three optional identity-override fields exist for transports that accept caller-supplied context; a mapped transport rejects a request carrying any of them with `context_rejected`. |
75//! | `response`         | server → client | `id: string`, `result: json`                                   | Successful terminal frame for a `request`; `result` is the verb-dispatch result, opaque to this crate. |
76//! | `error`            | server → client | `id?: string`, `code: string`, `message: string`               | Wire-level failure. `id` is present for a request-scoped error, absent for a connection-terminal error. |
77//! | `cancel`           | client → server | `id: string`                                                    | Asks the server to terminate the named `request`. No-op on an unknown/subscribe/unsubscribe/already-terminal id. |
78//! | `subscribe`        | client → server | `id: string`, `topic: string`, `resume_cursor?: u64`            | Opens delivery for one topic. |
79//! | `subscribe_ack`    | server → client | `id: string`, `topic: string`, `start_cursor: u64`              | Confirms a `subscribe`; names the cursor delivery begins after. |
80//! | `unsubscribe`      | client → server | `id: string`, `topic: string`                                   | Ends delivery for one topic. Idempotent no-op if not subscribed. |
81//! | `unsubscribe_ack`  | server → client | `id: string`, `topic: string`                                   | Confirms an `unsubscribe`. |
82//! | `event`            | server → client | `topic: string`, `cursor: u64`, `occurred_at: string`, `payload: object` | One state-change delivery. Carries no operation id — correlated by topic and ordered by `cursor` instead. `occurred_at` is RFC 3339. `payload` must be a JSON object (Amendment 1 Decision 10); its members are owned by the per-topic catalog. |
83//!
84//! The set is closed within one protocol version. A decoder that sees a
85//! `"kind"` value outside this table rejects the frame
86//! ([`codec::CodecError::UnknownFrameKind`]) rather than skipping it.
87//!
88//! ## Strict field rejection (closed grammar)
89//!
90//! The grammar is closed in both dimensions — kinds AND fields. Every
91//! payload is parsed by its kind's payload struct
92//! ([`frame::HandshakePayload`], [`frame::RequestPayload`], ...), each of
93//! which carries `#[serde(deny_unknown_fields)]`: a payload carrying any
94//! field its kind does not declare is rejected with
95//! [`codec::CodecError::InvalidFields`], never silently ignored. Unknown
96//! fields are rejected within a protocol version; forward compatibility is
97//! carried by the version handshake ([`version::ProtocolVersion`]), not by
98//! field tolerance — new fields arrive by bumping the protocol version and
99//! teaching the new version's grammar about them. This is the fail-closed
100//! posture ADR-137 requires: a decoder never guesses that an unrecognized
101//! field is ignorable.
102//!
103//! The strictness covers the fields each frame KIND declares. A Response
104//! result may be any JSON value; an Event payload must be a JSON object
105//! (Amendment 1 Decision 10). Inside those values, members are opaque data:
106//! their field-by-field shape is owned by the verb result surface (ADR-016)
107//! and the per-topic event catalog respectively, not by this crate.
108//!
109//! Three details of the strictness, stated so nobody re-derives them:
110//!
111//! - **Optional envelope fields may be omitted, but may not be `null`.**
112//!   ADR-137 Amendment 1 Decision 4 rejects present-null on the declared
113//!   optional Request, Subscribe and Error fields. Opaque JSON nulls remain
114//!   data; this is not a recursive field-name or null prohibition.
115//! - **Duplicate envelope members are rejected before field validation.**
116//!   Raw serde and the codec compare decoded member names, including
117//!   escaped-equivalent and unknown names. This rule does not inspect
118//!   duplicate members inside opaque `result` or `payload` values.
119//! - **`topic` syntax is not validated here.** The codec accepts any JSON
120//!   string (including empty) for `subscribe`/`unsubscribe`/`event`
121//!   topics; the `<domain>.<event>` shape is enforced by the server
122//!   against its topic catalog, where the catalog lives.
123//!
124//! ## Opaque payload fidelity
125//!
126//! Under ADR-137 Amendment 1 Decision 9, received `response.result` and
127//! `event.payload` use owned [`OpaqueValue`] tokens. Decode and re-encode
128//! preserve the exact opaque token, including object member order, duplicate
129//! members, whitespace, escape spellings and number lexemes. The outer frame
130//! envelope is serialized normally; its original spelling is not retained.
131//!
132//! Local values constructed with `OpaqueValue::from(serde_json::Value)` use
133//! serde_json's normal serializer. A fallible [`OpaqueValue::to_value`] returns
134//! a separate parsed value on request: it can round out-of-range numbers or
135//! refuse numbers outside serde_json's representable range. Editing that
136//! projection never changes the retained token. No parsed projection is cached.
137//!
138//! `PartialEq` compares parsed Value semantics when both projections succeed;
139//! if both received tokens cannot be projected, it compares their exact raw
140//! tokens instead. Equality is not a lexical-fidelity test. The codec's local
141//! opaque-value compatibility test retains the ordinary Value serialization
142//! behavior, while separate received-token tests pin lexical preservation.
143//!
144//! ## Server-produced fields
145//!
146//! `event.occurred_at` (RFC 3339) and `event.topic` are SERVER-PRODUCED
147//! fields: the server validates them when it produces an event, and the
148//! codec accepts them as plain strings without parsing. This crate
149//! deliberately takes no timestamp-parsing dependency for decode-side
150//! validation of server-produced data.
151//!
152//! ## Handshake sequence
153//!
154//! 1. The client opens the transport connection (Unix-domain socket or
155//!    tailnet TCP) and sends `handshake` as its first frame, naming the
156//!    highest protocol version it supports.
157//! 2. The server checks that version against its own supported range
158//!    ([`version::SupportedVersions`]):
159//!    - If supported, it replies `handshake_ack` naming the accepted
160//!      version. The connection now accepts `request`, `subscribe`,
161//!      `unsubscribe`, and `cancel` frames.
162//!    - If not supported, it replies `error` with code
163//!      `unsupported_version` (no `id` — connection-terminal) and closes
164//!      the connection. The client must surface this rejection; it must
165//!      not fall back to a different protocol or a local code path.
166//! 3. No `request`, `subscribe`, `unsubscribe`, or `cancel` frame is valid
167//!    before step 2 completes successfully.
168//!
169//! [`handshake::HandshakeGate`] implements the server side of this sequence
170//! as a type: it is fed every inbound frame and returns an admit/accept/
171//! reject decision, so "no request frame before handshake completes" is a
172//! property of the gate's API rather than a rule every call site has to
173//! remember to check.
174//!
175//! [`client_handshake::ClientHandshakeGate`] implements the client side. After
176//! successfully writing its handshake, a transport calls
177//! [`ClientHandshakeGate::record_handshake_sent`] with the exact version sent,
178//! then feeds every decoded inbound frame to [`ClientHandshakeGate::admit`]. A
179//! fresh gate admits nothing. An outstanding offer admits only an acknowledgment
180//! naming that exact version or a connection-terminal server error; after an
181//! exact acknowledgment, server application frames are admitted and another
182//! handshake/acknowledgment or any client-to-server kind is a violation.
183//!
184//! Both gates close permanently on a sequence or direction violation. A client
185//! gate also closes when it admits a connection-terminal server error:
186//! [`ClientHandshakeOutcome::ServerTerminated`] means the original inbound error
187//! was admitted for surfacing, not replaced by `malformed_frame`. The caller
188//! retains that frame and must surface its original code/message, close the
189//! transport, and never fall back. Local misuse of `record_handshake_sent`,
190//! including version zero, is a distinct [`ClientHandshakeStartError`] and leaves
191//! state unchanged. Encoding/decoding stays role-agnostic; the gates do no I/O.
192//!
193//! ## Wire error taxonomy
194//!
195//! [`error::WireErrorCode`] is the closed set of wire-level error codes for
196//! protocol version 1, matching ADR-137's "Wire error taxonomy" table
197//! exactly (serialized as the `snake_case` names below). A wire error is
198//! distinct from a DSL-level per-operation error (ADR-016's `{ok: false,
199//! error}` result carried inside a *successful* `response` frame) — a wire
200//! error is returned instead of, or before, DSL dispatch.
201//!
202//! | Code                        | Condition                                                                                      | Terminal |
203//! | ---------------------------- | ----------------------------------------------------------------------------------------------- | -------- |
204//! | `unsupported_version`        | Handshake named no mutually supported protocol version.                                        | Connection |
205//! | `identity_rejected`          | Whois lookup failed, no/invalid node mapping, or native-frame ingress by a class without access. | Connection |
206//! | `malformed_frame`            | A frame cannot be decoded or violates the frame grammar.                                        | Connection |
207//! | `frame_too_large`            | A frame exceeds the configured maximum size.                                                    | Connection |
208//! | `subscriber_overflow`        | The connection's bounded outbound event queue reached its limit.                                | Connection |
209//! | `subscription_revoked`       | A live mapping/class change short of deletion removed authorization for an active subscription. | Connection |
210//! | `context_rejected`           | A frame-level attempt to supply `namespace`/`actor_id`/`visible_namespaces` on a mapped transport. | Request |
211//! | `peer_class_denied`          | A parsed operation names a verb outside the mapped class allowlist.                             | Request |
212//! | `subscription_denied`        | A `subscribe` names a topic outside the mapped class's allowed-topic set.                       | Request |
213//! | `already_subscribed`         | A `subscribe` names a topic with an already-active subscription on this connection.             | Request |
214//! | `cursor_expired`             | A `subscribe` resume cursor is older than the topic's retention window.                         | Request |
215//! | `in_flight_limit_exceeded`   | A `request` arrives while the per-connection in-flight limit is reached.                        | Request |
216//! | `deadline_exceeded`          | The server abandoned the request at its deadline.                                               | Request |
217//! | `cancelled`                  | The request was terminated by a `cancel` frame before normal completion.                        | Request |
218//! | `shutting_down`              | The server is draining and refuses new work.                                                    | Request |
219//! | `internal`                   | An unclassified server-side transport failure — also the fallback for an unrecognized code.     | Request |
220//!
221//! A **connection-terminal** error is followed by connection close and
222//! carries no operation id. A **request-terminal** error terminates only
223//! the operation id it echoes; the connection stays usable. That pairing
224//! is enforced at encode AND decode time: an `error` frame whose id
225//! presence contradicts its code's terminal scope is rejected, never
226//! represented and never emitted. The check lives in
227//! [`frame::Frame`]'s serde visitor, so EVERY decode path agrees — the
228//! codec's `decode_payload` path (which re-classifies the
229//! rejection into the typed [`codec::CodecError::InconsistentErrorScope`])
230//! AND a direct `serde_json::from_str::<Frame>`. The check covers the
231//! same wire invariants in `Frame`'s serializer, so direct
232//! `serde_json::to_vec::<Frame>` cannot bypass the encode-side validation.
233//! On decode, known codes obey their fixed id/scope pairing. Under ADR-137
234//! Amendment 1 Decision 5, an unknown code is accepted only with a non-empty
235//! operation id: it falls back to `internal` (request-terminal), retains its
236//! raw string in `unrecognized_code`, and cannot be re-encoded. An unknown
237//! code without an operation id is malformed and connection-terminal at the
238//! decode boundary; it is never returned as a fallback frame.
239//!
240//! **Fallback frames are not re-encodable by this relay.** A decoded frame
241//! carrying `unrecognized_code` can be inspected locally, but the encode
242//! path rejects it with [`codec::CodecError::FallbackFrameNotEncodable`]:
243//! re-encoding would emit `internal` and silently discard the newer code
244//! the peer sent, so this crate never corrupts it; the connection remains
245//! healthy. A relay that must pass unknown codes through has to operate on
246//! the raw frame bytes, not on a decoded-and-re-encoded frame. The one
247//! decode-only guarantee the codec path holds over a direct serde decode is
248//! the finer-grained
249//! [`codec::CodecError::UnknownFrameKind`] classification for a `"kind"`
250//! outside the closed set; every other decode-time rule — strict field
251//! rejection, the id/scope pairing, and the unknown-code diagnostic — is
252//! enforced identically on both paths.
253//!
254//! The set is
255//! closed within a protocol version: adding a code requires a version bump,
256//! and a client that decodes a code it does not recognize treats it as
257//! `internal` (request-terminal) rather than inventing semantics for it —
258//! [`error::WireErrorCode`] implements this with `#[serde(other)]`.
259//!
260//! ## Versioning and compatibility
261//!
262//! Protocol version numbers ([`version::ProtocolVersion`]) are monotonic
263//! `u32`s. A server supports the current version and at least the
264//! immediately prior version ([`version::SupportedVersions::current`]). A
265//! breaking wire change — a new frame kind, a new wire error code, or a
266//! non-backward-compatible change to an existing frame's fields — is never
267//! introduced within a version number; it requires incrementing the
268//! version and updating this documentation as the normative source.
269//!
270//! ## What this crate does not define
271//!
272//! - Transport (socket binding, TLS/WireGuard, `tailscale whois`, peer
273//!   mapping) — ADR-137's "Transport identity and actor mapping".
274//! - The DSL carried in a `request` frame's `ops` string — ADR-016.
275//! - The per-topic `event` payload catalog — ADR-137's
276//!   "Implementation-phase deliverables".
277//! - Peer-class allowlists and dispatch enforcement — ADR-137's "Peer
278//!   classes and dispatch enforcement".
279
280pub mod client_handshake;
281pub mod codec;
282pub mod error;
283pub mod frame;
284pub mod handshake;
285mod opaque;
286pub mod version;
287
288pub use client_handshake::{
289    ClientHandshakeGate, ClientHandshakeOutcome, ClientHandshakeStartError,
290};
291pub use codec::{
292    decode_frame, decode_frame_with_consumed, encode_frame, encode_frame_with_max, CodecError,
293    FrameCodec, DEFAULT_MAX_FRAME_BYTES,
294};
295pub use error::{TerminalScope, WireErrorCode, WIRE_ERROR_CODES};
296pub use frame::{Cursor, Frame, OperationId, CLIENT_TO_SERVER_KINDS, FRAME_KINDS};
297pub use handshake::{HandshakeGate, HandshakeOutcome, HandshakeSequenceError};
298pub use opaque::OpaqueValue;
299pub use version::{ProtocolVersion, SupportedVersions, SupportedVersionsError, CURRENT_VERSION};