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