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