Skip to main content

subc_client_rs/
lib.rs

1#![forbid(unsafe_code)]
2
3pub mod activity;
4mod agent_commands;
5pub mod config;
6mod control_ops;
7pub use agent_commands::AgentCommandsError;
8pub use subc_protocol::session::{AgentCommandFinished, AgentCommandRoot};
9pub mod consumer;
10mod operator_app;
11pub mod policy_cache;
12#[cfg(any(test, feature = "test-support"))]
13mod stand_in;
14#[cfg(feature = "test-support")]
15pub mod test_support;
16pub use activity::*;
17pub use consumer::{
18    is_retryable_route_open_code, AppOpenError, CallError, CallOptions, CallReply, CancelHandle,
19    CancelOutcome, CatalogList, CatalogSubscription, CloseRouteOptions, ConfigApplyResponse,
20    ConfigEdit, ConfigEditAction, ConfigFileError, ConfigFileErrorLayer, ConfigModule,
21    ConfigModulesResponse, ConfigPlanRefusal, ConfigPlanView, ConfigSchemaResponse,
22    ConfigSettingsLayer, ConfigShowResponse, ConfigStatus, ConfigSubscription, ConfigThrough,
23    ConfigWatchEvent, ConnectionFacts, ConnectionState, ConsumerCapabilityError, ConsumerError,
24    ConsumerOptions, ControlPush, CorrelationId, Digest, HealthProbeResponse, NotSentCause,
25    OutcomeUnknownCause, PendingReply, PushEvent, RequestBody, RequestReservation, RetryBackoff,
26    ReverseRequestContext, ReverseRequestError, ReverseRequestRegistrationError,
27    ReverseRequestRegistry, RouteCloseDisposition, RouteCloseReason, RouteEndReason,
28    RouteOpenTarget, RouteOpenTargetKind, RoutePollResult, ScopeBindProofRefusal, ScopeSelector,
29    ServerDescription, SpawnStreamError, SpawnSubscription, StderrTailResponse, SubcConsumer,
30    SubscribeOptions, Subscription, SubscriptionClosed, SubscriptionEnd, SupervisorAck,
31    SupervisorEntry, SupervisorHealthResponse, SupervisorListResponse,
32    SupervisorProvenanceResponse, ACCEPTED_CLOSE_REASONS, DEFAULT_CALL_TIMEOUT,
33    DEFAULT_LIVENESS_PROBE_WINDOW, DEFAULT_ROUTE_RETRY_DEADLINE, SPAWN_CURSOR_INCARNATION_MISMATCH,
34    SPAWN_CURSOR_TOO_OLD, SPAWN_SUBSCRIBER_LAGGED,
35};
36pub use operator_app::{operator_app_candidates, operator_app_path, OperatorAppPathError};
37pub use policy_cache::{
38    PolicyResolveError, PolicyResolver, PolicyResolverConfig, PolicyResolverFootprint,
39    PolicyVerdict, ProjectRef, Subject, DEFAULT_POLICY_RESOLVER_MODULE_ID,
40};
41pub use subc_control::{AppOpenReply, AppOpenStatus, CatalogOrigin, CatalogWatchResponse};
42pub use subc_control::{
43    ScopeRef, ScopeWatchEvent, ScopeWatchPush, ScopeWatchResponse, ScopeWatchSelector,
44    ScopeWatchState, ScopeWatchStatus,
45};
46
47mod module_subscription;
48pub use module_subscription::ScopeSubscription;
49
50use std::{
51    collections::{BTreeMap, HashMap, VecDeque},
52    env,
53    error::Error,
54    ffi::OsString,
55    fmt,
56    future::Future,
57    io,
58    panic::{catch_unwind, AssertUnwindSafe},
59    path::{Path, PathBuf},
60    pin::Pin,
61    sync::{
62        atomic::{AtomicBool, AtomicU64, Ordering},
63        Arc, Mutex,
64    },
65    time::{Duration, SystemTime, UNIX_EPOCH},
66};
67
68pub use async_trait::async_trait;
69pub use subc_control::{CatalogEntry, ConsumerIdentity};
70mod scope_served_by;
71pub use scope_served_by::{ScopeServedByAnswer, ScopeServedByReply};
72pub mod registration;
73mod route_authorize;
74pub use route_authorize::{
75    RouteAuthorizeExpected, RouteAuthorizeOutcome, RouteAuthorizeResponse, RouteAuthorizeScope,
76};
77mod request_pools;
78pub use registration::ClaimError;
79use request_pools::{wait_for_permit, DispatchPools, PermitWaitOutcome, WaitingRequest};
80pub use request_pools::{RequestClass, RequestPool, RequestPoolSnapshot, RequestPools};
81/// The one launch-nonce reader for a module process: `launch_nonce()` reads
82/// the inherited Unix descriptor, the Windows named pipe, or, when neither is
83/// named, the `SUBC_LAUNCH_NONCE` environment copy once and caches it. The SDK's
84/// HELLO and route opens go through it too; a module's own readers must as well.
85/// Read before spawning children so they cannot inherit an unread Unix pipe
86/// containing the module's credential.
87pub use subc_os::launch_nonce;
88use subc_protocol::{
89    call_mode::derive_call_mode,
90    error_codes,
91    manifest::ModuleManifest,
92    scope::{
93        ScopeEnd, ScopeEndResult, ScopeEnded, ScopeRecord, ScopeRecordResult, ScopeStamp,
94        ScopeStatus, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP, SCOPE_SYNC_OP,
95    },
96    session::{
97        ModuleControlCommand, ModuleControlRequest, ModuleControlRequestFromModule,
98        ModuleControlResponse, ModuleControlResponseToModule, OperatorConfirmKind,
99        OperatorConfirmReply, OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK,
100        MODULE_TO_SUBC_OP_CATALOG_UPDATE, MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS,
101    },
102    BindIdentity, ErrorBody, Flags, Frame, FrameBuildError, FrameType, ModuleHelloAckBody,
103    ModuleHelloBody, Principal, Priority, RouteTarget, PROTOCOL_VERSION, SUBC_MODULE_ID_ENV,
104};
105pub use subc_protocol::{
106    call_mode::{CallMode, CALL_MODES_CAPABILITY},
107    manifest::{
108        build_provenance, CapabilityDeclarations, CapabilityNeed, CapabilityRequirement,
109        ExecutionMode, LaunchNonceSource, ManifestProvenance, ProvenanceFormError, ProviderRole,
110        Tool, PROVENANCE_SENTINELS,
111    },
112    session::{HealthReport, HealthStatus},
113    AdmissionClass, MachineId, SUBC_PROTOCOL_CRATE_VERSION,
114};
115pub use subc_transport::connection_file::{
116    discover, discovery_candidates, Discovered, DiscoveryError,
117};
118
119use subc_transport::{
120    authenticate_client, connection_file, read_frame, write_frame, AuthError, ConnectionFileError,
121    FrameIoError,
122};
123use tokio::{
124    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufWriter},
125    net::TcpStream,
126    sync::{mpsc, oneshot},
127    time::{timeout, timeout_at, Instant},
128};
129use tokio_util::{
130    sync::{CancellationToken, WaitForCancellationFuture},
131    task::TaskTracker,
132};
133
134const AUTH_DEADLINE: Duration = Duration::from_secs(2);
135const CATALOG_UPDATE_TIMEOUT: Duration = Duration::from_secs(10);
136const OPERATOR_CONFIRM_TIMEOUT: Duration = Duration::from_secs(290);
137const OPERATOR_CONFIRM_OP: &str = "operator.confirm";
138const EGRESS_BUFFER: usize = 64;
139const HANDLER_TASK_CAPACITY: usize = 64;
140/// A full dispatcher is normal during a burst. Report dispatch impairment only
141/// once a data request has waited more than two seconds for a handler slot.
142const DISPATCH_SATURATION_WAIT: Duration = Duration::from_secs(2);
143const HELLO_CORR: u64 = 1;
144const DEFAULT_WRITER_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
145/// When a module's daemon connection ends (GOODBYE, EOF, reset, or module stop),
146/// how long the serve loop waits for each `on_draining` hook it already
147/// spawned to start running before it cancels requests and calls
148/// `on_connection_end`. The wait is only for the hook's first step, which is
149/// normally immediate; the bound matters because the daemon kills a module
150/// that has not exited within its stop timeout after GOODBYE, and a hook that
151/// blocks its thread must not hold the shutdown up that long.
152const DRAINING_HOOK_START_LIMIT: Duration = Duration::from_secs(2);
153static NEXT_MODULE_CONNECTION_TOKEN: AtomicU64 = AtomicU64::new(1);
154/// The connection token of a [`RouteHandle::detached`] handle. Module
155/// connection tokens start at 1 (above) and a consumer's generation starts at
156/// 1 and only grows, so no live connection ever has this token.
157const DETACHED_CONNECTION_TOKEN: u64 = 0;
158
159type RequestKey = (u16, u32, u64);
160type InFlight = Arc<Mutex<HashMap<RequestKey, CancellationToken>>>;
161
162/// Immutable identity of one route binding on one live connection.
163///
164/// Only `channel` and `epoch` are serialized. The private connection token prevents
165/// work retained from an earlier connection from acting on a later connection that
166/// happens to reuse the same wire pair.
167#[derive(Clone, Copy)]
168pub struct RouteHandle {
169    pub channel: u16,
170    pub epoch: u32,
171    connection_token: u64,
172    reverse_request_registry_id: u64,
173}
174
175impl RouteHandle {
176    /// A handle for `channel` and `epoch` that belongs to no connection, for
177    /// building values in tests, such as a [`RouteBindRequest`] passed to a
178    /// module's own `on_bind`. It is never bound to a connection and cannot
179    /// become one.
180    ///
181    /// Every operation that would reach a connection fails with the error
182    /// it returns for a closed or stale route, and sends nothing:
183    /// [`ModuleHandle::push`] returns [`SubcModuleError::StaleRouteHandle`];
184    /// [`SubcConsumer::request`], [`SubcConsumer::subscribe_route`],
185    /// [`SubcConsumer::poll_route`], [`SubcConsumer::push_events`] and
186    /// [`SubcConsumer::close_handle`] return [`CallError::StaleRouteHandle`];
187    /// [`Self::on_request`] and [`Self::on_request_fallible`] return
188    /// [`ReverseRequestRegistrationError::NotConsumerRoute`].
189    pub fn detached(channel: u16, epoch: u32) -> Self {
190        Self::new(channel, epoch, DETACHED_CONNECTION_TOKEN)
191    }
192
193    pub(crate) fn new(channel: u16, epoch: u32, connection_token: u64) -> Self {
194        Self {
195            channel,
196            epoch,
197            connection_token,
198            reverse_request_registry_id: 0,
199        }
200    }
201
202    pub(crate) fn new_consumer(
203        channel: u16,
204        epoch: u32,
205        connection_token: u64,
206        reverse_requests: ReverseRequestRegistry,
207    ) -> Self {
208        reverse_requests.seal();
209        Self {
210            channel,
211            epoch,
212            connection_token,
213            reverse_request_registry_id: consumer::install_reverse_request_registry(
214                reverse_requests,
215            ),
216        }
217    }
218
219    pub(crate) fn connection_token(self) -> u64 {
220        self.connection_token
221    }
222
223    pub fn on_request<F, Fut>(
224        &self,
225        method_family: impl Into<String>,
226        handler: F,
227    ) -> Result<(), ReverseRequestRegistrationError>
228    where
229        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
230        Fut: Future<Output = Vec<u8>> + Send + 'static,
231    {
232        consumer::route_reverse_request_registry(self.reverse_request_registry_id)?
233            .on_request(method_family, handler)
234    }
235
236    pub fn on_request_fallible<F, Fut>(
237        &self,
238        method_family: impl Into<String>,
239        handler: F,
240    ) -> Result<(), ReverseRequestRegistrationError>
241    where
242        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
243        Fut: Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static,
244    {
245        consumer::route_reverse_request_registry(self.reverse_request_registry_id)?
246            .on_request_fallible(method_family, handler)
247    }
248
249    pub(crate) fn reverse_request_registry_id(self) -> u64 {
250        self.reverse_request_registry_id
251    }
252}
253
254impl PartialEq for RouteHandle {
255    fn eq(&self, other: &Self) -> bool {
256        self.channel == other.channel
257            && self.epoch == other.epoch
258            && self.connection_token == other.connection_token
259    }
260}
261
262impl Eq for RouteHandle {}
263
264impl std::hash::Hash for RouteHandle {
265    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
266        std::hash::Hash::hash(&self.channel, state);
267        std::hash::Hash::hash(&self.epoch, state);
268        std::hash::Hash::hash(&self.connection_token, state);
269    }
270}
271
272impl fmt::Debug for RouteHandle {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.debug_struct("RouteHandle")
275            .field("channel", &self.channel)
276            .field("epoch", &self.epoch)
277            .finish_non_exhaustive()
278    }
279}
280/// A single read-lock snapshot of bound and pending project routes.
281#[derive(Debug, Clone, PartialEq, Eq)]
282pub struct LiveRootsSnapshot {
283    pub roots: Vec<subc_protocol::session::LiveRoot>,
284    pub unknown_root_bindings: u64,
285    pub total_bindings: u64,
286}
287
288/// The daemon's answer to an accepted [`ModuleHandle::scope_sync`].
289///
290/// A refusal of the whole sync is never a reply: it is
291/// [`ScopeCallError::Refused`], and the daemon changed nothing.
292#[derive(Debug, Clone, PartialEq, Eq)]
293#[non_exhaustive]
294pub struct ScopeSyncReply {
295    /// The generation the daemon accepted, echoed from the request.
296    pub generation: u64,
297    /// One result per record sent, in request order. A record refused on its
298    /// own merits is here with outcome `refused` and its code; the rest of the
299    /// sync still applied.
300    pub results: Vec<ScopeRecordResult>,
301    /// Scopes of this owner that the sync ended, by leaving them out, sending
302    /// a higher epoch for the same ref, or sweeping their expired deadlines.
303    pub ended: Vec<ScopeEnded>,
304}
305
306/// The daemon's answer to an accepted [`ModuleHandle::scope_apply`].
307///
308/// A refusal of the whole delta is [`ScopeCallError::Refused`]; nothing changed.
309#[derive(Debug, Clone, PartialEq, Eq)]
310#[non_exhaustive]
311pub struct ScopeApplyReply {
312    /// The generation the daemon accepted, echoed from the request.
313    pub generation: u64,
314    /// One result per upsert, in request order, including per-record refusals.
315    pub results: Vec<ScopeRecordResult>,
316    /// One result per requested end, in request order. A ref not live at the
317    /// named epoch has outcome `not_live`, which does not refuse the delta.
318    pub end_results: Vec<ScopeEndResult>,
319    /// Scopes this call ended, once each, through explicit ends, higher-epoch
320    /// upserts, or the calling owner's expiry sweep.
321    pub ended: Vec<ScopeEnded>,
322}
323
324/// The daemon's answer to [`ModuleHandle::scope_describe`] about one
325/// `(owner, ref)`.
326#[derive(Debug, Clone, PartialEq, Eq)]
327#[non_exhaustive]
328pub struct ScopeDescribeReply {
329    pub status: ScopeStatus,
330    /// The live epoch, or for `ended` the most recent epoch that ended.
331    pub scope_epoch: Option<u64>,
332    /// Identifies the daemon process that answered. A different value means
333    /// the daemon restarted, and owners re-sync after a restart.
334    pub daemon_incarnation: String,
335    /// Whether the owner has synced since this daemon incarnation started.
336    pub owner_synced: bool,
337    /// Whether the owner is a module in the daemon's supervised roster.
338    pub owner_configured: bool,
339    /// The stamped fields, present only when `status` is `live`. The daemon
340    /// includes `attributes.on_behalf_of_agent` only when this module's manifest
341    /// provides `scope-on-behalf-of/v1`; the field is attribution, never authority.
342    pub scope: Option<ScopeStamp>,
343}
344
345// The protocol's module-control enum predates the separately typed authorization
346// reply. Keep both wire types in the same correlation table and deadline path.
347#[derive(Debug, serde::Deserialize)]
348#[serde(untagged)]
349enum ModuleControlReply {
350    Control(Box<ModuleControlResponseToModule>),
351    RouteAuthorize(RouteAuthorizeResponse),
352}
353
354impl ModuleControlReply {
355    fn control(self) -> Result<ModuleControlResponseToModule, CatalogUpdateError> {
356        match self {
357            Self::Control(reply) => Ok(*reply),
358            other => Err(CatalogUpdateError::Protocol(format!(
359                "unexpected module control response: {other:?}"
360            ))),
361        }
362    }
363}
364
365type CatalogUpdateReply = oneshot::Sender<Result<ModuleControlReply, CatalogUpdateError>>;
366type CatalogUpdateWaiter = oneshot::Receiver<Result<ModuleControlReply, CatalogUpdateError>>;
367type CatalogUpdateRequest = (u64, mpsc::Sender<Frame>, CatalogUpdateWaiter);
368type OperatorConfirmRequestWaiter = (u64, mpsc::Sender<Frame>, oneshot::Receiver<Frame>);
369
370/// Future returned by [`serve_with_handle`] that runs the module until GOODBYE or EOF.
371pub type ModuleServeFuture = Pin<Box<dyn Future<Output = Result<(), SubcModuleError>> + Send>>;
372
373#[derive(Clone)]
374struct RequestDispatcher {
375    in_flight: InFlight,
376    control_slots: Arc<tokio::sync::Semaphore>,
377    /// The connection's handler-slot pools, shared with its [`ModuleHandle`]
378    /// so the module can read their figures.
379    pools: Arc<DispatchPools>,
380    /// One receiver per `on_draining` hook spawned on this connection, resolved
381    /// once that hook has started running. The connection waits on them before
382    /// acting on its end, so a hook is always called before the GOODBYE that
383    /// follows its drain is handled.
384    draining_hooks: Arc<Mutex<Vec<oneshot::Receiver<()>>>>,
385    /// Set after the first channel-0 push this SDK could not decode has been
386    /// logged, so a daemon that repeats a newer push cannot flood the log.
387    undecodable_push_logged: Arc<AtomicBool>,
388    failure: Arc<Mutex<Option<SubcModuleError>>>,
389    failed: CancellationToken,
390    tasks: TaskTracker,
391    aborts: Arc<Mutex<Vec<tokio::task::AbortHandle>>>,
392    undelivered_replies: Arc<AtomicU64>,
393}
394
395impl RequestDispatcher {
396    /// A dispatcher with the default pool only, as a module that declares no
397    /// classifier gets.
398    #[cfg(test)]
399    fn new() -> Self {
400        Self::with_pools(Arc::new(DispatchPools::new(RequestPools::new())))
401    }
402
403    fn with_pools(pools: Arc<DispatchPools>) -> Self {
404        Self {
405            in_flight: Arc::new(Mutex::new(HashMap::new())),
406            control_slots: Arc::new(tokio::sync::Semaphore::new(16)),
407            pools,
408            draining_hooks: Arc::new(Mutex::new(Vec::new())),
409            undecodable_push_logged: Arc::new(AtomicBool::new(false)),
410            failure: Arc::new(Mutex::new(None)),
411            failed: CancellationToken::new(),
412            tasks: TaskTracker::new(),
413            aborts: Arc::new(Mutex::new(Vec::new())),
414            undelivered_replies: Arc::new(AtomicU64::new(0)),
415        }
416    }
417
418    fn fail(&self, error: SubcModuleError) {
419        let mut failure = self.failure.lock().unwrap_or_else(|e| e.into_inner());
420        if failure.is_none() {
421            *failure = Some(error);
422        }
423        self.failed.cancel();
424    }
425
426    fn take_failure(&self) -> Option<SubcModuleError> {
427        self.failure
428            .lock()
429            .unwrap_or_else(|e| e.into_inner())
430            .take()
431    }
432
433    fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
434        let task = self.tasks.spawn(future);
435        let mut aborts = self.aborts.lock().unwrap_or_else(|e| e.into_inner());
436        aborts.retain(|task| !task.is_finished());
437        aborts.push(task.abort_handle());
438    }
439
440    fn abort_all(&self) {
441        for task in self
442            .aborts
443            .lock()
444            .unwrap_or_else(|e| e.into_inner())
445            .drain(..)
446        {
447            task.abort();
448        }
449    }
450
451    fn fold_health(&self, mut report: HealthReport) -> HealthReport {
452        if let Some(saturation) = self.pools.saturation() {
453            if report.status == HealthStatus::Ok {
454                report.status = HealthStatus::Degraded;
455            }
456            report.detail = Some(match report.detail {
457                Some(detail) => format!("{saturation}; {detail}"),
458                None => saturation,
459            });
460        }
461        report
462    }
463
464    /// Wait, within [`DRAINING_HOOK_START_LIMIT`], until every `on_draining`
465    /// hook spawned on this connection has started. Only the start is awaited:
466    /// a hook may still be finishing its work after the connection has ended.
467    async fn wait_for_draining_hooks_to_start(&self) {
468        let started = std::mem::take(
469            &mut *self
470                .draining_hooks
471                .lock()
472                .unwrap_or_else(|poisoned| poisoned.into_inner()),
473        );
474        let deadline = tokio::time::Instant::now() + DRAINING_HOOK_START_LIMIT;
475        for hook in started {
476            // A dropped sender means the hook task ended (or panicked) before
477            // reporting; either way there is nothing left to wait for.
478            if tokio::time::timeout_at(deadline, hook).await.is_err() {
479                return;
480            }
481        }
482    }
483
484    /// Cancel every request still in flight and refuse ones still waiting for a
485    /// handler slot, as a route's GOODBYE does for that route's requests. Run
486    /// when the connection ends: each request task holds a sender to the egress
487    /// channel, so until they finish the writer never sees the channel close.
488    fn cancel_all(&self) {
489        self.pools.close();
490        let cancelled = match self.in_flight.lock() {
491            Ok(guard) => guard.values().cloned().collect::<Vec<_>>(),
492            Err(poisoned) => poisoned.into_inner().values().cloned().collect(),
493        };
494        for cancellation in cancelled {
495            cancellation.cancel();
496        }
497    }
498}
499
500/// Cloneable handle for module-originated control RPCs on channel 0.
501#[derive(Clone)]
502pub struct ModuleHandle {
503    shared: Arc<ModuleHandleShared>,
504}
505
506struct ModuleHandleShared {
507    registration: registration::Session,
508    negotiated_ver: u8,
509    daemon_capabilities: Vec<String>,
510    supports_catalog_update: bool,
511    supports_role_declarations_update: bool,
512    supports_live_roots: bool,
513    supports_agent_commands: bool,
514    supports_scope_sync: bool,
515    supports_scope_apply: bool,
516    supports_scope_describe: bool,
517    supports_scope_watch: bool,
518    supports_route_authorize: bool,
519    supports_operator_confirm: bool,
520    supports_activity: bool,
521    connection_runtime: tokio::runtime::Handle,
522    connection_token: u64,
523    machine_id: Option<MachineId>,
524    live_routes: Mutex<HashMap<u16, RouteHandle>>,
525    dropped_route_frames: AtomicU64,
526    close_token: CancellationToken,
527    /// The handler-slot pools this connection's dispatcher uses. Replaced once,
528    /// with the pools the module's handler declares, before serving starts.
529    dispatch_pools: Mutex<Arc<DispatchPools>>,
530    catalog_send: tokio::sync::Mutex<()>,
531    config: config::Session,
532    served_control_ops: std::sync::OnceLock<Vec<String>>,
533    inner: Mutex<ModuleHandleState>,
534}
535
536struct ModuleHandleState {
537    pending_control_streams: HashMap<u64, module_subscription::ControlStreamSender>,
538    pending_claim_calls: HashMap<u64, oneshot::Sender<Frame>>,
539    writer: Option<mpsc::Sender<Frame>>,
540    next_corr: Option<u64>,
541    pending_catalog_updates: HashMap<u64, CatalogUpdateReply>,
542    pending_operator_confirms: HashMap<u64, oneshot::Sender<Frame>>,
543    pending_activity_records: HashMap<u64, oneshot::Sender<Frame>>,
544    pending_scope_served_by: HashMap<u64, oneshot::Sender<Frame>>,
545    pending_config_calls: HashMap<u64, oneshot::Sender<Frame>>,
546    pending_agent_commands: HashMap<u64, oneshot::Sender<Frame>>,
547    current_provides: Option<Vec<ProviderRole>>,
548    catalog_changes: VecDeque<CatalogChange>,
549    closed: bool,
550}
551
552struct CatalogChange {
553    corr: u64,
554    provides: Vec<ProviderRole>,
555    outcome: Option<CatalogChangeOutcome>,
556}
557
558enum CatalogChangeOutcome {
559    Accepted,
560    Rejected,
561    Unknown,
562}
563
564struct CatalogUpdateGuard {
565    shared: Arc<ModuleHandleShared>,
566    corr: u64,
567}
568
569impl Drop for CatalogUpdateGuard {
570    fn drop(&mut self) {
571        self.shared.remove_pending_catalog_update(self.corr);
572    }
573}
574
575impl ModuleHandle {
576    fn new(
577        ack: &ModuleHelloAckBody,
578        writer: mpsc::Sender<Frame>,
579        connection_token: u64,
580        close_token: CancellationToken,
581        connection_runtime: tokio::runtime::Handle,
582    ) -> Self {
583        Self {
584            shared: Arc::new(ModuleHandleShared {
585                registration: registration::Session::default(),
586                negotiated_ver: ack.negotiated_ver,
587                daemon_capabilities: ack.subc_capabilities.clone(),
588                supports_catalog_update: ack
589                    .subc_ops
590                    .iter()
591                    .any(|op| op == MODULE_TO_SUBC_OP_CATALOG_UPDATE),
592                supports_role_declarations_update: ack
593                    .subc_ops
594                    .iter()
595                    .any(|op| op == MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS),
596                supports_live_roots: ack.subc_ops.iter().any(|op| op == "supervisor.live_roots"),
597                supports_agent_commands: ack
598                    .subc_ops
599                    .iter()
600                    .any(|op| op == "supervisor.agent_commands"),
601                supports_scope_sync: ack.subc_ops.iter().any(|op| op == SCOPE_SYNC_OP),
602                supports_scope_apply: ack.subc_ops.iter().any(|op| op == SCOPE_APPLY_OP),
603                supports_scope_describe: ack.subc_ops.iter().any(|op| op == SCOPE_DESCRIBE_OP),
604                supports_scope_watch: ack
605                    .subc_ops
606                    .iter()
607                    .any(|op| op == subc_control::ops::SCOPE_WATCH),
608                supports_route_authorize: ack
609                    .subc_ops
610                    .iter()
611                    .any(|op| op == subc_protocol::scope::ROUTE_AUTHORIZE_OP),
612                supports_operator_confirm: ack.subc_ops.iter().any(|op| op == OPERATOR_CONFIRM_OP),
613                supports_activity: ack
614                    .subc_capabilities
615                    .iter()
616                    .any(|capability| capability == ACTIVITY_LEDGER_CAPABILITY),
617                connection_runtime,
618                connection_token,
619                // A value that does not parse is treated like an absent one:
620                // the module learns nothing rather than a name that is wrong.
621                machine_id: ack
622                    .machine_id
623                    .as_deref()
624                    .and_then(|id| MachineId::parse(id).ok()),
625                live_routes: Mutex::new(HashMap::new()),
626                dropped_route_frames: AtomicU64::new(0),
627                close_token,
628                dispatch_pools: Mutex::new(Arc::new(DispatchPools::new(RequestPools::new()))),
629                catalog_send: tokio::sync::Mutex::new(()),
630                config: config::Session::default(),
631                served_control_ops: std::sync::OnceLock::new(),
632                inner: Mutex::new(ModuleHandleState {
633                    pending_control_streams: HashMap::new(),
634                    pending_claim_calls: HashMap::new(),
635                    writer: Some(writer),
636                    next_corr: Some(HELLO_CORR + 1),
637                    pending_catalog_updates: HashMap::new(),
638                    pending_operator_confirms: HashMap::new(),
639                    pending_activity_records: HashMap::new(),
640                    pending_scope_served_by: HashMap::new(),
641                    pending_config_calls: HashMap::new(),
642                    pending_agent_commands: HashMap::new(),
643                    current_provides: None,
644                    catalog_changes: VecDeque::new(),
645                    closed: false,
646                }),
647            }),
648        }
649    }
650
651    /// The daemon's machine id, as delivered on HELLO_ACK.
652    ///
653    /// `None` means the daemon did not send one (it predates the machine id, or
654    /// was embedded without one) or sent a malformed value. Read that as "the
655    /// daemon has not named this machine", never as "no machine", and never mint
656    /// a substitute. The id is a name, never an authority: see [`MachineId`].
657    pub fn machine_id(&self) -> Option<&MachineId> {
658        self.shared.machine_id.as_ref()
659    }
660
661    /// The daemon capability identifiers delivered in this connection's HELLO_ACK.
662    ///
663    /// The list preserves the daemon's order and unknown capability identifiers.
664    pub fn daemon_capabilities(&self) -> &[String] {
665        &self.shared.daemon_capabilities
666    }
667
668    /// Whether this daemon advertised `capability` in this connection's HELLO_ACK.
669    ///
670    /// Scope owners should check
671    /// `daemon_supports(subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1)`
672    /// before setting `ScopeRecord.bind_proof_sha256` on records sent over
673    /// this connection.
674    ///
675    /// Daemons before 0.50.33 list `config.settings/v1` and
676    /// `config.settings.projects/v1` only in `server.describe`. Modules that
677    /// support those versions must check `server.describe` as well.
678    pub fn daemon_supports(&self, capability: &str) -> bool {
679        self.shared
680            .daemon_capabilities
681            .iter()
682            .any(|advertised| advertised == capability)
683    }
684
685    /// Resolves once this module's connection to the daemon has closed: after a
686    /// channel-0 GOODBYE, EOF, or a connection error. A module ends its own
687    /// background work on it, so nothing outlives the connection.
688    pub fn closed(&self) -> impl Future<Output = ()> + Send + 'static {
689        self.shared.close_token.clone().cancelled_owned()
690    }
691
692    /// Whether this module's connection to the daemon has closed.
693    pub fn is_closed(&self) -> bool {
694        self.shared.close_token.is_cancelled()
695    }
696
697    /// Ask the daemon to replace this module's advertised provider roles in place.
698    ///
699    /// The returned result resolves when the daemon ACKs the update, rejects it with
700    /// a typed channel-0 Error frame, the request times out, or the connection dies.
701    pub async fn catalog_update(
702        &self,
703        provides: Vec<ProviderRole>,
704    ) -> Result<(), CatalogUpdateError> {
705        self.catalog_update_inner(Some(provides), None, None).await
706    }
707
708    /// Replace this module's complete registered role-declaration map in place.
709    ///
710    /// An empty map (`{}` on the wire) clears all declarations. Requires
711    /// subc-daemon 0.44.9 or later; returns [`CatalogUpdateError::NotSupported`]
712    /// without sending when HELLO_ACK does not advertise the operation. Invalid
713    /// declarations are refused by the daemon as [`CatalogUpdateError::Rejected`],
714    /// preserving the previous map and the refusal's code and reason.
715    pub async fn update_role_declarations(
716        &self,
717        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
718    ) -> Result<(), CatalogUpdateError> {
719        if !self.shared.supports_role_declarations_update {
720            return Err(CatalogUpdateError::NotSupported);
721        }
722        let body = serde_json::to_vec(
723            &ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations {
724                role_declarations: serde_json::to_value(role_declarations)
725                    .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?,
726            },
727        )
728        .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
729        let (corr, writer, rx) = self.shared.begin_catalog_update()?;
730        let _pending = CatalogUpdateGuard {
731            shared: self.shared.clone(),
732            corr,
733        };
734        let frame = Frame::build_with_version(
735            self.shared.negotiated_ver,
736            FrameType::Request,
737            control_flags(),
738            0,
739            0,
740            corr,
741            body,
742        )
743        .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
744        if writer.send(frame).await.is_err() {
745            return Err(CatalogUpdateError::ConnectionClosed);
746        }
747        match timeout(CATALOG_UPDATE_TIMEOUT, rx).await {
748            Ok(Ok(Ok(reply))) => match reply.control()? {
749                ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {} => Ok(()),
750                _ => Err(CatalogUpdateError::Protocol(
751                    "unexpected catalog.update_role_declarations response".into(),
752                )),
753            },
754            Ok(Ok(Err(err))) => Err(err),
755            Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
756            Err(_) => Err(CatalogUpdateError::Timeout),
757        }
758    }
759
760    /// Replace provider roles and attest a new static capability declaration.
761    ///
762    /// The declaration must be the same static metadata emitted by the module's
763    /// current manifest; this update exists so the daemon can reconcile live routes
764    /// when that attested metadata changes.
765    pub async fn catalog_update_with_capabilities(
766        &self,
767        provides: Vec<ProviderRole>,
768        capabilities: CapabilityDeclarations,
769    ) -> Result<(), CatalogUpdateError> {
770        self.catalog_update_inner(Some(provides), Some(capabilities), None)
771            .await
772    }
773
774    /// Change readiness without changing provider roles or capability declarations.
775    ///
776    /// Register with `ready(false)`, start polling the serving future immediately,
777    /// and do slow startup work on another task before calling `set_ready(true)`.
778    /// Setting readiness to false refuses new binds but leaves existing routes up.
779    /// Requires subc-daemon 0.20.3 or later (including subc-daemon 0.38.x).
780    ///
781    /// Returns [`CatalogUpdateError::Protocol`] without sending if the current roles
782    /// are unknown: a catalog replacement is still in flight, or an earlier update
783    /// timed out, was cancelled or had an undecodable reply. After an uncertain result, a successful
784    /// explicit catalog replacement establishes the roles again.
785    pub async fn set_ready(&self, ready: bool) -> Result<(), CatalogUpdateError> {
786        self.catalog_update_inner(None, None, Some(ready)).await
787    }
788
789    async fn catalog_update_inner(
790        &self,
791        provides: Option<Vec<ProviderRole>>,
792        capabilities: Option<CapabilityDeclarations>,
793        ready: Option<bool>,
794    ) -> Result<(), CatalogUpdateError> {
795        if !self.shared.supports_catalog_update {
796            return Err(CatalogUpdateError::NotSupported);
797        }
798
799        // Order role snapshots and outbound updates together, but release the lock
800        // before waiting for ACKs so existing concurrent catalog RPCs still work.
801        let send_guard = self.shared.catalog_send.lock().await;
802        let provides = match provides {
803            Some(provides) => provides,
804            None => {
805                let inner = self.shared.lock_inner();
806                if inner.closed {
807                    return Err(CatalogUpdateError::ConnectionClosed);
808                }
809                inner
810                    .current_provides
811                    .as_ref()
812                    .filter(|_| inner.catalog_changes.is_empty())
813                    .cloned()
814                    .ok_or_else(|| {
815                        CatalogUpdateError::Protocol(
816                            "current provider roles are unknown or a catalog update is in flight"
817                                .into(),
818                        )
819                    })?
820            }
821        };
822        let body = serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
823            provides: provides.clone(),
824            capabilities,
825            ready,
826        })
827        .map_err(|err| {
828            CatalogUpdateError::Protocol(format!(
829                "failed to encode catalog.update request body: {err}"
830            ))
831        })?;
832        let (corr, writer, rx) = self.shared.begin_catalog_update()?;
833        let _pending = CatalogUpdateGuard {
834            shared: self.shared.clone(),
835            corr,
836        };
837        let frame = Frame::build_with_version(
838            self.shared.negotiated_ver,
839            FrameType::Request,
840            control_flags(),
841            0,
842            0,
843            corr,
844            body,
845        )
846        .map_err(|err| {
847            self.shared.remove_pending_catalog_update(corr);
848            CatalogUpdateError::Protocol(format!(
849                "failed to build catalog.update request frame: {err}"
850            ))
851        })?;
852
853        let permit = match writer.reserve().await {
854            Ok(permit) => permit,
855            Err(_) => {
856                self.shared.remove_pending_catalog_update(corr);
857                return Err(CatalogUpdateError::ConnectionClosed);
858            }
859        };
860        self.shared
861            .lock_inner()
862            .catalog_changes
863            .push_back(CatalogChange {
864                corr,
865                provides,
866                outcome: None,
867            });
868        permit.send(frame);
869        drop(send_guard);
870
871        match timeout(CATALOG_UPDATE_TIMEOUT, async {
872            rx.await
873                .map(|reply| reply.and_then(ModuleControlReply::control))
874        })
875        .await
876        {
877            Ok(Ok(Ok(ModuleControlResponseToModule::CatalogUpdate {}))) => Ok(()),
878            Ok(Ok(Ok(_))) => Err(CatalogUpdateError::Protocol(
879                "unexpected catalog.update response".into(),
880            )),
881            Ok(Ok(Err(err))) => Err(err),
882            Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
883            Err(_) => {
884                self.shared.remove_pending_catalog_update(corr);
885                Err(CatalogUpdateError::Timeout)
886            }
887        }
888    }
889
890    /// Snapshot the roots served by this module's routable endpoint.
891    pub async fn live_roots(&self) -> Result<LiveRootsSnapshot, CatalogUpdateError> {
892        if !self.shared.supports_live_roots {
893            return Err(CatalogUpdateError::NotSupported);
894        }
895        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {})
896            .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
897        let (corr, writer, rx) = self.shared.begin_catalog_update()?;
898        let frame = Frame::build_with_version(
899            self.shared.negotiated_ver,
900            FrameType::Request,
901            control_flags(),
902            0,
903            0,
904            corr,
905            body,
906        )
907        .map_err(|err| {
908            self.shared.remove_pending_catalog_update(corr);
909            CatalogUpdateError::Protocol(err.to_string())
910        })?;
911        if writer.send(frame).await.is_err() {
912            self.shared.remove_pending_catalog_update(corr);
913            return Err(CatalogUpdateError::ConnectionClosed);
914        }
915        match timeout(CATALOG_UPDATE_TIMEOUT, async {
916            rx.await
917                .map(|reply| reply.and_then(ModuleControlReply::control))
918        })
919        .await
920        {
921            Ok(Ok(Ok(ModuleControlResponseToModule::LiveRoots {
922                roots,
923                unknown_root_bindings,
924                total_bindings,
925            }))) => Ok(LiveRootsSnapshot {
926                roots,
927                unknown_root_bindings,
928                total_bindings,
929            }),
930            Ok(Ok(Ok(_))) => Err(CatalogUpdateError::Protocol(
931                "unexpected live_roots response".into(),
932            )),
933            Ok(Ok(Err(err))) => Err(err),
934            Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
935            Err(_) => {
936                self.shared.remove_pending_catalog_update(corr);
937                Err(CatalogUpdateError::Timeout)
938            }
939        }
940    }
941
942    /// Register this module's full scope set with the daemon (`scope.sync`).
943    ///
944    /// Owners can set [`ScopeRecord::workdir`] and [`ScopeRecord::project_id`] with
945    /// the record builders after discovering `scope-workdir/v1`. These fields
946    /// attribute the session and grant no authority.
947    ///
948    /// The owner is this module; nothing in the request names it. `scopes` is
949    /// the whole set: a live scope left out ends. `generation` must be larger
950    /// than the last one the daemon accepted from this owner's sync authority,
951    /// or the sync is refused with `scope_sync_stale`.
952    ///
953    /// A refusal of the whole sync comes back as [`ScopeCallError::Refused`]
954    /// carrying the daemon's code (see `subc_protocol::error_codes`, e.g.
955    /// `SCOPE_SYNC_STALE`, `SCOPE_SYNC_NOT_AUTHORITY`), and nothing changed.
956    /// Only a module the daemon itself launched can hold sync authority.
957    pub async fn scope_sync(
958        &self,
959        generation: u64,
960        scopes: Vec<ScopeRecord>,
961    ) -> Result<ScopeSyncReply, ScopeCallError> {
962        if !self.shared.supports_scope_sync {
963            return Err(ScopeCallError::NotSupported { op: SCOPE_SYNC_OP });
964        }
965        let request = ModuleControlRequestFromModule::ScopeSync { generation, scopes };
966        match self
967            .scope_call(SCOPE_SYNC_OP, &request)
968            .await?
969            .control()
970            .map_err(ScopeCallError::from_control_error)?
971        {
972            ModuleControlResponseToModule::ScopeSync {
973                generation,
974                results,
975                ended,
976            } => Ok(ScopeSyncReply {
977                generation,
978                results,
979                ended,
980            }),
981            other => Err(ScopeCallError::Protocol(format!(
982                "unexpected {SCOPE_SYNC_OP} response: {other:?}"
983            ))),
984        }
985    }
986
987    /// Apply a delta to this module's scope set (`scope.apply`).
988    ///
989    /// This connection must first have established sync authority through an
990    /// accepted [`Self::scope_sync`]. `generation` shares the full-sync sequence
991    /// and must exceed the last accepted generation. Unnamed scopes stay live;
992    /// `end` ends only the named ref at the named epoch.
993    ///
994    /// Whole-call refusals return [`ScopeCallError::Refused`] without changing
995    /// the set or generation. Per-record refusals and `not_live` ends remain in
996    /// the reply. Without `scope.apply` in HELLO_ACK, nothing is sent.
997    pub async fn scope_apply(
998        &self,
999        generation: u64,
1000        upsert: Vec<ScopeRecord>,
1001        end: Vec<ScopeEnd>,
1002    ) -> Result<ScopeApplyReply, ScopeCallError> {
1003        if !self.shared.supports_scope_apply {
1004            return Err(ScopeCallError::NotSupported { op: SCOPE_APPLY_OP });
1005        }
1006        let request = ModuleControlRequestFromModule::ScopeApply {
1007            generation,
1008            upsert,
1009            end,
1010        };
1011        match self
1012            .scope_call(SCOPE_APPLY_OP, &request)
1013            .await?
1014            .control()
1015            .map_err(ScopeCallError::from_control_error)?
1016        {
1017            ModuleControlResponseToModule::ScopeApply {
1018                generation,
1019                results,
1020                end_results,
1021                ended,
1022            } => Ok(ScopeApplyReply {
1023                generation,
1024                results,
1025                end_results,
1026                ended,
1027            }),
1028            other => Err(ScopeCallError::Protocol(format!(
1029                "unexpected {SCOPE_APPLY_OP} response: {other:?}"
1030            ))),
1031        }
1032    }
1033
1034    /// Read one scope's current state (`scope.describe`). Any registered
1035    /// module may read any owner's scope.
1036    ///
1037    /// An unknown ref is not an error: the daemon answers it with status
1038    /// `not_live`. `owner_synced` says whether the owner has synced since this
1039    /// daemon started (if so, the scope is gone), and `owner_configured` whether
1040    /// the owner is a module the daemon supervises (if not, it never will sync).
1041    pub async fn scope_describe(
1042        &self,
1043        owner: Principal,
1044        scope_ref: String,
1045    ) -> Result<ScopeDescribeReply, ScopeCallError> {
1046        if !self.shared.supports_scope_describe {
1047            return Err(ScopeCallError::NotSupported {
1048                op: SCOPE_DESCRIBE_OP,
1049            });
1050        }
1051        let request = ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref };
1052        match self
1053            .scope_call(SCOPE_DESCRIBE_OP, &request)
1054            .await?
1055            .control()
1056            .map_err(ScopeCallError::from_control_error)?
1057        {
1058            ModuleControlResponseToModule::ScopeDescribe {
1059                status,
1060                scope_epoch,
1061                daemon_incarnation,
1062                owner_synced,
1063                owner_configured,
1064                scope,
1065            } => Ok(ScopeDescribeReply {
1066                status,
1067                scope_epoch,
1068                daemon_incarnation,
1069                owner_synced,
1070                owner_configured,
1071                scope,
1072            }),
1073            other => Err(ScopeCallError::Protocol(format!(
1074                "unexpected {SCOPE_DESCRIBE_OP} response: {other:?}"
1075            ))),
1076        }
1077    }
1078
1079    /// Ask the operator to authorise one in-flight, unchanged write.
1080    ///
1081    /// Every error means the module must refuse the write. `Ok(())` authorises
1082    /// only the write this call was made for; it must never be cached or reused.
1083    /// The daemon checks the summary and whether this module may ask for the
1084    /// caller's route. No failure is retried.
1085    ///
1086    /// A consumer call that may trigger confirmation must set
1087    /// [`CallOptions::timeout`] to at least 300 seconds. This helper waits up to
1088    /// 290 seconds, including egress backpressure, and dropping it withdraws an
1089    /// accepted request.
1090    pub async fn confirm_operator(
1091        &self,
1092        summary: &str,
1093        caller_route: &RouteHandle,
1094    ) -> Result<(), OperatorConfirmError> {
1095        self.confirm_operator_with_deadline(summary, caller_route, OPERATOR_CONFIRM_TIMEOUT)
1096            .await
1097    }
1098
1099    /// Ask the operator to authorise one in-flight, unchanged write for a named
1100    /// management operation.
1101    ///
1102    /// This sends the same `operator.confirm` request as [`Self::confirm_operator`],
1103    /// with `kind` set to `"operation"` and `operation` set to the given name.
1104    /// It shares the same deadline, withdrawal-on-drop and error mapping: every
1105    /// error means the module must refuse the write, and `Ok(())` authorises
1106    /// only the write this call was made for; it must never be cached or reused.
1107    ///
1108    /// A later daemon may answer without a prompt only when the name is listed
1109    /// in this module's manifest `confirm_operations`; the daemon decides.
1110    /// Naming an operation the module did not declare still prompts; it is not
1111    /// refused.
1112    /// An empty name is refused locally as
1113    /// [`OperatorConfirmError::OperationInvalid`] without sending anything.
1114    ///
1115    /// A consumer call that may trigger confirmation must set
1116    /// [`CallOptions::timeout`] to at least 300 seconds. This helper waits up to
1117    /// 290 seconds, including egress backpressure, and dropping it withdraws an
1118    /// accepted request.
1119    pub async fn confirm_operation(
1120        &self,
1121        summary: &str,
1122        caller_route: &RouteHandle,
1123        operation: &str,
1124    ) -> Result<(), OperatorConfirmError> {
1125        if operation.is_empty() {
1126            return Err(OperatorConfirmError::OperationInvalid);
1127        }
1128        self.confirm_operation_with_deadline(
1129            summary,
1130            caller_route,
1131            operation,
1132            OPERATOR_CONFIRM_TIMEOUT,
1133        )
1134        .await
1135    }
1136
1137    /// Ask the operator to authorise pairing or enrolling a device or credential.
1138    ///
1139    /// This sends the same `operator.confirm` request as [`Self::confirm_operator`],
1140    /// with `kind` set to `"enrollment"`. It shares the same deadline,
1141    /// withdrawal-on-drop and error mapping: every error means the module must
1142    /// refuse the enrollment, and `Ok(())` authorises only the enrollment this
1143    /// call was made for; it must never be cached or reused.
1144    ///
1145    /// The daemon never approves an enrollment without an operator prompt; it
1146    /// may still refuse one before prompting, as for any confirmation. A
1147    /// daemon built against subc-protocol before 0.33.5 ignores the kind and
1148    /// treats the request as [`Self::confirm_operator`] does.
1149    ///
1150    /// A consumer call that may trigger confirmation must set
1151    /// [`CallOptions::timeout`] to at least 300 seconds. This helper waits up to
1152    /// 290 seconds, including egress backpressure, and dropping it withdraws an
1153    /// accepted request.
1154    pub async fn confirm_enrollment(
1155        &self,
1156        summary: &str,
1157        caller_route: &RouteHandle,
1158    ) -> Result<(), OperatorConfirmError> {
1159        self.confirm_inner(
1160            summary,
1161            caller_route,
1162            Some(OperatorConfirmKind::Enrollment),
1163            None,
1164            OPERATOR_CONFIRM_TIMEOUT,
1165        )
1166        .await
1167    }
1168
1169    pub(crate) async fn confirm_operator_with_deadline(
1170        &self,
1171        summary: &str,
1172        caller_route: &RouteHandle,
1173        duration: Duration,
1174    ) -> Result<(), OperatorConfirmError> {
1175        self.confirm_inner(summary, caller_route, None, None, duration)
1176            .await
1177    }
1178
1179    async fn confirm_operation_with_deadline(
1180        &self,
1181        summary: &str,
1182        caller_route: &RouteHandle,
1183        operation: &str,
1184        duration: Duration,
1185    ) -> Result<(), OperatorConfirmError> {
1186        self.confirm_inner(
1187            summary,
1188            caller_route,
1189            Some(OperatorConfirmKind::Operation),
1190            Some(operation.to_owned()),
1191            duration,
1192        )
1193        .await
1194    }
1195
1196    async fn confirm_inner(
1197        &self,
1198        summary: &str,
1199        caller_route: &RouteHandle,
1200        kind: Option<OperatorConfirmKind>,
1201        operation: Option<String>,
1202        duration: Duration,
1203    ) -> Result<(), OperatorConfirmError> {
1204        if caller_route.connection_token() != self.shared.connection_token {
1205            return Err(OperatorConfirmError::NotPermitted);
1206        }
1207        if !self.shared.supports_operator_confirm {
1208            return Err(OperatorConfirmError::Unsupported);
1209        }
1210        // Use the same absolute deadline for both capacity and the reply: a
1211        // slow writer must not extend the time a confirmation can remain live.
1212        let deadline = Instant::now() + duration;
1213        let body = serde_json::to_vec(
1214            &OperatorConfirmRequest::new(summary, caller_route.channel, caller_route.epoch)
1215                .with_kind(kind)
1216                .with_operation(operation),
1217        )
1218        .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1219        let (corr, writer, rx) = self.shared.begin_operator_confirm()?;
1220        let mut guard = OperatorConfirmGuard {
1221            shared: Arc::clone(&self.shared),
1222            runtime: self.shared.connection_runtime.clone(),
1223            writer: writer.clone(),
1224            corr,
1225            accepted: false,
1226            armed: true,
1227        };
1228        let frame = Frame::build_with_version(
1229            self.shared.negotiated_ver,
1230            FrameType::Request,
1231            control_flags(),
1232            0,
1233            0,
1234            corr,
1235            body,
1236        )
1237        .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1238        tokio::select! {
1239            result = timeout_at(deadline, writer.send(frame)) => {
1240                result.map_err(|_| OperatorConfirmError::PresenceUnavailable)?
1241                    .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1242            }
1243            _ = self.shared.close_token.cancelled() => {
1244                return Err(OperatorConfirmError::PresenceUnavailable);
1245            }
1246        }
1247        guard.accepted = true;
1248        let reply = timeout_at(deadline, rx)
1249            .await
1250            .map_err(|_| OperatorConfirmError::PresenceUnavailable)?
1251            .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1252        guard.armed = false;
1253        match reply.header.ty {
1254            FrameType::Response => {
1255                match serde_json::from_slice::<OperatorConfirmReply>(&reply.body) {
1256                    Ok(body) if body.outcome == "confirmed" => Ok(()),
1257                    _ => Err(OperatorConfirmError::PresenceUnavailable),
1258                }
1259            }
1260            FrameType::Error => match serde_json::from_slice::<ErrorBody>(&reply.body) {
1261                Ok(body) => Err(match body.code.as_str() {
1262                    error_codes::OPERATOR_DECLINED => {
1263                        let detail = body.detail.as_ref();
1264                        if detail
1265                            .and_then(|detail| detail.get("reason"))
1266                            .and_then(serde_json::Value::as_str)
1267                            == Some("backoff")
1268                        {
1269                            OperatorConfirmError::Backoff {
1270                                retry_after_ms: detail
1271                                    .and_then(|detail| detail.get("retry_after_ms"))
1272                                    .and_then(serde_json::Value::as_u64),
1273                            }
1274                        } else {
1275                            OperatorConfirmError::Declined
1276                        }
1277                    }
1278                    error_codes::OPERATOR_PRESENCE_UNAVAILABLE
1279                        if body
1280                            .detail
1281                            .as_ref()
1282                            .and_then(|detail| detail.get("reason"))
1283                            .and_then(serde_json::Value::as_str)
1284                            == Some("unsupported_platform") =>
1285                    {
1286                        OperatorConfirmError::PresenceUnsupportedPlatform
1287                    }
1288                    error_codes::OPERATOR_SUMMARY_INVALID => OperatorConfirmError::SummaryInvalid,
1289                    error_codes::OPERATOR_REQUEST_NOT_PERMITTED | "not_registered" => {
1290                        OperatorConfirmError::NotPermitted
1291                    }
1292                    "unsupported_control_frame" => OperatorConfirmError::Unsupported,
1293                    _ => OperatorConfirmError::PresenceUnavailable,
1294                }),
1295                Err(_) => Err(OperatorConfirmError::PresenceUnavailable),
1296            },
1297            _ => Err(OperatorConfirmError::PresenceUnavailable),
1298        }
1299    }
1300
1301    /// Send one channel-0 control request and wait for its reply, through the
1302    /// same correlation table, writer and timeout as `catalog_update` and
1303    /// `live_roots`. The caller checks that the reply is the right variant.
1304    async fn scope_call(
1305        &self,
1306        op: &'static str,
1307        request: &ModuleControlRequestFromModule,
1308    ) -> Result<ModuleControlReply, ScopeCallError> {
1309        let body = serde_json::to_vec(request).map_err(|err| {
1310            ScopeCallError::Protocol(format!("failed to encode {op} request body: {err}"))
1311        })?;
1312        let (corr, writer, rx) = self
1313            .shared
1314            .begin_catalog_update()
1315            .map_err(ScopeCallError::from_control_error)?;
1316        let frame = Frame::build_with_version(
1317            self.shared.negotiated_ver,
1318            FrameType::Request,
1319            control_flags(),
1320            0,
1321            0,
1322            corr,
1323            body,
1324        )
1325        .map_err(|err| {
1326            self.shared.remove_pending_catalog_update(corr);
1327            ScopeCallError::Protocol(format!("failed to build {op} request frame: {err}"))
1328        })?;
1329        if writer.send(frame).await.is_err() {
1330            self.shared.remove_pending_catalog_update(corr);
1331            return Err(ScopeCallError::ConnectionClosed);
1332        }
1333        match timeout(CATALOG_UPDATE_TIMEOUT, rx).await {
1334            Ok(Ok(reply)) => reply.map_err(ScopeCallError::from_control_error),
1335            Ok(Err(_)) => Err(ScopeCallError::ConnectionClosed),
1336            Err(_) => {
1337                self.shared.remove_pending_catalog_update(corr);
1338                Err(ScopeCallError::Timeout)
1339            }
1340        }
1341    }
1342
1343    /// Emit an uncorrelated Push on a live route.
1344    pub async fn push(
1345        &self,
1346        handle: &RouteHandle,
1347        body: Vec<u8>,
1348        admission_class: Option<AdmissionClass>,
1349    ) -> Result<(), SubcModuleError> {
1350        self.validate_route(*handle)?;
1351        let writer = self
1352            .shared
1353            .lock_inner()
1354            .writer
1355            .clone()
1356            .ok_or(SubcModuleError::WriterClosed)?;
1357        let frame = Frame::build_with_version(
1358            self.shared.negotiated_ver,
1359            FrameType::Push,
1360            data_flags().with_admission_class(admission_class.unwrap_or(AdmissionClass::Normal)),
1361            handle.channel,
1362            handle.epoch,
1363            0,
1364            body,
1365        )
1366        .map_err(SubcModuleError::FrameBuild)?;
1367        send_outbound(&writer, frame).await
1368    }
1369
1370    /// Number of unknown or stale route frames silently dropped by endpoint validation.
1371    pub fn dropped_route_frames(&self) -> u64 {
1372        self.shared.dropped_route_frames.load(Ordering::Relaxed)
1373    }
1374
1375    fn validate_route(&self, handle: RouteHandle) -> Result<(), SubcModuleError> {
1376        if handle.connection_token() != self.shared.connection_token {
1377            return Err(SubcModuleError::StaleRouteHandle(handle));
1378        }
1379        let routes = self
1380            .shared
1381            .live_routes
1382            .lock()
1383            .map_err(|_| SubcModuleError::InFlightPoisoned)?;
1384        if routes.get(&handle.channel) == Some(&handle) {
1385            Ok(())
1386        } else {
1387            Err(SubcModuleError::StaleRouteHandle(handle))
1388        }
1389    }
1390
1391    fn install_route(&self, handle: RouteHandle) -> Result<(), SubcModuleError> {
1392        self.shared
1393            .live_routes
1394            .lock()
1395            .map_err(|_| SubcModuleError::InFlightPoisoned)?
1396            .insert(handle.channel, handle);
1397        Ok(())
1398    }
1399
1400    fn installed_route(&self, channel: u16) -> Result<Option<RouteHandle>, SubcModuleError> {
1401        Ok(self
1402            .shared
1403            .live_routes
1404            .lock()
1405            .map_err(|_| SubcModuleError::InFlightPoisoned)?
1406            .get(&channel)
1407            .copied())
1408    }
1409
1410    fn remove_route(&self, handle: RouteHandle) -> Result<bool, SubcModuleError> {
1411        let mut routes = self
1412            .shared
1413            .live_routes
1414            .lock()
1415            .map_err(|_| SubcModuleError::InFlightPoisoned)?;
1416        if routes.get(&handle.channel) == Some(&handle) {
1417            routes.remove(&handle.channel);
1418            Ok(true)
1419        } else {
1420            Ok(false)
1421        }
1422    }
1423
1424    fn validate_ingress(&self, channel: u16, epoch: u32) -> Result<bool, SubcModuleError> {
1425        let handle = RouteHandle::new(channel, epoch, self.shared.connection_token);
1426        let valid = self
1427            .shared
1428            .live_routes
1429            .lock()
1430            .map_err(|_| SubcModuleError::InFlightPoisoned)?
1431            .get(&channel)
1432            == Some(&handle);
1433        if !valid {
1434            self.shared
1435                .dropped_route_frames
1436                .fetch_add(1, Ordering::Relaxed);
1437        }
1438        Ok(valid)
1439    }
1440
1441    fn route_handle(&self, channel: u16, epoch: u32) -> RouteHandle {
1442        RouteHandle::new(channel, epoch, self.shared.connection_token)
1443    }
1444
1445    fn handle_control_reply(&self, frame: Frame) -> bool {
1446        let Some(frame) = self.handle_control_stream_frame(frame) else {
1447            return true;
1448        };
1449        let claim_reply = self
1450            .shared
1451            .lock_inner()
1452            .pending_claim_calls
1453            .remove(&frame.header.corr);
1454        if let Some(reply) = claim_reply {
1455            let _ = reply.send(frame);
1456            return true;
1457        }
1458        let config_reply = self
1459            .shared
1460            .lock_inner()
1461            .pending_config_calls
1462            .remove(&frame.header.corr);
1463        if let Some(reply) = config_reply {
1464            let _ = reply.send(frame);
1465            return true;
1466        }
1467        if let Some(reply) = self
1468            .shared
1469            .lock_inner()
1470            .pending_agent_commands
1471            .remove(&frame.header.corr)
1472        {
1473            let _ = reply.send(frame);
1474            return true;
1475        }
1476        let served_by_reply = self
1477            .shared
1478            .lock_inner()
1479            .pending_scope_served_by
1480            .remove(&frame.header.corr);
1481        if let Some(reply) = served_by_reply {
1482            let _ = reply.send(frame);
1483            return true;
1484        }
1485        let activity_reply = self
1486            .shared
1487            .lock_inner()
1488            .pending_activity_records
1489            .remove(&frame.header.corr);
1490        if let Some(reply) = activity_reply {
1491            let _ = reply.send(frame);
1492            return true;
1493        }
1494        let operator_reply = self
1495            .shared
1496            .lock_inner()
1497            .pending_operator_confirms
1498            .remove(&frame.header.corr);
1499        if let Some(reply) = operator_reply {
1500            let _ = reply.send(frame);
1501            return true;
1502        }
1503        let Some(reply) = self.shared.take_pending_catalog_update(frame.header.corr) else {
1504            return false;
1505        };
1506        let result = match frame.header.ty {
1507            FrameType::Response => serde_json::from_slice::<ModuleControlReply>(&frame.body)
1508                .map_err(|err| {
1509                    CatalogUpdateError::Protocol(format!(
1510                        "invalid module control response body: {err}"
1511                    ))
1512                }),
1513            FrameType::Error => match serde_json::from_slice::<ErrorBody>(&frame.body) {
1514                Ok(body) => Err(match body.code.as_str() {
1515                    "catalog_update_frozen_field" => CatalogUpdateError::FrozenField(body),
1516                    "not_registered" => CatalogUpdateError::NotRegistered(body),
1517                    _ => CatalogUpdateError::Rejected(body),
1518                }),
1519                Err(err) => Err(CatalogUpdateError::Protocol(format!(
1520                    "invalid catalog.update error body: {err}"
1521                ))),
1522            },
1523            ty => Err(CatalogUpdateError::Protocol(format!(
1524                "unexpected catalog.update terminal frame: {ty:?}"
1525            ))),
1526        };
1527        let outcome = match &result {
1528            Ok(ModuleControlReply::Control(reply))
1529                if matches!(
1530                    reply.as_ref(),
1531                    ModuleControlResponseToModule::CatalogUpdate {}
1532                ) =>
1533            {
1534                CatalogChangeOutcome::Accepted
1535            }
1536            Err(CatalogUpdateError::FrozenField(_))
1537            | Err(CatalogUpdateError::NotRegistered(_))
1538            | Err(CatalogUpdateError::Rejected(_)) => CatalogChangeOutcome::Rejected,
1539            _ => CatalogChangeOutcome::Unknown,
1540        };
1541        self.shared
1542            .finish_catalog_change(frame.header.corr, outcome);
1543        let _ = reply.send(result);
1544        true
1545    }
1546
1547    fn close_connection(&self) {
1548        self.shared.close_connection();
1549    }
1550}
1551
1552impl ModuleHandleShared {
1553    fn begin_catalog_update(&self) -> Result<CatalogUpdateRequest, CatalogUpdateError> {
1554        let mut inner = self.lock_inner();
1555        if inner.closed {
1556            return Err(CatalogUpdateError::ConnectionClosed);
1557        }
1558        let Some(writer) = inner.writer.clone() else {
1559            drop(inner);
1560            self.close_connection();
1561            return Err(CatalogUpdateError::ConnectionClosed);
1562        };
1563        let Some(corr) = next_module_control_corr(&mut inner) else {
1564            drop(inner);
1565            self.close_connection();
1566            return Err(CatalogUpdateError::ConnectionClosed);
1567        };
1568        let (tx, rx) = oneshot::channel();
1569        inner.pending_catalog_updates.insert(corr, tx);
1570        Ok((corr, writer, rx))
1571    }
1572
1573    fn begin_operator_confirm(&self) -> Result<OperatorConfirmRequestWaiter, OperatorConfirmError> {
1574        let mut inner = self.lock_inner();
1575        if inner.closed {
1576            return Err(OperatorConfirmError::PresenceUnavailable);
1577        }
1578        let Some(writer) = inner.writer.clone() else {
1579            drop(inner);
1580            self.close_connection();
1581            return Err(OperatorConfirmError::PresenceUnavailable);
1582        };
1583        let Some(corr) = next_module_control_corr(&mut inner) else {
1584            drop(inner);
1585            self.close_connection();
1586            return Err(OperatorConfirmError::PresenceUnavailable);
1587        };
1588        let (tx, rx) = oneshot::channel();
1589        inner.pending_operator_confirms.insert(corr, tx);
1590        Ok((corr, writer, rx))
1591    }
1592
1593    fn take_pending_catalog_update(&self, corr: u64) -> Option<CatalogUpdateReply> {
1594        self.lock_inner().pending_catalog_updates.remove(&corr)
1595    }
1596
1597    fn remove_pending_catalog_update(&self, corr: u64) {
1598        let removed = self
1599            .lock_inner()
1600            .pending_catalog_updates
1601            .remove(&corr)
1602            .is_some();
1603        if removed {
1604            self.finish_catalog_change(corr, CatalogChangeOutcome::Unknown);
1605        }
1606    }
1607
1608    fn finish_catalog_change(&self, corr: u64, outcome: CatalogChangeOutcome) {
1609        let mut inner = self.lock_inner();
1610        if let Some(change) = inner
1611            .catalog_changes
1612            .iter_mut()
1613            .find(|change| change.corr == corr)
1614        {
1615            change.outcome = Some(outcome);
1616        }
1617        // Replies may arrive out of order. Apply their effects in send order,
1618        // including replies whose caller dropped its waiting future.
1619        while inner
1620            .catalog_changes
1621            .front()
1622            .is_some_and(|change| change.outcome.is_some())
1623        {
1624            let change = inner.catalog_changes.pop_front().expect("completed change");
1625            match change.outcome.expect("completed outcome") {
1626                CatalogChangeOutcome::Accepted => inner.current_provides = Some(change.provides),
1627                CatalogChangeOutcome::Rejected => {}
1628                CatalogChangeOutcome::Unknown => inner.current_provides = None,
1629            }
1630        }
1631    }
1632
1633    fn close_connection(&self) {
1634        let pending = {
1635            let mut inner = self.lock_inner();
1636            if inner.closed {
1637                return;
1638            }
1639            inner.closed = true;
1640            inner.writer = None;
1641            inner.current_provides = None;
1642            inner.catalog_changes.clear();
1643            self.close_token.cancel();
1644            // Dropping these senders wakes raw-frame waiters immediately.
1645            inner.pending_operator_confirms.clear();
1646            inner.pending_activity_records.clear();
1647            inner.pending_scope_served_by.clear();
1648            inner.pending_config_calls.clear();
1649            inner.pending_agent_commands.clear();
1650            inner.pending_claim_calls.clear();
1651            inner.pending_control_streams.clear();
1652            inner
1653                .pending_catalog_updates
1654                .drain()
1655                .map(|(_, reply)| reply)
1656                .collect::<Vec<_>>()
1657        };
1658        self.clear_live_routes();
1659        for reply in pending {
1660            let _ = reply.send(Err(CatalogUpdateError::ConnectionClosed));
1661        }
1662    }
1663
1664    fn clear_live_routes(&self) {
1665        if let Ok(mut routes) = self.live_routes.lock() {
1666            routes.clear();
1667        }
1668    }
1669
1670    fn lock_inner(&self) -> std::sync::MutexGuard<'_, ModuleHandleState> {
1671        self.inner
1672            .lock()
1673            .unwrap_or_else(|poisoned| poisoned.into_inner())
1674    }
1675}
1676
1677fn next_module_control_corr(inner: &mut ModuleHandleState) -> Option<u64> {
1678    let corr = inner.next_corr?;
1679    inner.next_corr = corr.checked_add(1);
1680    Some(corr)
1681}
1682
1683struct OperatorConfirmGuard {
1684    shared: Arc<ModuleHandleShared>,
1685    runtime: tokio::runtime::Handle,
1686    writer: mpsc::Sender<Frame>,
1687    corr: u64,
1688    accepted: bool,
1689    armed: bool,
1690}
1691
1692impl Drop for OperatorConfirmGuard {
1693    fn drop(&mut self) {
1694        if !self.armed {
1695            return;
1696        }
1697        self.shared
1698            .lock_inner()
1699            .pending_operator_confirms
1700            .remove(&self.corr);
1701        if !self.accepted {
1702            return;
1703        }
1704        let Ok(cancel) = Frame::build_with_version(
1705            self.shared.negotiated_ver,
1706            FrameType::Cancel,
1707            control_flags(),
1708            0,
1709            0,
1710            self.corr,
1711            Vec::new(),
1712        ) else {
1713            return;
1714        };
1715        match self.writer.try_send(cancel) {
1716            Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
1717            Err(mpsc::error::TrySendError::Full(cancel)) => {
1718                // The connection owns this task even if the future was polled
1719                // on another runtime or dropped from a plain thread. A full
1720                // egress buffer delays withdrawal; it must not discard it.
1721                let writer = self.writer.clone();
1722                self.runtime.spawn(async move {
1723                    let _ = writer.send(cancel).await;
1724                });
1725            }
1726        }
1727    }
1728}
1729
1730/// Failure to authorise a write through [`ModuleHandle::confirm_operator`],
1731/// [`ModuleHandle::confirm_operation`] or [`ModuleHandle::confirm_enrollment`].
1732/// Every variant requires the module to refuse the write, with one exception
1733/// described on [`OperatorConfirmError::PresenceUnsupportedPlatform`].
1734#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1735#[non_exhaustive]
1736pub enum OperatorConfirmError {
1737    Declined,
1738    /// The daemon did not ask because a recent decline is still in effect.
1739    /// Older daemons omit the remaining cooldown, so `retry_after_ms` may be absent.
1740    Backoff {
1741        retry_after_ms: Option<u64>,
1742    },
1743    /// The daemon could not get an answer from the operator: the prompt
1744    /// failed or timed out, the connection dropped, or the reply was unknown
1745    /// or malformed. A withdrawn prompt can instead come back as
1746    /// [`OperatorConfirmError::Declined`].
1747    PresenceUnavailable,
1748    /// The daemon has no operator prompt on this platform (today Linux), so
1749    /// it showed none. It answered `operator_presence_unavailable` with
1750    /// `detail.reason` `unsupported_platform`. Every other
1751    /// `operator_presence_unavailable` reply stays
1752    /// [`OperatorConfirmError::PresenceUnavailable`].
1753    ///
1754    /// Like every variant, this refuses the write by default. A module may
1755    /// treat it differently only where its owner has ruled that, on a platform
1756    /// without a prompt, a confirmation typed by a person in a local app
1757    /// counts, and the product says so. It must never treat a
1758    /// `PresenceUnavailable` that way.
1759    PresenceUnsupportedPlatform,
1760    SummaryInvalid,
1761    /// The operation name for [`ModuleHandle::confirm_operation`] was empty.
1762    /// Operation names have no lexical grammar in Rust; membership in the
1763    /// module's manifest `confirm_operations` is decided by the daemon, which
1764    /// prompts for any name it does not recognise. Only the empty string can
1765    /// never name an operation, so it is refused before sending.
1766    OperationInvalid,
1767    NotPermitted,
1768    Unsupported,
1769}
1770
1771impl fmt::Display for OperatorConfirmError {
1772    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1773        f.write_str(match self {
1774            Self::Declined => "operator declined the write",
1775            Self::Backoff { retry_after_ms: None } => {
1776                "operator confirmation refused without asking: a recent decline holds new prompts for a short time"
1777            }
1778            Self::PresenceUnavailable => "operator confirmation is unavailable",
1779            Self::PresenceUnsupportedPlatform => {
1780                "operator confirmation has no prompt on this platform"
1781            }
1782            Self::SummaryInvalid => "operator confirmation summary is invalid",
1783            Self::OperationInvalid => "operator confirmation operation is invalid",
1784            Self::NotPermitted => "operator confirmation is not permitted for this route",
1785            Self::Unsupported => "daemon does not support operator confirmation",
1786            Self::Backoff {
1787                retry_after_ms: Some(_),
1788            } => return write!(
1789                f,
1790                "operator confirmation refused without asking: a recent decline holds new prompts for {} s",
1791                self.backoff_seconds().expect("backoff retry duration is present")
1792            ),
1793        })
1794    }
1795}
1796
1797impl OperatorConfirmError {
1798    fn backoff_seconds(&self) -> Option<u64> {
1799        match self {
1800            Self::Backoff {
1801                retry_after_ms: Some(milliseconds),
1802            } => Some(milliseconds / 1_000 + u64::from(!milliseconds.is_multiple_of(1_000))),
1803            _ => None,
1804        }
1805    }
1806}
1807
1808impl Error for OperatorConfirmError {}
1809
1810/// Errors returned by [`ModuleHandle::catalog_update`], [`ModuleHandle::set_ready`]
1811/// and [`ModuleHandle::update_role_declarations`].
1812#[derive(Debug)]
1813pub enum CatalogUpdateError {
1814    NotSupported,
1815    FrozenField(ErrorBody),
1816    NotRegistered(ErrorBody),
1817    Rejected(ErrorBody),
1818    Timeout,
1819    ConnectionClosed,
1820    Protocol(String),
1821}
1822
1823impl fmt::Display for CatalogUpdateError {
1824    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1825        match self {
1826            Self::NotSupported => write!(
1827                f,
1828                "daemon HELLO_ACK did not advertise catalog.update support"
1829            ),
1830            Self::FrozenField(body) => {
1831                write!(f, "catalog.update rejected frozen field: {}", body.message)
1832            }
1833            Self::NotRegistered(body) => write!(
1834                f,
1835                "catalog.update requires a registered module: {}",
1836                body.message
1837            ),
1838            Self::Rejected(body) => write!(
1839                f,
1840                "catalog.update rejected by subc: {} ({})",
1841                body.code, body.message
1842            ),
1843            Self::Timeout => write!(f, "catalog.update timed out waiting for an ACK"),
1844            Self::ConnectionClosed => {
1845                write!(f, "subc connection closed before catalog.update completed")
1846            }
1847            Self::Protocol(message) => write!(f, "catalog.update protocol error: {message}"),
1848        }
1849    }
1850}
1851
1852impl Error for CatalogUpdateError {}
1853
1854/// Errors returned by [`ModuleHandle::scope_sync`], [`ModuleHandle::scope_apply`] and
1855/// [`ModuleHandle::scope_describe`].
1856///
1857/// Non-exhaustive so a later failure kind can be added without breaking
1858/// callers' matches. Match the variants you handle, and treat any other variant
1859/// as a call whose effect you cannot know: after `scope_sync` or `scope_apply`,
1860/// send a full `scope_sync` at a higher generation rather than assume the change
1861/// did or did not apply.
1862#[derive(Debug, Clone, PartialEq, Eq)]
1863#[non_exhaustive]
1864pub enum ScopeCallError {
1865    /// HELLO_ACK did not advertise the operation (or its required capability),
1866    /// so nothing was sent.
1867    NotSupported { op: &'static str },
1868    /// The daemon refused the request with a channel-0 Error frame. `code` is
1869    /// the daemon's code as sent, to compare against the constants in
1870    /// `subc_protocol::error_codes` (`SCOPE_SYNC_STALE`,
1871    /// `SCOPE_SYNC_NOT_AUTHORITY`, `SCOPE_LIVE_LIMIT_EXCEEDED`, ...).
1872    Refused { code: String, message: String },
1873    /// No reply arrived in time. The daemon may still have applied the change.
1874    Timeout,
1875    /// The connection closed before a reply arrived.
1876    ConnectionClosed,
1877    /// The reply could not be read, or was a reply to a different op.
1878    Protocol(String),
1879}
1880
1881impl ScopeCallError {
1882    /// The daemon's error code, when the daemon refused the request.
1883    pub fn code(&self) -> Option<&str> {
1884        match self {
1885            Self::Refused { code, .. } => Some(code),
1886            _ => None,
1887        }
1888    }
1889
1890    /// Convert an error from the pending-reply handling that scope calls share
1891    /// with `catalog_update`, which reports failures as `CatalogUpdateError`.
1892    /// For a daemon Error frame, keep the daemon's code and message whatever
1893    /// the code is.
1894    fn from_control_error(err: CatalogUpdateError) -> Self {
1895        match err {
1896            CatalogUpdateError::FrozenField(body)
1897            | CatalogUpdateError::NotRegistered(body)
1898            | CatalogUpdateError::Rejected(body) => Self::Refused {
1899                code: body.code,
1900                message: body.message,
1901            },
1902            CatalogUpdateError::Timeout => Self::Timeout,
1903            CatalogUpdateError::ConnectionClosed => Self::ConnectionClosed,
1904            CatalogUpdateError::Protocol(message) => Self::Protocol(message),
1905            // The shared reply handling never returns this: whether the
1906            // daemon supports an op is checked before the request is sent.
1907            CatalogUpdateError::NotSupported => {
1908                Self::Protocol("unexpected NotSupported from the control reply table".into())
1909            }
1910        }
1911    }
1912}
1913
1914impl fmt::Display for ScopeCallError {
1915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1916        match self {
1917            Self::NotSupported { op } => {
1918                write!(f, "daemon HELLO_ACK did not advertise {op} support")
1919            }
1920            Self::Refused { code, message } => {
1921                write!(f, "subc refused the request: {code} ({message})")
1922            }
1923            Self::Timeout => write!(f, "timed out waiting for the daemon's reply"),
1924            Self::ConnectionClosed => {
1925                write!(f, "subc connection closed before the daemon replied")
1926            }
1927            Self::Protocol(message) => write!(f, "scope call protocol error: {message}"),
1928        }
1929    }
1930}
1931
1932impl Error for ScopeCallError {}
1933
1934/// Trait implemented by a module for its business logic. The serve functions in
1935/// this crate own all wire-protocol plumbing.
1936///
1937/// # Stopping cleanly: drains
1938///
1939/// Before the daemon stops a module (restart, reload, disable, swap, or its own
1940/// shutdown) it closes route admission, tells the module with
1941/// [`ModuleHandler::on_draining`], waits for the module's in-flight requests to
1942/// finish, and only then sends GOODBYE and closes the connection. The wait ends
1943/// at the drain deadline whether or not the work is done.
1944///
1945/// Requests the daemon forwarded are counted by the daemon itself. Work it
1946/// cannot see (a job a request started in the background, a batch being
1947/// flushed) holds the drain open only if the module says so. The module does
1948/// that with a counter it reports in its health answer (a "health gauge"),
1949/// and a manifest entry telling the daemon that the counter means "busy": a
1950/// `Busy` self-signal anchored to those health gauges. Declare it, and report those
1951/// gauges in [`ModuleHandler::health`]'s `metrics` above zero until the work
1952/// has finished. During a drain the daemon probes `health` and waits until
1953/// every declared gauge reads 0 (or the deadline passes); a declared gauge
1954/// missing from the report counts as busy. The manifest entry, as built by the
1955/// `echo-module` example in this crate:
1956///
1957/// ```
1958/// use subc_protocol::manifest::{
1959///     ModuleManifest, SelfSignalDeclaration, SelfSignalEffect, SelfSignalKind, SignalAnchor,
1960/// };
1961///
1962/// let manifest = ModuleManifest::builder("my-module", "1.0.0")
1963///     .self_signals(Some(vec![SelfSignalDeclaration {
1964///         name: "background_work".to_string(),
1965///         kind: SelfSignalKind::Busy,
1966///         effect: SelfSignalEffect::Observe,
1967///         anchored_to: SignalAnchor::HealthGauges {
1968///             gauges: vec!["background_jobs".to_string()],
1969///         },
1970///         cadence: None,
1971///         domain: None,
1972///         note: None,
1973///     }]))
1974///     .build();
1975/// # let _ = manifest;
1976/// ```
1977///
1978/// and `health` then reports `{"background_jobs": <count>}` in `metrics`. Count
1979/// only work whose result would still be delivered if it finished during the
1980/// drain; see [`SelfSignalDeclaration::kind`](subc_protocol::manifest::SelfSignalDeclaration::kind).
1981#[async_trait]
1982pub trait ModuleHandler: Send + Sync + 'static {
1983    /// Handle a data-plane request on a route channel. Return a unary response, a
1984    /// typed error, or stream interim events via [`RequestCtx::emit`] and return
1985    /// [`HandlerOutcome::Streamed`]. Each request runs in its own task so one slow
1986    /// handler cannot head-of-line-block another route.
1987    async fn handle(&self, ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome;
1988
1989    /// Called once after HELLO_ACK so the module can inspect the ack body for
1990    /// negotiated capabilities and any storage descriptor supplied by the daemon.
1991    async fn on_hello_ack(&self, _ack: &ModuleHelloAckBody) {}
1992
1993    /// Extra daemon-to-module operations served on channel 0, such as `consent/v1`.
1994    /// Read and validated once before HELLO: names must be nonempty ASCII names
1995    /// using letters, digits, `.`, `_`, `-` or `/`, with no empty segments.
1996    /// Duplicates and SDK-owned `health.check`, `config.review` and `route.bind`
1997    /// are refused with [`SubcModuleError::InvalidControlOp`] before advertising.
1998    fn control_ops(&self) -> Vec<String> {
1999        Vec::new()
2000    }
2001
2002    /// Handle a declared control op with its entire decoded JSON request body.
2003    /// The control name is the body's `op` string; for a protocol-tagged request
2004    /// with no `op`, such as `consent/v1`, it is the body's `protocol` string.
2005    /// Return a JSON RESPONSE body or an [`ErrorBody`] carrying a wire error code
2006    /// and message. Runs off the reader, independently of routes, health and
2007    /// config review, with at most 16 concurrent calls per connection and no
2008    /// queue; overload returns `resource_exhausted`. There is no SDK time limit.
2009    ///
2010    /// CANCEL for this request's correlation, or disconnect, signals `cancel`.
2011    /// A reply produced after cancellation is discarded. Cooperate with the
2012    /// signal to release resources promptly; a cancelled call still holds its
2013    /// slot until it returns, and connection teardown eventually aborts it.
2014    async fn on_control_request(
2015        &self,
2016        _op: &str,
2017        _body: serde_json::Value,
2018        _cancel: CancellationToken,
2019    ) -> Result<serde_json::Value, ErrorBody> {
2020        Err(ErrorBody::new(
2021            "unsupported_op",
2022            "no control handler implemented",
2023        ))
2024    }
2025
2026    /// Opt in once per connection. The SDK advertises `config.review`, declares
2027    /// these locations, and fetches immutable views before calling `config_apply`.
2028    /// Returning `None` leaves the existing module wire and file reader unchanged.
2029    fn config_declaration(&self) -> Option<config::ConfigDeclareRequest> {
2030        None
2031    }
2032
2033    /// Pure review of supplied snapshots and base. Do not read mutable files,
2034    /// environment, network or secrets here. Runs off the connection reader.
2035    async fn config_review(
2036        &self,
2037        _request: config::ConfigReviewRequest,
2038    ) -> config::ConfigReviewReply {
2039        config::ConfigReviewReply::new(
2040            vec![],
2041            vec![config::ConfigReviewRefusal::new(
2042                "value_invalid",
2043                vec![],
2044                vec!["module has no config review implementation".into()],
2045            )],
2046        )
2047    }
2048
2049    /// Atomically apply a complete view, or leave the previous view intact and
2050    /// return secret-free NACK reasons. Readiness is included in a successful
2051    /// return. Runs off the reader; health and drain hooks remain independent.
2052    async fn config_apply(&self, _view: config::ConfigView) -> Result<(), Vec<String>> {
2053        Err(vec!["module has no config apply implementation".into()])
2054    }
2055
2056    /// Use the module's existing file reader. Called only for an opted-in module
2057    /// whose HELLO_ACK lacks `config.gate`, never after a gate refusal.
2058    async fn config_files(&self) {}
2059
2060    /// Observe wire status and refusals without ending the serving connection.
2061    async fn on_config_state(&self, _state: config::ConfigState) {}
2062
2063    /// Observe transport, malformed-reply and other config errors. These never
2064    /// authorize a file fallback or end the module connection.
2065    async fn on_config_error(&self, error: config::ConfigError) {
2066        tracing::warn!(%error, "module configuration request failed");
2067    }
2068
2069    /// Observe refusals and protocol errors for a named project refresh.
2070    /// Keep the project's last good view, or use the user view if none exists.
2071    /// By default, forwards to [`Self::on_config_error`].
2072    async fn on_project_config_error(&self, _project_id: String, error: config::ConfigError) {
2073        self.on_config_error(error).await;
2074    }
2075
2076    /// Decide a route.bind. This hook is decision-only and must not emit route traffic.
2077    async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
2078        BindDecision::accept()
2079    }
2080
2081    /// Called after an accepted bind ACK is queued and the handle is installed.
2082    async fn on_bound(&self, _handle: &RouteHandle) {}
2083
2084    /// Return cheap in-memory health for the module.
2085    ///
2086    /// The default reports `Ok` with the detail "no health implementation;
2087    /// inherited default". The detail lets an operator reading
2088    /// `ck health <module>` tell "measured, nothing wrong" from "nobody
2089    /// measured", but the daemon decides on the status alone and never parses
2090    /// the detail, so to the daemon the default looks like a module that checked
2091    /// itself and found nothing wrong. It stays a default because health is
2092    /// optional: a module that advertises no health capability is never probed,
2093    /// so the value is never read. A module that does advertise health and
2094    /// keeps this default can report no fault beyond the serve helper's own
2095    /// saturation check.
2096    ///
2097    /// The serve helper calls this when the daemon sends `health.check`, on a
2098    /// task of its own rather than in a handler-slot pool, so a health check
2099    /// never waits behind the requests it reports on. It then folds in
2100    /// dispatch saturation: if every slot of a pool is in use and a request
2101    /// has waited more than two seconds for one, an `Ok` reply becomes
2102    /// `Degraded`, and the pool's slot count and oldest wait are prepended to
2103    /// `detail` (naming the pool when the module declared a long-held pool in
2104    /// [`ModuleHandler::request_pools`]). A `Degraded` or `Failing` status,
2105    /// the module's own detail and its metrics are kept.
2106    ///
2107    /// An implementation must not block: no blocking lock, no disk access and
2108    /// no subprocess on this path. Derive the status from signals the dispatch
2109    /// path already records in memory, such as a monotonic heartbeat or the age
2110    /// of the oldest queued item. A health reply that waits on a slow shared
2111    /// resource stalls under exactly the conditions it is meant to report,
2112    /// because that resource is what degrades first.
2113    async fn health(&self) -> HealthReport {
2114        // Say that nobody measured, rather than that everything is fine.
2115        //
2116        // The status stays Ok because a module advertising no health capability
2117        // is never probed, and one that advertises health but has nothing to
2118        // report is not unhealthy. What changes is that the report identifies
2119        // itself as the inherited default, so an operator reading
2120        // `ck health <module>` can tell "measured, nothing wrong" from "nobody
2121        // wrote a health path" -- which were previously the same bytes.
2122        //
2123        // `detail` is carried verbatim by the daemon and rendered for humans;
2124        // nothing parses it, so this is display-only and cannot change any
2125        // supervision decision.
2126        HealthReport {
2127            detail: Some("no health implementation; inherited default".to_string()),
2128            ..HealthReport::ok()
2129        }
2130    }
2131
2132    /// A route was torn down, rejected, or abandoned before its bind ACK was queued.
2133    async fn on_route_gone(&self, _handle: &RouteHandle) {}
2134
2135    /// How this module's data requests share handler slots. Called once per
2136    /// connection, before the serve loop reads its first frame after HELLO_ACK.
2137    ///
2138    /// Each data request waits for a slot before [`ModuleHandler::handle`]
2139    /// runs and holds it until `handle` returns. The default is one pool of
2140    /// 64 slots for every request, waited for in arrival order. A module whose
2141    /// requests can be held for minutes should declare a long-held pool for
2142    /// them, so they cannot take every slot and leave short requests queued
2143    /// behind them where the daemon cannot see:
2144    ///
2145    /// ```
2146    /// use subc_client_rs::{RequestClass, RequestPools};
2147    ///
2148    /// fn request_pools() -> RequestPools {
2149    ///     RequestPools::new().with_long_held(16, |body| {
2150    ///         if body.starts_with(br#"{"op":"research.run""#) {
2151    ///             RequestClass::long_held().with_op("research.run")
2152    ///         } else {
2153    ///             RequestClass::default_pool()
2154    ///         }
2155    ///     })
2156    /// }
2157    /// # let _ = request_pools();
2158    /// ```
2159    ///
2160    /// A request that waits two seconds for a slot is logged once at WARN
2161    /// while it is still waiting. While the connection is open, a request
2162    /// cancelled while waiting is answered `cancelled` at once; when the
2163    /// connection ends, waiting requests end without a reply, as before.
2164    /// [`ModuleHandle::request_pool_snapshots`]
2165    /// reports each pool's figures. Health checks never use a pool.
2166    fn request_pools(&self) -> RequestPools {
2167        RequestPools::new()
2168    }
2169
2170    /// The daemon has started draining this module: it will stop it for
2171    /// `reason` (a restart, reload, disable, or the daemon's own shutdown), and
2172    /// has already stopped admitting new routes to it. Stop taking new work
2173    /// here and finish or hand off what is in flight; see the trait docs for
2174    /// how to keep the drain open while background work finishes.
2175    ///
2176    /// `deadline` is the wall-clock time by which the module must be done. It
2177    /// is "no later than", never a grant of that much time: the daemon enforces
2178    /// its own ceiling on a monotonic clock and tears the connection down when
2179    /// that runs out, and after the host sleeps the ceiling can fall before
2180    /// this wall-clock time does. Aim to finish early.
2181    ///
2182    /// Called once for each drain notice the daemon sends, on its own task, so
2183    /// a slow hook never holds up pings, requests, or the GOODBYE that ends the
2184    /// drain. It is started before that GOODBYE is handled (and before
2185    /// [`ModuleHandler::on_connection_end`]). Connection teardown aborts hooks
2186    /// that have not finished within the drain budget.
2187    async fn on_draining(&self, _reason: RouteCloseReason, _deadline: SystemTime) {}
2188
2189    /// The connection ended orderly: a daemon GOODBYE is a planned stop, EOF
2190    /// or Reset means the daemon went away without one, and `Closed` is a
2191    /// module stop. Called once, after request tasks have finished or been
2192    /// cancelled. A module that wants a different exit code for an unannounced
2193    /// end can decide here. Not called for handler or protocol failures. A
2194    /// later, unexpected writer failure can still make serving return an error.
2195    async fn on_connection_end(&self, _end: ConnectionEnd) {}
2196}
2197
2198/// How a registered module's daemon connection ended. After the handshake, EOF
2199/// and socket disconnects are orderly ends on every platform: serving calls
2200/// `on_connection_end` and returns `Ok(())`. Handshake, handler, protocol and
2201/// other transport failures return errors.
2202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2203#[non_exhaustive]
2204pub enum ConnectionEnd {
2205    /// The daemon sent GOODBYE on channel 0: a planned stop.
2206    Goodbye,
2207    /// The daemon closed the connection without GOODBYE.
2208    Eof,
2209    /// The socket was reset or aborted, or its writer disconnected. This is how
2210    /// Windows reports a daemon that died, which Unix reports as [`Self::Eof`].
2211    Reset,
2212    /// The module closed the connection itself, including a [`ModuleStopHandle`] stop.
2213    Closed,
2214}
2215
2216impl ConnectionEnd {
2217    /// Stable lower-case name for logs: `goodbye`, `eof`, `reset`, `closed`.
2218    pub fn as_str(self) -> &'static str {
2219        match self {
2220            Self::Goodbye => "goodbye",
2221            Self::Eof => "eof",
2222            Self::Reset => "reset",
2223            Self::Closed => "closed",
2224        }
2225    }
2226}
2227
2228impl std::fmt::Display for ConnectionEnd {
2229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2230        f.write_str(self.as_str())
2231    }
2232}
2233
2234/// The terminal result of a module request handler.
2235#[derive(Debug, Clone, PartialEq)]
2236pub enum HandlerOutcome {
2237    /// Send a Response frame carrying these bytes.
2238    Response(Vec<u8>),
2239    /// Send an Error frame carrying an [`ErrorBody`] with this code and message.
2240    Error { code: String, message: String },
2241    /// Send an Error frame with stable machine-readable detail.
2242    ErrorWithDetail {
2243        code: String,
2244        message: String,
2245        detail: serde_json::Value,
2246    },
2247    /// The handler emitted stream data with [`RequestCtx::emit`]; the serve code
2248    /// sends the StreamEnd terminal frame.
2249    Streamed,
2250}
2251
2252/// Per-request context. Retains the full route handle and correlation id, provides
2253/// interim stream emission, and exposes a cancellation signal.
2254#[derive(Clone)]
2255pub struct RequestCtx {
2256    handle: RouteHandle,
2257    corr: u64,
2258    ver: u8,
2259    egress: mpsc::Sender<Frame>,
2260    module_handle: ModuleHandle,
2261    cancelled: CancellationToken,
2262    binary_reply: Arc<AtomicBool>,
2263    request_flags: Flags,
2264    request_body: Arc<[u8]>,
2265}
2266
2267impl RequestCtx {
2268    /// Clone the connection's control handle, for readiness and other module RPCs.
2269    pub fn module_handle(&self) -> ModuleHandle {
2270        self.module_handle.clone()
2271    }
2272
2273    /// Decodes a framed request only when ingress carried `FLAG_BINARY`.
2274    /// Call this only for management operations that declared `operation_payload`.
2275    /// Return a malformed body's named error as a refusal before doing any work;
2276    /// the serve helper deliberately leaves that policy to the handler.
2277    pub fn request_payload(
2278        &self,
2279    ) -> Result<Option<(serde_json::Value, &[u8])>, subc_protocol::framed_body::FramedBodyError>
2280    {
2281        if !self.request_flags.is_binary() {
2282            return Ok(None);
2283        }
2284        subc_protocol::framed_body::decode(&self.request_body).map(Some)
2285    }
2286
2287    /// Full route handle retained from ingress.
2288    pub fn route_handle(&self) -> RouteHandle {
2289        self.handle
2290    }
2291
2292    /// Correlation id for this request.
2293    pub fn corr(&self) -> u64 {
2294        self.corr
2295    }
2296
2297    /// Declare this request's terminal [`HandlerOutcome::Response`] as raw bytes,
2298    /// not JSON, by setting `FLAG_BINARY` on its frame.
2299    ///
2300    /// Mark a reply only when the operation's contract defines a raw-byte reply,
2301    /// never for JSON contracts such as tool results or JSON management replies.
2302    /// The body is sent unchanged either way; the flag only declares that it is
2303    /// not JSON, and the daemon forwards it as is. The delivered frame is still
2304    /// bounded by [`subc_protocol::MAX_DELIVERED_FRAME_LEN`], including its header.
2305    ///
2306    /// All clones of this request's context share the mark; other requests do not.
2307    /// It has no effect on errors, interim stream frames, or `Streamed` outcomes.
2308    pub fn mark_binary_reply(&self) {
2309        self.binary_reply.store(true, Ordering::Relaxed);
2310    }
2311
2312    /// Emit an interim StreamData frame on this request's `(channel, corr)`. Once
2313    /// the request is cancelled or its route is gone, late emits are dropped.
2314    pub async fn emit(&self, body: Vec<u8>) -> Result<(), SubcModuleError> {
2315        self.emit_with_admission(body, None).await
2316    }
2317
2318    /// Emit StreamData with an explicit admission class. `None` means NORMAL.
2319    pub async fn emit_with_admission(
2320        &self,
2321        body: Vec<u8>,
2322        admission_class: Option<AdmissionClass>,
2323    ) -> Result<(), SubcModuleError> {
2324        self.module_handle.validate_route(self.handle)?;
2325        if self.cancelled.is_cancelled() {
2326            return Ok(());
2327        }
2328        self.send_frame(
2329            FrameType::StreamData,
2330            data_flags().with_admission_class(admission_class.unwrap_or(AdmissionClass::Normal)),
2331            body,
2332        )
2333        .await
2334    }
2335
2336    /// Completes when the other side sends Cancel for this request or the route
2337    /// is torn down.
2338    pub fn cancelled(&self) -> WaitForCancellationFuture<'_> {
2339        self.cancelled.cancelled()
2340    }
2341
2342    /// Return a cloneable cancellation token for code that prefers token polling.
2343    pub fn cancellation_token(&self) -> CancellationToken {
2344        self.cancelled.clone()
2345    }
2346
2347    async fn send_frame(
2348        &self,
2349        frame_type: FrameType,
2350        flags: Flags,
2351        body: Vec<u8>,
2352    ) -> Result<(), SubcModuleError> {
2353        self.module_handle.validate_route(self.handle)?;
2354        let (frame_type, flags, body) = bounded_terminal(frame_type, flags, body)?;
2355        let frame = Frame::build_with_version(
2356            self.ver,
2357            frame_type,
2358            flags,
2359            self.handle.channel,
2360            self.handle.epoch,
2361            self.corr,
2362            body,
2363        )
2364        .map_err(SubcModuleError::FrameBuild)?;
2365        send_outbound(&self.egress, frame).await
2366    }
2367}
2368
2369/// Adds one to `counter` and returns the value it held before, or `None` once
2370/// the counter is at `u64::MAX`. Written as a compare-exchange loop rather than
2371/// with `fetch_update` (deprecated in Rust 1.99) or its replacement
2372/// `try_update` (absent before 1.99), so it builds on both toolchains.
2373fn checked_increment(counter: &AtomicU64) -> Option<u64> {
2374    let mut current = counter.load(Ordering::Relaxed);
2375    loop {
2376        let next = current.checked_add(1)?;
2377        match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
2378            Ok(previous) => return Some(previous),
2379            Err(actual) => current = actual,
2380        }
2381    }
2382}
2383
2384/// Route-bind request delivered on channel 0.
2385///
2386/// `#[non_exhaustive]` so it can gain fields in a later release without
2387/// breaking the handlers that read it. The SDK builds it from the daemon's
2388/// bind; code outside this crate (a module's own tests of its `on_bind`)
2389/// builds one with [`RouteBindRequest::new`] and the `with_*` setters.
2390#[derive(Debug, Clone)]
2391#[non_exhaustive]
2392pub struct RouteBindRequest {
2393    pub handle: RouteHandle,
2394    pub target: RouteTarget,
2395    pub identity: BindIdentity,
2396    pub principal: Option<Principal>,
2397    /// Consumer-declared reverse-request families and provider-contract
2398    /// capabilities for this bind. For example, `tool-result/v1` declares that a
2399    /// consumer understands the tool-provider content result format. This is an
2400    /// unverified declaration, not a privilege grant; providers treat an absent
2401    /// field as no declared capability. Known MCP method-family values today
2402    /// are "elicitation", "sampling", and "roots".
2403    pub consumer_capabilities: Option<Vec<String>>,
2404    /// The versions of provider roles the consumer declared it speaks on this
2405    /// route, role name to version (`{"tool-provider": "v1"}`), as the daemon
2406    /// forwarded them. A declaration, not a verified privilege: use it to pick
2407    /// which version of a role's wire shape to speak. `None` means the consumer
2408    /// declared none (a legacy consumer, or a daemon that predates the field);
2409    /// it is never an empty map.
2410    pub role_versions: Option<std::collections::BTreeMap<String, String>>,
2411    /// Opaque admission facts relayed by subc from its configured carrier.
2412    pub admission_facts: Option<serde_json::Value>,
2413    /// The daemon's stamp of the scope the route was admitted under (owner,
2414    /// ref, epoch, kind, attributes), copied from the bind unchanged. It is
2415    /// the daemon's, never the opener's. `attributes.on_behalf_of_agent` is
2416    /// attribution only, never authority, consent or access to per-agent handles.
2417    /// A target must declare `scope-on-behalf-of/v1` to receive that field. The stamp
2418    /// is fixed for the route's life: a change that revokes authority closes
2419    /// the route. `None` means the route was opened without a scope, or by a
2420    /// daemon that predates scopes.
2421    pub scope: Option<ScopeStamp>,
2422    /// The daemon's call mode, or the mode derived from `scope` when an older
2423    /// daemon omits it. Providers must refuse [`CallMode::Unknown`].
2424    pub call_mode: CallMode,
2425    /// The daemon's facts about the connection that opened this route, read
2426    /// from the same bind. Like the scope stamp, they are the daemon's, never
2427    /// the opener's.
2428    ///
2429    /// - `observed_peer` is sent only when this module's manifest lists
2430    ///   `observed-peer/v1` in `capabilities.provides`. It is then always
2431    ///   present, possibly with status `unobserved`; only an `observed` status
2432    ///   carries the peer's identity.
2433    /// - `operator_app` is sent only when the manifest lists `operator-app/v1`,
2434    ///   the daemon's operator-app policy for this platform is switched on,
2435    ///   and the daemon recognised the connection as an operator app when it
2436    ///   was made. It records that recognition at connection time. It is not
2437    ///   authority: a write on the person's behalf still asks the daemon with
2438    ///   `operator.confirm`. Released daemons switch this policy off, so they
2439    ///   never send it yet.
2440    ///
2441    /// - `caller` is sent only for `caller-attestation/v1`. Automatic provider
2442    ///   permission grants require a well-formed caller with claim `own` and `first_party: true`.
2443    ///   An absent or incomplete caller establishes no first-party mark.
2444    ///
2445    /// - `peer_build` is sent only for `peer-build/v1`, when the opener is
2446    ///   `reserved:callosum` and its phone build claim was exactly `production`.
2447    ///   Otherwise it is absent; the opener's raw `build_class` is never relayed.
2448    ///
2449    /// The peer keys decode together. If they don't decode, the bind still
2450    /// reaches [`ModuleHandler::on_bind`] with all absent and a warning is
2451    /// logged, so a handler that admits only on `operator_app` refuses it.
2452    pub peer: subc_protocol::peer::RouteBindPeer,
2453}
2454
2455impl RouteBindRequest {
2456    /// A bind with the members every bind has and every optional one absent:
2457    /// no principal, no consumer capabilities, no role versions, no admission
2458    /// facts and no scope. The call mode is classic. Set fields with the
2459    /// `with_*` methods.
2460    pub fn new(handle: RouteHandle, target: RouteTarget, identity: BindIdentity) -> Self {
2461        Self {
2462            handle,
2463            target,
2464            identity,
2465            principal: None,
2466            consumer_capabilities: None,
2467            role_versions: None,
2468            admission_facts: None,
2469            scope: None,
2470            call_mode: derive_call_mode(None),
2471            peer: subc_protocol::peer::RouteBindPeer::new(),
2472        }
2473    }
2474
2475    /// Set [`Self::peer`] to synthetic daemon facts, for testing a handler.
2476    /// It checks nothing: a real bind's facts come only from the daemon.
2477    pub fn with_peer(mut self, peer: subc_protocol::peer::RouteBindPeer) -> Self {
2478        self.peer = peer;
2479        self
2480    }
2481
2482    /// The daemon's attested phone build fact, present only for `peer-build/v1`.
2483    /// A supporting daemon sends only `production`, otherwise the key is absent.
2484    pub fn peer_build(&self) -> Option<&str> {
2485        self.peer.peer_build.as_deref()
2486    }
2487
2488    /// Set [`Self::principal`].
2489    pub fn with_principal(mut self, principal: Principal) -> Self {
2490        self.principal = Some(principal);
2491        self
2492    }
2493
2494    /// Set [`Self::consumer_capabilities`].
2495    pub fn with_consumer_capabilities(mut self, consumer_capabilities: Vec<String>) -> Self {
2496        self.consumer_capabilities = Some(consumer_capabilities);
2497        self
2498    }
2499
2500    /// Set [`Self::role_versions`].
2501    pub fn with_role_versions(
2502        mut self,
2503        role_versions: std::collections::BTreeMap<String, String>,
2504    ) -> Self {
2505        self.role_versions = Some(role_versions);
2506        self
2507    }
2508
2509    /// Set [`Self::admission_facts`].
2510    pub fn with_admission_facts(mut self, admission_facts: serde_json::Value) -> Self {
2511        self.admission_facts = Some(admission_facts);
2512        self
2513    }
2514
2515    /// Set [`Self::scope`] and derive its call mode. To override the derived
2516    /// mode, call [`Self::with_call_mode`] afterwards.
2517    pub fn with_scope(mut self, scope: ScopeStamp) -> Self {
2518        self.call_mode = derive_call_mode(Some(&scope));
2519        self.scope = Some(scope);
2520        self
2521    }
2522
2523    /// Set [`Self::call_mode`], overriding the mode derived from the scope.
2524    pub fn with_call_mode(mut self, call_mode: CallMode) -> Self {
2525        self.call_mode = call_mode;
2526        self
2527    }
2528}
2529
2530/// Decision returned by [`ModuleHandler::on_bind`].
2531#[derive(Debug, Clone)]
2532pub struct BindDecision {
2533    kind: BindDecisionKind,
2534}
2535
2536impl BindDecision {
2537    /// Accept the route.bind request.
2538    pub fn accept() -> Self {
2539        Self {
2540            kind: BindDecisionKind::Accept,
2541        }
2542    }
2543
2544    /// Reject the route.bind request with a typed Error frame.
2545    pub fn reject(code: impl Into<String>, message: impl Into<String>) -> Self {
2546        Self {
2547            kind: BindDecisionKind::Reject {
2548                code: code.into(),
2549                message: message.into(),
2550                detail: None,
2551            },
2552        }
2553    }
2554
2555    /// Reject the route.bind request with a typed Error frame whose `detail`
2556    /// carries the code's machine-readable fields, such as `bind_busy`'s
2557    /// `reason` and `retry_after_ms`. Pass a JSON object: a JSON `null` is
2558    /// dropped on the way, since an absent detail and a null one encode the
2559    /// same. The daemon relays the code, message and detail to the opener,
2560    /// so the detail must never hold secrets.
2561    pub fn reject_with_detail(
2562        code: impl Into<String>,
2563        message: impl Into<String>,
2564        detail: serde_json::Value,
2565    ) -> Self {
2566        Self {
2567            kind: BindDecisionKind::Reject {
2568                code: code.into(),
2569                message: message.into(),
2570                detail: Some(detail),
2571            },
2572        }
2573    }
2574}
2575
2576#[derive(Debug, Clone)]
2577enum BindDecisionKind {
2578    Accept,
2579    Reject {
2580        code: String,
2581        message: String,
2582        detail: Option<serde_json::Value>,
2583    },
2584}
2585
2586/// Run a module to completion. Reads `--subc <connection-file>` from args, uses
2587/// `SUBC_MODULE_ID` when set by the process that launched the module, connects,
2588/// authenticates, sends HELLO, waits for HELLO_ACK, then serves frames until
2589/// GOODBYE, clean EOF or a socket disconnect. How it ended is passed to
2590/// [`ModuleHandler::on_connection_end`].
2591/// A validated inherited registration channel replaces TCP when available.
2592/// It is never reconnected; its end exits the process after the lifecycle hook
2593/// and teardown, so the supervisor can restart the module with a new channel.
2594pub async fn serve<H>(manifest: ModuleManifest, handler: H) -> Result<(), SubcModuleError>
2595where
2596    H: ModuleHandler,
2597{
2598    ServeOptions::default().serve(manifest, handler).await
2599}
2600
2601/// A cooperative stop signal that can be created before connecting to the daemon.
2602/// Clones share the same, irreversible stop request. Await the serving future
2603/// after calling [`stop`](Self::stop); dropping it does not perform teardown.
2604#[derive(Clone, Debug, Default)]
2605pub struct ModuleStopHandle {
2606    token: CancellationToken,
2607}
2608
2609impl ModuleStopHandle {
2610    pub fn new() -> Self {
2611        Self::default()
2612    }
2613
2614    /// Stop the handshake or stop admitting requests, drain accepted work, send
2615    /// GOODBYE and flush. The serving future completes the teardown.
2616    pub fn stop(&self) {
2617        self.token.cancel();
2618    }
2619}
2620
2621/// Configuration for a module's connection lifecycle. Existing `serve*`
2622/// functions use the defaults; use these builder methods to customize serving.
2623#[derive(Clone, Debug)]
2624#[non_exhaustive]
2625pub struct ServeOptions {
2626    registration_channel: bool,
2627    prefix_child: bool,
2628    writer_drain_timeout: Duration,
2629    stop_handle: ModuleStopHandle,
2630}
2631
2632impl Default for ServeOptions {
2633    fn default() -> Self {
2634        Self {
2635            writer_drain_timeout: DEFAULT_WRITER_DRAIN_TIMEOUT,
2636            registration_channel: false,
2637            prefix_child: false,
2638            stop_handle: ModuleStopHandle::new(),
2639        }
2640    }
2641}
2642
2643impl ServeOptions {
2644    /// Set the writer drain budget (default: two seconds). A module stop also
2645    /// gives in-flight handlers up to this long to finish before sending
2646    /// GOODBYE, then gives the writer its own budget to flush. Other connection
2647    /// ends cancel handlers immediately. Work still running at a drain
2648    /// deadline is aborted.
2649    ///
2650    /// Keep the combined handler and writer waits below the daemon's per-module
2651    /// stop budget: the daemon caps it at 25 seconds, and a module may be
2652    /// configured with less. Leave room for lifecycle hooks as well.
2653    pub fn with_writer_drain_timeout(mut self, timeout: Duration) -> Self {
2654        self.writer_drain_timeout = timeout;
2655        self
2656    }
2657
2658    /// Install a stop handle created before calling `serve` or `serve_with`,
2659    /// so a stop also interrupts connection establishment and HELLO.
2660    pub fn with_stop_handle(mut self, handle: ModuleStopHandle) -> Self {
2661        self.stop_handle = handle;
2662        self
2663    }
2664
2665    /// Serve using the same launch arguments and environment as [`serve`].
2666    pub async fn serve<H: ModuleHandler>(
2667        self,
2668        mut manifest: ModuleManifest,
2669        handler: H,
2670    ) -> Result<(), SubcModuleError> {
2671        let connection_file = parse_subc_arg(env::args_os().skip(1))?;
2672        if let Some(module_id) = module_id_from_env()? {
2673            manifest.module_id = module_id;
2674        }
2675        self.serve_with(&connection_file, manifest, handler).await
2676    }
2677
2678    /// Serve with an explicit connection file and an unchanged manifest.
2679    pub async fn serve_with<H: ModuleHandler>(
2680        self,
2681        connection_file: &Path,
2682        manifest: ModuleManifest,
2683        handler: H,
2684    ) -> Result<(), SubcModuleError> {
2685        if let Some((_handle, future)) = self
2686            .serve_with_handle(connection_file, manifest, handler)
2687            .await?
2688        {
2689            future.await?;
2690        }
2691        Ok(())
2692    }
2693
2694    /// Connect and register using the same launch inputs as [`Self::serve`],
2695    /// returning a cloneable handle and the future that keeps the module serving.
2696    ///
2697    /// Reads `--subc <connection-file>` (or `--subc=<connection-file>`) from argv
2698    /// and overrides the manifest's module id with `SUBC_MODULE_ID` when present.
2699    /// Uses this options value's stop handle and writer drain timeout. A requested
2700    /// stop before registration completes returns `Ok(None)`; this is an expected
2701    /// outcome, not a connection error.
2702    ///
2703    /// The returned serve future **must be awaited or spawned**. A module can give
2704    /// the returned handle to its handler's shared state before starting that future.
2705    /// Spawn the serve future before slow startup work or awaiting control RPCs:
2706    /// it reads their replies and answers health and stop.
2707    pub async fn serve_from_env_with_handle<H: ModuleHandler>(
2708        self,
2709        mut manifest: ModuleManifest,
2710        handler: H,
2711    ) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
2712        let connection_file = parse_subc_arg(env::args_os().skip(1))?;
2713        if let Some(module_id) = module_id_from_env()? {
2714            manifest.module_id = module_id;
2715        }
2716        self.serve_with_handle(&connection_file, manifest, handler)
2717            .await
2718    }
2719
2720    /// Connect with an explicit connection file and an unchanged manifest,
2721    /// returning a cloneable handle and the future that keeps the module serving.
2722    ///
2723    /// Uses this options value's stop handle and writer drain timeout. A requested
2724    /// stop before registration completes returns `Ok(None)`; this is an expected
2725    /// outcome, not a connection error.
2726    ///
2727    /// The returned serve future **must be awaited or spawned**. A module can give
2728    /// the returned handle to its handler's shared state before starting that future.
2729    /// Spawn the serve future before slow startup work or awaiting control RPCs:
2730    /// it reads their replies and answers health and stop.
2731    pub async fn serve_with_handle<H: ModuleHandler>(
2732        self,
2733        connection_file: &Path,
2734        manifest: ModuleManifest,
2735        handler: H,
2736    ) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
2737        prepare_connection(connection_file, manifest, handler, self).await
2738    }
2739}
2740
2741/// Connect and register using the same launch inputs as [`serve`], returning a
2742/// cloneable handle and the future that keeps the module serving.
2743///
2744/// Reads `--subc <connection-file>` (or `--subc=<connection-file>`) from argv
2745/// and overrides the manifest's module id with `SUBC_MODULE_ID` when present.
2746/// Authentication, the launch-secret pipe, HELLO and their errors are identical
2747/// to [`serve`]. Unlike [`serve_with_handle`], the caller need not duplicate
2748/// argument parsing or launch-environment handling.
2749///
2750/// The returned serve future **must be awaited or spawned**. A module can give
2751/// the returned handle to its handler's shared state before starting that future,
2752/// so the handler can call [`ModuleHandle::confirm_operator`] or
2753/// [`ModuleHandle::set_ready`]. Spawn the serve future before slow startup work
2754/// or awaiting control RPCs: it reads their replies and answers health and stop.
2755pub async fn serve_from_env_with_handle<H>(
2756    manifest: ModuleManifest,
2757    handler: H,
2758) -> Result<(ModuleHandle, ModuleServeFuture), SubcModuleError>
2759where
2760    H: ModuleHandler,
2761{
2762    ServeOptions::default()
2763        .serve_from_env_with_handle(manifest, handler)
2764        .await?
2765        .ok_or(SubcModuleError::ConnectionClosedBeforeHelloAck)
2766}
2767
2768/// Run a module with an explicit connection-file path. The manifest is sent as
2769/// provided; callers that need a nonstandard module id should set it before calling.
2770pub async fn serve_with<H>(
2771    connection_file: &Path,
2772    manifest: ModuleManifest,
2773    handler: H,
2774) -> Result<(), SubcModuleError>
2775where
2776    H: ModuleHandler,
2777{
2778    ServeOptions::default()
2779        .serve_with(connection_file, manifest, handler)
2780        .await
2781}
2782
2783/// Connect, register the module, and return a cloneable handle plus the future that
2784/// must be awaited or spawned to keep serving the connection.
2785pub async fn serve_with_handle<H>(
2786    connection_file: &Path,
2787    manifest: ModuleManifest,
2788    handler: H,
2789) -> Result<(ModuleHandle, ModuleServeFuture), SubcModuleError>
2790where
2791    H: ModuleHandler,
2792{
2793    ServeOptions::default()
2794        .serve_with_handle(connection_file, manifest, handler)
2795        .await?
2796        .ok_or(SubcModuleError::ConnectionClosedBeforeHelloAck)
2797}
2798
2799async fn prepare_connection<H: ModuleHandler>(
2800    connection_file: &Path,
2801    manifest: ModuleManifest,
2802    handler: H,
2803    mut options: ServeOptions,
2804) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
2805    options.registration_channel = registration::adopt(&manifest.module_id)?;
2806    let stream = tokio::select! {
2807        biased;
2808        () = options.stop_handle.token.cancelled() => return Ok(None),
2809        stream = async {
2810            let claim = if registration::supervised() && !options.registration_channel {
2811                registration::prefix_claim(&manifest.module_id).await
2812                    .map_err(|error| registration::serve_claim_error(&manifest.module_id, error))?
2813            } else {
2814                None
2815            };
2816            let mut stream = connect_to_subc(connection_file, options.registration_channel).await?;
2817            if let Some(claim) = claim {
2818                registration::present_claim(&mut stream, claim, AUTH_DEADLINE).await
2819                    .map_err(|error| registration::serve_claim_error(&manifest.module_id, error))?;
2820                options.prefix_child = true;
2821            }
2822            Ok::<_, SubcModuleError>(stream)
2823        } => stream?,
2824    };
2825    register_connection(stream, manifest, handler, options).await
2826}
2827
2828async fn register_connection<S, H>(
2829    stream: S,
2830    manifest: ModuleManifest,
2831    handler: H,
2832    options: ServeOptions,
2833) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError>
2834where
2835    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
2836    H: ModuleHandler,
2837{
2838    let control_ops = control_ops::validate(handler.control_ops())?;
2839    let (mut read_half, write_half) = tokio::io::split(stream);
2840    let (tx, rx) = mpsc::channel::<Frame>(EGRESS_BUFFER);
2841    let connection_runtime = tokio::runtime::Handle::current();
2842    let mut writer = tokio::spawn(drain_writer(write_half, rx));
2843    let handler = Arc::new(handler);
2844    let declaration = if options.prefix_child {
2845        None
2846    } else {
2847        handler.config_declaration()
2848    };
2849
2850    let mut hello_ack = None;
2851    let provides = manifest.provides.clone();
2852    let handshake = async {
2853        send_hello(&tx, manifest, declaration.is_some(), &control_ops).await?;
2854        // A validated ACK means the daemon accepted the module, even while the
2855        // module's callback is pending. Keep that boundary when the writer wins.
2856        hello_ack = Some(expect_hello_ack(&mut read_half).await?);
2857        handler
2858            .on_hello_ack(hello_ack.as_ref().expect("validated HELLO_ACK"))
2859            .await;
2860        Ok::<_, SubcModuleError>(())
2861    };
2862    let mut writer_result = None;
2863    let handshake_result = tokio::select! {
2864        biased;
2865        () = options.stop_handle.token.cancelled() => None,
2866        result = handshake => Some(result),
2867        result = &mut writer => {
2868            writer_result = Some(result);
2869            Some(Ok(()))
2870        }
2871    };
2872    match handshake_result {
2873        Some(Ok(())) => {}
2874        other => {
2875            let result = match other {
2876                None => {
2877                    let deadline = Instant::now() + options.writer_drain_timeout;
2878                    let result = timeout_at(deadline, send_goodbye(&tx)).await;
2879                    drop(tx);
2880                    let flush = finish_writer_and_drain(writer, &mut read_half, deadline).await;
2881                    handler.on_connection_end(ConnectionEnd::Closed).await;
2882                    match result.unwrap_or(Ok(())) {
2883                        Ok(()) | Err(SubcModuleError::WriterClosed) => {}
2884                        Err(error) => return Err(error),
2885                    }
2886                    match flush.0 {
2887                        Err(SubcModuleError::FrameIo(FrameIoError::Io(error)))
2888                            if is_disconnect(&error) => {}
2889                        result => result?,
2890                    }
2891                    return Ok(None);
2892                }
2893                Some(Err(error)) => error,
2894                Some(Ok(_)) => unreachable!(),
2895            };
2896            drop(tx);
2897            let deadline = Instant::now() + options.writer_drain_timeout;
2898            let _ = finish_writer_and_drain(writer, &mut read_half, deadline).await;
2899            return Err(result);
2900        }
2901    }
2902    let mut ack = match hello_ack {
2903        Some(ack) => ack,
2904        None => {
2905            return Err(writer_ended(
2906                writer_result.expect("writer ended before HELLO_ACK"),
2907            ))
2908        }
2909    };
2910    if options.prefix_child {
2911        // A prefix registration is brokered, not another primary channel. Keep
2912        // its registration RPCs while refusing owner-only operations locally.
2913        ack.subc_ops.retain(|op| {
2914            matches!(
2915                op.as_str(),
2916                "catalog.update" | "scope.describe" | "supervisor.live_roots" | "activity.record"
2917            )
2918        });
2919    }
2920    // The callback can be cancelled by a writer failure, but a failure after
2921    // acceptance belongs to the serving lifecycle, including its teardown hook.
2922    let writer_end = writer_result.map(writer_connection_end);
2923
2924    let Some(connection_token) = checked_increment(&NEXT_MODULE_CONNECTION_TOKEN) else {
2925        drop(tx);
2926        let deadline = Instant::now() + options.writer_drain_timeout;
2927        if writer_end.is_none() {
2928            let _ = finish_writer_and_drain(writer, &mut read_half, deadline).await;
2929        }
2930        return Err(SubcModuleError::ConnectionTokenExhausted);
2931    };
2932    let close_token = CancellationToken::new();
2933    let handle = ModuleHandle::new(
2934        &ack,
2935        tx.clone(),
2936        connection_token,
2937        close_token,
2938        connection_runtime,
2939    );
2940    handle.shared.lock_inner().current_provides = Some(provides);
2941    handle
2942        .shared
2943        .registration
2944        .prefix_child
2945        .store(options.prefix_child, Ordering::Release);
2946    let _ = handle.shared.served_control_ops.set(control_ops);
2947    if options.registration_channel {
2948        registration::install_owner(&handle)?;
2949    }
2950    if let Some(declaration) = declaration {
2951        let _ = handle.shared.config.declaration.set(declaration);
2952    }
2953    let serve_future = connection_serve_future_with_options(
2954        read_half,
2955        tx,
2956        handler,
2957        handle.clone(),
2958        writer,
2959        options,
2960        writer_end,
2961    );
2962    Ok(Some((handle, serve_future)))
2963}
2964
2965// Both real connections and the in-memory test stand-in run this lifecycle,
2966// including request cancellation, connection-end hooks and the writer drain.
2967#[cfg(any(test, feature = "test-support"))]
2968fn connection_serve_future<R, H>(
2969    read_half: R,
2970    tx: mpsc::Sender<Frame>,
2971    handler: Arc<H>,
2972    handle: ModuleHandle,
2973    writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
2974) -> ModuleServeFuture
2975where
2976    R: AsyncRead + Unpin + Send + 'static,
2977    H: ModuleHandler,
2978{
2979    connection_serve_future_with_options(
2980        read_half,
2981        tx,
2982        handler,
2983        handle,
2984        writer,
2985        ServeOptions::default(),
2986        None,
2987    )
2988}
2989
2990fn registration_channel_exit_code(result: &Result<ConnectionEnd, SubcModuleError>) -> i32 {
2991    if matches!(result, Ok(ConnectionEnd::Goodbye)) {
2992        0
2993    } else {
2994        1
2995    }
2996}
2997
2998fn connection_serve_future_with_options<R, H>(
2999    mut read_half: R,
3000    tx: mpsc::Sender<Frame>,
3001    handler: Arc<H>,
3002    handle: ModuleHandle,
3003    mut writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3004    options: ServeOptions,
3005    writer_end: Option<Result<ConnectionEnd, SubcModuleError>>,
3006) -> ModuleServeFuture
3007where
3008    R: AsyncRead + Unpin + Send + 'static,
3009    H: ModuleHandler,
3010{
3011    let serve_handle = handle.clone();
3012    // Before the caller gets the future (and before the serve loop reads its
3013    // first frame after HELLO_ACK), so the
3014    // handle's pool figures describe the pools the dispatcher will use.
3015    handle.install_dispatch_pools(handler.request_pools());
3016    Box::pin(async move {
3017        // Connection loss ends this serve future. Module serving retains no
3018        // reconnect task or in-flight reconnect gate; a supervisor that needs
3019        // recovery starts a fresh serve_with_handle invocation.
3020        let dispatcher = RequestDispatcher::with_pools(serve_handle.dispatch_pools());
3021        if !options.prefix_child {
3022            config::start(serve_handle.clone(), Arc::clone(&handler), &dispatcher);
3023        }
3024        let mut writer_finished = writer_end.is_some();
3025        let mut loop_result = if let Some(end) = writer_end {
3026            end
3027        } else {
3028            tokio::select! {
3029                biased;
3030                result = module_loop(&mut read_half, &tx, Arc::clone(&handler), serve_handle.clone(), &dispatcher, &options.stop_handle) => result,
3031                result = &mut writer => {
3032                    writer_finished = true;
3033                    writer_connection_end(result)
3034                }
3035            }
3036        };
3037        // A failed terminal enqueue can win the select just before the writer
3038        // reports why it closed. Classify that same disconnect before calling
3039        // the connection-end hook, rather than exposing a scheduling race.
3040        if matches!(loop_result, Err(SubcModuleError::WriterClosed)) && !writer_finished {
3041            writer_finished = true;
3042            loop_result = writer_connection_end((&mut writer).await);
3043        }
3044        let deadline = Instant::now() + options.writer_drain_timeout;
3045        serve_handle.shared.config.stop.cancel();
3046        dispatcher.wait_for_draining_hooks_to_start().await;
3047        dispatcher.tasks.close();
3048        if matches!(loop_result, Ok(ConnectionEnd::Closed))
3049            && options.stop_handle.token.is_cancelled()
3050        {
3051            // Keep routes live until accepted work has sent its terminal reply.
3052            let _ = timeout_at(deadline, dispatcher.tasks.wait()).await;
3053        }
3054        let orderly = loop_result.is_ok();
3055        if let Some(error) = dispatcher.take_failure() {
3056            if !orderly || !matches!(error, SubcModuleError::WriterClosed) {
3057                loop_result = Err(error);
3058            }
3059        }
3060        dispatcher.cancel_all();
3061        let _ = timeout_at(deadline, dispatcher.tasks.wait()).await;
3062        let abandoned_replies = dispatcher
3063            .in_flight
3064            .lock()
3065            .unwrap_or_else(|e| e.into_inner())
3066            .len();
3067        if let Some(error) = dispatcher.take_failure() {
3068            if !orderly || !matches!(error, SubcModuleError::WriterClosed) {
3069                loop_result = Err(error);
3070            }
3071        }
3072        dispatcher.abort_all();
3073        dispatcher.tasks.wait().await;
3074        let daemon_eof = matches!(loop_result, Ok(ConnectionEnd::Eof));
3075        let locally_closed = matches!(loop_result, Ok(ConnectionEnd::Closed));
3076        // The module ended the connection itself: a stop, an internal close
3077        // or a module-side error. Close it in order, so the daemon reads a
3078        // FIN rather than a reset. When the daemon ended it (EOF, GOODBYE or
3079        // a reset) or the writer already failed, there is nothing to drain.
3080        let module_ended =
3081            !writer_finished && matches!(loop_result, Ok(ConnectionEnd::Closed) | Err(_));
3082        let deadline = Instant::now() + options.writer_drain_timeout;
3083        if matches!(loop_result, Ok(ConnectionEnd::Closed))
3084            && options.stop_handle.token.is_cancelled()
3085        {
3086            match timeout_at(deadline, send_goodbye(&tx)).await {
3087                Ok(Ok(())) | Err(_) => {}
3088                Ok(Err(SubcModuleError::WriterClosed)) => {}
3089                Ok(Err(error)) => loop_result = Err(error),
3090            }
3091        }
3092        serve_handle.close_connection();
3093        drop(tx);
3094        let loop_result = match loop_result {
3095            Ok(end) => {
3096                handler.on_connection_end(end).await;
3097                Ok(end)
3098            }
3099            Err(error) => Err(error),
3100        };
3101
3102        let (writer_result, undelivered_replies) = if writer_finished {
3103            (Ok(()), 0)
3104        } else if module_ended {
3105            finish_writer_and_drain(writer, &mut read_half, deadline).await
3106        } else {
3107            finish_writer(writer, deadline).await
3108        };
3109        let undelivered_replies = undelivered_replies as u64
3110            + dispatcher.undelivered_replies.load(Ordering::Relaxed)
3111            + abandoned_replies as u64;
3112        if daemon_eof && undelivered_replies > 0 {
3113            tracing::warn!(
3114                undelivered_replies,
3115                "daemon EOF: replies could not be delivered during drain"
3116            );
3117        }
3118        if options.registration_channel && !locally_closed {
3119            // An inherited registration cannot be recreated. Finish the hook
3120            // and teardown before letting the supervisor restart the process.
3121            // The supervisor treats an unrequested clean exit as a stop, so
3122            // only a daemon GOODBYE may exit successfully.
3123            std::process::exit(registration_channel_exit_code(&loop_result));
3124        }
3125        match (loop_result.map(|_| ()), writer_result) {
3126            (Err(SubcModuleError::WriterClosed), Err(writer_error)) => Err(writer_error),
3127            (Err(loop_err), _) => Err(loop_err),
3128            (Ok(()), Ok(())) => Ok(()),
3129            // EOF or GOODBYE can precede a failed flush, especially when a
3130            // daemon restart outlasts its drain budget. Once the daemon has
3131            // ended the connection, Windows RST and Unix BrokenPipe are
3132            // consequences of that orderly end, not independent failures.
3133            (Ok(()), Err(SubcModuleError::FrameIo(FrameIoError::Io(err))))
3134                if is_disconnect(&err) =>
3135            {
3136                Ok(())
3137            }
3138            (Ok(()), Err(error)) => Err(error),
3139        }
3140    })
3141}
3142
3143async fn module_loop<R, H>(
3144    mut reader: R,
3145    egress: &mpsc::Sender<Frame>,
3146    handler: Arc<H>,
3147    module_handle: ModuleHandle,
3148    dispatcher: &RequestDispatcher,
3149    stop: &ModuleStopHandle,
3150) -> Result<ConnectionEnd, SubcModuleError>
3151where
3152    R: AsyncRead + Unpin,
3153    H: ModuleHandler,
3154{
3155    serve_frames(
3156        &mut reader,
3157        egress,
3158        &handler,
3159        &module_handle,
3160        dispatcher,
3161        stop,
3162    )
3163    .await
3164}
3165
3166async fn serve_frames<R, H>(
3167    reader: &mut R,
3168    egress: &mpsc::Sender<Frame>,
3169    handler: &Arc<H>,
3170    module_handle: &ModuleHandle,
3171    dispatcher: &RequestDispatcher,
3172    stop: &ModuleStopHandle,
3173) -> Result<ConnectionEnd, SubcModuleError>
3174where
3175    R: AsyncRead + Unpin,
3176    H: ModuleHandler,
3177{
3178    loop {
3179        let read = tokio::select! {
3180            biased;
3181            () = dispatcher.failed.cancelled() => return Err(dispatcher.take_failure().expect("failure signalled")),
3182            () = stop.token.cancelled() => return Ok(ConnectionEnd::Closed),
3183            () = module_handle.shared.close_token.cancelled() => return Ok(ConnectionEnd::Closed),
3184            read = read_frame(reader) => read,
3185        };
3186        let frame = match read {
3187            Ok(Some(frame)) => frame,
3188            // Clean EOF: the daemon closed the connection.
3189            Ok(None) => return Ok(ConnectionEnd::Eof),
3190            // A killed daemon can close with FIN on Unix and RST on Windows.
3191            // Both end serving and run the same connection-end teardown hook.
3192            Err(FrameIoError::Io(error)) if is_disconnect(&error) => {
3193                return Ok(ConnectionEnd::Reset);
3194            }
3195            Err(err) => return Err(SubcModuleError::FrameIo(err)),
3196        };
3197        if !handle_frame(
3198            frame,
3199            egress,
3200            Arc::clone(handler),
3201            dispatcher.clone(),
3202            module_handle.clone(),
3203        )
3204        .await?
3205        {
3206            // handle_frame returns false only for a channel-0 GOODBYE.
3207            return Ok(ConnectionEnd::Goodbye);
3208        }
3209    }
3210}
3211
3212async fn handle_frame<H>(
3213    frame: Frame,
3214    egress: &mpsc::Sender<Frame>,
3215    handler: Arc<H>,
3216    dispatcher: RequestDispatcher,
3217    module_handle: ModuleHandle,
3218) -> Result<bool, SubcModuleError>
3219where
3220    H: ModuleHandler,
3221{
3222    if frame.header.channel != 0
3223        && !module_handle.validate_ingress(frame.header.channel, frame.header.epoch)?
3224    {
3225        return Ok(true);
3226    }
3227    match frame.header.ty {
3228        FrameType::Ping if frame.header.channel == 0 => {
3229            let pong = Frame::build_with_version(
3230                frame.header.ver,
3231                FrameType::Pong,
3232                frame.header.flags,
3233                0,
3234                0,
3235                frame.header.corr,
3236                Vec::new(),
3237            )
3238            .map_err(SubcModuleError::FrameBuild)?;
3239            send_outbound(egress, pong).await?;
3240            Ok(true)
3241        }
3242        FrameType::Goodbye if frame.header.channel == 0 => Ok(false),
3243        FrameType::Goodbye => {
3244            let handle = module_handle.route_handle(frame.header.channel, frame.header.epoch);
3245            if module_handle.remove_route(handle)? {
3246                cancel_handle(&dispatcher.in_flight, handle)?;
3247                handler.on_route_gone(&handle).await;
3248            }
3249            Ok(true)
3250        }
3251        FrameType::Response if frame.header.channel == 0 => {
3252            let _ = module_handle.handle_control_reply(frame);
3253            Ok(true)
3254        }
3255        FrameType::Error | FrameType::StreamData | FrameType::StreamEnd
3256            if frame.header.channel == 0 =>
3257        {
3258            let _ = module_handle.handle_control_reply(frame);
3259            Ok(true)
3260        }
3261        FrameType::Cancel => {
3262            handle_cancel(frame, &dispatcher.in_flight)?;
3263            Ok(true)
3264        }
3265        FrameType::Request if frame.header.channel == 0 => {
3266            handle_control_request(frame, egress, handler, dispatcher, module_handle.clone())
3267                .await?;
3268            Ok(true)
3269        }
3270        FrameType::Request => {
3271            spawn_data_request(frame, egress.clone(), handler, dispatcher, module_handle)?;
3272            Ok(true)
3273        }
3274        FrameType::Push if frame.header.channel == 0 => {
3275            if config::changed(&frame, &module_handle) {
3276                return Ok(true);
3277            }
3278            handle_control_push(&frame, handler, &dispatcher);
3279            Ok(true)
3280        }
3281        _ => Ok(true),
3282    }
3283}
3284
3285/// Act on a one-way channel-0 command from the daemon. Never fails the
3286/// connection: a push this SDK cannot decode is most likely a newer daemon's
3287/// command, and ignoring it is what an older module did before this SDK
3288/// decoded any of them.
3289fn handle_control_push<H>(frame: &Frame, handler: Arc<H>, dispatcher: &RequestDispatcher)
3290where
3291    H: ModuleHandler,
3292{
3293    match serde_json::from_slice::<ModuleControlCommand>(&frame.body) {
3294        Ok(ModuleControlCommand::Draining {
3295            reason,
3296            deadline_ms,
3297        }) => {
3298            let started = spawn_draining_hook(
3299                handler,
3300                sdk_route_close_reason(reason),
3301                drain_deadline(deadline_ms),
3302                dispatcher,
3303            );
3304            dispatcher
3305                .draining_hooks
3306                .lock()
3307                .unwrap_or_else(|poisoned| poisoned.into_inner())
3308                .push(started);
3309        }
3310        Err(error) => {
3311            if !dispatcher
3312                .undecodable_push_logged
3313                .swap(true, Ordering::Relaxed)
3314            {
3315                let op = serde_json::from_slice::<serde_json::Value>(&frame.body)
3316                    .ok()
3317                    .and_then(|body| body.get("op")?.as_str().map(str::to_string));
3318                tracing::warn!(
3319                    op = op.as_deref().unwrap_or("<none>"),
3320                    error = %error,
3321                    "ignoring a channel-0 push from subc that this SDK cannot decode; \
3322                     further undecodable pushes on this connection are ignored without logging"
3323                );
3324            }
3325        }
3326    }
3327}
3328
3329/// Run `on_draining` on its own task, so a slow hook cannot stall the frame
3330/// reader. The returned receiver resolves once the hook has been polled for
3331/// the first time, i.e. has run up to its first await.
3332fn spawn_draining_hook<H>(
3333    handler: Arc<H>,
3334    reason: RouteCloseReason,
3335    deadline: SystemTime,
3336    dispatcher: &RequestDispatcher,
3337) -> oneshot::Receiver<()>
3338where
3339    H: ModuleHandler,
3340{
3341    let (started_tx, started_rx) = oneshot::channel();
3342    dispatcher.spawn(async move {
3343        let mut hook = handler.on_draining(reason, deadline);
3344        let mut started_tx = Some(started_tx);
3345        std::future::poll_fn(|cx| {
3346            let poll = hook.as_mut().poll(cx);
3347            if let Some(started) = started_tx.take() {
3348                let _ = started.send(());
3349            }
3350            poll
3351        })
3352        .await;
3353    });
3354    started_rx
3355}
3356
3357/// Convert the wire reason into this crate's public [`RouteCloseReason`], via
3358/// its wire name so a reason this crate has no variant for arrives as
3359/// [`RouteCloseReason::Unknown`] rather than being dropped.
3360fn sdk_route_close_reason(reason: subc_protocol::RouteCloseReason) -> RouteCloseReason {
3361    match serde_json::to_value(reason) {
3362        Ok(serde_json::Value::String(wire)) => RouteCloseReason::from_wire(&wire),
3363        _ => RouteCloseReason::Unknown(format!("{reason:?}")),
3364    }
3365}
3366
3367/// The drain deadline as a wall-clock time. A value too large for this
3368/// platform's clock becomes "now": the deadline is a "no later than", so
3369/// reading it early is the safe direction.
3370fn drain_deadline(deadline_ms: u64) -> SystemTime {
3371    UNIX_EPOCH
3372        .checked_add(Duration::from_millis(deadline_ms))
3373        .unwrap_or_else(SystemTime::now)
3374}
3375
3376fn spawn_data_request<H>(
3377    frame: Frame,
3378    egress: mpsc::Sender<Frame>,
3379    handler: Arc<H>,
3380    dispatcher: RequestDispatcher,
3381    module_handle: ModuleHandle,
3382) -> Result<(), SubcModuleError>
3383where
3384    H: ModuleHandler,
3385{
3386    let handle = module_handle.route_handle(frame.header.channel, frame.header.epoch);
3387    let corr = frame.header.corr;
3388    let cancellation = CancellationToken::new();
3389    {
3390        let mut guard = lock_in_flight(&dispatcher.in_flight)?;
3391        guard.insert((handle.channel, handle.epoch, corr), cancellation.clone());
3392    }
3393
3394    let ctx = RequestCtx {
3395        handle,
3396        corr,
3397        ver: frame.header.ver,
3398        egress,
3399        module_handle,
3400        cancelled: cancellation,
3401        binary_reply: Arc::new(AtomicBool::new(false)),
3402        request_flags: frame.header.flags,
3403        request_body: Arc::from(frame.body.as_slice()),
3404    };
3405    let body = frame.body;
3406    let in_flight = Arc::clone(&dispatcher.in_flight);
3407    // The module's classifier picks the pool from the raw body before the
3408    // request takes a slot; the SDK passes the body on without interpreting it.
3409    let (pool, op) = dispatcher.pools.classify(&body);
3410    let pool = pool.clone();
3411    let wait = pool.start_waiting((handle.channel, handle.epoch, corr));
3412    dispatcher.clone().spawn(async move {
3413        let waiting = WaitingRequest {
3414            op,
3415            channel: handle.channel,
3416            corr,
3417        };
3418        let permit = match wait_for_permit(&pool, wait, waiting, &ctx.cancelled).await {
3419            PermitWaitOutcome::Acquired(permit) => Some(permit),
3420            // Cancelled while waiting: answered below at once, without a
3421            // slot, rather than after one frees.
3422            PermitWaitOutcome::Cancelled => None,
3423            PermitWaitOutcome::Closed => {
3424                // A closed dispatcher means connection teardown will release every route credit.
3425                dispatcher
3426                    .undelivered_replies
3427                    .fetch_add(1, Ordering::Relaxed);
3428                if let Ok(mut guard) = in_flight.lock() {
3429                    guard.remove(&(handle.channel, handle.epoch, corr));
3430                }
3431                return;
3432            }
3433        };
3434        // A slot and the cancellation can become ready together and the slot
3435        // is taken first, so check again before running the handler.
3436        let outcome = if permit.is_none() || ctx.cancelled.is_cancelled() {
3437            Ok(HandlerOutcome::Error {
3438                code: "cancelled".to_string(),
3439                message: "request cancelled".to_string(),
3440            })
3441        } else {
3442            catch_handler_panic(async { handler.handle(ctx.clone(), body).await }).await
3443        };
3444        let panicked = outcome.is_err();
3445        let outcome = outcome.unwrap_or_else(|()| HandlerOutcome::Error {
3446            code: "internal".to_string(),
3447            message: "module handler panicked".to_string(),
3448        });
3449        match send_handler_outcome(&ctx, outcome).await {
3450            // A route GOODBYE/rebind withdraws the reply destination. Dropping
3451            // that late terminal is intentional; an egress failure on a live
3452            // route is not. A panic remains fatal even if its route is gone.
3453            Err(SubcModuleError::StaleRouteHandle(_)) if !panicked => {}
3454            Err(error) => {
3455                if matches!(error, SubcModuleError::WriterClosed) {
3456                    dispatcher
3457                        .undelivered_replies
3458                        .fetch_add(1, Ordering::Relaxed);
3459                }
3460                dispatcher.fail(error);
3461            }
3462            Ok(()) if panicked => dispatcher.fail(SubcModuleError::HandlerPanic),
3463            Ok(()) => {}
3464        }
3465        if let Ok(mut guard) = in_flight.lock() {
3466            guard.remove(&(handle.channel, handle.epoch, corr));
3467        }
3468    });
3469    Ok(())
3470}
3471
3472fn spawn_health_request<H>(
3473    frame: Frame,
3474    egress: mpsc::Sender<Frame>,
3475    handler: Arc<H>,
3476    dispatcher: RequestDispatcher,
3477) -> Result<(), SubcModuleError>
3478where
3479    H: ModuleHandler,
3480{
3481    let channel = frame.header.channel;
3482    let epoch = frame.header.epoch;
3483    let corr = frame.header.corr;
3484    let ver = frame.header.ver;
3485    let cancellation = CancellationToken::new();
3486    {
3487        let mut guard = lock_in_flight(&dispatcher.in_flight)?;
3488        guard.insert((channel, epoch, corr), cancellation.clone());
3489    }
3490
3491    let in_flight = Arc::clone(&dispatcher.in_flight);
3492    dispatcher.clone().spawn(async move {
3493        // Health must not queue behind the data work whose liveness it reports.
3494        // Registration and cancellation still use the same in-flight registry.
3495        if !cancellation.is_cancelled() {
3496            let result = async {
3497                let report = catch_handler_panic(async { handler.health().await }).await;
3498                let panicked = report.is_err();
3499                let (ty, body) = match report {
3500                    Ok(report) => (
3501                        FrameType::Response,
3502                        serde_json::to_vec(&ModuleControlResponse::from(
3503                            dispatcher.fold_health(report),
3504                        ))?,
3505                    ),
3506                    Err(()) => (
3507                        FrameType::Error,
3508                        serde_json::to_vec(&ErrorBody::new("internal", "module handler panicked"))?,
3509                    ),
3510                };
3511                let (ty, flags, body) = bounded_terminal(ty, control_flags(), body)?;
3512                let frame = Frame::build_with_version(ver, ty, flags, channel, epoch, corr, body)
3513                    .map_err(SubcModuleError::FrameBuild)?;
3514                send_outbound(&egress, frame).await?;
3515                if panicked {
3516                    return Err(SubcModuleError::HandlerPanic);
3517                }
3518                Ok(())
3519            }
3520            .await;
3521            if let Err(error) = result {
3522                if matches!(error, SubcModuleError::WriterClosed) {
3523                    dispatcher
3524                        .undelivered_replies
3525                        .fetch_add(1, Ordering::Relaxed);
3526                }
3527                dispatcher.fail(error);
3528            }
3529        }
3530        if let Ok(mut guard) = in_flight.lock() {
3531            guard.remove(&(channel, epoch, corr));
3532        }
3533    });
3534    Ok(())
3535}
3536
3537async fn send_handler_outcome(
3538    ctx: &RequestCtx,
3539    outcome: HandlerOutcome,
3540) -> Result<(), SubcModuleError> {
3541    match outcome {
3542        HandlerOutcome::Response(body) => {
3543            let flags = Flags::new(
3544                ctx.binary_reply.load(Ordering::Relaxed),
3545                Priority::Interactive,
3546                false,
3547            );
3548            ctx.send_frame(FrameType::Response, flags, body).await
3549        }
3550        HandlerOutcome::Error { code, message } => {
3551            let body = serde_json::to_vec(&ErrorBody::new(code, message))
3552                .map_err(SubcModuleError::Json)?;
3553            ctx.send_frame(FrameType::Error, data_flags(), body).await
3554        }
3555        HandlerOutcome::ErrorWithDetail {
3556            code,
3557            message,
3558            detail,
3559        } => {
3560            let body = serde_json::to_vec(&ErrorBody::new(code, message).with_detail(detail))
3561                .map_err(SubcModuleError::Json)?;
3562            ctx.send_frame(FrameType::Error, data_flags(), body).await
3563        }
3564        HandlerOutcome::Streamed => {
3565            ctx.send_frame(FrameType::StreamEnd, data_flags(), Vec::new())
3566                .await
3567        }
3568    }
3569}
3570
3571/// Catch unwinds across every poll, including construction of the handler future.
3572/// Never expose the panic payload on the wire: it may contain request data.
3573async fn catch_handler_panic<F: Future>(future: F) -> Result<F::Output, ()> {
3574    let mut future = std::pin::pin!(future);
3575    std::future::poll_fn(
3576        |cx| match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
3577            Ok(poll) => poll.map(Ok),
3578            Err(_) => std::task::Poll::Ready(Err(())),
3579        },
3580    )
3581    .await
3582}
3583
3584fn bounded_terminal(
3585    ty: FrameType,
3586    flags: Flags,
3587    body: Vec<u8>,
3588) -> Result<(FrameType, Flags, Vec<u8>), SubcModuleError> {
3589    let size = subc_protocol::HEADER_LEN + body.len();
3590    let limit = subc_protocol::MAX_DELIVERED_FRAME_LEN;
3591    if matches!(ty, FrameType::Response | FrameType::Error) && size > limit {
3592        let body = serde_json::to_vec(
3593            &ErrorBody::new("frame_too_large", "module reply exceeds frame limit")
3594                .with_detail(serde_json::json!({ "size": size, "limit": limit })),
3595        )?;
3596        // Keep the original priority: a control-plane reply stays passive.
3597        return Ok((FrameType::Error, flags, body));
3598    }
3599    Ok((ty, flags, body))
3600}
3601
3602fn handle_cancel(frame: Frame, in_flight: &InFlight) -> Result<(), SubcModuleError> {
3603    let guard = lock_in_flight(in_flight)?;
3604    if let Some(cancellation) =
3605        guard.get(&(frame.header.channel, frame.header.epoch, frame.header.corr))
3606    {
3607        cancellation.cancel();
3608    }
3609    Ok(())
3610}
3611
3612fn cancel_handle(in_flight: &InFlight, handle: RouteHandle) -> Result<(), SubcModuleError> {
3613    let cancelled = {
3614        let mut guard = lock_in_flight(in_flight)?;
3615        let keys = guard
3616            .keys()
3617            .copied()
3618            .filter(|(channel, epoch, _)| *channel == handle.channel && *epoch == handle.epoch)
3619            .collect::<Vec<_>>();
3620        keys.into_iter()
3621            .filter_map(|key| guard.remove(&key))
3622            .collect::<Vec<_>>()
3623    };
3624    for cancellation in cancelled {
3625        cancellation.cancel();
3626    }
3627    Ok(())
3628}
3629
3630async fn handle_control_request<H>(
3631    frame: Frame,
3632    egress: &mpsc::Sender<Frame>,
3633    handler: Arc<H>,
3634    dispatcher: RequestDispatcher,
3635    module_handle: ModuleHandle,
3636) -> Result<(), SubcModuleError>
3637where
3638    H: ModuleHandler,
3639{
3640    if control_ops::request(
3641        &frame,
3642        egress,
3643        Arc::clone(&handler),
3644        &dispatcher,
3645        &module_handle,
3646    )
3647    .await?
3648    {
3649        return Ok(());
3650    }
3651    if config::review(
3652        &frame,
3653        egress,
3654        Arc::clone(&handler),
3655        &dispatcher,
3656        &module_handle,
3657    ) {
3658        return Ok(());
3659    }
3660    // A control request this SDK cannot decode (most likely a newer daemon's
3661    // field or operation) is refused on its own correlation id, and the
3662    // connection stays up. Returning the decode error would end the serve loop,
3663    // so one unknown field on one route.bind would stop the whole module, and
3664    // the next such bind after its respawn would stop it again.
3665    let request = match serde_json::from_slice::<ModuleControlRequest>(&frame.body) {
3666        Ok(request) => request,
3667        Err(error) => {
3668            let body = serde_json::to_vec(&ErrorBody::new(
3669                "invalid_request",
3670                format!("control request could not be decoded by this module: {error}"),
3671            ))
3672            .map_err(SubcModuleError::Json)?;
3673            let refusal = Frame::build_with_version(
3674                frame.header.ver,
3675                FrameType::Error,
3676                control_flags(),
3677                0,
3678                0,
3679                frame.header.corr,
3680                body,
3681            )
3682            .map_err(SubcModuleError::FrameBuild)?;
3683            send_outbound(egress, refusal).await?;
3684            return Ok(());
3685        }
3686    };
3687    match request {
3688        ModuleControlRequest::RouteBind {
3689            route_channel,
3690            epoch,
3691            target,
3692            identity,
3693            principal,
3694            consumer_capabilities,
3695            role_versions,
3696            admission_facts,
3697            scope,
3698            call_mode,
3699        } => {
3700            // Implicit-replace rule (wire spec 3.3.0): the daemon never rebinds a live
3701            // channel, but its route-gone GOODBYE to modules is best-effort, so a bind
3702            // can arrive for a channel this endpoint still believes installed. A
3703            // strictly higher epoch proves the daemon freed the old binding: tear the
3704            // stale install down locally and proceed. Equal or lower epoch is a
3705            // protocol violation the daemon cannot produce: reject the bind.
3706            if let Some(stale) = module_handle.installed_route(route_channel)? {
3707                if epoch <= stale.epoch {
3708                    let body = serde_json::to_vec(&ErrorBody::new(
3709                        "route_rejected",
3710                        format!(
3711                            "route.bind epoch {epoch} does not supersede installed epoch {} on channel {route_channel}",
3712                            stale.epoch
3713                        ),
3714                    ))
3715                    .map_err(SubcModuleError::Json)?;
3716                    let reject = Frame::build_with_version(
3717                        frame.header.ver,
3718                        FrameType::Error,
3719                        control_flags(),
3720                        0,
3721                        0,
3722                        frame.header.corr,
3723                        body,
3724                    )
3725                    .map_err(SubcModuleError::FrameBuild)?;
3726                    send_outbound(egress, reject).await?;
3727                    return Ok(());
3728                }
3729                if module_handle.remove_route(stale)? {
3730                    cancel_handle(&dispatcher.in_flight, stale)?;
3731                    handler.on_route_gone(&stale).await;
3732                }
3733            }
3734            let handle = module_handle.route_handle(route_channel, epoch);
3735            // The peer keys sit beside the bind's members in the same body.
3736            // They decode as one value: if any is malformed all read as
3737            // absent, and the bind still goes to `on_bind`, which decides.
3738            let peer =
3739                match serde_json::from_slice::<subc_protocol::peer::RouteBindPeer>(&frame.body) {
3740                    Ok(peer) => peer,
3741                    Err(error) => {
3742                        tracing::warn!(
3743                            channel = route_channel,
3744                            epoch,
3745                            %error,
3746                            "route.bind peer keys did not decode; treating them as absent"
3747                        );
3748                        subc_protocol::peer::RouteBindPeer::new()
3749                    }
3750                };
3751            let req = RouteBindRequest {
3752                handle,
3753                target,
3754                identity,
3755                principal,
3756                consumer_capabilities,
3757                role_versions,
3758                admission_facts,
3759                call_mode: call_mode.unwrap_or_else(|| derive_call_mode(scope.as_ref())),
3760                scope,
3761                peer,
3762            };
3763            let decision = handler.on_bind(&req).await;
3764            match decision.kind {
3765                BindDecisionKind::Accept => {
3766                    let response = match serde_json::to_vec(&ModuleControlResponse::RouteBindAck {})
3767                        .map_err(SubcModuleError::Json)
3768                        .and_then(|body| {
3769                            Frame::build_with_version(
3770                                frame.header.ver,
3771                                FrameType::Response,
3772                                control_flags(),
3773                                0,
3774                                0,
3775                                frame.header.corr,
3776                                body,
3777                            )
3778                            .map_err(SubcModuleError::FrameBuild)
3779                        }) {
3780                        Ok(response) => response,
3781                        Err(err) => {
3782                            handler.on_route_gone(&handle).await;
3783                            return Err(err);
3784                        }
3785                    };
3786                    if let Err(err) = send_outbound(egress, response).await {
3787                        handler.on_route_gone(&handle).await;
3788                        return Err(err);
3789                    }
3790                    if let Err(err) = module_handle.install_route(handle) {
3791                        handler.on_route_gone(&handle).await;
3792                        return Err(err);
3793                    }
3794                    handler.on_bound(&handle).await;
3795                }
3796                BindDecisionKind::Reject {
3797                    code,
3798                    message,
3799                    detail,
3800                } => {
3801                    let body = match detail {
3802                        Some(detail) => ErrorBody::new(code, message).with_detail(detail),
3803                        None => ErrorBody::new(code, message),
3804                    };
3805                    let result = serde_json::to_vec(&body)
3806                        .map_err(SubcModuleError::Json)
3807                        .and_then(|body| {
3808                            Frame::build_with_version(
3809                                frame.header.ver,
3810                                FrameType::Error,
3811                                control_flags(),
3812                                0,
3813                                0,
3814                                frame.header.corr,
3815                                body,
3816                            )
3817                            .map_err(SubcModuleError::FrameBuild)
3818                        });
3819                    let result = match result {
3820                        Ok(response) => send_outbound(egress, response).await,
3821                        Err(err) => Err(err),
3822                    };
3823                    handler.on_route_gone(&handle).await;
3824                    result?;
3825                }
3826            }
3827        }
3828        ModuleControlRequest::HealthCheck {} => {
3829            spawn_health_request(frame, egress.clone(), handler, dispatcher)?;
3830        }
3831    }
3832    Ok(())
3833}
3834
3835async fn send_hello(
3836    egress: &mpsc::Sender<Frame>,
3837    mut manifest: ModuleManifest,
3838    config_gate: bool,
3839    extra_control_ops: &[String],
3840) -> Result<(), SubcModuleError> {
3841    let launch_nonce = if registration::supervised() {
3842        None
3843    } else {
3844        match retained_launch_nonce() {
3845            Some(retained) => Some(retained),
3846            None => launch_nonce()
3847                .map_err(SubcModuleError::LaunchNonce)?
3848                .map(|nonce| nonce.value().to_string()),
3849        }
3850    };
3851    stamp_launch_nonce_source(&mut manifest, launch_nonce.as_deref());
3852    let mut control_ops = vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()];
3853    if config_gate {
3854        control_ops.push(config::CONFIG_REVIEW_OP.to_owned());
3855    }
3856    control_ops.extend_from_slice(extra_control_ops);
3857    let body = serde_json::to_vec(&ModuleHelloBody {
3858        manifest,
3859        protocol_ver: PROTOCOL_VERSION,
3860        control_ops: Some(control_ops),
3861        launch_nonce,
3862    })
3863    .map_err(SubcModuleError::Json)?;
3864    let frame = Frame::build(FrameType::Hello, control_flags(), 0, 0, HELLO_CORR, body)
3865        .map_err(SubcModuleError::FrameBuild)?;
3866    send_outbound(egress, frame).await
3867}
3868
3869async fn expect_hello_ack<R>(reader: &mut R) -> Result<ModuleHelloAckBody, SubcModuleError>
3870where
3871    R: AsyncRead + Unpin,
3872{
3873    let Some(frame) = read_frame(reader).await.map_err(SubcModuleError::FrameIo)? else {
3874        return Err(SubcModuleError::ConnectionClosedBeforeHelloAck);
3875    };
3876    match frame.header.ty {
3877        FrameType::HelloAck => serde_json::from_slice(&frame.body).map_err(SubcModuleError::Json),
3878        FrameType::Error => {
3879            let body =
3880                serde_json::from_slice::<ErrorBody>(&frame.body).map_err(SubcModuleError::Json)?;
3881            Err(SubcModuleError::HelloRejected { body })
3882        }
3883        ty => Err(SubcModuleError::UnexpectedHelloAck { ty }),
3884    }
3885}
3886
3887/// Owned byte transport for a module connection, before or after authentication.
3888pub trait ModuleStream: AsyncRead + AsyncWrite + Unpin + Send {}
3889impl<T: AsyncRead + AsyncWrite + Unpin + Send> ModuleStream for T {}
3890
3891async fn connect_to_subc(
3892    connection_file_path: &Path,
3893    registration_channel: bool,
3894) -> Result<Box<dyn ModuleStream>, SubcModuleError> {
3895    let conn = connection_file::read_for_client(connection_file_path).map_err(|source| {
3896        SubcModuleError::ConnectionFile {
3897            path: connection_file_path.to_path_buf(),
3898            source,
3899        }
3900    })?;
3901    if let Some(mut stream) = if registration_channel {
3902        registration::take_stream()?
3903    } else {
3904        None
3905    } {
3906        authenticate_client(&mut stream, &conn, AUTH_DEADLINE)
3907            .await
3908            .map_err(|source| SubcModuleError::Auth {
3909                path: connection_file_path.to_path_buf(),
3910                endpoint: "registration channel".into(),
3911                source,
3912            })?;
3913        return Ok(stream);
3914    }
3915    let endpoint = conn
3916        .endpoints
3917        .first()
3918        .ok_or_else(|| SubcModuleError::NoEndpoint {
3919            path: connection_file_path.to_path_buf(),
3920        })?;
3921    let endpoint_label = format!("{}:{}", endpoint.host, endpoint.port);
3922    let mut stream = connect_endpoint(&endpoint.host, endpoint.port)
3923        .await
3924        .map_err(|source| SubcModuleError::Connect {
3925            path: connection_file_path.to_path_buf(),
3926            endpoint: endpoint_label.clone(),
3927            source,
3928        })?;
3929    // This socket carries the module's replies back to the daemon, so Nagle here
3930    // delays every response rather than every request -- the same cost on the
3931    // return leg. Both ends of the hop have to disable it for either to help.
3932    //
3933    // The result is deliberately dropped rather than logged: this crate takes no
3934    // logging dependency, and the only ways setting a socket option on a
3935    // just-connected stream fail leave the socket unusable, which the handshake on
3936    // the very next line reports as a typed Auth error. Swallowing it here would
3937    // hide nothing that stays hidden.
3938    let _ = stream.set_nodelay(true);
3939    authenticate_client(&mut stream, &conn, AUTH_DEADLINE)
3940        .await
3941        .map_err(|source| SubcModuleError::Auth {
3942            path: connection_file_path.to_path_buf(),
3943            endpoint: endpoint_label,
3944            source,
3945        })?;
3946    Ok(Box::new(stream))
3947}
3948
3949async fn connect_endpoint(host: &str, port: u16) -> io::Result<TcpStream> {
3950    let host = host
3951        .strip_prefix('[')
3952        .and_then(|h| h.strip_suffix(']'))
3953        .unwrap_or(host);
3954    TcpStream::connect((host, port)).await
3955}
3956
3957async fn send_goodbye(tx: &mpsc::Sender<Frame>) -> Result<(), SubcModuleError> {
3958    let frame = Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 0, Vec::new())
3959        .map_err(SubcModuleError::FrameBuild)?;
3960    send_outbound(tx, frame).await
3961}
3962
3963fn is_disconnect(error: &io::Error) -> bool {
3964    matches!(
3965        error.kind(),
3966        io::ErrorKind::ConnectionReset
3967            | io::ErrorKind::ConnectionAborted
3968            | io::ErrorKind::BrokenPipe
3969    )
3970}
3971
3972fn writer_ended(
3973    result: Result<Result<(), WriterFailure>, tokio::task::JoinError>,
3974) -> SubcModuleError {
3975    match result {
3976        Ok(Ok(())) => SubcModuleError::WriterClosed,
3977        Ok(Err(error)) => SubcModuleError::FrameIo(error.error),
3978        Err(error) => SubcModuleError::WriterTask(error),
3979    }
3980}
3981
3982fn writer_connection_end(
3983    result: Result<Result<(), WriterFailure>, tokio::task::JoinError>,
3984) -> Result<ConnectionEnd, SubcModuleError> {
3985    match writer_ended(result) {
3986        SubcModuleError::FrameIo(FrameIoError::Io(error)) if is_disconnect(&error) => {
3987            Ok(ConnectionEnd::Reset)
3988        }
3989        error => Err(error),
3990    }
3991}
3992
3993async fn finish_writer(
3994    mut writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3995    deadline: Instant,
3996) -> (Result<(), SubcModuleError>, usize) {
3997    match timeout_at(deadline, &mut writer).await {
3998        Ok(Ok(Ok(()))) => (Ok(()), 0),
3999        Ok(Ok(Err(failure))) => (
4000            Err(SubcModuleError::FrameIo(failure.error)),
4001            failure.undelivered_replies,
4002        ),
4003        Ok(Err(error)) => (Err(SubcModuleError::WriterTask(error)), 0),
4004        Err(_) => {
4005            writer.abort();
4006            let _ = writer.await;
4007            (Ok(()), 0)
4008        }
4009    }
4010}
4011
4012struct WriterFailure {
4013    error: FrameIoError,
4014    undelivered_replies: usize,
4015}
4016
4017/// [`finish_writer`] for a connection the module ends itself: once the writer
4018/// has flushed and shut down the sending side, drain the reader as
4019/// [`drain_until_peer_closes`] describes. A writer that failed means the socket
4020/// is already broken, so there is nothing to drain.
4021async fn finish_writer_and_drain<R>(
4022    writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
4023    reader: &mut R,
4024    deadline: Instant,
4025) -> (Result<(), SubcModuleError>, usize)
4026where
4027    R: AsyncRead + Unpin,
4028{
4029    let flushed = finish_writer(writer, deadline).await;
4030    if flushed.0.is_ok() {
4031        drain_until_peer_closes(reader, deadline).await;
4032    }
4033    flushed
4034}
4035
4036/// Orderly close for a connection the module ends itself (a stop, an internal
4037/// close or a module-side error), called once the writer has flushed its last
4038/// frame and shut down the sending side.
4039///
4040/// Closing a TCP socket while received bytes are still unread makes the OS
4041/// send a reset (RST) instead of an orderly FIN. Linux and Windows do this;
4042/// where an OS does not, the drain below only waits for a close that comes
4043/// anyway. A daemon that receives the reset can fail its next read with
4044/// `ConnectionReset` and lose data it had not read yet, including the module's
4045/// GOODBYE, so a planned stop would look like a crash. Frames the daemon sent
4046/// after the module stopped reading (a PING, a request, its own GOODBYE) are
4047/// exactly such unread bytes. So keep reading and discarding until the daemon
4048/// closes its side, which it does once it reads the module's FIN.
4049///
4050/// `deadline` is the writer drain deadline, so a daemon that never closes
4051/// cannot hold the stop past the drain budget. Read errors end the drain: the
4052/// socket is already broken and nothing is left to protect.
4053async fn drain_until_peer_closes<R>(reader: &mut R, deadline: Instant)
4054where
4055    R: AsyncRead + Unpin,
4056{
4057    if Instant::now() >= deadline {
4058        return;
4059    }
4060    let mut discard = [0u8; 4096];
4061    let _ = timeout_at(deadline, async {
4062        while let Ok(read) = reader.read(&mut discard).await {
4063            if read == 0 {
4064                break;
4065            }
4066        }
4067    })
4068    .await;
4069}
4070
4071fn is_reply(frame: &Frame) -> bool {
4072    matches!(
4073        frame.header.ty,
4074        FrameType::Response | FrameType::Error | FrameType::StreamEnd
4075    )
4076}
4077
4078async fn drain_writer<W>(write_half: W, mut rx: mpsc::Receiver<Frame>) -> Result<(), WriterFailure>
4079where
4080    W: AsyncWrite + Unpin,
4081{
4082    let mut writer = BufWriter::new(write_half);
4083    let mut pending_replies = 0;
4084    let result = async {
4085        while let Some(frame) = rx.recv().await {
4086            pending_replies += usize::from(is_reply(&frame));
4087            write_frame(&mut writer, &frame).await?;
4088            while let Ok(frame) = rx.try_recv() {
4089                pending_replies += usize::from(is_reply(&frame));
4090                write_frame(&mut writer, &frame).await?;
4091            }
4092            writer.flush().await.map_err(FrameIoError::Io)?;
4093            pending_replies = 0;
4094        }
4095        writer.flush().await.map_err(FrameIoError::Io)?;
4096        // Every sender is gone, so nothing more will be written: shut down the
4097        // sending side so the daemon reads a FIN (EOF) right after the last
4098        // frame, typically the module's GOODBYE. The socket stays open for
4099        // reading, which `drain_until_peer_closes` relies on. When the daemon
4100        // ended the connection first, this sends the same FIN that dropping
4101        // the socket would. A failure here only means the socket is already
4102        // broken; whatever was flushed has been handed to the OS, so it is
4103        // not an undelivered-frame error.
4104        let _ = writer.shutdown().await;
4105        Ok(())
4106    }
4107    .await;
4108    result.map_err(|error| {
4109        rx.close();
4110        while let Ok(frame) = rx.try_recv() {
4111            pending_replies += usize::from(is_reply(&frame));
4112        }
4113        WriterFailure {
4114            error,
4115            undelivered_replies: pending_replies,
4116        }
4117    })
4118}
4119
4120async fn send_outbound(egress: &mpsc::Sender<Frame>, frame: Frame) -> Result<(), SubcModuleError> {
4121    egress
4122        .send(frame)
4123        .await
4124        .map_err(|_| SubcModuleError::WriterClosed)
4125}
4126
4127fn parse_subc_arg(args: impl IntoIterator<Item = OsString>) -> Result<PathBuf, SubcModuleError> {
4128    let mut args = args.into_iter();
4129    while let Some(arg) = args.next() {
4130        if arg == "--subc" {
4131            let value = args.next().ok_or(SubcModuleError::MissingSubcValue)?;
4132            return Ok(PathBuf::from(value));
4133        }
4134        if let Some(raw) = arg.to_str().and_then(|arg| arg.strip_prefix("--subc=")) {
4135            if raw.is_empty() {
4136                return Err(SubcModuleError::MissingSubcValue);
4137            }
4138            return Ok(PathBuf::from(raw));
4139        }
4140    }
4141    Err(SubcModuleError::MissingSubcArg)
4142}
4143
4144fn module_id_from_env() -> Result<Option<String>, SubcModuleError> {
4145    match env::var(SUBC_MODULE_ID_ENV) {
4146        Ok(value) if !value.trim().is_empty() => Ok(Some(value)),
4147        Ok(_) => Err(SubcModuleError::EmptyModuleIdEnv),
4148        Err(env::VarError::NotPresent) => Ok(None),
4149        Err(env::VarError::NotUnicode(value)) => {
4150            Err(SubcModuleError::NonUnicodeModuleIdEnv { value })
4151        }
4152    }
4153}
4154
4155fn lock_in_flight(
4156    in_flight: &InFlight,
4157) -> Result<std::sync::MutexGuard<'_, HashMap<RequestKey, CancellationToken>>, SubcModuleError> {
4158    in_flight
4159        .lock()
4160        .map_err(|_| SubcModuleError::InFlightPoisoned)
4161}
4162
4163fn control_flags() -> Flags {
4164    Flags::new(false, Priority::Passive, false)
4165}
4166
4167fn data_flags() -> Flags {
4168    Flags::new(false, Priority::Interactive, false)
4169}
4170
4171#[derive(Debug)]
4172#[non_exhaustive]
4173pub enum SubcModuleError {
4174    /// A module declared a malformed, duplicate or SDK-owned control operation.
4175    InvalidControlOp(String),
4176    /// A daemon reused an outstanding channel-0 request's correlation.
4177    DuplicateControlCorrelation(u64),
4178    RegistrationChannel(io::Error),
4179    MissingSubcArg,
4180    MissingSubcValue,
4181    EmptyModuleIdEnv,
4182    NonUnicodeModuleIdEnv {
4183        value: OsString,
4184    },
4185    ConnectionFile {
4186        path: PathBuf,
4187        source: ConnectionFileError,
4188    },
4189    NoEndpoint {
4190        path: PathBuf,
4191    },
4192    Connect {
4193        path: PathBuf,
4194        endpoint: String,
4195        source: io::Error,
4196    },
4197    Auth {
4198        path: PathBuf,
4199        endpoint: String,
4200        source: AuthError,
4201    },
4202    FrameIo(FrameIoError),
4203    FrameBuild(FrameBuildError),
4204    Json(serde_json::Error),
4205    WriterClosed,
4206    /// A request handler panicked. Its payload is never sent to the daemon.
4207    HandlerPanic,
4208    StaleRouteHandle(RouteHandle),
4209    ConnectionTokenExhausted,
4210    WriterTask(tokio::task::JoinError),
4211    InFlightPoisoned,
4212    ConnectionClosedBeforeHelloAck,
4213    UnexpectedHelloAck {
4214        ty: FrameType,
4215    },
4216    HelloRejected {
4217        body: ErrorBody,
4218    },
4219    /// The descriptor named for the launch nonce could not be read. HELLO is
4220    /// not sent without it, and the environment copy is not tried instead.
4221    LaunchNonce(launch_nonce::LaunchNonceError),
4222}
4223
4224impl fmt::Display for SubcModuleError {
4225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4226        match self {
4227            Self::InvalidControlOp(op) => {
4228                write!(f, "invalid or reserved control operation: {op:?}")
4229            }
4230            Self::DuplicateControlCorrelation(corr) => {
4231                write!(f, "duplicate in-flight control correlation: {corr}")
4232            }
4233            Self::RegistrationChannel(error) => write!(f, "registration channel: {error}"),
4234            Self::MissingSubcArg => write!(f, "missing required --subc <connection-file> argument"),
4235            Self::MissingSubcValue => write!(f, "--subc requires a connection-file path value"),
4236            Self::EmptyModuleIdEnv => write!(f, "{SUBC_MODULE_ID_ENV} must not be empty when set"),
4237            Self::NonUnicodeModuleIdEnv { value } => write!(
4238                f,
4239                "{SUBC_MODULE_ID_ENV} must be valid UTF-8, got '{}'",
4240                value.to_string_lossy()
4241            ),
4242            Self::ConnectionFile { path, source } => write!(
4243                f,
4244                "failed to read subc connection file '{}': {source}",
4245                path.display()
4246            ),
4247            Self::NoEndpoint { path } => write!(
4248                f,
4249                "subc connection file '{}' has no endpoints",
4250                path.display()
4251            ),
4252            Self::Connect {
4253                path,
4254                endpoint,
4255                source,
4256            } => write!(
4257                f,
4258                "failed to connect to subc endpoint {endpoint} from '{}': {source}",
4259                path.display()
4260            ),
4261            Self::Auth {
4262                path,
4263                endpoint,
4264                source,
4265            } => write!(
4266                f,
4267                "failed to authenticate to subc endpoint {endpoint} from '{}': {source}",
4268                path.display()
4269            ),
4270            Self::FrameIo(err) => fmt::Display::fmt(err, f),
4271            Self::FrameBuild(err) => write!(f, "frame build error: {err}"),
4272            Self::Json(err) => write!(f, "JSON error: {err}"),
4273            Self::WriterClosed => write!(f, "module writer task closed"),
4274            Self::HandlerPanic => write!(f, "module handler panicked"),
4275            Self::StaleRouteHandle(handle) => write!(f, "stale route handle: {handle:?}"),
4276            Self::ConnectionTokenExhausted => write!(f, "module connection token exhausted"),
4277            Self::WriterTask(err) => write!(f, "module writer task failed: {err}"),
4278            Self::InFlightPoisoned => write!(f, "in-flight registry lock poisoned"),
4279            Self::ConnectionClosedBeforeHelloAck => write!(f, "connection closed before HELLO_ACK"),
4280            Self::UnexpectedHelloAck { ty } => write!(f, "expected HELLO_ACK, got {ty:?}"),
4281            Self::HelloRejected { body } => write!(
4282                f,
4283                "HELLO rejected by subc: {} ({})",
4284                body.code, body.message
4285            ),
4286            Self::LaunchNonce(err) => write!(f, "launch nonce unavailable: {err}"),
4287        }
4288    }
4289}
4290
4291impl Error for SubcModuleError {
4292    fn source(&self) -> Option<&(dyn Error + 'static)> {
4293        match self {
4294            Self::RegistrationChannel(error) => Some(error),
4295            Self::ConnectionFile { source, .. } => Some(source),
4296            Self::Connect { source, .. } => Some(source),
4297            Self::Auth { source, .. } => Some(source),
4298            Self::FrameIo(err) => Some(err),
4299            Self::FrameBuild(err) => Some(err),
4300            Self::Json(err) => Some(err),
4301            Self::LaunchNonce(err) => Some(err),
4302            Self::WriterTask(err) => Some(err),
4303            Self::MissingSubcArg
4304            | Self::InvalidControlOp(_)
4305            | Self::DuplicateControlCorrelation(_)
4306            | Self::MissingSubcValue
4307            | Self::EmptyModuleIdEnv
4308            | Self::NonUnicodeModuleIdEnv { .. }
4309            | Self::NoEndpoint { .. }
4310            | Self::WriterClosed
4311            | Self::HandlerPanic
4312            | Self::StaleRouteHandle(_)
4313            | Self::ConnectionTokenExhausted
4314            | Self::InFlightPoisoned
4315            | Self::ConnectionClosedBeforeHelloAck
4316            | Self::UnexpectedHelloAck { .. }
4317            | Self::HelloRejected { .. } => None,
4318        }
4319    }
4320}
4321
4322impl From<serde_json::Error> for SubcModuleError {
4323    fn from(err: serde_json::Error) -> Self {
4324        Self::Json(err)
4325    }
4326}
4327
4328#[cfg(test)]
4329mod call_mode_tests;
4330
4331#[cfg(test)]
4332mod tests {
4333    use std::sync::atomic::{AtomicUsize, Ordering};
4334
4335    use serde_json::json;
4336
4337    use subc_protocol::manifest::{Concurrency, ExecutionMode, IdentityScope, Tool};
4338    use tokio::sync::Semaphore;
4339    use tokio::time::{advance, timeout};
4340
4341    use super::*;
4342
4343    struct EchoHandler;
4344
4345    #[async_trait]
4346    impl ModuleHandler for EchoHandler {
4347        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
4348            HandlerOutcome::Response(body)
4349        }
4350    }
4351
4352    struct BlockingHandler {
4353        entered: Arc<AtomicUsize>,
4354        release: Semaphore,
4355        report: HealthReport,
4356    }
4357
4358    #[async_trait]
4359    impl ModuleHandler for BlockingHandler {
4360        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
4361            self.entered.fetch_add(1, Ordering::SeqCst);
4362            self.release.acquire().await.unwrap().forget();
4363            HandlerOutcome::Streamed
4364        }
4365
4366        async fn health(&self) -> HealthReport {
4367            self.report.clone()
4368        }
4369    }
4370
4371    fn health_request(corr: u64) -> Frame {
4372        Frame::build(
4373            FrameType::Request,
4374            control_flags(),
4375            0,
4376            0,
4377            corr,
4378            serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).unwrap(),
4379        )
4380        .unwrap()
4381    }
4382
4383    fn data_request(channel: u16, corr: u64) -> Frame {
4384        Frame::build(
4385            FrameType::Request,
4386            data_flags(),
4387            channel,
4388            1,
4389            corr,
4390            b"opaque".to_vec(),
4391        )
4392        .unwrap()
4393    }
4394
4395    fn catalog_update_response(corr: u64) -> Frame {
4396        Frame::build(
4397            FrameType::Response,
4398            control_flags(),
4399            0,
4400            0,
4401            corr,
4402            serde_json::to_vec(&ModuleControlResponseToModule::CatalogUpdate {}).unwrap(),
4403        )
4404        .unwrap()
4405    }
4406
4407    fn test_module_handle(subc_ops: &[&str]) -> (ModuleHandle, mpsc::Receiver<Frame>) {
4408        let (tx, rx) = mpsc::channel(4);
4409        let ack = ModuleHelloAckBody {
4410            negotiated_ver: PROTOCOL_VERSION,
4411            subc_ops: subc_ops.iter().map(|op| (*op).to_string()).collect(),
4412            subc_capabilities: Vec::new(),
4413            storage: None,
4414            machine_id: None,
4415        };
4416        (
4417            ModuleHandle::new(
4418                &ack,
4419                tx,
4420                1,
4421                CancellationToken::new(),
4422                tokio::runtime::Handle::current(),
4423            ),
4424            rx,
4425        )
4426    }
4427
4428    #[test]
4429    fn module_handle_exposes_the_acked_machine_id_and_none_otherwise() {
4430        let runtime = tokio::runtime::Runtime::new().unwrap();
4431        let handle_for = |machine_id: Option<&str>| {
4432            let (tx, _rx) = mpsc::channel(1);
4433            let ack = ModuleHelloAckBody {
4434                negotiated_ver: PROTOCOL_VERSION,
4435                subc_ops: Vec::new(),
4436                subc_capabilities: Vec::new(),
4437                storage: None,
4438                machine_id: machine_id.map(str::to_owned),
4439            };
4440            ModuleHandle::new(
4441                &ack,
4442                tx,
4443                1,
4444                CancellationToken::new(),
4445                runtime.handle().clone(),
4446            )
4447        };
4448        assert_eq!(
4449            handle_for(Some("0123456789abcdef0123456789abcdef"))
4450                .machine_id()
4451                .map(MachineId::as_str),
4452            Some("0123456789abcdef0123456789abcdef")
4453        );
4454        // An older daemon sends nothing, and nothing is invented in its place.
4455        assert_eq!(handle_for(None).machine_id(), None);
4456        assert_eq!(handle_for(Some("not-a-machine-id")).machine_id(), None);
4457    }
4458
4459    fn test_provider_role(tool_names: &[&str]) -> ProviderRole {
4460        ProviderRole::ToolProvider {
4461            tools: tool_names
4462                .iter()
4463                .map(|name| Tool {
4464                    name: (*name).to_string(),
4465                    description: None,
4466                    execution_mode: ExecutionMode::Pure,
4467                    schema: json!({"type": "object"}),
4468                })
4469                .collect(),
4470            identity_scope: vec![IdentityScope::Project],
4471            concurrency: Concurrency::ModuleManaged,
4472            emits_push: false,
4473            sub_supervises: false,
4474        }
4475    }
4476
4477    #[tokio::test]
4478    async fn catalog_update_fails_fast_when_hello_ack_does_not_advertise_support() {
4479        let (handle, mut rx) = test_module_handle(&[]);
4480
4481        let error = handle
4482            .catalog_update(vec![test_provider_role(&["a"])])
4483            .await
4484            .unwrap_err();
4485        assert!(matches!(error, CatalogUpdateError::NotSupported));
4486        assert!(matches!(
4487            handle.set_ready(true).await,
4488            Err(CatalogUpdateError::NotSupported)
4489        ));
4490        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
4491    }
4492
4493    #[tokio::test]
4494    async fn catalog_update_demuxes_multiple_in_flight_requests() {
4495        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4496        let first_handle = handle.clone();
4497        let second_handle = handle.clone();
4498        let first = tokio::spawn(async move {
4499            first_handle
4500                .catalog_update(vec![test_provider_role(&["a"])])
4501                .await
4502        });
4503        let second = tokio::spawn(async move {
4504            second_handle
4505                .catalog_update(vec![test_provider_role(&["b"])])
4506                .await
4507        });
4508
4509        let first_frame = timeout(Duration::from_secs(1), rx.recv())
4510            .await
4511            .unwrap()
4512            .unwrap();
4513        let second_frame = timeout(Duration::from_secs(1), rx.recv())
4514            .await
4515            .unwrap()
4516            .unwrap();
4517        assert_eq!(first_frame.header.ty, FrameType::Request);
4518        assert_eq!(first_frame.header.channel, 0);
4519        assert_eq!(second_frame.header.ty, FrameType::Request);
4520        assert_eq!(second_frame.header.channel, 0);
4521        assert_ne!(first_frame.header.corr, second_frame.header.corr);
4522
4523        let (earlier, later) =
4524            if json_body(&first_frame.body)["provides"] == json!([test_provider_role(&["a"])]) {
4525                (first, second)
4526            } else {
4527                (second, first)
4528            };
4529        assert!(handle.handle_control_reply(catalog_update_response(second_frame.header.corr)));
4530        assert!(later.await.unwrap().is_ok());
4531        assert!(handle.handle_control_reply(catalog_update_response(first_frame.header.corr)));
4532        assert!(earlier.await.unwrap().is_ok());
4533
4534        let expected = json_body(&second_frame.body)["provides"].clone();
4535        let (result, ()) = tokio::join!(handle.set_ready(true), async {
4536            let frame = rx.recv().await.unwrap();
4537            assert_eq!(json_body(&frame.body)["provides"], expected);
4538            assert_eq!(json_body(&frame.body)["ready"], true);
4539            handle.handle_control_reply(catalog_update_response(frame.header.corr));
4540        });
4541        result.unwrap();
4542    }
4543
4544    fn json_body(body: &[u8]) -> serde_json::Value {
4545        serde_json::from_slice(body).unwrap()
4546    }
4547
4548    #[tokio::test]
4549    async fn role_declarations_update_requires_its_own_advertised_op() {
4550        for ops in [vec![], vec![MODULE_TO_SUBC_OP_CATALOG_UPDATE]] {
4551            let (handle, mut rx) = test_module_handle(&ops);
4552            assert!(matches!(
4553                handle.update_role_declarations(BTreeMap::new()).await,
4554                Err(CatalogUpdateError::NotSupported)
4555            ));
4556            assert!(matches!(
4557                rx.try_recv(),
4558                Err(mpsc::error::TryRecvError::Empty)
4559            ));
4560        }
4561    }
4562
4563    #[tokio::test]
4564    async fn role_declarations_update_sends_map_and_preserves_refusal() {
4565        let (handle, mut rx) =
4566            test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS]);
4567        let initial_roles = vec![test_provider_role(&["original"])];
4568        handle.shared.lock_inner().current_provides = Some(initial_roles.clone());
4569        for declarations in [
4570            json!({"media-provider/v1": {"engines": ["image"]}}),
4571            json!({}),
4572        ] {
4573            let map = serde_json::from_value(declarations.clone()).unwrap();
4574            let (result, ()) = tokio::join!(handle.update_role_declarations(map), async {
4575                let frame = rx.recv().await.unwrap();
4576                assert_eq!(frame.header.ty, FrameType::Request);
4577                assert_eq!(frame.header.channel, 0);
4578                assert_eq!(
4579                    json_body(&frame.body),
4580                    json!({"op": "catalog.update_role_declarations", "role_declarations": declarations})
4581                );
4582                handle.handle_control_reply(control_reply(
4583                    FrameType::Response,
4584                    frame.header.corr,
4585                    serde_json::to_vec(&json!({"op": "catalog.update_role_declarations"})).unwrap(),
4586                ));
4587            });
4588            result.unwrap();
4589        }
4590        let (result, ()) = tokio::join!(handle.update_role_declarations(BTreeMap::new()), async {
4591            let frame = rx.recv().await.unwrap();
4592            handle.handle_control_reply(control_reply(FrameType::Error, frame.header.corr,
4593                serde_json::to_vec(&json!({"code": "invalid_role_declarations", "message": "role_declarations key must use capability-name grammar"})).unwrap()));
4594        });
4595        let Err(CatalogUpdateError::Rejected(body)) = result else {
4596            panic!("expected typed refusal")
4597        };
4598        assert_eq!(body.code, "invalid_role_declarations");
4599        assert_eq!(
4600            body.message,
4601            "role_declarations key must use capability-name grammar"
4602        );
4603        assert_eq!(
4604            handle.shared.lock_inner().current_provides,
4605            Some(initial_roles)
4606        );
4607    }
4608
4609    async fn ack_catalog_update(
4610        handle: &ModuleHandle,
4611        rx: &mut mpsc::Receiver<Frame>,
4612        provides: &[ProviderRole],
4613        ready: Option<bool>,
4614        capabilities: Option<&CapabilityDeclarations>,
4615    ) {
4616        let frame = rx.recv().await.unwrap();
4617        let mut expected = json!({"op": "catalog.update", "provides": provides});
4618        if let Some(ready) = ready {
4619            expected["ready"] = json!(ready);
4620        }
4621        if let Some(capabilities) = capabilities {
4622            expected["capabilities"] = json!(capabilities);
4623        }
4624        assert_eq!(json_body(&frame.body), expected);
4625        let mut wire = format!(
4626            r#"{{"op":"catalog.update","provides":{}"#,
4627            serde_json::to_string(provides).unwrap()
4628        );
4629        if let Some(capabilities) = capabilities {
4630            wire.push_str(&format!(
4631                r#","capabilities":{}"#,
4632                serde_json::to_string(capabilities).unwrap()
4633            ));
4634        }
4635        if let Some(ready) = ready {
4636            wire.push_str(&format!(r#","ready":{ready}"#));
4637        }
4638        wire.push('}');
4639        assert_eq!(frame.body, wire.as_bytes());
4640        assert!(handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4641    }
4642
4643    #[tokio::test]
4644    async fn catalog_update_set_ready_preserves_registered_and_replaced_roles() {
4645        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4646        let initial = vec![test_provider_role(&["initial", "second"])];
4647        handle.shared.lock_inner().current_provides = Some(initial.clone());
4648        let (result, ()) = tokio::join!(
4649            handle.set_ready(true),
4650            ack_catalog_update(&handle, &mut rx, &initial, Some(true), None)
4651        );
4652        result.unwrap();
4653
4654        let replaced = vec![test_provider_role(&["replacement"])];
4655        let (result, ()) = tokio::join!(
4656            handle.catalog_update(replaced.clone()),
4657            ack_catalog_update(&handle, &mut rx, &replaced, None, None)
4658        );
4659        result.unwrap();
4660        let (result, ()) = tokio::join!(
4661            handle.set_ready(false),
4662            ack_catalog_update(&handle, &mut rx, &replaced, Some(false), None)
4663        );
4664        result.unwrap();
4665
4666        let attested = vec![test_provider_role(&["attested"])];
4667        let capabilities = CapabilityDeclarations {
4668            provides: vec!["test.capability".into()],
4669            requires: Vec::new(),
4670            must_never_reach: Vec::new(),
4671        };
4672        let (result, ()) = tokio::join!(
4673            handle.catalog_update_with_capabilities(attested.clone(), capabilities.clone()),
4674            ack_catalog_update(&handle, &mut rx, &attested, None, Some(&capabilities))
4675        );
4676        result.unwrap();
4677        let (result, ()) = tokio::join!(
4678            handle.set_ready(true),
4679            ack_catalog_update(&handle, &mut rx, &attested, Some(true), None)
4680        );
4681        result.unwrap();
4682    }
4683
4684    #[tokio::test]
4685    async fn catalog_update_set_ready_refuses_unknown_or_in_flight_roles() {
4686        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4687        assert!(matches!(
4688            handle.set_ready(true).await,
4689            Err(CatalogUpdateError::Protocol(_))
4690        ));
4691        assert!(rx.try_recv().is_err());
4692
4693        let updating = handle.clone();
4694        let update = tokio::spawn(async move {
4695            updating
4696                .catalog_update(vec![test_provider_role(&["new"])])
4697                .await
4698        });
4699        let frame = rx.recv().await.unwrap();
4700        assert!(matches!(
4701            handle.set_ready(true).await,
4702            Err(CatalogUpdateError::Protocol(_))
4703        ));
4704        assert!(rx.try_recv().is_err());
4705        update.abort();
4706        assert!(update.await.unwrap_err().is_cancelled());
4707        assert!(!handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4708        assert!(matches!(
4709            handle.set_ready(true).await,
4710            Err(CatalogUpdateError::Protocol(_))
4711        ));
4712
4713        let roles = vec![test_provider_role(&["recovered"])];
4714        let (result, ()) = tokio::join!(
4715            handle.catalog_update(roles.clone()),
4716            ack_catalog_update(&handle, &mut rx, &roles, None, None)
4717        );
4718        result.unwrap();
4719        let (result, ()) = tokio::join!(
4720            handle.set_ready(true),
4721            ack_catalog_update(&handle, &mut rx, &roles, Some(true), None)
4722        );
4723        result.unwrap();
4724    }
4725
4726    #[tokio::test(start_paused = true)]
4727    async fn catalog_update_set_ready_timeout_does_not_replay_stale_roles() {
4728        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4729        handle.shared.lock_inner().current_provides = Some(vec![test_provider_role(&["old"])]);
4730        assert!(matches!(
4731            handle
4732                .catalog_update(vec![test_provider_role(&["new"])])
4733                .await,
4734            Err(CatalogUpdateError::Timeout)
4735        ));
4736        let frame = rx.recv().await.unwrap();
4737        assert!(!handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4738        assert!(matches!(
4739            handle.set_ready(true).await,
4740            Err(CatalogUpdateError::Protocol(_))
4741        ));
4742        assert!(rx.try_recv().is_err());
4743    }
4744
4745    #[tokio::test]
4746    async fn catalog_update_set_ready_rejection_retains_last_accepted_roles() {
4747        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4748        let initial = vec![test_provider_role(&["kept"])];
4749        handle.shared.lock_inner().current_provides = Some(initial.clone());
4750        let (result, ()) = tokio::join!(
4751            handle.catalog_update(vec![test_provider_role(&["rejected"])]),
4752            async {
4753                let frame = rx.recv().await.unwrap();
4754                handle.handle_control_reply(control_reply(
4755                    FrameType::Error,
4756                    frame.header.corr,
4757                    br#"{"code":"catalog_update_frozen_field","message":"frozen"}"#.to_vec(),
4758                ));
4759            }
4760        );
4761        assert!(matches!(result, Err(CatalogUpdateError::FrozenField(_))));
4762        let (result, ()) = tokio::join!(
4763            handle.set_ready(true),
4764            ack_catalog_update(&handle, &mut rx, &initial, Some(true), None)
4765        );
4766        result.unwrap();
4767    }
4768
4769    fn control_reply(ty: FrameType, corr: u64, body: Vec<u8>) -> Frame {
4770        Frame::build(ty, control_flags(), 0, 0, corr, body).unwrap()
4771    }
4772
4773    async fn authorize_for_test(
4774        handle: &ModuleHandle,
4775    ) -> Result<RouteAuthorizeResponse, ScopeCallError> {
4776        handle
4777            .route_authorize(
4778                Principal::Direct,
4779                RouteAuthorizeScope::new(
4780                    Principal::Reserved {
4781                        module_id: "owner".into(),
4782                    },
4783                    "stored-scope",
4784                    7,
4785                ),
4786                "target".into(),
4787                RouteAuthorizeExpected::new(
4788                    subc_protocol::scope::ScopeKind::Head,
4789                    &subc_protocol::scope::ScopeAttributes::default(),
4790                ),
4791            )
4792            .await
4793    }
4794
4795    #[tokio::test]
4796    async fn route_authorize_requires_advertised_operation() {
4797        let (tx, mut rx) = mpsc::channel(4);
4798        let ack = ModuleHelloAckBody {
4799            negotiated_ver: PROTOCOL_VERSION,
4800            subc_ops: vec![],
4801            // A module-provided capability is not the daemon's op advertisement.
4802            subc_capabilities: vec![subc_protocol::scope::ROUTE_AUTHORIZE_CAPABILITY.into()],
4803            storage: None,
4804            machine_id: None,
4805        };
4806        let handle = ModuleHandle::new(
4807            &ack,
4808            tx,
4809            1,
4810            CancellationToken::new(),
4811            tokio::runtime::Handle::current(),
4812        );
4813        let result = timeout(Duration::from_millis(100), authorize_for_test(&handle))
4814            .await
4815            .expect("an unsupported operation must return without sending or awaiting a reply");
4816        assert_eq!(
4817            result,
4818            Err(ScopeCallError::NotSupported {
4819                op: subc_protocol::scope::ROUTE_AUTHORIZE_OP,
4820            })
4821        );
4822        assert!(
4823            rx.try_recv().is_err(),
4824            "unsupported calls must send nothing"
4825        );
4826    }
4827
4828    #[tokio::test]
4829    async fn route_authorize_decodes_every_answer_and_permission_refusal() {
4830        use RouteAuthorizeOutcome::*;
4831        let (handle, mut rx) = test_module_handle(&[subc_protocol::scope::ROUTE_AUTHORIZE_OP]);
4832        for (wire, outcome, code) in [
4833            ("authorized", Authorized, None),
4834            ("scope_ended", ScopeEnded, Some("scope_not_live")),
4835            ("indeterminate", Indeterminate, Some("scope_not_synced")),
4836            ("epoch_changed", EpochChanged, Some("scope_ended")),
4837            ("claim_changed", ClaimChanged, None),
4838            (
4839                "proof_required",
4840                ProofRequired,
4841                Some("scope_bind_proof_required"),
4842            ),
4843            ("not_authorized", NotAuthorized, Some("scope_not_carrier")),
4844            ("target_absent", TargetAbsent, None),
4845        ] {
4846            let caller = handle.clone();
4847            let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4848            let request = rx.recv().await.unwrap();
4849            assert_eq!(request.header.ty, FrameType::Request);
4850            assert_eq!(request.header.channel, 0);
4851            assert_eq!(request.header.ver, PROTOCOL_VERSION);
4852            assert_eq!(
4853                serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
4854                serde_json::json!({
4855                    "op": "route.authorize", "principal": {"kind": "direct"},
4856                    "scope": {"owner": {"kind": "reserved", "module_id": "owner"},
4857                              "ref": "stored-scope", "epoch": 7},
4858                    "target": "target", "expected": {"kind": "head"}
4859                })
4860            );
4861            let content_version = (outcome == Authorized).then_some("sha256:content");
4862            let mut body = serde_json::json!({
4863                "op": "route.authorize", "outcome": wire, "message": "judgment"
4864            });
4865            if let Some(code) = code {
4866                body["route_open_code"] = code.into();
4867            }
4868            if let Some(version) = content_version {
4869                body["content_version"] = version.into();
4870            }
4871            assert!(handle.handle_control_reply(control_reply(
4872                FrameType::Response,
4873                request.header.corr,
4874                serde_json::to_vec(&body).unwrap(),
4875            )));
4876            let reply = pending.await.unwrap().unwrap();
4877            assert_eq!(reply.outcome, outcome);
4878            assert_eq!(reply.message, "judgment");
4879            assert_eq!(reply.route_open_code.as_deref(), code);
4880            assert_eq!(reply.content_version.as_deref(), content_version);
4881        }
4882
4883        for (code, message) in [
4884            ("route_authorize_not_permitted", "not the configured owner"),
4885            ("not_registered", "connection is not registered"),
4886            ("unexpected", "a future daemon call refusal"),
4887        ] {
4888            let caller = handle.clone();
4889            let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4890            let request = rx.recv().await.unwrap();
4891            assert!(handle.handle_control_reply(control_reply(
4892                FrameType::Error,
4893                request.header.corr,
4894                serde_json::to_vec(&serde_json::json!({"code": code, "message": message})).unwrap(),
4895            )));
4896            assert_eq!(
4897                pending.await.unwrap(),
4898                Err(ScopeCallError::Refused {
4899                    code: code.into(),
4900                    message: message.into(),
4901                })
4902            );
4903        }
4904    }
4905
4906    #[tokio::test]
4907    async fn route_authorize_rejects_malformed_and_unexpected_replies() {
4908        let (handle, mut rx) = test_module_handle(&[subc_protocol::scope::ROUTE_AUTHORIZE_OP]);
4909        for (ty, body) in [
4910            (FrameType::Response, r#"{"op":"catalog.update"}"#),
4911            (
4912                FrameType::Response,
4913                r#"{"op":"route.authorize","outcome":"authorized"}"#,
4914            ),
4915            (
4916                FrameType::Response,
4917                r#"{"op":"route.authorize","outcome":"future","message":"new"}"#,
4918            ),
4919            (FrameType::Error, "not json"),
4920            (FrameType::Request, "{}"),
4921        ] {
4922            let caller = handle.clone();
4923            let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4924            let request = rx.recv().await.unwrap();
4925            assert!(handle.handle_control_reply(control_reply(
4926                ty,
4927                request.header.corr,
4928                body.as_bytes().to_vec(),
4929            )));
4930            assert!(
4931                matches!(pending.await.unwrap(), Err(ScopeCallError::Protocol(_))),
4932                "{body}"
4933            );
4934        }
4935    }
4936
4937    #[tokio::test]
4938    async fn scope_served_by_requires_capability_and_decodes_open_replies() {
4939        let (unsupported, mut rx) = test_module_handle(&[subc_control::SCOPE_SERVED_BY_OP]);
4940        assert_eq!(
4941            unsupported
4942                .scope_served_by("s".into(), 1, "tool".into())
4943                .await,
4944            Err(ScopeCallError::NotSupported {
4945                op: subc_control::SCOPE_SERVED_BY_OP
4946            })
4947        );
4948        assert!(rx.try_recv().is_err());
4949        let (tx, mut rx) = mpsc::channel(4);
4950        let ack = ModuleHelloAckBody {
4951            negotiated_ver: PROTOCOL_VERSION,
4952            subc_ops: vec![],
4953            subc_capabilities: vec![subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.into()],
4954            storage: None,
4955            machine_id: None,
4956        };
4957        let handle = ModuleHandle::new(
4958            &ack,
4959            tx,
4960            1,
4961            CancellationToken::new(),
4962            tokio::runtime::Handle::current(),
4963        );
4964        for answer in ["served", "not_served", "unknown", "future"] {
4965            let caller = handle.clone();
4966            let pending =
4967                tokio::spawn(
4968                    async move { caller.scope_served_by("s".into(), 7, "tool".into()).await },
4969                );
4970            let request = rx.recv().await.unwrap();
4971            let decoded: subc_control::ScopeServedByRequest =
4972                serde_json::from_slice(&request.body).unwrap();
4973            assert_eq!(
4974                (
4975                    decoded.scope_ref.as_str(),
4976                    decoded.scope_epoch,
4977                    decoded.module_id.as_str()
4978                ),
4979                ("s", 7, "tool")
4980            );
4981            assert!(handle.handle_control_reply(control_reply(FrameType::Response, request.header.corr,
4982                serde_json::to_vec(&serde_json::json!({"op":"scope.served_by", "answer":answer, "daemon_incarnation":"d"})).unwrap())));
4983            let reply = pending.await.unwrap().unwrap();
4984            assert_eq!(reply.daemon_incarnation, "d");
4985            assert_eq!(serde_json::to_value(reply.answer).unwrap(), answer);
4986        }
4987        let caller = handle.clone();
4988        let pending =
4989            tokio::spawn(async move { caller.scope_served_by("s".into(), 7, "tool".into()).await });
4990        let request = rx.recv().await.unwrap();
4991        assert!(handle.handle_control_reply(control_reply(
4992            FrameType::Error,
4993            request.header.corr,
4994            serde_json::to_vec(&serde_json::json!({"code":"not_registered", "message":"gone"}))
4995                .unwrap()
4996        )));
4997        assert_eq!(
4998            pending.await.unwrap().unwrap_err().code(),
4999            Some("not_registered")
5000        );
5001    }
5002
5003    fn owner() -> Principal {
5004        Principal::Reserved {
5005            module_id: "owner".to_string(),
5006        }
5007    }
5008
5009    mod scope_watch {
5010        use super::*;
5011        include!("module_subscription_tests.rs");
5012    }
5013
5014    /// Each scope op is gated on its own `subc_ops` entry: a daemon that
5015    /// lists one but not the other gets only the one it listed, and a gated
5016    /// call sends nothing.
5017    #[tokio::test]
5018    async fn scope_ops_fail_fast_when_hello_ack_does_not_advertise_them() {
5019        let (handle, mut rx) = test_module_handle(&[]);
5020        assert_eq!(
5021            handle.scope_sync(1, Vec::new()).await.unwrap_err(),
5022            ScopeCallError::NotSupported { op: SCOPE_SYNC_OP }
5023        );
5024        assert_eq!(
5025            handle
5026                .scope_describe(owner(), "s".to_string())
5027                .await
5028                .unwrap_err(),
5029            ScopeCallError::NotSupported {
5030                op: SCOPE_DESCRIBE_OP
5031            }
5032        );
5033        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5034
5035        let (describe_only, mut rx) = test_module_handle(&[SCOPE_DESCRIBE_OP]);
5036        assert_eq!(
5037            describe_only.scope_sync(1, Vec::new()).await.unwrap_err(),
5038            ScopeCallError::NotSupported { op: SCOPE_SYNC_OP }
5039        );
5040        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5041
5042        let (sync_only, mut rx) = test_module_handle(&[SCOPE_SYNC_OP]);
5043        assert_eq!(
5044            sync_only
5045                .scope_describe(owner(), "s".to_string())
5046                .await
5047                .unwrap_err(),
5048            ScopeCallError::NotSupported {
5049                op: SCOPE_DESCRIBE_OP
5050            }
5051        );
5052        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5053    }
5054
5055    #[tokio::test]
5056    async fn scope_apply_sends_nothing_without_its_own_advertised_op() {
5057        for ops in [&[][..], &[SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP][..]] {
5058            let (handle, mut rx) = test_module_handle(ops);
5059            assert_eq!(
5060                handle.scope_apply(2, Vec::new(), Vec::new()).await,
5061                Err(ScopeCallError::NotSupported { op: SCOPE_APPLY_OP })
5062            );
5063            assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5064        }
5065    }
5066
5067    #[tokio::test]
5068    async fn scope_apply_sends_the_delta_and_preserves_per_entry_outcomes() {
5069        let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5070        let apply = tokio::spawn({
5071            let handle = handle.clone();
5072            async move {
5073                handle
5074                    .scope_apply(
5075                        2,
5076                        vec![ScopeRecord::new(
5077                            "run",
5078                            1,
5079                            subc_protocol::scope::ScopeKind::Ephemeral,
5080                        )
5081                        .with_expires_at_ms(Some(12345))
5082                        .with_workdir(Some("/session/folder".into()))
5083                        .with_project_id(Some("project:1".into()))],
5084                        vec![ScopeEnd::new("old", 3), ScopeEnd::new("missing", 1)],
5085                    )
5086                    .await
5087            }
5088        });
5089        let request = timeout(Duration::from_secs(1), rx.recv())
5090            .await
5091            .unwrap()
5092            .unwrap();
5093        assert_eq!(request.header.ty, FrameType::Request);
5094        assert_eq!(request.header.channel, 0);
5095        assert_eq!(
5096            serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
5097            serde_json::json!({
5098                "op": "scope.apply", "generation": 2,
5099                "upsert": [{"ref": "run", "scope_epoch": 1, "kind": "ephemeral", "expires_at_ms": 12345,
5100                    "workdir": "/session/folder", "project_id": "project:1"}],
5101                "end": [{"ref": "old", "scope_epoch": 3}, {"ref": "missing", "scope_epoch": 1}]
5102            })
5103        );
5104        let body = serde_json::to_vec(&serde_json::json!({
5105            "op": "scope.apply", "generation": 2,
5106            "results": [{"ref": "run", "scope_epoch": 1, "outcome": "refused", "code": "scope_expired"}],
5107            "end_results": [
5108                {"ref": "old", "scope_epoch": 3, "outcome": "ended"},
5109                {"ref": "missing", "scope_epoch": 1, "outcome": "not_live"}
5110            ],
5111            "ended": [{"ref": "old", "scope_epoch": 3}]
5112        }))
5113        .unwrap();
5114        assert!(handle.handle_control_reply(control_reply(
5115            FrameType::Response,
5116            request.header.corr,
5117            body
5118        )));
5119        let reply = apply.await.unwrap().unwrap();
5120        assert_eq!(reply.generation, 2);
5121        assert_eq!(reply.results.len(), 1);
5122        assert_eq!(reply.results[0].scope_ref, "run");
5123        assert_eq!(
5124            reply.results[0].outcome,
5125            subc_protocol::scope::ScopeRecordOutcome::Refused
5126        );
5127        assert_eq!(reply.results[0].code.as_deref(), Some("scope_expired"));
5128        assert_eq!(reply.end_results.len(), 2);
5129        assert_eq!(reply.end_results[0].scope_ref, "old");
5130        assert_eq!(reply.end_results[0].scope_epoch, 3);
5131        assert_eq!(
5132            reply.end_results[0].outcome,
5133            subc_protocol::scope::ScopeEndOutcome::Ended
5134        );
5135        assert_eq!(reply.end_results[1].scope_ref, "missing");
5136        assert_eq!(
5137            reply.end_results[1].outcome,
5138            subc_protocol::scope::ScopeEndOutcome::NotLive
5139        );
5140        assert_eq!(reply.ended.len(), 1);
5141        assert_eq!(reply.ended[0].scope_ref, "old");
5142        assert_eq!(reply.ended[0].scope_epoch, 3);
5143    }
5144
5145    #[tokio::test]
5146    async fn scope_apply_rejects_a_reply_for_another_op() {
5147        let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5148        let apply = tokio::spawn({
5149            let handle = handle.clone();
5150            async move { handle.scope_apply(2, Vec::new(), Vec::new()).await }
5151        });
5152        let request = timeout(Duration::from_secs(1), rx.recv())
5153            .await
5154            .unwrap()
5155            .unwrap();
5156        let body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeSync {
5157            generation: 2,
5158            results: Vec::new(),
5159            ended: Vec::new(),
5160        })
5161        .unwrap();
5162        assert!(handle.handle_control_reply(control_reply(
5163            FrameType::Response,
5164            request.header.corr,
5165            body
5166        )));
5167        assert!(matches!(
5168            apply.await.unwrap(),
5169            Err(ScopeCallError::Protocol(_))
5170        ));
5171    }
5172
5173    #[tokio::test]
5174    async fn scope_apply_preserves_whole_call_refusal_codes() {
5175        let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5176        for code in [
5177            subc_protocol::error_codes::SCOPE_SYNC_REQUIRED,
5178            subc_protocol::error_codes::SCOPE_SYNC_STALE,
5179            subc_protocol::error_codes::SCOPE_SYNC_NOT_AUTHORITY,
5180            "not_registered",
5181        ] {
5182            let apply = tokio::spawn({
5183                let handle = handle.clone();
5184                async move { handle.scope_apply(2, Vec::new(), Vec::new()).await }
5185            });
5186            let request = timeout(Duration::from_secs(1), rx.recv())
5187                .await
5188                .unwrap()
5189                .unwrap();
5190            let body = serde_json::to_vec(&ErrorBody::new(code, "why")).unwrap();
5191            assert!(handle.handle_control_reply(control_reply(
5192                FrameType::Error,
5193                request.header.corr,
5194                body
5195            )));
5196            let error = apply.await.unwrap().unwrap_err();
5197            assert_eq!(
5198                error,
5199                ScopeCallError::Refused {
5200                    code: code.to_string(),
5201                    message: "why".to_string()
5202                }
5203            );
5204            assert_eq!(error.code(), Some(code));
5205        }
5206    }
5207
5208    /// A reply carrying another op's body is not taken as an answer.
5209    #[tokio::test]
5210    async fn a_scope_reply_of_another_op_is_a_protocol_error() {
5211        let (handle, mut rx) = test_module_handle(&[SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP]);
5212        let sync = tokio::spawn({
5213            let handle = handle.clone();
5214            async move { handle.scope_sync(1, Vec::new()).await }
5215        });
5216        let request = timeout(Duration::from_secs(1), rx.recv())
5217            .await
5218            .unwrap()
5219            .unwrap();
5220        let describe_body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeDescribe {
5221            status: ScopeStatus::NotLive,
5222            scope_epoch: None,
5223            daemon_incarnation: "i".to_string(),
5224            owner_synced: false,
5225            owner_configured: false,
5226            scope: None,
5227        })
5228        .unwrap();
5229        assert!(handle.handle_control_reply(control_reply(
5230            FrameType::Response,
5231            request.header.corr,
5232            describe_body
5233        )));
5234        assert!(matches!(
5235            sync.await.unwrap(),
5236            Err(ScopeCallError::Protocol(_))
5237        ));
5238
5239        let describe = tokio::spawn({
5240            let handle = handle.clone();
5241            async move { handle.scope_describe(owner(), "s".to_string()).await }
5242        });
5243        let request = timeout(Duration::from_secs(1), rx.recv())
5244            .await
5245            .unwrap()
5246            .unwrap();
5247        let sync_body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeSync {
5248            generation: 1,
5249            results: Vec::new(),
5250            ended: Vec::new(),
5251        })
5252        .unwrap();
5253        assert!(handle.handle_control_reply(control_reply(
5254            FrameType::Response,
5255            request.header.corr,
5256            sync_body
5257        )));
5258        assert!(matches!(
5259            describe.await.unwrap(),
5260            Err(ScopeCallError::Protocol(_))
5261        ));
5262    }
5263
5264    /// Every Error-frame code reaches the caller as sent, including codes the
5265    /// reply handling shared with `catalog_update` sorts into its own
5266    /// `CatalogUpdateError` variants (`not_registered`).
5267    #[tokio::test]
5268    async fn a_scope_error_frame_keeps_the_daemons_code_and_message() {
5269        let (handle, mut rx) = test_module_handle(&[SCOPE_SYNC_OP]);
5270        for code in [
5271            subc_protocol::error_codes::SCOPE_SYNC_STALE,
5272            subc_protocol::error_codes::SCOPE_SYNC_NOT_AUTHORITY,
5273            "not_registered",
5274        ] {
5275            let sync = tokio::spawn({
5276                let handle = handle.clone();
5277                async move { handle.scope_sync(1, Vec::new()).await }
5278            });
5279            let request = timeout(Duration::from_secs(1), rx.recv())
5280                .await
5281                .unwrap()
5282                .unwrap();
5283            let body = serde_json::to_vec(&ErrorBody::new(code, "why")).unwrap();
5284            assert!(handle.handle_control_reply(control_reply(
5285                FrameType::Error,
5286                request.header.corr,
5287                body
5288            )));
5289            let error = sync.await.unwrap().unwrap_err();
5290            assert_eq!(
5291                error,
5292                ScopeCallError::Refused {
5293                    code: code.to_string(),
5294                    message: "why".to_string()
5295                }
5296            );
5297            assert_eq!(error.code(), Some(code));
5298        }
5299    }
5300
5301    /// A route.bind whose scope stamp carries a field this SDK does not know
5302    /// (a newer daemon's attribute) must be refused on its own correlation id,
5303    /// and the module must keep serving: the next control request is answered.
5304    #[tokio::test]
5305    async fn an_undecodable_control_request_is_refused_and_the_module_keeps_serving() {
5306        let (tx, mut rx) = mpsc::channel(4);
5307        let handler = Arc::new(EchoHandler);
5308        let dispatcher = RequestDispatcher::new();
5309        let (module_handle, _unused_rx) = test_module_handle(&[]);
5310        // A well-formed bind from this SDK's own types, then one scope
5311        // attribute this SDK does not know, so that is the only defect.
5312        let mut body: serde_json::Value =
5313            serde_json::from_slice(&route_bind_frame(9, 1, 41).body).unwrap();
5314        body["scope"] = serde_json::json!({
5315            "owner": { "kind": "reserved", "module_id": "prefrontal-core" },
5316            "ref": "s",
5317            "scope_epoch": 1,
5318            "kind": "head",
5319            "attributes": { "a_field_from_a_newer_daemon": "x" },
5320            "owner_authorized": true
5321        });
5322        let body = serde_json::to_vec(&body).unwrap();
5323        let bind = Frame::build(FrameType::Request, control_flags(), 0, 0, 41, body).unwrap();
5324
5325        let kept_serving = handle_frame(
5326            bind,
5327            &tx,
5328            Arc::clone(&handler),
5329            dispatcher.clone(),
5330            module_handle.clone(),
5331        )
5332        .await
5333        .expect("an undecodable control request must not end the module");
5334        assert!(kept_serving);
5335        let refusal = timeout(Duration::from_secs(1), rx.recv())
5336            .await
5337            .unwrap()
5338            .unwrap();
5339        assert_eq!(refusal.header.ty, FrameType::Error);
5340        assert_eq!(refusal.header.corr, 41);
5341        let error: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
5342        assert_eq!(error.code, "invalid_request");
5343        // Prove the refusal is about the unknown attribute, not some other
5344        // defect in this fixture.
5345        assert!(
5346            error.message.contains("a_field_from_a_newer_daemon"),
5347            "{}",
5348            error.message
5349        );
5350
5351        assert!(
5352            handle_frame(health_request(42), &tx, handler, dispatcher, module_handle)
5353                .await
5354                .unwrap()
5355        );
5356        let health = timeout(Duration::from_secs(1), rx.recv())
5357            .await
5358            .unwrap()
5359            .unwrap();
5360        assert_eq!(health.header.ty, FrameType::Response);
5361        assert_eq!(health.header.corr, 42);
5362    }
5363
5364    #[tokio::test]
5365    async fn default_health_check_answers_ok() {
5366        let (tx, mut rx) = mpsc::channel(4);
5367        let handler = Arc::new(EchoHandler);
5368        let dispatcher = RequestDispatcher::new();
5369        let (module_handle, _unused_rx) = test_module_handle(&[]);
5370
5371        assert!(
5372            handle_frame(health_request(77), &tx, handler, dispatcher, module_handle)
5373                .await
5374                .unwrap()
5375        );
5376
5377        let response = timeout(Duration::from_secs(1), rx.recv())
5378            .await
5379            .unwrap()
5380            .unwrap();
5381        assert_eq!(response.header.ty, FrameType::Response);
5382        assert_eq!(response.header.channel, 0);
5383        assert_eq!(response.header.corr, 77);
5384
5385        // Assert the PROPERTIES that matter rather than byte-equality with
5386        // HealthReport::ok(). Comparing against the constructor made this test a
5387        // restatement of the implementation: it reddened on any change to the
5388        // default without saying which property had broken.
5389        let parsed = serde_json::from_slice::<ModuleControlResponse>(&response.body).unwrap();
5390        let ModuleControlResponse::HealthCheck { status, detail, .. } = parsed else {
5391            panic!("expected a health.check response");
5392        };
5393        // A module that never implemented health is not UNHEALTHY -- the daemon
5394        // must not escalate on it.
5395        assert_eq!(status, HealthStatus::Ok);
5396        // ...but the report must SAY that nobody measured, so an operator can
5397        // tell it from a real all-clear. Substring rather than exact text: the
5398        // wording is for humans and nothing parses it.
5399        assert!(
5400            detail
5401                .as_deref()
5402                .is_some_and(|d| d.contains("no health implementation")),
5403            "the inherited default must identify itself, got {detail:?}"
5404        );
5405    }
5406
5407    struct DispatchHarness {
5408        tx: mpsc::Sender<Frame>,
5409        rx: mpsc::Receiver<Frame>,
5410        handler: Arc<BlockingHandler>,
5411        dispatcher: RequestDispatcher,
5412        module_handle: ModuleHandle,
5413    }
5414
5415    impl DispatchHarness {
5416        fn new(report: HealthReport) -> Self {
5417            let (tx, rx) = mpsc::channel(HANDLER_TASK_CAPACITY + 4);
5418            let (module_handle, _unused_rx) = test_module_handle(&[]);
5419            module_handle
5420                .install_route(RouteHandle::new(7, 1, 1))
5421                .unwrap();
5422            Self {
5423                tx,
5424                rx,
5425                handler: Arc::new(BlockingHandler {
5426                    entered: Arc::new(AtomicUsize::new(0)),
5427                    release: Semaphore::new(0),
5428                    report,
5429                }),
5430                dispatcher: RequestDispatcher::new(),
5431                module_handle,
5432            }
5433        }
5434
5435        async fn request(&self, corr: u64) {
5436            handle_frame(
5437                data_request(7, corr),
5438                &self.tx,
5439                Arc::clone(&self.handler),
5440                self.dispatcher.clone(),
5441                self.module_handle.clone(),
5442            )
5443            .await
5444            .unwrap();
5445        }
5446
5447        async fn wait_for_entered(&self, count: usize) {
5448            timeout(Duration::from_secs(1), async {
5449                while self.handler.entered.load(Ordering::SeqCst) != count {
5450                    tokio::task::yield_now().await;
5451                }
5452            })
5453            .await
5454            .expect("data handlers should acquire the available slots");
5455        }
5456
5457        async fn saturate(&self) {
5458            for corr in 1..=HANDLER_TASK_CAPACITY as u64 {
5459                self.request(corr).await;
5460            }
5461            self.wait_for_entered(HANDLER_TASK_CAPACITY).await;
5462            self.request(HANDLER_TASK_CAPACITY as u64 + 1).await;
5463            tokio::task::yield_now().await;
5464            assert_eq!(self.dispatcher.pools.default.permits.available_permits(), 0);
5465            assert_eq!(
5466                self.dispatcher.pools.default.waiting.lock().unwrap().len(),
5467                1
5468            );
5469            assert_eq!(
5470                self.handler.entered.load(Ordering::SeqCst),
5471                HANDLER_TASK_CAPACITY
5472            );
5473        }
5474
5475        async fn health(&mut self, corr: u64) -> HealthReport {
5476            handle_frame(
5477                health_request(corr),
5478                &self.tx,
5479                Arc::clone(&self.handler),
5480                self.dispatcher.clone(),
5481                self.module_handle.clone(),
5482            )
5483            .await
5484            .unwrap();
5485            let frame = timeout(Duration::from_millis(100), self.rx.recv())
5486                .await
5487                .expect("health.check must answer within 100 ms while data slots are busy")
5488                .unwrap();
5489            assert_eq!(frame.header.ty, FrameType::Response);
5490            assert_eq!(frame.header.channel, 0);
5491            assert_eq!(frame.header.corr, corr);
5492            serde_json::from_slice::<ModuleControlResponse>(&frame.body)
5493                .unwrap()
5494                .health_report()
5495                .unwrap()
5496        }
5497
5498        async fn release(&mut self, count: usize) {
5499            self.handler.release.add_permits(count);
5500            for _ in 0..count {
5501                let frame = timeout(Duration::from_secs(1), self.rx.recv())
5502                    .await
5503                    .unwrap()
5504                    .unwrap();
5505                assert_eq!(frame.header.ty, FrameType::StreamEnd);
5506                assert_eq!(frame.header.channel, 7);
5507            }
5508            assert!(self
5509                .dispatcher
5510                .pools
5511                .default
5512                .waiting
5513                .lock()
5514                .unwrap()
5515                .is_empty());
5516            assert!(self.dispatcher.in_flight.lock().unwrap().is_empty());
5517            assert_eq!(
5518                self.dispatcher.pools.default.permits.available_permits(),
5519                HANDLER_TASK_CAPACITY
5520            );
5521        }
5522    }
5523
5524    #[tokio::test(start_paused = true)]
5525    async fn health_check_answers_degraded_under_saturation_and_recovers() {
5526        let own_report = HealthReport {
5527            status: HealthStatus::Ok,
5528            detail: Some("module gauges healthy".to_string()),
5529            metrics: Some(json!({"transforms": 64})),
5530        };
5531        let mut harness = DispatchHarness::new(own_report.clone());
5532        harness.saturate().await;
5533        // A brief burst is not dispatch impairment, even with no slot free.
5534        assert_eq!(harness.health(899).await, own_report);
5535        // Advance the real dispatch stamp's monotonic clock, not a test-only
5536        // health gauge. Keeping handlers blocked proves the transport isolation.
5537        advance(Duration::from_millis(7300)).await;
5538        let report = harness.health(900).await;
5539        assert_eq!(report.status, HealthStatus::Degraded);
5540        assert_eq!(report.metrics, own_report.metrics);
5541        assert_eq!(
5542            report.detail.as_deref(),
5543            Some("request dispatch saturated: 64/64 in use, oldest waiting 7.3 s; module gauges healthy")
5544        );
5545
5546        harness.release(HANDLER_TASK_CAPACITY + 1).await;
5547        assert_eq!(harness.health(901).await, own_report);
5548    }
5549
5550    #[tokio::test(start_paused = true)]
5551    async fn health_check_preserves_failing_under_saturation() {
5552        let mut harness = DispatchHarness::new(HealthReport {
5553            status: HealthStatus::Failing,
5554            detail: Some("module dispatch heartbeat stale".to_string()),
5555            metrics: Some(json!({"heartbeat_age_s": 12})),
5556        });
5557        harness.saturate().await;
5558        advance(Duration::from_millis(7300)).await;
5559        let report = harness.health(900).await;
5560        assert_eq!(report.status, HealthStatus::Failing);
5561        assert_eq!(report.metrics, Some(json!({"heartbeat_age_s": 12})));
5562        assert_eq!(
5563            report.detail.as_deref(),
5564            Some("request dispatch saturated: 64/64 in use, oldest waiting 7.3 s; module dispatch heartbeat stale")
5565        );
5566        harness.release(HANDLER_TASK_CAPACITY + 1).await;
5567    }
5568
5569    #[tokio::test(start_paused = true)]
5570    async fn health_check_passes_module_report_through_with_free_permits() {
5571        for status in [
5572            HealthStatus::Ok,
5573            HealthStatus::Degraded,
5574            HealthStatus::Failing,
5575        ] {
5576            let own_report = HealthReport {
5577                status,
5578                detail: Some("module's own assessment".to_string()),
5579                metrics: Some(json!({"gauge": 42})),
5580            };
5581            let mut harness = DispatchHarness::new(own_report.clone());
5582            harness.request(1).await;
5583            harness.wait_for_entered(1).await;
5584            advance(Duration::from_millis(7300)).await;
5585            assert_eq!(harness.health(900).await, own_report);
5586            harness.release(1).await;
5587        }
5588    }
5589
5590    struct CorrBlockingHandler {
5591        entered: Arc<Mutex<Vec<u64>>>,
5592        release_first: Arc<Semaphore>,
5593    }
5594
5595    #[async_trait]
5596    impl ModuleHandler for CorrBlockingHandler {
5597        async fn handle(&self, ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5598            let corr = ctx.corr();
5599            self.entered.lock().unwrap().push(corr);
5600            if corr == 1 {
5601                self.release_first.acquire().await.unwrap().forget();
5602            }
5603            HandlerOutcome::Response(Vec::new())
5604        }
5605    }
5606
5607    /// A request cancelled while it waits for a handler slot is answered
5608    /// `cancelled` at once: it does not wait for a slot to free just to say
5609    /// so, it never takes one, and its handler never runs.
5610    #[tokio::test]
5611    async fn cancelled_capacity_queued_data_request_is_answered_without_waiting_for_a_slot() {
5612        let (tx, mut rx) = mpsc::channel(4);
5613        let entered = Arc::new(Mutex::new(Vec::new()));
5614        let release_first = Arc::new(Semaphore::new(0));
5615        let handler = Arc::new(CorrBlockingHandler {
5616            entered: Arc::clone(&entered),
5617            release_first: Arc::clone(&release_first),
5618        });
5619        let dispatcher = RequestDispatcher::with_pools(Arc::new(
5620            DispatchPools::with_default_limit(1, RequestPools::new()),
5621        ));
5622        let (module_handle, _unused_rx) = test_module_handle(&[]);
5623        module_handle
5624            .install_route(RouteHandle::new(7, 1, 1))
5625            .unwrap();
5626
5627        handle_frame(
5628            data_request(7, 1),
5629            &tx,
5630            Arc::clone(&handler),
5631            dispatcher.clone(),
5632            module_handle.clone(),
5633        )
5634        .await
5635        .unwrap();
5636        timeout(Duration::from_secs(1), async {
5637            while entered.lock().unwrap().as_slice() != [1] {
5638                tokio::task::yield_now().await;
5639            }
5640        })
5641        .await
5642        .unwrap();
5643
5644        handle_frame(
5645            data_request(7, 2),
5646            &tx,
5647            Arc::clone(&handler),
5648            dispatcher.clone(),
5649            module_handle.clone(),
5650        )
5651        .await
5652        .unwrap();
5653        timeout(Duration::from_secs(1), async {
5654            while !dispatcher
5655                .in_flight
5656                .lock()
5657                .unwrap()
5658                .contains_key(&(7, 1, 2))
5659            {
5660                tokio::task::yield_now().await;
5661            }
5662        })
5663        .await
5664        .unwrap();
5665        handle_frame(
5666            Frame::build(FrameType::Cancel, data_flags(), 7, 1, 2, Vec::new()).unwrap(),
5667            &tx,
5668            Arc::clone(&handler),
5669            dispatcher.clone(),
5670            module_handle,
5671        )
5672        .await
5673        .unwrap();
5674        assert!(
5675            dispatcher
5676                .in_flight
5677                .lock()
5678                .unwrap()
5679                .get(&(7, 1, 2))
5680                .unwrap()
5681                .is_cancelled(),
5682            "cancel must land while the second request waits for handler capacity"
5683        );
5684
5685        // The first request still holds the only slot, so the answer below
5686        // cannot have come from a slot freeing.
5687        let cancelled = timeout(Duration::from_secs(1), rx.recv())
5688            .await
5689            .expect("a request cancelled while waiting must be answered without waiting for a slot")
5690            .unwrap();
5691        assert_eq!(cancelled.header.ty, FrameType::Error);
5692        assert_eq!(cancelled.header.channel, 7);
5693        assert_eq!(cancelled.header.epoch, 1);
5694        assert_eq!(cancelled.header.corr, 2);
5695        assert_eq!(
5696            serde_json::from_slice::<ErrorBody>(&cancelled.body).unwrap(),
5697            ErrorBody {
5698                code: "cancelled".to_string(),
5699                message: "request cancelled".to_string(),
5700                detail: None,
5701            }
5702        );
5703        timeout(Duration::from_secs(1), async {
5704            while dispatcher
5705                .in_flight
5706                .lock()
5707                .unwrap()
5708                .contains_key(&(7, 1, 2))
5709            {
5710                tokio::task::yield_now().await;
5711            }
5712        })
5713        .await
5714        .unwrap();
5715        assert_eq!(dispatcher.pools.default.permits.available_permits(), 0);
5716        assert!(dispatcher.pools.default.waiting.lock().unwrap().is_empty());
5717        assert_eq!(*entered.lock().unwrap(), vec![1]);
5718
5719        release_first.add_permits(1);
5720        let response = timeout(Duration::from_secs(1), rx.recv())
5721            .await
5722            .unwrap()
5723            .unwrap();
5724        assert_eq!(response.header.ty, FrameType::Response);
5725        assert_eq!(response.header.corr, 1);
5726        timeout(Duration::from_secs(1), async {
5727            while !dispatcher.in_flight.lock().unwrap().is_empty() {
5728                tokio::task::yield_now().await;
5729            }
5730        })
5731        .await
5732        .unwrap();
5733        assert_eq!(*entered.lock().unwrap(), vec![1]);
5734        assert_eq!(dispatcher.pools.default.permits.available_permits(), 1);
5735        assert!(timeout(Duration::from_millis(50), rx.recv()).await.is_err());
5736    }
5737
5738    #[tokio::test]
5739    async fn cancelled_terminal_is_not_sent_after_route_teardown() {
5740        let (tx, mut rx) = mpsc::channel(1);
5741        let (module_handle, _unused_rx) = test_module_handle(&[]);
5742        let handle = RouteHandle::new(7, 1, 1);
5743        module_handle.install_route(handle).unwrap();
5744        let ctx = RequestCtx {
5745            handle,
5746            corr: 2,
5747            ver: PROTOCOL_VERSION,
5748            egress: tx,
5749            module_handle: module_handle.clone(),
5750            cancelled: CancellationToken::new(),
5751            binary_reply: Arc::new(AtomicBool::new(false)),
5752            request_flags: Flags::new(false, Priority::Interactive, false),
5753            request_body: Arc::from([]),
5754        };
5755        assert!(module_handle.remove_route(handle).unwrap());
5756
5757        let result = send_handler_outcome(
5758            &ctx,
5759            HandlerOutcome::Error {
5760                code: "cancelled".to_string(),
5761                message: "request cancelled".to_string(),
5762            },
5763        )
5764        .await;
5765
5766        assert!(matches!(
5767            result,
5768            Err(SubcModuleError::StaleRouteHandle(stale)) if stale == handle
5769        ));
5770        assert!(rx.try_recv().is_err());
5771    }
5772
5773    struct CountingHandler {
5774        calls: Arc<AtomicUsize>,
5775    }
5776
5777    #[async_trait]
5778    impl ModuleHandler for CountingHandler {
5779        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5780            self.calls.fetch_add(1, Ordering::SeqCst);
5781            HandlerOutcome::Response(Vec::new())
5782        }
5783    }
5784
5785    #[tokio::test]
5786    async fn endpoint_validation_drops_stale_request_before_handler_dispatch() {
5787        let (tx, mut rx) = mpsc::channel(4);
5788        let calls = Arc::new(AtomicUsize::new(0));
5789        let handler = Arc::new(CountingHandler {
5790            calls: Arc::clone(&calls),
5791        });
5792        let dispatcher = RequestDispatcher::new();
5793        let (module_handle, _unused_rx) = test_module_handle(&[]);
5794        module_handle
5795            .install_route(RouteHandle::new(7, 2, 1))
5796            .unwrap();
5797        let stale = Frame::build(FrameType::Request, data_flags(), 7, 1, 55, Vec::new()).unwrap();
5798
5799        assert!(
5800            handle_frame(stale, &tx, handler, dispatcher, module_handle.clone())
5801                .await
5802                .unwrap()
5803        );
5804        tokio::task::yield_now().await;
5805        assert_eq!(calls.load(Ordering::SeqCst), 0);
5806        assert_eq!(module_handle.dropped_route_frames(), 1);
5807        assert!(rx.try_recv().is_err());
5808    }
5809
5810    struct BindOrderingHandler {
5811        module_handle: ModuleHandle,
5812        bind_emit_rejected: Arc<AtomicUsize>,
5813        bound: Arc<AtomicUsize>,
5814        cleanup: Arc<AtomicUsize>,
5815    }
5816
5817    #[async_trait]
5818    impl ModuleHandler for BindOrderingHandler {
5819        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5820            HandlerOutcome::Response(Vec::new())
5821        }
5822
5823        async fn on_bind(&self, req: &RouteBindRequest) -> BindDecision {
5824            if matches!(
5825                self.module_handle
5826                    .push(&req.handle, b"too-early".to_vec(), None)
5827                    .await,
5828                Err(SubcModuleError::StaleRouteHandle(_))
5829            ) {
5830                self.bind_emit_rejected.fetch_add(1, Ordering::SeqCst);
5831            }
5832            BindDecision::accept()
5833        }
5834
5835        async fn on_bound(&self, handle: &RouteHandle) {
5836            self.bound.fetch_add(1, Ordering::SeqCst);
5837            self.module_handle
5838                .push(handle, b"bound".to_vec(), Some(AdmissionClass::Expedite))
5839                .await
5840                .unwrap();
5841        }
5842
5843        async fn on_route_gone(&self, _handle: &RouteHandle) {
5844            self.cleanup.fetch_add(1, Ordering::SeqCst);
5845        }
5846    }
5847
5848    fn route_bind_frame(channel: u16, epoch: u32, corr: u64) -> Frame {
5849        let body = serde_json::to_vec(&ModuleControlRequest::RouteBind {
5850            route_channel: channel,
5851            epoch,
5852            target: RouteTarget::ToolProvider {
5853                module_id: "provider".to_string(),
5854            },
5855            identity: BindIdentity::new("test".to_string(), "bind".to_string()),
5856            principal: None,
5857            consumer_capabilities: None,
5858            role_versions: None,
5859            admission_facts: None,
5860            scope: None,
5861            call_mode: None,
5862        })
5863        .unwrap();
5864        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
5865    }
5866
5867    #[tokio::test]
5868    async fn on_bound_runs_only_after_ack_queue_and_handle_install() {
5869        let (module_handle, mut rx) = test_module_handle(&[]);
5870        let tx = module_handle.shared.lock_inner().writer.clone().unwrap();
5871        let bind_emit_rejected = Arc::new(AtomicUsize::new(0));
5872        let bound = Arc::new(AtomicUsize::new(0));
5873        let cleanup = Arc::new(AtomicUsize::new(0));
5874        let handler = Arc::new(BindOrderingHandler {
5875            module_handle: module_handle.clone(),
5876            bind_emit_rejected: Arc::clone(&bind_emit_rejected),
5877            bound: Arc::clone(&bound),
5878            cleanup: Arc::clone(&cleanup),
5879        });
5880
5881        assert!(handle_frame(
5882            route_bind_frame(8, 4, 90),
5883            &tx,
5884            handler,
5885            RequestDispatcher::new(),
5886            module_handle.clone(),
5887        )
5888        .await
5889        .unwrap());
5890        assert_eq!(bind_emit_rejected.load(Ordering::SeqCst), 1);
5891        assert_eq!(bound.load(Ordering::SeqCst), 1);
5892        assert_eq!(cleanup.load(Ordering::SeqCst), 0);
5893
5894        let ack = rx.recv().await.unwrap();
5895        let push = rx.recv().await.unwrap();
5896        assert_eq!(ack.header.ty, FrameType::Response);
5897        assert_eq!(ack.header.channel, 0);
5898        assert_eq!(push.header.ty, FrameType::Push);
5899        assert_eq!((push.header.channel, push.header.epoch), (8, 4));
5900        assert_eq!(
5901            push.header.flags.admission_class(),
5902            Some(AdmissionClass::Expedite)
5903        );
5904
5905        let captured = RouteHandle::new(8, 4, 1);
5906        assert!(module_handle.remove_route(captured).unwrap());
5907        let stale = module_handle
5908            .push(&captured, Vec::new(), None)
5909            .await
5910            .unwrap_err();
5911        assert!(matches!(stale, SubcModuleError::StaleRouteHandle(_)));
5912        assert!(rx.try_recv().is_err());
5913    }
5914
5915    struct RejectingHandler {
5916        bound: Arc<AtomicUsize>,
5917        cleanup: Arc<AtomicUsize>,
5918    }
5919
5920    #[async_trait]
5921    impl ModuleHandler for RejectingHandler {
5922        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5923            HandlerOutcome::Response(Vec::new())
5924        }
5925
5926        async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
5927            BindDecision::reject("no", "rejected")
5928        }
5929
5930        async fn on_bound(&self, _handle: &RouteHandle) {
5931            self.bound.fetch_add(1, Ordering::SeqCst);
5932        }
5933
5934        async fn on_route_gone(&self, _handle: &RouteHandle) {
5935            self.cleanup.fetch_add(1, Ordering::SeqCst);
5936        }
5937    }
5938
5939    #[tokio::test]
5940    async fn rejected_bind_cleans_up_without_installing_or_calling_on_bound() {
5941        let (module_handle, mut rx) = test_module_handle(&[]);
5942        let tx = module_handle.shared.lock_inner().writer.clone().unwrap();
5943        let bound = Arc::new(AtomicUsize::new(0));
5944        let cleanup = Arc::new(AtomicUsize::new(0));
5945        let handler = Arc::new(RejectingHandler {
5946            bound: Arc::clone(&bound),
5947            cleanup: Arc::clone(&cleanup),
5948        });
5949        handle_frame(
5950            route_bind_frame(6, 3, 91),
5951            &tx,
5952            handler,
5953            RequestDispatcher::new(),
5954            module_handle.clone(),
5955        )
5956        .await
5957        .unwrap();
5958        let refusal = rx.recv().await.unwrap();
5959        assert_eq!(refusal.header.ty, FrameType::Error);
5960        // A plain rejection keeps its detail-free bytes.
5961        assert_eq!(refusal.body, br#"{"code":"no","message":"rejected"}"#);
5962        assert_eq!(bound.load(Ordering::SeqCst), 0);
5963        assert_eq!(cleanup.load(Ordering::SeqCst), 1);
5964        assert!(matches!(
5965            module_handle.validate_route(RouteHandle::new(6, 3, 1)),
5966            Err(SubcModuleError::StaleRouteHandle(_))
5967        ));
5968    }
5969
5970    struct BusyHandler;
5971
5972    #[async_trait]
5973    impl ModuleHandler for BusyHandler {
5974        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5975            HandlerOutcome::Response(Vec::new())
5976        }
5977
5978        async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
5979            BindDecision::reject_with_detail(
5980                "bind_busy",
5981                "a read is still running on this root",
5982                serde_json::json!({"reason": "reader", "retry_after_ms": 2000}),
5983            )
5984        }
5985    }
5986
5987    #[tokio::test]
5988    async fn rejected_bind_carries_its_detail_to_the_daemon() {
5989        let (module_handle, mut rx) = test_module_handle(&[]);
5990        let tx = module_handle.shared.lock_inner().writer.clone().unwrap();
5991        handle_frame(
5992            route_bind_frame(6, 3, 92),
5993            &tx,
5994            Arc::new(BusyHandler),
5995            RequestDispatcher::new(),
5996            module_handle.clone(),
5997        )
5998        .await
5999        .unwrap();
6000        let refusal = rx.recv().await.unwrap();
6001        assert_eq!(refusal.header.ty, FrameType::Error);
6002        let body: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
6003        assert_eq!(body.code, "bind_busy");
6004        assert_eq!(
6005            body.detail,
6006            Some(serde_json::json!({"reason": "reader", "retry_after_ms": 2000}))
6007        );
6008    }
6009
6010    struct RebindCountingHandler {
6011        bound: Arc<AtomicUsize>,
6012        cleanup: Arc<AtomicUsize>,
6013    }
6014
6015    #[async_trait]
6016    impl ModuleHandler for RebindCountingHandler {
6017        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6018            HandlerOutcome::Response(Vec::new())
6019        }
6020
6021        async fn on_bound(&self, _handle: &RouteHandle) {
6022            self.bound.fetch_add(1, Ordering::SeqCst);
6023        }
6024
6025        async fn on_route_gone(&self, _handle: &RouteHandle) {
6026            self.cleanup.fetch_add(1, Ordering::SeqCst);
6027        }
6028    }
6029
6030    // Wire spec 3.3.0: a bind on an installed channel with a strictly higher epoch
6031    // replaces the stale install (the daemon freed that binding; its route-gone
6032    // GOODBYE is best-effort and can be dropped), firing the replaced install's
6033    // route-gone teardown. Equal-or-lower epoch is a protocol violation: rejected,
6034    // installed route untouched.
6035    #[tokio::test]
6036    async fn rebind_on_installed_channel_replaces_on_higher_epoch_only() {
6037        let (module_handle, mut rx) = test_module_handle(&[]);
6038        let tx = module_handle.shared.lock_inner().writer.clone().unwrap();
6039        let bound = Arc::new(AtomicUsize::new(0));
6040        let cleanup = Arc::new(AtomicUsize::new(0));
6041        let handler = Arc::new(RebindCountingHandler {
6042            bound: Arc::clone(&bound),
6043            cleanup: Arc::clone(&cleanup),
6044        });
6045
6046        // Install epoch 4 on channel 8.
6047        handle_frame(
6048            route_bind_frame(8, 4, 90),
6049            &tx,
6050            Arc::clone(&handler),
6051            RequestDispatcher::new(),
6052            module_handle.clone(),
6053        )
6054        .await
6055        .unwrap();
6056        assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Response);
6057        assert_eq!(
6058            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6059            (1, 0)
6060        );
6061
6062        // Same epoch: rejected, install untouched, no teardown fired.
6063        handle_frame(
6064            route_bind_frame(8, 4, 91),
6065            &tx,
6066            Arc::clone(&handler),
6067            RequestDispatcher::new(),
6068            module_handle.clone(),
6069        )
6070        .await
6071        .unwrap();
6072        let reject = rx.recv().await.unwrap();
6073        assert_eq!(reject.header.ty, FrameType::Error);
6074        assert_eq!(
6075            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6076            (1, 0)
6077        );
6078        module_handle
6079            .validate_route(RouteHandle::new(8, 4, 1))
6080            .expect("epoch-4 install must survive the rejected rebind");
6081
6082        // Lower epoch: same rejection shape.
6083        handle_frame(
6084            route_bind_frame(8, 3, 92),
6085            &tx,
6086            Arc::clone(&handler),
6087            RequestDispatcher::new(),
6088            module_handle.clone(),
6089        )
6090        .await
6091        .unwrap();
6092        assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Error);
6093        assert_eq!(
6094            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6095            (1, 0)
6096        );
6097
6098        // Strictly higher epoch: implicit replace — stale install torn down
6099        // (route-gone fired exactly once), new epoch installed and bound.
6100        handle_frame(
6101            route_bind_frame(8, 5, 93),
6102            &tx,
6103            Arc::clone(&handler),
6104            RequestDispatcher::new(),
6105            module_handle.clone(),
6106        )
6107        .await
6108        .unwrap();
6109        assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Response);
6110        assert_eq!(
6111            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6112            (2, 1)
6113        );
6114        assert!(matches!(
6115            module_handle.validate_route(RouteHandle::new(8, 4, 1)),
6116            Err(SubcModuleError::StaleRouteHandle(_))
6117        ));
6118        module_handle
6119            .validate_route(RouteHandle::new(8, 5, 1))
6120            .expect("epoch-5 install must be live after implicit replace");
6121    }
6122
6123    #[tokio::test]
6124    async fn module_control_corr_is_monotonic_and_exhausts_without_wrap() {
6125        let (module_handle, _rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
6126        let mut inner = module_handle.shared.lock_inner();
6127        inner.next_corr = Some(u64::MAX);
6128        assert_eq!(next_module_control_corr(&mut inner), Some(u64::MAX));
6129        assert_eq!(next_module_control_corr(&mut inner), None);
6130    }
6131}
6132
6133/// How a served module ends when its connection closes, driven against a stand-in
6134/// daemon on a framed in-memory connection with the real writer task and drain.
6135#[cfg(test)]
6136mod module_close_tests {
6137    use std::time::Instant;
6138
6139    use tokio::{io::DuplexStream, sync::Notify};
6140
6141    use super::stand_in::{serve_against_stand_in_with_ops, Served};
6142    use super::*;
6143
6144    /// How the test handler treats the one request it is given.
6145    #[derive(Clone, Copy)]
6146    enum Hold {
6147        /// Hold the request open until it is cancelled, then answer.
6148        UntilCancelled,
6149        /// Hold the request open forever, whatever happens.
6150        IgnoringCancellation,
6151    }
6152
6153    struct HoldingHandler {
6154        hold: Hold,
6155        entered: Arc<Notify>,
6156        token: Arc<Mutex<Option<CancellationToken>>>,
6157    }
6158
6159    #[async_trait]
6160    impl ModuleHandler for HoldingHandler {
6161        async fn handle(&self, ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6162            *self.token.lock().unwrap() = Some(ctx.cancellation_token());
6163            self.entered.notify_one();
6164            match self.hold {
6165                Hold::UntilCancelled => {
6166                    ctx.cancelled().await;
6167                    HandlerOutcome::Error {
6168                        code: "cancelled".to_string(),
6169                        message: "request cancelled".to_string(),
6170                    }
6171                }
6172                Hold::IgnoringCancellation => std::future::pending().await,
6173            }
6174        }
6175    }
6176
6177    /// Serve `handler` on the shared stand-in and hand its framed connection to the test.
6178    async fn serve_against_stand_in<H: ModuleHandler>(handler: H) -> Served {
6179        serve_against_stand_in_with_ops(|_| handler, &[]).await
6180    }
6181
6182    async fn send(daemon: &mut DuplexStream, frame: Frame) {
6183        write_frame(daemon, &frame).await.unwrap();
6184        daemon.flush().await.unwrap();
6185    }
6186
6187    /// Bind route 7/1 and send one data request on it, returning once the
6188    /// handler holds it.
6189    async fn hold_one_request(served: &mut Served, entered: &Notify) {
6190        let bind = serde_json::to_vec(&ModuleControlRequest::RouteBind {
6191            route_channel: 7,
6192            epoch: 1,
6193            target: RouteTarget::ToolProvider {
6194                module_id: "close-test".to_string(),
6195            },
6196            identity: BindIdentity::new("test".to_string(), "close".to_string()),
6197            principal: None,
6198            consumer_capabilities: None,
6199            role_versions: None,
6200            admission_facts: None,
6201            scope: None,
6202            call_mode: None,
6203        })
6204        .unwrap();
6205        send(
6206            &mut served.daemon,
6207            Frame::build(FrameType::Request, control_flags(), 0, 0, 2, bind).unwrap(),
6208        )
6209        .await;
6210        loop {
6211            let frame = read_frame(&mut served.daemon).await.unwrap().unwrap();
6212            if frame.header.channel == 0 && frame.header.corr == 2 {
6213                assert_eq!(
6214                    frame.header.ty,
6215                    FrameType::Response,
6216                    "route.bind must be acked"
6217                );
6218                break;
6219            }
6220        }
6221        send(
6222            &mut served.daemon,
6223            Frame::build(FrameType::Request, data_flags(), 7, 1, 10, b"hold".to_vec()).unwrap(),
6224        )
6225        .await;
6226        timeout(Duration::from_secs(2), entered.notified())
6227            .await
6228            .expect("the handler must receive the request");
6229    }
6230
6231    fn goodbye() -> Frame {
6232        Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 0, Vec::new()).unwrap()
6233    }
6234
6235    fn holding(
6236        hold: Hold,
6237    ) -> (
6238        HoldingHandler,
6239        Arc<Notify>,
6240        Arc<Mutex<Option<CancellationToken>>>,
6241    ) {
6242        let entered = Arc::new(Notify::new());
6243        let token = Arc::new(Mutex::new(None));
6244        let handler = HoldingHandler {
6245            hold,
6246            entered: Arc::clone(&entered),
6247            token: Arc::clone(&token),
6248        };
6249        (handler, entered, token)
6250    }
6251
6252    #[tokio::test]
6253    async fn goodbye_cancels_an_open_request_and_the_serve_future_completes() {
6254        let (handler, entered, token) = holding(Hold::UntilCancelled);
6255        let mut served = serve_against_stand_in(handler).await;
6256        hold_one_request(&mut served, &entered).await;
6257
6258        let started = Instant::now();
6259        send(&mut served.daemon, goodbye()).await;
6260        let result = timeout(Duration::from_secs(5), &mut served.serve)
6261            .await
6262            .expect("a held request must not keep the serve future alive after GOODBYE");
6263        result.unwrap().unwrap();
6264        assert!(
6265            token.lock().unwrap().as_ref().unwrap().is_cancelled(),
6266            "GOODBYE must cancel the request's token"
6267        );
6268        // Well inside the writer's drain limit: the handler answered its
6269        // cancellation, so nothing had to be aborted.
6270        assert!(
6271            started.elapsed() < DEFAULT_WRITER_DRAIN_TIMEOUT,
6272            "closing took {:?}",
6273            started.elapsed()
6274        );
6275    }
6276
6277    #[tokio::test]
6278    async fn a_handler_ignoring_cancellation_cannot_keep_the_serve_future_alive() {
6279        let (handler, entered, _token) = holding(Hold::IgnoringCancellation);
6280        let mut served = serve_against_stand_in(handler).await;
6281        hold_one_request(&mut served, &entered).await;
6282
6283        let started = Instant::now();
6284        send(&mut served.daemon, goodbye()).await;
6285        let result = timeout(
6286            DEFAULT_WRITER_DRAIN_TIMEOUT + Duration::from_secs(3),
6287            &mut served.serve,
6288        )
6289        .await
6290        .expect("the writer drain must be bounded");
6291        result.unwrap().unwrap();
6292        assert!(started.elapsed() >= DEFAULT_WRITER_DRAIN_TIMEOUT);
6293    }
6294
6295    #[tokio::test]
6296    async fn closed_resolves_after_goodbye() {
6297        let served = serve_against_stand_in(EchoHandler).await;
6298        let mut served = served;
6299        assert!(!served.handle.is_closed());
6300        let closed = served.handle.closed();
6301        send(&mut served.daemon, goodbye()).await;
6302        timeout(Duration::from_secs(2), closed)
6303            .await
6304            .expect("closed() must resolve after GOODBYE");
6305        assert!(served.handle.is_closed());
6306    }
6307
6308    #[tokio::test]
6309    async fn closed_resolves_after_eof() {
6310        let Served {
6311            daemon,
6312            handle,
6313            serve: _serve,
6314        } = serve_against_stand_in(EchoHandler).await;
6315        assert!(!handle.is_closed());
6316        drop(daemon);
6317        timeout(Duration::from_secs(2), handle.closed())
6318            .await
6319            .expect("closed() must resolve after EOF");
6320        assert!(handle.is_closed());
6321    }
6322
6323    struct EchoHandler;
6324
6325    #[async_trait]
6326    impl ModuleHandler for EchoHandler {
6327        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6328            HandlerOutcome::Response(body)
6329        }
6330    }
6331
6332    /// Records every `on_connection_end` call, so a test can assert both the
6333    /// cause and that it was reported exactly once.
6334    #[derive(Clone, Default)]
6335    struct EndRecorder(Arc<Mutex<Vec<ConnectionEnd>>>);
6336
6337    #[async_trait]
6338    impl ModuleHandler for EndRecorder {
6339        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6340            HandlerOutcome::Response(body)
6341        }
6342        async fn on_connection_end(&self, end: ConnectionEnd) {
6343            self.0.lock().unwrap().push(end);
6344        }
6345    }
6346
6347    async fn reported_end(recorder: &EndRecorder, served: &mut Served) -> Vec<ConnectionEnd> {
6348        timeout(Duration::from_secs(5), &mut served.serve)
6349            .await
6350            .expect("serving must end")
6351            .unwrap()
6352            .unwrap();
6353        recorder.0.lock().unwrap().clone()
6354    }
6355
6356    #[tokio::test]
6357    async fn a_daemon_goodbye_is_reported_as_goodbye() {
6358        let recorder = EndRecorder::default();
6359        let mut served = serve_against_stand_in(recorder.clone()).await;
6360        send(&mut served.daemon, goodbye()).await;
6361        assert_eq!(
6362            reported_end(&recorder, &mut served).await,
6363            vec![ConnectionEnd::Goodbye]
6364        );
6365    }
6366
6367    #[tokio::test]
6368    async fn a_daemon_closing_without_goodbye_is_reported_as_eof() {
6369        let recorder = EndRecorder::default();
6370        let mut served = serve_against_stand_in(recorder.clone()).await;
6371        served.daemon.shutdown().await.unwrap();
6372        assert_eq!(
6373            reported_end(&recorder, &mut served).await,
6374            vec![ConnectionEnd::Eof]
6375        );
6376    }
6377
6378    /// What a drain-recording handler saw, in the order it saw it.
6379    #[derive(Debug, Clone, PartialEq)]
6380    enum Seen {
6381        Draining(RouteCloseReason, SystemTime),
6382        End(ConnectionEnd),
6383    }
6384
6385    /// Records drain notices and the connection end. With `park` set, the
6386    /// drain hook never returns after recording, to stand for a slow hook.
6387    #[derive(Clone, Default)]
6388    struct DrainRecorder {
6389        seen: Arc<Mutex<Vec<Seen>>>,
6390        park: bool,
6391    }
6392
6393    #[async_trait]
6394    impl ModuleHandler for DrainRecorder {
6395        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6396            HandlerOutcome::Response(body)
6397        }
6398        async fn on_draining(&self, reason: RouteCloseReason, deadline: SystemTime) {
6399            self.seen
6400                .lock()
6401                .unwrap()
6402                .push(Seen::Draining(reason, deadline));
6403            if self.park {
6404                std::future::pending::<()>().await;
6405            }
6406        }
6407        async fn on_connection_end(&self, end: ConnectionEnd) {
6408            self.seen.lock().unwrap().push(Seen::End(end));
6409        }
6410    }
6411
6412    fn control_push(body: &[u8]) -> Frame {
6413        Frame::build(FrameType::Push, control_flags(), 0, 0, 0, body.to_vec()).unwrap()
6414    }
6415
6416    fn draining_push(reason: subc_protocol::RouteCloseReason, deadline_ms: u64) -> Frame {
6417        control_push(
6418            &serde_json::to_vec(&ModuleControlCommand::Draining {
6419                reason,
6420                deadline_ms,
6421            })
6422            .unwrap(),
6423        )
6424    }
6425
6426    /// Send a channel-0 PING and require the PONG, proving the frame reader
6427    /// is still serving.
6428    async fn ping_is_answered(served: &mut Served, corr: u64) {
6429        send(
6430            &mut served.daemon,
6431            Frame::build(FrameType::Ping, control_flags(), 0, 0, corr, Vec::new()).unwrap(),
6432        )
6433        .await;
6434        let pong = timeout(Duration::from_secs(2), read_frame(&mut served.daemon))
6435            .await
6436            .expect("the module must answer PING")
6437            .unwrap()
6438            .expect("the module must not close the connection");
6439        assert_eq!(pong.header.ty, FrameType::Pong);
6440        assert_eq!(pong.header.corr, corr);
6441    }
6442
6443    /// The daemon sends `module.draining` and, once the drain settles, GOODBYE;
6444    /// with nothing to wait for, both can land in one read. The hook runs on its
6445    /// own task, and must still be called before the GOODBYE is acted on.
6446    #[tokio::test]
6447    async fn a_drain_notice_calls_on_draining_before_the_goodbye_that_follows_it() {
6448        let recorder = DrainRecorder::default();
6449        let mut served = serve_against_stand_in(recorder.clone()).await;
6450        // Any fixed value works; this one (2100-01-01T00:00:00Z) is far enough
6451        // ahead to be plainly a future deadline.
6452        let deadline_ms = 4_102_444_800_000;
6453        write_frame(
6454            &mut served.daemon,
6455            &draining_push(subc_protocol::RouteCloseReason::Restart, deadline_ms),
6456        )
6457        .await
6458        .unwrap();
6459        write_frame(&mut served.daemon, &goodbye()).await.unwrap();
6460        served.daemon.flush().await.unwrap();
6461
6462        timeout(Duration::from_secs(5), &mut served.serve)
6463            .await
6464            .expect("serving must end after GOODBYE")
6465            .unwrap()
6466            .unwrap();
6467        assert_eq!(
6468            *recorder.seen.lock().unwrap(),
6469            vec![
6470                Seen::Draining(
6471                    RouteCloseReason::Restart,
6472                    UNIX_EPOCH + Duration::from_millis(deadline_ms)
6473                ),
6474                Seen::End(ConnectionEnd::Goodbye),
6475            ]
6476        );
6477    }
6478
6479    /// A drain lasts until the daemon's deadline, and the daemon keeps pinging
6480    /// through it; a hook still busy must not stop the module answering.
6481    #[tokio::test]
6482    async fn a_drain_hook_that_never_returns_does_not_stop_the_frame_reader() {
6483        let recorder = DrainRecorder {
6484            park: true,
6485            ..DrainRecorder::default()
6486        };
6487        let mut served = serve_against_stand_in(recorder.clone()).await;
6488        send(
6489            &mut served.daemon,
6490            draining_push(subc_protocol::RouteCloseReason::Reload, 1),
6491        )
6492        .await;
6493        ping_is_answered(&mut served, 41).await;
6494        assert!(matches!(
6495            recorder.seen.lock().unwrap().as_slice(),
6496            [Seen::Draining(RouteCloseReason::Reload, _)]
6497        ));
6498
6499        send(&mut served.daemon, goodbye()).await;
6500        timeout(Duration::from_secs(5), &mut served.serve)
6501            .await
6502            .expect("a parked drain hook must not keep the serve future alive")
6503            .unwrap()
6504            .unwrap();
6505    }
6506
6507    /// A channel-0 push this SDK cannot decode (a newer daemon's command, or a
6508    /// malformed body) is ignored: no hook is called and the connection keeps
6509    /// serving.
6510    #[tokio::test]
6511    async fn an_undecodable_channel_zero_push_is_ignored_and_the_connection_stays_up() {
6512        let recorder = DrainRecorder::default();
6513        let mut served = serve_against_stand_in(recorder.clone()).await;
6514        send(
6515            &mut served.daemon,
6516            control_push(br#"{"op":"module.some_future_command","x":1}"#),
6517        )
6518        .await;
6519        send(&mut served.daemon, control_push(b"not json")).await;
6520        send(
6521            &mut served.daemon,
6522            control_push(br#"{"op":"module.draining","reason":"restart"}"#),
6523        )
6524        .await;
6525        ping_is_answered(&mut served, 42).await;
6526        assert!(!served.handle.is_closed());
6527        assert!(!served.serve.is_finished());
6528        assert!(recorder.seen.lock().unwrap().is_empty());
6529    }
6530
6531    #[tokio::test]
6532    async fn a_module_closing_its_own_connection_is_reported_as_closed() {
6533        let recorder = EndRecorder::default();
6534        let mut served = serve_against_stand_in(recorder.clone()).await;
6535        served.handle.close_connection();
6536        assert_eq!(
6537            reported_end(&recorder, &mut served).await,
6538            vec![ConnectionEnd::Closed]
6539        );
6540    }
6541}
6542
6543#[cfg(test)]
6544mod operator_confirm_tests;
6545
6546#[cfg(test)]
6547mod binary_reply_tests;
6548
6549#[cfg(test)]
6550mod serve_lifecycle_tests;
6551
6552#[cfg(test)]
6553mod request_pool_tests;
6554
6555#[cfg(test)]
6556mod detailed_error_body_tests {
6557    use serde_json::json;
6558
6559    use subc_protocol::ErrorBody;
6560
6561    /// The wire bytes a detail-carrying module error serializes to are pinned
6562    /// here because subc-mcp and route consumers parse them; the shape predates
6563    /// ErrorBody.detail and must not drift now that ErrorBody subsumes it.
6564    #[test]
6565    fn detailed_error_body_keeps_code_message_and_detail() {
6566        let body = ErrorBody::new("bad_request", "invalid envelope")
6567            .with_detail(json!({"reason": "missing_server"}));
6568
6569        assert_eq!(
6570            serde_json::to_value(body).unwrap(),
6571            json!({
6572                "code": "bad_request",
6573                "message": "invalid envelope",
6574                "detail": {"reason": "missing_server"},
6575            })
6576        );
6577    }
6578
6579    /// A detail-less body serializes byte-identically to the pre-detail wire:
6580    /// deserializing the old two-field shape and re-serializing adds nothing.
6581    #[test]
6582    fn detail_less_error_body_is_byte_identical_to_the_pre_detail_wire() {
6583        let old_wire = r#"{"code":"cancelled","message":"caller cancelled"}"#;
6584        let parsed: ErrorBody = serde_json::from_str(old_wire).unwrap();
6585        assert_eq!(parsed.detail, None);
6586        assert_eq!(serde_json::to_string(&parsed).unwrap(), old_wire);
6587    }
6588}
6589
6590// A reserved module may scrub its launch nonce before it opens a daemon
6591// connection. The retained copy exists only for encoding that module's HELLO.
6592static RETAINED_LAUNCH_NONCE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
6593
6594/// Retain a reserved module's launch nonce for its HELLO after the module has
6595/// scrubbed the nonce from the process environment.
6596pub fn retain_launch_nonce_for_hello(launch_nonce: String) -> Result<(), String> {
6597    RETAINED_LAUNCH_NONCE
6598        .set(launch_nonce)
6599        .map_err(|_| "launch nonce was already retained for this process".to_string())
6600}
6601
6602fn retained_launch_nonce() -> Option<String> {
6603    RETAINED_LAUNCH_NONCE.get().cloned()
6604}
6605
6606/// The cached launch-nonce source (`fd`, `pipe` or `env`), or `None` when no
6607/// nonce is available. The SDK records this in the registration message's
6608/// `manifest.provenance.launch_nonce_source`; the daemon stores that declaration
6609/// for `ck provenance` to display. A module constructing that record can use:
6610/// `.with_launch_nonce_source(subc_client_rs::launch_nonce_source())`.
6611pub fn launch_nonce_source() -> Option<LaunchNonceSource> {
6612    launch_nonce()
6613        .ok()
6614        .flatten()
6615        .map(|nonce| LaunchNonceSource::from_wire_name(nonce.source().as_str()))
6616}
6617
6618/// Fill in `launch_nonce_source` on a module's declared provenance, so
6619/// `ck provenance` can tell a module reading the pipe from one still reading
6620/// the environment variable. Only when the module declared provenance and left the field
6621/// unset. A registration channel supplies authority without sending a nonce,
6622/// but an unstamped launch may still supply a legacy nonce whose source is
6623/// diagnostic. Otherwise the nonce HELLO carries must be the one the accessor
6624/// read: a module-retained nonce may have come from somewhere else.
6625fn stamp_launch_nonce_source(manifest: &mut ModuleManifest, sent: Option<&str>) {
6626    let Some(provenance) = manifest.provenance.as_mut() else {
6627        return;
6628    };
6629    if provenance.launch_nonce_source.is_some() {
6630        return;
6631    }
6632    if let Ok(Some(nonce)) = launch_nonce() {
6633        // A re-export may send the owner's legacy nonce, but cannot claim the
6634        // launched module's nonce provenance.
6635        let launched = registration::is_launched_module(&manifest.module_id).unwrap_or(false);
6636        if launched && (registration::supervised() || sent == Some(nonce.value())) {
6637            provenance.launch_nonce_source =
6638                Some(LaunchNonceSource::from_wire_name(nonce.source().as_str()));
6639        }
6640    }
6641}
6642
6643#[cfg(test)]
6644mod checked_increment_tests {
6645    use super::checked_increment;
6646    use std::sync::atomic::{AtomicU64, Ordering};
6647
6648    #[test]
6649    fn returns_the_previous_value_and_stops_at_the_maximum() {
6650        let counter = AtomicU64::new(7);
6651        assert_eq!(checked_increment(&counter), Some(7));
6652        assert_eq!(counter.load(Ordering::Relaxed), 8);
6653
6654        let full = AtomicU64::new(u64::MAX);
6655        assert_eq!(checked_increment(&full), None);
6656        assert_eq!(
6657            full.load(Ordering::Relaxed),
6658            u64::MAX,
6659            "an exhausted counter is left unchanged"
6660        );
6661    }
6662}