subc_protocol/lib.rs
1//! subc wire contract.
2//!
3//! This crate is the single source of truth for the subc <-> module wire,
4//! shared by subc-core and AFT. It defines the **envelope** (the fixed
5//! 21-byte routing header subc splices on), the canonical subc-generated body
6//! schemas such as [`ErrorBody`], and the capability manifest. JSON-RPC request
7//! and response bodies remain module-owned opaque payloads to subc.
8//!
9//! ## The envelope (locked — see docs/subc-core-architecture.md §4.8)
10//!
11//! ```text
12//! offset size field type purpose
13//! 0 4 len u32 # of BODY bytes after this 21-byte header
14//! 4 1 ver u8 envelope version
15//! 5 1 type u8 frame kind (see FrameType)
16//! 6 1 flags u8 bit0 BINARY · bits1-2 PRIORITY · bit3 LAST · bits4-5 ADMISSION · bit6 DAEMON_ORIGIN · bit7 SUBSCRIPTION
17//! 7 2 channel u16 route = (component, session); 0 = subc itself
18//! 9 4 epoch u32 per-slot binding epoch; 0 on channel 0
19//! 13 8 corr u64 correlation id; CANCEL carries the target call's corr
20//! 21 -> body
21//! ```
22//!
23//! Little-endian (same-machine, native, no byte-swap on the hot path).
24//!
25//! **Frozen prefix (the versioning invariant):** `len` (u32 @ 0) and `ver`
26//! (u8 @ 4) keep fixed meaning + position in *every* future version. A reader
27//! of any version can therefore always read the first 5 bytes, learn `ver`,
28//! look up that version's header length, read the rest, and splice `len` body
29//! bytes. `decode_header` enforces this discipline.
30
31#![forbid(unsafe_code)]
32
33use std::{error::Error, fmt, path::PathBuf};
34
35use serde::{Deserialize, Serialize};
36
37pub use machine_id::{MachineId, MachineIdError};
38
39pub mod call_mode;
40pub mod frame;
41pub mod framed_body;
42pub mod machine_id;
43pub mod manifest;
44pub mod scope;
45pub mod session;
46pub mod tool_call;
47
48/// Canonical error codes emitted by subc.
49///
50/// Error frames remain extensible strings, but these daemon-owned route-open
51/// outcomes need identical spelling across the daemon and SDK retry policies.
52pub mod error_codes {
53 use crate::Flags;
54
55 pub const UNKNOWN_CHANNEL: &str = "unknown_channel";
56 pub const STALE_ROUTE_EPOCH: &str = "stale_route_epoch";
57 /// A module reply exceeds the client connection's whole egress byte budget.
58 /// TERMINAL for this request: the module already received it, and retrying
59 /// unchanged would produce the same oversized reply. The route stays open.
60 pub const FRAME_TOO_LARGE: &str = "frame_too_large";
61 pub const UNKNOWN_MODULE: &str = "unknown_module";
62 pub const MODULE_REMOVED: &str = "module_removed";
63 /// The target module's endpoint is draining for a reload, restart or disable.
64 ///
65 /// On the data plane (an `ERROR` frame answering a `REQUEST` on a bound route)
66 /// this code is a PRE-SEND GUARANTEE: the daemon returns it only when the
67 /// request could not take a route credit because the endpoint is draining,
68 /// and it returns it BEFORE forwarding, so the module never received the
69 /// request. A caller may therefore re-dispatch the same request once the
70 /// route is reopened without risking a duplicated side effect, exactly as it
71 /// may after `unknown_channel`. The daemon keeps this guarantee:
72 /// `supervisor_reload_rejects_new_work_during_drain` asserts the module's
73 /// event journal never records the rejected request. A request the module
74 /// already received is answered by the module (or its route closes with
75 /// `route.closed`), never by this code.
76 pub const MODULE_RELOADING: &str = "module_reloading";
77 pub const MODULE_WARMING: &str = "module_warming";
78 pub const TARGET_UNAVAILABLE: &str = "target_unavailable";
79 /// A flow-scoped route targets a module that does not provide
80 /// either `flow-scopes/v1` or `call-modes/v1`. TERMINAL: decoding `flow_id`
81 /// alone does not promise flow behaviour, and removing it would silently
82 /// change the identity.
83 pub const TARGET_FLOW_UNSUPPORTED: &str = "target_flow_unsupported";
84 /// An agent-run-scoped route targets a module providing neither
85 /// `agent-run-scopes/v1` nor `call-modes/v1`, or a delegating run targets a
86 /// module without `call-modes/v1`. TERMINAL: removing `run_id` or delegation
87 /// would silently change the identity or authority under which the route acts.
88 pub const TARGET_AGENT_RUN_UNSUPPORTED: &str = "target_agent_run_unsupported";
89 pub const MODULE_TIMEOUT: &str = "module_timeout";
90 /// The target module is declared as speaking no subc wire protocol
91 /// (`protocol: "none"` in daemon config), so it has no control lane and can
92 /// never accept a route. The daemon supervises its process and nothing else.
93 ///
94 /// TERMINAL, and deliberately neither of its two neighbours. It is not
95 /// `unknown_module`, which means "no module of this id is registered or
96 /// supervised here" and is likewise terminal; retrying here would storm the
97 /// daemon forever, because the answer is a property of the module's
98 /// declaration rather than of its current state. It is not `module_removed` either: the module is configured,
99 /// running, and supervised. Only an edit to its configuration can change
100 /// this answer, and a caller cannot wait that out.
101 pub const MODULE_NO_PROTOCOL: &str = "module_no_protocol";
102 /// A request field is malformed. The error's `detail.field` names the field
103 /// (for a `route.open`, `role_versions`). TERMINAL: the same request will be
104 /// refused the same way every time, so only a corrected request can succeed.
105 pub const INVALID_REQUEST: &str = "invalid_request";
106
107 /// A `route.open` named a scope whose owner is configured but has not
108 /// synced since this daemon incarnation started. RETRYABLE: after a daemon
109 /// restart a carrier's open can arrive before the owner re-syncs, and the
110 /// carrier waits within its own deadline. See `docs/designs/daemon-scopes.md`.
111 pub const SCOPE_NOT_SYNCED: &str = "scope_not_synced";
112 /// A scoped `route.open` was admitted, but the scope record changed before
113 /// the module's bind committed. Nothing was sent on the route, so the caller
114 /// may re-open against the current record: RETRYABLE.
115 pub const SCOPE_CHANGED: &str = "scope_changed";
116 /// A scoped `route.open` named no `scope_epoch`. Every opener names one,
117 /// the owner included, so an old call can never be carried into a newer
118 /// session that reused the ref. TERMINAL.
119 pub const SCOPE_EPOCH_REQUIRED: &str = "scope_epoch_required";
120 /// A scoped `route.open` named a ref the owner's synced set does not hold,
121 /// or an owner that is not a configured module. TERMINAL.
122 pub const SCOPE_NOT_LIVE: &str = "scope_not_live";
123 /// A scoped `route.open` named a `scope_epoch` that is not the live one, or
124 /// the scope ended between admission and commit. TERMINAL.
125 pub const SCOPE_ENDED: &str = "scope_ended";
126 /// The opener of a scoped `route.open` is neither the scope's owner nor a
127 /// listed carrier, or it is a targeted carrier and the target module is not
128 /// in its list. TERMINAL.
129 pub const SCOPE_NOT_CARRIER: &str = "scope_not_carrier";
130 /// A scope with a bind-proof hash requires every opener, including its
131 /// owner, to present the proof. TERMINAL.
132 pub const SCOPE_BIND_PROOF_REQUIRED: &str = "scope_bind_proof_required";
133 /// The proof is malformed or does not match the scope's hash. TERMINAL.
134 pub const SCOPE_BIND_PROOF_MISMATCH: &str = "scope_bind_proof_mismatch";
135 /// An idle-only epoch/proof replacement found routes, admitted binds or
136 /// connected presence under the live epoch. Per-record refusal. TERMINAL.
137 pub const SCOPE_EPOCH_IN_USE: &str = "scope_epoch_in_use";
138 /// Raised by a carrier, never by the daemon: the daemon does not advertise
139 /// `scopes/v1`, so the carrier fails the call instead of opening an
140 /// unscoped route.
141 pub const SCOPE_UNSUPPORTED: &str = "scope_unsupported";
142
143 /// `scope.sync` or `scope.apply` came from a connection that is not the
144 /// owner's sync authority: another connection of the same launch holds it,
145 /// or this connection's launch is no longer the owner's current one (a
146 /// blue/green swap candidate before cutover, or an incumbent after it).
147 pub const SCOPE_SYNC_NOT_AUTHORITY: &str = "scope_sync_not_authority";
148 /// `scope.apply` came from a connection that has not taken sync authority
149 /// through an accepted full `scope.sync`. The whole call changes nothing.
150 pub const SCOPE_SYNC_REQUIRED: &str = "scope_sync_required";
151 /// `scope.sync` or `scope.apply` carried a generation no larger than the last
152 /// one the authority accepted. The whole call is refused and nothing changes.
153 pub const SCOPE_SYNC_STALE: &str = "scope_sync_stale";
154 /// `scope.sync` or `scope.apply` exceeds the owner's live-scope limit.
155 /// The whole call is refused and nothing changes.
156 pub const SCOPE_LIVE_LIMIT_EXCEEDED: &str = "scope_live_limit_exceeded";
157 /// One record in a `scope.sync` or `scope.apply` carried more attribute bytes
158 /// than a scope may hold. The whole call is refused and nothing changes.
159 pub const SCOPE_ATTRIBUTES_TOO_LARGE: &str = "scope_attributes_too_large";
160
161 // Per-record refusals: each is reported against one record in the
162 // `scope.sync` or `scope.apply` reply. A refusal itself does not change the
163 // ref or undo expiry processing; other records in the call still apply.
164
165 /// The record lowers the `scope_epoch` the daemon holds for its ref.
166 pub const SCOPE_EPOCH_REGRESSED: &str = "scope_epoch_regressed";
167 /// The record names an `(owner, ref, scope_epoch)` that already ended in
168 /// this daemon incarnation; an ended session cannot come back.
169 pub const SCOPE_EPOCH_ENDED: &str = "scope_epoch_ended";
170 /// The record's deadline has passed, or this ref at this epoch was ended by
171 /// expiry and its tombstone is still held. The same session epoch cannot
172 /// return.
173 pub const SCOPE_EXPIRED: &str = "scope_expired";
174 /// The record adds, removes or changes the deadline of a live scope at the
175 /// same epoch. A different deadline requires a new session epoch.
176 pub const SCOPE_EXPIRY_IMMUTABLE: &str = "scope_expiry_immutable";
177 /// The record's deadline is more than `scope::MAX_SCOPE_EXPIRY_AHEAD_MS`
178 /// ahead of the daemon's current Unix wall clock.
179 pub const SCOPE_EXPIRY_TOO_FAR: &str = "scope_expiry_too_far";
180 /// The record changes `kind` at the same `scope_epoch`.
181 pub const SCOPE_KIND_CHANGED: &str = "scope_kind_changed";
182 pub const INVALID_WORKDIR: &str = "invalid_workdir";
183 pub const SCOPE_WORKDIR_CHANGED: &str = "scope_workdir_changed";
184 pub const SCOPE_PROJECT_CHANGED: &str = "scope_project_changed";
185 /// The record sets authority-controlled attributes and its owner is not
186 /// listed in `scope_authority_owners`, or combines `on_behalf_of_agent` with
187 /// `agent_id`, `delegates`, `flow_id` or `run_id`.
188 pub const SCOPE_ATTRIBUTE_NOT_PERMITTED: &str = "scope_attribute_not_permitted";
189 /// The record's parent link is not permitted: the parent's owner has synced
190 /// and the parent is not live at the named epoch, the syncing owner is
191 /// neither the parent's owner nor in its `child_owners`, or the link would
192 /// close a cycle.
193 pub const SCOPE_PARENT_NOT_PERMITTED: &str = "scope_parent_not_permitted";
194 /// A targeted carrier entry lists no target modules, or more than
195 /// `scope::MAX_CARRIER_TARGETS`.
196 pub const SCOPE_CARRIER_TARGETS_INVALID: &str = "scope_carrier_targets_invalid";
197 /// The record sets `delegates` without an `agent_id` to delegate.
198 pub const SCOPE_DELEGATES_WITHOUT_AGENT: &str = "scope_delegates_without_agent";
199 /// The record sets `run_id` without `agent_id`, the agent this run is on
200 /// behalf of.
201 pub const SCOPE_RUN_ID_WITHOUT_AGENT: &str = "scope_run_id_without_agent";
202 /// The record sets both `run_id` and `flow_id`; a run scope is not a flow scope.
203 pub const SCOPE_RUN_ID_WITH_FLOW_ID: &str = "scope_run_id_with_flow_id";
204 /// Legacy refusal for a record setting `run_id` with `delegates`.
205 /// No longer emitted by validation: run records may delegate, and route
206 /// admission instead requires a target providing `call-modes/v1`.
207 pub const SCOPE_RUN_ID_DELEGATES: &str = "scope_run_id_delegates";
208
209 /// An `operator.confirm` was declined or withdrawn. `detail.reason` is
210 /// `person`, `backoff`, `route_closed`, `module_closed` or `caller_cancelled`.
211 pub const OPERATOR_DECLINED: &str = "operator_declined";
212 /// An `operator.confirm` could not prompt or complete. `detail.reason` is
213 /// `no_presence`, `timeout`, `module_limit`, `queue_full`, `queue_wait`,
214 /// `provider_stuck`, `unsupported_platform` or `provider_error`.
215 pub const OPERATOR_PRESENCE_UNAVAILABLE: &str = "operator_presence_unavailable";
216 /// The summary of an `operator.confirm` breaks the daemon's summary rules.
217 pub const OPERATOR_SUMMARY_INVALID: &str = "operator_summary_invalid";
218 /// An `operator.confirm` is not from a nonce-proven module connection for
219 /// an open route with a verified opener on that connection.
220 pub const OPERATOR_REQUEST_NOT_PERMITTED: &str = "operator_request_not_permitted";
221
222 /// Whether a `route.open` refusal carrying `code` may be retried in place
223 /// within the caller's deadline, or is terminal for the target as named.
224 ///
225 /// This lives beside the codes because every consumer with its own
226 /// connection layer needs the same answer: a copied list breaks loudly on
227 /// a renamed code and silently on an added one. The SDKs call this; the
228 /// golden `decision_tables.json` (`route_open_retryable`) is the record
229 /// the daemon and every SDK are tested against, and the test in
230 /// `golden_json.rs` holds this function to it.
231 ///
232 /// Unknown codes are terminal: a refusal this crate has never heard of
233 /// must not be retried on the strength of a match-all arm.
234 ///
235 /// `unknown_module` is terminal: it now means only "no module of this id
236 /// is registered or supervised here" — a typo, or a peer not deployed on
237 /// this host. The daemon reports a configured-but-late target with its own
238 /// retryable codes (`module_warming`, `target_unavailable`), so a caller
239 /// that races an unsupervised module's HELLO owns its own retry; retrying
240 /// in place only papers over that race for one narrow window.
241 pub fn is_retryable_route_open(code: &str) -> bool {
242 if matches!(
243 code,
244 TARGET_FLOW_UNSUPPORTED
245 | TARGET_AGENT_RUN_UNSUPPORTED
246 | SCOPE_BIND_PROOF_REQUIRED
247 | SCOPE_BIND_PROOF_MISMATCH
248 | SCOPE_EPOCH_IN_USE
249 ) {
250 return false;
251 }
252 matches!(
253 code,
254 MODULE_RELOADING
255 | MODULE_WARMING
256 | TARGET_UNAVAILABLE
257 | MODULE_TIMEOUT
258 | SCOPE_NOT_SYNCED
259 | SCOPE_CHANGED
260 )
261 }
262
263 /// Whether the caller should evict this established route, reopen it, and
264 /// resend the request once. Consumers mapping route death to their own
265 /// custody, provider, or suspect verdict keep their own named code lists;
266 /// sharing this predicate for those meanings can change a verdict on a
267 /// protocol bump (prefrontal#59).
268 ///
269 /// Takes envelope flags so the daemon-origin check can be enabled here in
270 /// one place. Phase 2 requires first that every daemon a consumer can meet
271 /// sets DAEMON_ORIGIN on these error frames, both landed and deployed;
272 /// only then may this predicate require the bit. Requiring it sooner makes
273 /// a new SDK against an older daemon stop evicting on a genuine
274 /// `stale_route_epoch` — the failure this predicate is meant to prevent.
275 ///
276 /// The daemon emits these codes in `RouterError::to_error_frame` at
277 /// `crates/subc-daemon/src/router.rs` (UnknownChannel and StaleRouteEpoch).
278 pub fn is_established_route_dead(_flags: Flags, code: &str) -> bool {
279 matches!(code, UNKNOWN_CHANNEL | STALE_ROUTE_EPOCH)
280 }
281}
282
283pub use frame::{Frame, FrameBuildError};
284
285/// Why subc is closing a module's client routes.
286#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
287#[serde(rename_all = "snake_case")]
288pub enum RouteCloseReason {
289 Reload,
290 Restart,
291 Disable,
292 Crash,
293 /// A live route became forbidden because newly attested capability metadata
294 /// matched its supervised opening module's deny edge.
295 CapabilityDenied,
296 /// The route's scope ended: it expired, its owner ended it, or replaced it
297 /// with a higher `scope_epoch` (a new session under the same ref).
298 ScopeEnded,
299 /// The route's opener is no longer a listed carrier of its scope, or the
300 /// route's target was removed from that carrier's target list.
301 ScopeCarrierRemoved,
302 /// The scope's `delegates` went from true to false, or its `agent_id`,
303 /// `on_behalf_of_agent`, `flow_id` or `run_id` changed.
304 ScopeDelegationChanged,
305 /// The scope's parent ended, so its stamp no longer names a live parent.
306 ScopeParentEnded,
307}
308
309/// Per-route bind identity shared by client-facing and module-facing control.
310///
311/// EVERY FIELD HERE IS CLIENT-SUPPLIED AND UNATTESTED. The daemon canonicalizes
312/// `project_root` as a path but does not verify that the caller has any relation
313/// to it, and `harness`, `session`, and `project_id` are strings the caller chose.
314/// A client holding the connection key can present any values it likes.
315///
316/// This sits directly above `Principal`, which is the opposite: stamped BY the
317/// daemon from a launch nonce it minted. The two travel together on every
318/// `route.bind`, so a module reading them side by side is reading one fact it can
319/// trust and four it cannot. THE DISTINCTION IS INVISIBLE FROM THE TYPES, which
320/// is why it is written here.
321///
322/// So these fields are for SCOPING AND ATTRIBUTION -- which project's state to
323/// open, which session to thread, what to log -- and never for authorization. A
324/// module that grants capability on `harness` or trusts `project_root` to bound
325/// what a caller may reach has built an authorization check on a value the caller
326/// controls. Gate on `Principal` instead, and where a module needs a caller fact
327/// subc does not stamp, it must establish that fact itself rather than believe
328/// this struct.
329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
330#[non_exhaustive]
331pub struct BindIdentity {
332 pub project_root: PathBuf,
333 pub harness: String,
334 pub session: String,
335 /// The entorhinal-registered project id (`pj-…`) for `project_root`, when
336 /// the root is a registered project. Aliases count as registered projects;
337 /// implicit roots do not. Absent means "no stable id, key on the triple",
338 /// not "unknown".
339 ///
340 /// A producer sends the id on every bind of a session or on none. A producer
341 /// that alternates between `Some(id)` and `None` across binds silently forks
342 /// the consumer's lineage into separate stores, with no error at either end.
343 /// Therefore, a producer that cannot answer consistently must answer `None`
344 /// consistently.
345 ///
346 /// Resolve this at most once per session, before its first bind, and persist
347 /// the outcome with the session. ALF's resolver has real `Resolved`, `Unavailable`,
348 /// and `Disabled` outcomes: if unavailable at cold start is re-resolved on a
349 /// later bind, the session can alternate from `None` to `Some(id)`. Send only
350 /// registered or alias resolutions, never implicit, unavailable, or disabled
351 /// fallback ids.
352 #[serde(default, skip_serializing_if = "Option::is_none")]
353 pub project_id: Option<String>,
354}
355
356impl BindIdentity {
357 /// Constructs an identity with no registered project id.
358 ///
359 /// Use this instead of a struct literal so future additive identity fields do
360 /// not force construction-site migrations across the fleet.
361 pub fn new(
362 project_root: impl Into<PathBuf>,
363 harness: impl Into<String>,
364 session: impl Into<String>,
365 ) -> Self {
366 Self {
367 project_root: project_root.into(),
368 harness: harness.into(),
369 session: session.into(),
370 project_id: None,
371 }
372 }
373}
374
375/// Caller fact stamped by subc on each route.bind relayed to a module.
376#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
377#[serde(tag = "kind", rename_all = "snake_case")]
378pub enum Principal {
379 /// A daemon-spawned module proved possession of its launch nonce.
380 Reserved { module_id: String },
381 /// No consumer identity was presented; the caller is a direct key-holder.
382 Direct,
383 /// Reserved vocabulary for a future degraded/no-key-auth mode.
384 Unverified,
385}
386
387/// Explicit target for a route open/bind operation.
388///
389/// RouteTarget.kind ↔ ProviderRole mapping:
390///
391/// | RouteTarget.kind | required ProviderRole | disambiguator |
392/// |---|---|---|
393/// | `tool_provider` | `ToolProvider` | v1: ≤1 per module |
394/// | `management_surface` | `ManagementSurface` | v1: ≤1 per module |
395/// | `internal_service` | `InternalService` | `service_id` (multiple allowed) |
396///
397/// `ProviderRole::PipelineStage` is intentionally unroutable; pipeline modules
398/// are wired by an orchestrator rather than opened directly by clients.
399#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
400#[serde(tag = "kind", rename_all = "snake_case")]
401pub enum RouteTarget {
402 ToolProvider {
403 module_id: String,
404 },
405 ManagementSurface {
406 module_id: String,
407 },
408 InternalService {
409 module_id: String,
410 service_id: String,
411 },
412}
413
414/// Envelope protocol version this build speaks.
415pub const PROTOCOL_VERSION: u8 = 2;
416
417/// The version of THIS crate (`subc-protocol`) as compiled into the linking
418/// binary — the fleet's shared wire-vocabulary version, and the value
419/// `ManifestProvenance.wire_crate_version` declares. Not the version of a
420/// module's own envelope or payload crates: those are different numbering
421/// spaces, and declaring one here produces a confident wrong answer at any
422/// version gate (insula shipped exactly that before the referent was written
423/// down). `env!` makes it a property of the compiled binary, not of whatever
424/// source tree sits beside it at run time.
425pub const SUBC_PROTOCOL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
426
427/// Oldest envelope protocol version this build accepts.
428pub const MIN_SUPPORTED_VERSION: u8 = 2;
429
430/// Env var subc sets on each supervised child telling it the module_id it is
431/// supervised under, so it can register under that id.
432pub const SUBC_MODULE_ID_ENV: &str = "SUBC_MODULE_ID";
433
434/// Env var subc sets, on each spawn of a `reserved` module only, to a fresh
435/// one-time launch nonce. The child echoes it in `ModuleHelloBody::launch_nonce`;
436/// subc accepts a reserved module_id's HELLO only when the nonce matches the one it
437/// last injected for that id. Non-reserved modules never receive it.
438pub const SUBC_LAUNCH_NONCE_ENV: &str = "SUBC_LAUNCH_NONCE";
439
440/// Fixed header length for `PROTOCOL_VERSION` 2.
441pub const HEADER_LEN: usize = 21;
442
443/// Bytes of the frozen prefix (`len` u32 + `ver` u8) that are stable across
444/// every envelope version. A reader needs only these to learn the version and
445/// thus the full header length.
446pub const FROZEN_PREFIX_LEN: usize = 5;
447
448/// Maximum frame body accepted before allocation.
449///
450/// This 64 MiB starting cap prevents a malformed header from forcing an
451/// unbounded allocation. Future protocol versions can negotiate or encode a
452/// different cap while preserving the frozen prefix.
453pub const MAX_FRAME_BODY_LEN: u32 = 64 * 1024 * 1024;
454
455/// Largest frame, `HEADER_LEN` included, that the daemon delivers from a module
456/// to a client: a reply, stream frame, error, reverse request or push. A module
457/// sizes what it sends to a client against this, not against
458/// `MAX_FRAME_BODY_LEN`.
459///
460/// A larger module frame is never forwarded to the client. A reply, stream
461/// frame or error that is too large ends its request with a `frame_too_large`
462/// error; a reverse request that is too large is answered with an error to the
463/// module; an unsolicited push that is too large closes the client connection.
464///
465/// Requests from a client to a module are not held to this limit; they are
466/// bounded only by `MAX_FRAME_BODY_LEN`.
467pub const MAX_DELIVERED_FRAME_LEN: usize = 4 * 1024 * 1024;
468
469/// Canonical JSON body for all subc-generated `ERROR` frames.
470///
471/// `detail` is an optional machine-parsable surface for refusals whose remedy
472/// needs more than a code (e.g. a producer-published backoff number, an
473/// observed-vs-configured size pair). Absent detail serializes to nothing, so
474/// bodies without it are byte-identical to the pre-detail wire and older
475/// readers simply never see the field. Producers document each code's detail
476/// fields where the code is defined; `detail` must never carry secrets.
477#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
478pub struct ErrorBody {
479 pub code: String,
480 pub message: String,
481 #[serde(default, skip_serializing_if = "Option::is_none")]
482 pub detail: Option<serde_json::Value>,
483}
484
485impl ErrorBody {
486 /// A detail-less error body; the common case.
487 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
488 Self {
489 code: code.into(),
490 message: message.into(),
491 detail: None,
492 }
493 }
494
495 /// Attach a machine-parsable detail object to this error.
496 pub fn with_detail(mut self, detail: serde_json::Value) -> Self {
497 self.detail = Some(detail);
498 self
499 }
500}
501
502/// Module-to-subc `HELLO` body used during module registration.
503#[derive(Clone, Serialize, Deserialize, PartialEq)]
504pub struct ModuleHelloBody {
505 pub manifest: manifest::ModuleManifest,
506 pub protocol_ver: u8,
507 #[serde(default)]
508 pub control_ops: Option<Vec<String>>,
509 /// One-time launch nonce, echoed back from the `SUBC_LAUNCH_NONCE` environment
510 /// variable the daemon injected when it spawned this process. Only a daemon-spawned
511 /// process for a `reserved` module receives a nonce; subc accepts a reserved
512 /// `module_id`'s HELLO only when this matches the nonce it last injected for that
513 /// id, so a different process cannot register as a reserved module while the real
514 /// one is down/restarting. Absent (`serde(default)`) for non-reserved modules and
515 /// self-connecting providers, which are never nonce-checked.
516 #[serde(default, skip_serializing_if = "Option::is_none")]
517 pub launch_nonce: Option<String>,
518}
519
520// Hand-written so the launch nonce is never printed. The nonce is the credential
521// that attributes a connection to a supervised module, and a derived Debug would
522// write it into any log line or panic message that formats this value. Same
523// reasoning as ConnectionInfo's Debug in subc-transport.
524impl fmt::Debug for ModuleHelloBody {
525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526 f.debug_struct("ModuleHelloBody")
527 .field("manifest", &self.manifest)
528 .field("protocol_ver", &self.protocol_ver)
529 .field("control_ops", &self.control_ops)
530 .field(
531 "launch_nonce",
532 &self
533 .launch_nonce
534 .as_ref()
535 .map(|nonce| format!("<{} bytes redacted>", nonce.len())),
536 )
537 .finish()
538 }
539}
540
541/// subc-to-module `HELLO_ACK` body used during module registration.
542#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
543pub struct ModuleHelloAckBody {
544 pub negotiated_ver: u8,
545 pub subc_ops: Vec<String>,
546 pub subc_capabilities: Vec<String>,
547 /// The module's resolved storage descriptor, when the daemon's central config
548 /// configures managed storage. Carried opaquely here (subc-protocol stays a
549 /// thin wire crate with no storage/database dependency); a module that uses
550 /// managed storage deserializes it into `cortexkit_store_types::StorageDescriptor`
551 /// and hands it to `cortexkit-store`. Absent when no storage is configured, and
552 /// `serde(default)` so an older module simply ignores it.
553 #[serde(default, skip_serializing_if = "Option::is_none")]
554 pub storage: Option<serde_json::Value>,
555 /// The daemon's machine id (see [`MachineId`]): a name for this machine,
556 /// never an authority. Nothing may admit a peer, grant trust or skip a check
557 /// because two messages carry the same value.
558 ///
559 /// Carried as a plain string so one malformed value cannot fail the whole
560 /// registration reply; a module validates it with [`MachineId::parse`].
561 /// Absent from a daemon that predates the machine id, which a module must
562 /// read as exactly that, never as "no machine" and never as a reason to mint
563 /// its own.
564 #[serde(default, skip_serializing_if = "Option::is_none")]
565 pub machine_id: Option<String>,
566}
567
568/// Frame kind (`type` byte at offset 5).
569///
570/// `CANCEL`, `PING`, `PONG`, and `GOODBYE` are pure-header frames (`len == 0`);
571/// only `HELLO`/`HELLO_ACK` and the RPC payloads carry bodies.
572#[derive(Debug, Clone, Copy, PartialEq, Eq)]
573#[repr(u8)]
574pub enum FrameType {
575 Request = 0,
576 Response = 1,
577 Push = 2,
578 StreamData = 3,
579 StreamEnd = 4,
580 Error = 5,
581 Cancel = 6,
582 Ping = 7,
583 Pong = 8,
584 Hello = 9,
585 HelloAck = 10,
586 Goodbye = 11,
587}
588
589impl FrameType {
590 /// Map the raw `type` byte to a `FrameType`, or `None` if unknown.
591 pub fn from_u8(b: u8) -> Option<Self> {
592 Some(match b {
593 0 => Self::Request,
594 1 => Self::Response,
595 2 => Self::Push,
596 3 => Self::StreamData,
597 4 => Self::StreamEnd,
598 5 => Self::Error,
599 6 => Self::Cancel,
600 7 => Self::Ping,
601 8 => Self::Pong,
602 9 => Self::Hello,
603 10 => Self::HelloAck,
604 11 => Self::Goodbye,
605 _ => return None,
606 })
607 }
608
609 pub fn is_pure_header(self) -> bool {
610 matches!(self, Self::Cancel | Self::Ping | Self::Pong | Self::Goodbye)
611 }
612}
613
614/// Scheduling priority carried in `flags` bits 1-2. subc schedules on this
615/// without parsing the body.
616#[derive(Debug, Clone, Copy, PartialEq, Eq)]
617#[repr(u8)]
618pub enum Priority {
619 Passive = 0,
620 Interactive = 1,
621 Background = 2,
622}
623
624impl Priority {
625 fn from_bits(bits: u8) -> Option<Self> {
626 Some(match bits {
627 0 => Self::Passive,
628 1 => Self::Interactive,
629 2 => Self::Background,
630 _ => return None,
631 })
632 }
633}
634
635/// Admission behavior carried in `flags` bits 4-5.
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
637#[repr(u8)]
638pub enum AdmissionClass {
639 Normal = 0,
640 Expedite = 1,
641 Sheddable = 2,
642}
643
644impl AdmissionClass {
645 fn from_bits(bits: u8) -> Option<Self> {
646 Some(match bits {
647 0 => Self::Normal,
648 1 => Self::Expedite,
649 2 => Self::Sheddable,
650 _ => return None,
651 })
652 }
653}
654
655const FLAG_BINARY: u8 = 0b0000_0001; // bit 0
656const FLAG_PRIORITY_MASK: u8 = 0b0000_0110; // bits 1-2
657const FLAG_PRIORITY_SHIFT: u8 = 1;
658const FLAG_LAST: u8 = 0b0000_1000; // bit 3
659const FLAG_ADMISSION_MASK: u8 = 0b0011_0000; // bits 4-5
660const FLAG_ADMISSION_SHIFT: u8 = 4;
661pub const FLAG_DAEMON_ORIGIN: u8 = 0b0100_0000;
662/// A request credit the client explicitly declares as a held-open subscription.
663pub const FLAG_SUBSCRIPTION: u8 = 0b1000_0000;
664
665/// The `flags` byte (offset 6): binary, priority, last, admission, daemon origin, subscription.
666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
667pub struct Flags(pub u8);
668
669impl Flags {
670 /// Build flags with the default [`AdmissionClass::Normal`] class.
671 pub fn new(binary: bool, priority: Priority, last: bool) -> Self {
672 let mut b = 0u8;
673 if binary {
674 b |= FLAG_BINARY;
675 }
676 b |= (priority as u8) << FLAG_PRIORITY_SHIFT;
677 if last {
678 b |= FLAG_LAST;
679 }
680 Flags(b)
681 }
682
683 /// Return these flags with a typed admission class.
684 pub fn with_admission_class(mut self, admission_class: AdmissionClass) -> Self {
685 self.0 =
686 (self.0 & !FLAG_ADMISSION_MASK) | ((admission_class as u8) << FLAG_ADMISSION_SHIFT);
687 self
688 }
689
690 /// Body is raw bytes (bulk lane) rather than JSON-RPC.
691 pub fn is_binary(self) -> bool {
692 self.0 & FLAG_BINARY != 0
693 }
694
695 /// Final frame of a streamed message.
696 pub fn is_last(self) -> bool {
697 self.0 & FLAG_LAST != 0
698 }
699
700 /// Decode the priority bits, or `None` if they hold a reserved value.
701 pub fn priority(self) -> Option<Priority> {
702 Priority::from_bits((self.0 & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT)
703 }
704
705 /// Decode the admission-class bits, or `None` if they hold `0b11`.
706 pub fn admission_class(self) -> Option<AdmissionClass> {
707 AdmissionClass::from_bits((self.0 & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT)
708 }
709
710 /// True when a request was explicitly opened as a held-open subscription.
711 pub fn is_subscription(self) -> bool {
712 self.0 & FLAG_SUBSCRIPTION != 0
713 }
714
715 /// True when the frame was authored by the daemon.
716 pub fn is_daemon_origin(self) -> bool {
717 self.0 & FLAG_DAEMON_ORIGIN != 0
718 }
719
720 /// Return these flags with daemon origin asserted.
721 pub fn with_daemon_origin(mut self) -> Self {
722 self.0 |= FLAG_DAEMON_ORIGIN;
723 self
724 }
725
726 /// Return these flags with daemon origin cleared.
727 pub fn without_daemon_origin(self) -> Self {
728 Self(self.0 & !FLAG_DAEMON_ORIGIN)
729 }
730}
731
732/// A decoded envelope header. The body is the `len` bytes that follow it.
733#[derive(Debug, Clone, Copy, PartialEq, Eq)]
734pub struct EnvelopeHeader {
735 /// Number of body bytes after the header.
736 pub len: u32,
737 /// Envelope version.
738 pub ver: u8,
739 /// Frame kind.
740 pub ty: FrameType,
741 /// Flag bits.
742 pub flags: Flags,
743 /// Sender-local route slot; 0 is the control channel.
744 pub channel: u16,
745 /// Sender-local binding epoch; 0 is reserved for the control channel.
746 pub epoch: u32,
747 /// Correlation id.
748 pub corr: u64,
749}
750
751impl EnvelopeHeader {
752 /// Serialize the header to its fixed 21-byte little-endian form.
753 pub fn encode(&self) -> [u8; HEADER_LEN] {
754 let mut buf = [0u8; HEADER_LEN];
755 buf[0..4].copy_from_slice(&self.len.to_le_bytes());
756 buf[4] = self.ver;
757 buf[5] = self.ty as u8;
758 buf[6] = self.flags.0;
759 buf[7..9].copy_from_slice(&self.channel.to_le_bytes());
760 buf[9..13].copy_from_slice(&self.epoch.to_le_bytes());
761 buf[13..21].copy_from_slice(&self.corr.to_le_bytes());
762 buf
763 }
764}
765
766/// Why a header could not be decoded.
767#[derive(Debug, Clone, Copy, PartialEq, Eq)]
768pub enum DecodeError {
769 /// Fewer than `FROZEN_PREFIX_LEN` bytes — cannot even read `len`/`ver`.
770 TooShortForPrefix { have: usize },
771 /// `ver` is not a version this build understands.
772 UnsupportedVersion { ver: u8 },
773 /// Version known but fewer than its header length is present.
774 TooShortForHeader { have: usize, need: usize },
775 /// `type` byte is not a known `FrameType`.
776 UnknownFrameType { byte: u8 },
777 /// A reserved flag bit is set (retained for older decoder error compatibility).
778 ReservedFlagBits { flags: u8 },
779 /// Priority bits 1-2 hold the reserved value `0b11`.
780 ReservedPriorityBits { flags: u8 },
781 /// Admission bits 4-5 hold the reserved value `0b11`.
782 ReservedAdmissionClass { flags: u8 },
783 /// SHEDDABLE is set on a frame type that must be delivered.
784 SheddableIllegalFrameType { ty: FrameType, flags: u8 },
785 /// Channel 0 carried an epoch other than its reserved epoch 0.
786 NonzeroEpochOnControlChannel { epoch: u32 },
787 /// A pure-header frame declared body bytes.
788 PureHeaderFrameWithBody { ty: FrameType, len: u32 },
789}
790
791impl fmt::Display for DecodeError {
792 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
793 match self {
794 Self::TooShortForPrefix { have } => {
795 write!(f, "header shorter than frozen prefix: have {have} bytes")
796 }
797 Self::UnsupportedVersion { ver } => write!(f, "unsupported envelope version {ver}"),
798 Self::TooShortForHeader { have, need } => {
799 write!(
800 f,
801 "header too short for version: have {have} bytes, need {need}"
802 )
803 }
804 Self::UnknownFrameType { byte } => write!(f, "unknown frame type byte {byte}"),
805 Self::ReservedFlagBits { flags } => {
806 write!(f, "reserved flag bits set in flags 0b{flags:08b}")
807 }
808 Self::ReservedPriorityBits { flags } => {
809 write!(f, "reserved priority bits set in flags 0b{flags:08b}")
810 }
811 Self::ReservedAdmissionClass { flags } => {
812 write!(f, "reserved admission class set in flags 0b{flags:08b}")
813 }
814 Self::SheddableIllegalFrameType { ty, flags } => write!(
815 f,
816 "SHEDDABLE admission class is illegal on {ty:?} in flags 0b{flags:08b}"
817 ),
818 Self::NonzeroEpochOnControlChannel { epoch } => {
819 write!(f, "control channel carried nonzero epoch {epoch}")
820 }
821 Self::PureHeaderFrameWithBody { ty, len } => {
822 write!(
823 f,
824 "pure-header frame {ty:?} declared non-zero body length {len}"
825 )
826 }
827 }
828 }
829}
830
831impl Error for DecodeError {}
832
833/// How many header bytes a given envelope version occupies. Driven by the
834/// frozen prefix: read `ver`, then learn the full header length here.
835fn header_len_for_version(ver: u8) -> Option<usize> {
836 match ver {
837 PROTOCOL_VERSION => Some(HEADER_LEN),
838 _ => None,
839 }
840}
841
842/// Decode an envelope header from the front of `bytes`, following the
843/// frozen-prefix discipline:
844/// 1. need at least the 5-byte prefix to read `len` + `ver`;
845/// 2. dispatch the full header length on `ver`;
846/// 3. need the full header present; then parse the rest.
847///
848/// Never panics on malformed input — returns a typed [`DecodeError`].
849pub fn decode_header(bytes: &[u8]) -> Result<EnvelopeHeader, DecodeError> {
850 if bytes.len() < FROZEN_PREFIX_LEN {
851 return Err(DecodeError::TooShortForPrefix { have: bytes.len() });
852 }
853 let ver = bytes[4];
854 let need = header_len_for_version(ver).ok_or(DecodeError::UnsupportedVersion { ver })?;
855 if bytes.len() < need {
856 return Err(DecodeError::TooShortForHeader {
857 have: bytes.len(),
858 need,
859 });
860 }
861
862 let len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
863 let ty =
864 FrameType::from_u8(bytes[5]).ok_or(DecodeError::UnknownFrameType { byte: bytes[5] })?;
865 let flags = Flags(bytes[6]);
866 if flags.priority().is_none() {
867 return Err(DecodeError::ReservedPriorityBits { flags: bytes[6] });
868 }
869 let admission_class = flags
870 .admission_class()
871 .ok_or(DecodeError::ReservedAdmissionClass { flags: bytes[6] })?;
872 if admission_class == AdmissionClass::Sheddable
873 && !matches!(ty, FrameType::Push | FrameType::StreamData)
874 {
875 return Err(DecodeError::SheddableIllegalFrameType {
876 ty,
877 flags: bytes[6],
878 });
879 }
880 if ty.is_pure_header() && len != 0 {
881 return Err(DecodeError::PureHeaderFrameWithBody { ty, len });
882 }
883 let channel = u16::from_le_bytes([bytes[7], bytes[8]]);
884 let epoch = u32::from_le_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]);
885 if channel == 0 && epoch != 0 {
886 return Err(DecodeError::NonzeroEpochOnControlChannel { epoch });
887 }
888 let corr = u64::from_le_bytes([
889 bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], bytes[20],
890 ]);
891
892 Ok(EnvelopeHeader {
893 len,
894 ver,
895 ty,
896 flags,
897 channel,
898 epoch,
899 corr,
900 })
901}
902
903#[cfg(test)]
904mod tests {
905 use super::*;
906
907 fn hdr(len: u32, ty: FrameType, flags: Flags, channel: u16, corr: u64) -> EnvelopeHeader {
908 hdr_with_epoch(len, ty, flags, channel, u32::from(channel != 0), corr)
909 }
910
911 fn hdr_with_epoch(
912 len: u32,
913 ty: FrameType,
914 flags: Flags,
915 channel: u16,
916 epoch: u32,
917 corr: u64,
918 ) -> EnvelopeHeader {
919 EnvelopeHeader {
920 len,
921 ver: PROTOCOL_VERSION,
922 ty,
923 flags,
924 channel,
925 epoch,
926 corr,
927 }
928 }
929
930 /// Modules size their replies against this limit and the TypeScript and
931 /// Swift clients mirror it, so changing it must be a deliberate edit here
932 /// as well as in the constant.
933 #[test]
934 fn max_delivered_frame_len_is_four_mebibytes_including_the_header() {
935 assert_eq!(MAX_DELIVERED_FRAME_LEN, 4_194_304);
936 }
937
938 #[test]
939 fn bind_identity_with_project_id_round_trips_json() {
940 let mut identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
941 identity.project_id = Some("pj-a1b2c3d4".to_string());
942
943 let encoded = serde_json::to_vec(&identity).unwrap();
944 let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
945
946 assert_eq!(decoded, identity);
947 }
948
949 #[test]
950 fn bind_identity_without_project_id_round_trips_json() {
951 let identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
952
953 let encoded = serde_json::to_vec(&identity).unwrap();
954 let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
955
956 assert_eq!(decoded, identity);
957 }
958
959 #[test]
960 fn legacy_bind_identity_without_project_id_decodes() {
961 let decoded: BindIdentity = serde_json::from_value(serde_json::json!({
962 "project_root": "/tmp/project",
963 "harness": "opencode",
964 "session": "session-1"
965 }))
966 .unwrap();
967
968 assert_eq!(decoded.project_id, None);
969 }
970
971 #[test]
972 fn bind_identity_none_omits_project_id_instead_of_serializing_null() {
973 let encoded =
974 serde_json::to_value(BindIdentity::new("/tmp/project", "opencode", "session-1"))
975 .unwrap();
976
977 assert!(encoded.get("project_id").is_none());
978 }
979
980 #[test]
981 fn wire_crate_version_is_a_numeric_three_component_version() {
982 let components = SUBC_PROTOCOL_CRATE_VERSION.split('.').collect::<Vec<_>>();
983
984 assert!(!SUBC_PROTOCOL_CRATE_VERSION.is_empty());
985 assert_eq!(components.len(), 3);
986 assert!(components
987 .iter()
988 .all(|component| !component.is_empty() && component.parse::<u64>().is_ok()));
989 }
990
991 #[test]
992 fn route_target_variants_round_trip_json() {
993 let targets = [
994 RouteTarget::ToolProvider {
995 module_id: "aft".to_string(),
996 },
997 RouteTarget::ManagementSurface {
998 module_id: "memory".to_string(),
999 },
1000 RouteTarget::InternalService {
1001 module_id: "bus".to_string(),
1002 service_id: "dm".to_string(),
1003 },
1004 ];
1005
1006 for target in targets {
1007 let encoded = serde_json::to_vec(&target).unwrap();
1008 let decoded: RouteTarget = serde_json::from_slice(&encoded).unwrap();
1009 assert_eq!(decoded, target);
1010 }
1011 }
1012
1013 #[test]
1014 fn error_body_round_trips_json() {
1015 let body = ErrorBody {
1016 code: "config_divergence".to_string(),
1017 message: "active config differs".to_string(),
1018 detail: None,
1019 };
1020
1021 let encoded = serde_json::to_vec(&body).unwrap();
1022 let decoded: ErrorBody = serde_json::from_slice(&encoded).unwrap();
1023
1024 assert_eq!(decoded, body);
1025 }
1026
1027 #[test]
1028 fn round_trip_request() {
1029 let h = hdr(
1030 1234,
1031 FrameType::Request,
1032 Flags::new(false, Priority::Interactive, false),
1033 42,
1034 0xDEAD_BEEF_0000_0001,
1035 );
1036 let decoded = decode_header(&h.encode()).unwrap();
1037 assert_eq!(h, decoded);
1038 }
1039
1040 #[test]
1041 fn round_trip_all_frame_types() {
1042 for b in 0u8..=11 {
1043 let ty = FrameType::from_u8(b).unwrap();
1044 let h = hdr(0, ty, Flags::new(false, Priority::Passive, false), 0, 0);
1045 assert_eq!(decode_header(&h.encode()).unwrap().ty, ty);
1046 }
1047 }
1048
1049 #[test]
1050 fn pure_header_frame_has_zero_len() {
1051 // CANCEL carries only header (len = 0) + the target corr.
1052 let h = hdr(
1053 0,
1054 FrameType::Cancel,
1055 Flags::new(false, Priority::Passive, false),
1056 7,
1057 99,
1058 );
1059 let d = decode_header(&h.encode()).unwrap();
1060 assert_eq!(d.len, 0);
1061 assert_eq!(d.corr, 99);
1062 }
1063
1064 #[test]
1065 fn flags_round_trip() {
1066 let f = Flags::new(true, Priority::Background, true)
1067 .with_admission_class(AdmissionClass::Expedite);
1068 assert!(f.is_binary());
1069 assert!(f.is_last());
1070 assert_eq!(f.priority(), Some(Priority::Background));
1071 assert_eq!(f.admission_class(), Some(AdmissionClass::Expedite));
1072 let h = hdr(8, FrameType::StreamData, f, 1, 1);
1073 assert_eq!(decode_header(&h.encode()).unwrap().flags, f);
1074 }
1075
1076 #[test]
1077 fn daemon_origin_flags_decode_and_round_trip() {
1078 let old = hdr(0, FrameType::Error, Flags(0), 7, 1);
1079 let old_decoded = decode_header(&old.encode()).unwrap();
1080 assert!(!old_decoded.flags.is_daemon_origin());
1081
1082 let daemon = hdr(0, FrameType::Error, Flags(0).with_daemon_origin(), 7, 1);
1083 let daemon_decoded = decode_header(&daemon.encode()).unwrap();
1084 assert!(daemon_decoded.flags.is_daemon_origin());
1085 assert_eq!(daemon_decoded.flags.without_daemon_origin(), Flags(0));
1086 assert!(Flags(0).with_daemon_origin().is_daemon_origin());
1087 }
1088
1089 #[test]
1090 fn little_endian_and_frozen_prefix_layout() {
1091 let h = hdr_with_epoch(
1092 0x0403_0201,
1093 FrameType::Request,
1094 Flags(0),
1095 0x0605,
1096 0x0a09_0807,
1097 0x1211_100f_0e0d_0c0b,
1098 );
1099 let buf = h.encode();
1100 assert_eq!(&buf[0..4], &[1, 2, 3, 4]);
1101 assert_eq!(buf[4], PROTOCOL_VERSION);
1102 assert_eq!(&buf[7..9], &[5, 6]);
1103 assert_eq!(&buf[9..13], &[7, 8, 9, 10]);
1104 assert_eq!(&buf[13..21], &[11, 12, 13, 14, 15, 16, 17, 18]);
1105 assert_eq!(buf.len(), HEADER_LEN);
1106 }
1107
1108 #[test]
1109 fn reject_too_short_for_prefix() {
1110 assert_eq!(
1111 decode_header(&[0, 0, 0, 0]),
1112 Err(DecodeError::TooShortForPrefix { have: 4 })
1113 );
1114 }
1115
1116 #[test]
1117 fn reject_too_short_for_header() {
1118 // Valid 5-byte prefix but the v2 header is truncated.
1119 let mut b = [0u8; 10];
1120 b[4] = PROTOCOL_VERSION;
1121 assert_eq!(
1122 decode_header(&b),
1123 Err(DecodeError::TooShortForHeader {
1124 have: 10,
1125 need: HEADER_LEN
1126 })
1127 );
1128 }
1129
1130 #[test]
1131 fn reject_unsupported_version() {
1132 let mut b = [0u8; HEADER_LEN];
1133 b[4] = 1;
1134 assert_eq!(
1135 decode_header(&b),
1136 Err(DecodeError::UnsupportedVersion { ver: 1 })
1137 );
1138 }
1139
1140 #[test]
1141 fn reject_unknown_frame_type() {
1142 let mut b = [0u8; HEADER_LEN];
1143 b[4] = PROTOCOL_VERSION;
1144 b[5] = 99;
1145 assert_eq!(
1146 decode_header(&b),
1147 Err(DecodeError::UnknownFrameType { byte: 99 })
1148 );
1149 }
1150
1151 #[test]
1152 fn subscription_flag_decodes_and_tags_the_request() {
1153 let mut b = [0u8; HEADER_LEN];
1154 b[4] = PROTOCOL_VERSION;
1155 b[5] = FrameType::Request as u8;
1156 b[6] = FLAG_SUBSCRIPTION;
1157 let decoded = decode_header(&b).unwrap();
1158 assert!(decoded.flags.is_subscription());
1159 }
1160
1161 #[test]
1162 fn reject_reserved_priority_bits() {
1163 let mut b = [0u8; HEADER_LEN];
1164 b[4] = PROTOCOL_VERSION;
1165 b[5] = FrameType::Request as u8;
1166 b[6] = 0b0000_0110; // priority bits 1-2 are reserved value 0b11
1167 assert_eq!(
1168 decode_header(&b),
1169 Err(DecodeError::ReservedPriorityBits { flags: 0b0000_0110 })
1170 );
1171 }
1172
1173 #[test]
1174 fn reject_pure_header_frame_with_body_len() {
1175 let h = hdr(
1176 1,
1177 FrameType::Ping,
1178 Flags::new(false, Priority::Passive, false),
1179 0,
1180 1,
1181 );
1182 assert_eq!(
1183 decode_header(&h.encode()),
1184 Err(DecodeError::PureHeaderFrameWithBody {
1185 ty: FrameType::Ping,
1186 len: 1
1187 })
1188 );
1189 }
1190
1191 #[test]
1192 fn epoch_boundaries_round_trip() {
1193 for (channel, epoch) in [(0, 0), (1, 1), (u16::MAX, u32::MAX)] {
1194 let h = hdr_with_epoch(
1195 0,
1196 FrameType::Request,
1197 Flags::new(false, Priority::Passive, false),
1198 channel,
1199 epoch,
1200 9,
1201 );
1202 assert_eq!(decode_header(&h.encode()).unwrap(), h);
1203 }
1204 }
1205
1206 #[test]
1207 fn admission_classes_accept_three_values_and_reject_reserved_value() {
1208 for (ty, admission_class) in [
1209 (FrameType::Request, AdmissionClass::Normal),
1210 (FrameType::Request, AdmissionClass::Expedite),
1211 (FrameType::Push, AdmissionClass::Sheddable),
1212 (FrameType::StreamData, AdmissionClass::Sheddable),
1213 ] {
1214 let flags = Flags::new(false, Priority::Interactive, false)
1215 .with_admission_class(admission_class);
1216 let h = hdr(0, ty, flags, 1, 2);
1217 assert_eq!(decode_header(&h.encode()).unwrap().flags, flags);
1218 }
1219
1220 let mut h = hdr(
1221 0,
1222 FrameType::Push,
1223 Flags::new(false, Priority::Passive, false),
1224 1,
1225 2,
1226 )
1227 .encode();
1228 h[6] |= 0b0011_0000;
1229 assert_eq!(
1230 decode_header(&h),
1231 Err(DecodeError::ReservedAdmissionClass { flags: h[6] })
1232 );
1233 }
1234
1235 #[test]
1236 fn sheddable_rejected_on_every_illegal_frame_type() {
1237 let flags = Flags::new(false, Priority::Passive, false)
1238 .with_admission_class(AdmissionClass::Sheddable);
1239 for ty in [
1240 FrameType::Request,
1241 FrameType::Response,
1242 FrameType::StreamEnd,
1243 FrameType::Error,
1244 FrameType::Cancel,
1245 FrameType::Ping,
1246 FrameType::Pong,
1247 FrameType::Hello,
1248 FrameType::HelloAck,
1249 FrameType::Goodbye,
1250 ] {
1251 let h = hdr(0, ty, flags, 1, 2);
1252 assert_eq!(
1253 decode_header(&h.encode()),
1254 Err(DecodeError::SheddableIllegalFrameType { ty, flags: flags.0 })
1255 );
1256 }
1257 }
1258
1259 #[test]
1260 fn nonzero_epoch_on_control_channel_is_rejected() {
1261 let h = hdr_with_epoch(
1262 0,
1263 FrameType::Request,
1264 Flags::new(false, Priority::Passive, false),
1265 0,
1266 u32::MAX,
1267 2,
1268 );
1269 assert_eq!(
1270 decode_header(&h.encode()),
1271 Err(DecodeError::NonzeroEpochOnControlChannel { epoch: u32::MAX })
1272 );
1273 }
1274}
1275
1276#[cfg(test)]
1277mod launch_nonce_redaction_tests {
1278 use super::*;
1279
1280 #[test]
1281 fn hello_body_debug_never_prints_the_nonce() {
1282 let body = ModuleHelloBody {
1283 manifest: manifest::ModuleManifest::builder("broca", "0.1.0").build(),
1284 protocol_ver: 2,
1285 control_ops: None,
1286 launch_nonce: Some("nonce-f00dfeed1234abcd".to_string()),
1287 };
1288 let printed = format!("{body:?}");
1289 assert!(printed.contains("broca"), "{printed}");
1290 assert!(
1291 !printed.contains("nonce-f00dfeed1234abcd"),
1292 "launch nonce printed: {printed}"
1293 );
1294 }
1295}