Skip to main content

subc_daemon/
control.rs

1#[path = "control/list_diagnostics.rs"]
2pub(crate) mod list_diagnostics;
3mod route_open_refusal_log;
4
5use std::{
6    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
7    fmt,
8    net::SocketAddr,
9    path::{Path, PathBuf},
10    sync::{Arc, Mutex, RwLock},
11    time::{Duration, Instant as StdInstant},
12};
13
14use crate::scopes::admission::denied_capability;
15use serde::{Deserialize, Serialize};
16use subc_control::{
17    ops, CapabilityRequirementStatus, CatalogEntry, ClientControlPush, ClientControlRequest,
18    ClientControlResponse, ConsumerIdentity, DaemonBuildProvenance, DaemonObservedProcess,
19    ModuleDeclaredProvenance, ModuleProtocol, NotReadyReason, PendingReloadVerdict, PollKind,
20    ReloadPathAgreement, ReloadPathUnavailableReason, RouteCloseReason, SpawnCursor,
21    StderrCaptureState, StderrTail, StderrTailEntry, SupervisorDaemonProvenance, SupervisorEntry,
22    SupervisorHealthEntry, SupervisorModuleProvenance, SupervisorObservedProcess,
23    SupervisorRescanResult, SupervisorRoute, SupervisorRouteConsumer, SupervisorRouteModule,
24};
25use subc_protocol::{
26    call_mode::{derive_call_mode, CALL_MODES_CAPABILITY},
27    error_codes,
28    manifest::{
29        validate_hello_capability_grammar, validate_hello_confirm_operations,
30        validate_hello_display_name, validate_hello_event_declarations,
31        validate_hello_flow_operations, validate_hello_operation_deferral,
32        validate_hello_rich_ui_descriptor, validate_hello_role_declarations,
33        validate_hello_self_signal_declarations, validate_role_declarations_value,
34        CapabilityDeclarations, CapabilityNeed, Concurrency, ManifestProvenance, ModuleManifest,
35        ProviderRole,
36    },
37    peer::{
38        ObservedPeer, RouteBindPeer, OBSERVED_PEER_CAPABILITY, OPERATOR_APP_CAPABILITY,
39        PEER_BUILD_CAPABILITY,
40    },
41    provider_declarations::ProviderDeclarations,
42    scope::{
43        ScopeEnd, ScopeRecord, ScopeRecordOutcome, ScopeRecordResult, ScopeSelector,
44        CAP_ROUTE_ROLE_VERSIONS_V1, CAP_SCOPES_V1, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP,
45        SCOPE_SYNC_OP,
46    },
47    session::{
48        validate_role_versions, HealthReport, ModuleControlPush, ModuleControlRequest,
49        ModuleControlRequestFromModule, ModuleControlResponse, ModuleControlResponseToModule,
50        OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK, MODULE_TO_SUBC_OP_CATALOG_UPDATE,
51        MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS, ROLE_VERSIONS_FIELD,
52    },
53    BindIdentity, ErrorBody, Flags, FrameType, ModuleHelloAckBody, ModuleHelloBody, Principal,
54    Priority, RouteTarget, PROTOCOL_VERSION,
55};
56use tokio::time::{timeout_at, Instant};
57use tracing::{debug, info, instrument::WithSubscriber, warn};
58
59use crate::{
60    caller_identity::CallerIdentity,
61    capability_requirements::{
62        log_duplicate_claim_events, log_manifest_change, log_requirement_events,
63        CapabilityRequirementEvaluator, CapabilityVerdict, DuplicateClaimSource, RegisteredModule,
64        RequirementStatus, RuntimeModule,
65    },
66    child_roster::DaemonShutdownFlag,
67    daemon_config::{PrivilegedOperatorPrompt, RestartRequiredSection},
68    forwarding::{
69        CloseReason, EndpointRoute, ForwardingError, ForwardingTable, GoodbyeTarget,
70        ModuleControlRpcCompletion, ModuleControlRpcOutcome, ModuleEndpointId,
71        PendingModuleControlRpc, RouteBindRelayOutcome, RoutePollSnapshot, RouteRelease,
72    },
73    observability::{
74        ROUTE_OPEN_REFUSED_DECLARED_NOT_READY, ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED,
75    },
76    privileged_prompt::{prompt_text, PrivilegedOperation},
77    provenance::{
78        process_start_time, spawned_file_identity, ExecutableIdentityProbe, SpawnedFileIdentity,
79    },
80    registry::{ChannelState, ConnectionId, RegistrationEndReason, Registry, RegistryError},
81    router::{daemon_error_flags, RouteCtx, RouterError},
82    scopes::{HelloLaunchNonces, ScopeRecords, ScopeTable},
83    server::MAX_PENDING_ROUTE_BINDS_PER_TARGET,
84    stderr_tail::{CaptureState, TailEntry},
85    supervise::{
86        validate_spec, ModuleProcessLiveness, ReservedHelloRejection, ReservedHelloVerification,
87        SpawnSubscribeRefusal, SupervisorHandle, SwapHelloAdmission,
88    },
89    ConnectedClients, DaemonCounters, Frame, ProjectRootId, Supervisor,
90};
91
92/// Lowest envelope version this subc build will negotiate.
93///
94/// Module HELLO negotiation is exact: peers must use the daemon's locked
95/// protocol version. Older and newer peers receive `version_unsupported` and
96/// are not registered.
97pub const MIN_SUPPORTED_VERSION: u8 = PROTOCOL_VERSION;
98
99mod route_open;
100use route_open::is_routable_role;
101use route_open::principal_label;
102#[cfg(test)]
103use route_open::RouteBindAdmission;
104pub(crate) use route_open::RouteBindBreakers;
105pub(crate) use route_open::RouteBindConcurrency;
106use route_open::RouteOpenCaller;
107use route_open::RouteOpenRequest;
108use route_open::RouteOpenTimings;
109pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN;
110pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD;
111pub use route_open::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT;
112
113mod server_describe;
114use server_describe::subc_ops;
115use server_describe::CAP_ADMISSION_FACTS_RELAY;
116use server_describe::CAP_CHANNEL_LIFECYCLE;
117use server_describe::CAP_MANIFEST_REGISTRATION;
118use server_describe::CAP_PING_PONG;
119use server_describe::CAP_SESSION_ATTACH;
120
121mod supervisor_operations;
122use supervisor_operations::launch_spec_agreement;
123#[cfg(test)]
124use supervisor_operations::reload_verdict;
125use supervisor_operations::DaemonProvenanceFacts;
126use supervisor_operations::ModuleControlRpcGuard;
127use supervisor_operations::DEFAULT_HEALTH_PROBE_TIMEOUT;
128
129mod activity;
130#[cfg(test)]
131use activity::ActivityRequestPause;
132
133mod scopes;
134#[cfg(test)]
135use scopes::ScopeOutcomeCounts;
136
137mod module_operations;
138use module_operations::is_known_module_request_op;
139use module_operations::manifest_concurrency;
140#[cfg(test)]
141use module_operations::manifest_concurrency_was_defaulted;
142#[cfg(test)]
143use module_operations::module_baseline_control_ops;
144use module_operations::module_control_request_op;
145use module_operations::module_registration_grants_op;
146use module_operations::parse_module_control_request_from_module;
147#[cfg(all(test, unix, feature = "test-support"))]
148use module_operations::MODULE_TO_SUBC_UNADVERTISED_OPS;
149mod advertised_ops;
150use advertised_ops::*;
151mod caller_attestation;
152mod channel_operations;
153#[cfg(all(test, unix, feature = "test-support"))]
154#[path = "control/channel_operations_tests.rs"]
155mod channel_operations_tests;
156pub(crate) mod claims;
157#[cfg(test)]
158#[path = "control/config_advertisement_tests.rs"]
159mod config_advertisement_tests;
160mod config_gate;
161#[path = "operator_apps/connection.rs"]
162mod peer_identity;
163use caller_attestation::scope_acts_for_another;
164mod activity_reservations;
165#[cfg(all(test, unix, feature = "test-support"))]
166#[path = "control/caller_attestation_tests.rs"]
167mod caller_attestation_tests;
168mod capability_census;
169use capability_census::append_capability_problem_detail;
170use capability_census::capability_census_trigger;
171mod route_bind_settlement;
172mod scope_expiry;
173mod scope_watch;
174mod usage;
175
176mod agent_commands;
177pub(crate) mod catalog;
178mod policy_root;
179mod rescan_checked;
180use rescan_checked::RescanMode;
181use rescan_checked::SupervisorRescanContext;
182
183const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
184
185/// A test hold: signal arrival, then wait for release on the holding thread.
186#[cfg(test)]
187type TestPause = (
188    tokio::sync::oneshot::Sender<()>,
189    std::sync::mpsc::Receiver<()>,
190);
191
192/// A test hook run once at a fixed point in a handler.
193#[cfg(test)]
194type TestHook = Box<dyn FnOnce() + Send>;
195
196/// A test hold for async code: signal arrival, then await release.
197#[cfg(test)]
198type AsyncTestPause = (
199    tokio::sync::oneshot::Sender<()>,
200    tokio::sync::oneshot::Receiver<()>,
201);
202
203/// Accept-time diagnostics, kept apart from peer observations used for trust.
204#[derive(Clone)]
205pub(crate) enum RouteOpenerConnection {
206    Local(Option<subc_os::local_peer::DiagnosticProcess>),
207    Tcp,
208}
209
210/// Real channel-0 control handler for subc itself.
211#[derive(Clone)]
212pub struct ControlHandler {
213    #[cfg(test)]
214    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
215    /// Holds connection cleanup at a numbered point: 0 is just after the agent
216    /// declaration queue closes, 1 just after the registration channel is
217    /// forgotten.
218    #[cfg(test)]
219    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
220    /// Runs once in `route.open`'s launch-nonce attestation, right after the
221    /// nonce is resolved, to interleave a nonce withdrawal there.
222    #[cfg(test)]
223    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
224    /// Holds a registration channel's HELLO after its reader resolved the
225    /// channel and before the blocking HELLO handler starts.
226    #[cfg(test)]
227    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
228    /// Holds an agent command declaration at a numbered point in its handler.
229    #[cfg(test)]
230    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
231    claims: Arc<claims::Claims>,
232    registry: Arc<Registry>,
233    control_usage: Arc<Mutex<usage::ControlUsage>>,
234    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
235    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
236    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
237    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
238    config_review_admission_is_default: bool,
239    activity: Option<crate::activity::ActivityLedger>,
240    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
241    activity_reservations: activity_reservations::ActivityReservations,
242    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
243    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
244    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
245    forwarding: Arc<ForwardingTable>,
246    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
247    supervisor: SupervisorHandle,
248    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
249    agent_declarations: agent_commands::Queues,
250    list_admission: Arc<tokio::sync::Semaphore>,
251    subc_capabilities: Arc<[String]>,
252    /// Daemon-wide route.bind relay budget. Used as the fallback when the
253    /// target module has no per-module override in
254    /// `route_bind_relay_timeouts`.
255    route_bind_relay_timeout: Duration,
256    /// Per-module route.bind relay budget overrides, keyed by module id. When
257    /// `handle_route_open` resolves the deadline for a target module, a
258    /// per-module entry wins over the daemon-wide value above.
259    route_bind_relay_timeouts: BTreeMap<String, Duration>,
260    /// Per-target-module bind-relay breaker state. Shared with the forwarding
261    /// table, which is where a new module connection resets it.
262    route_bind_breakers: RouteBindBreakers,
263    /// Live relay admissions keyed by target module. Shared through the
264    /// forwarding table so cloned or separately built handlers enforce one cap.
265    route_bind_concurrency: RouteBindConcurrency,
266    /// Start and end of each module's not-serving period as seen by
267    /// `route.open`, so an outage gets one line at each edge instead of only
268    /// the per-refusal INFO lines. Taken from the forwarding table, so every
269    /// handler built over one table shares it.
270    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
271    route_refusal_log: route_open_refusal_log::RefusalLog,
272    /// Consecutive relay timeouts that open a module's breaker.
273    route_bind_breaker_threshold: u32,
274    /// How long a breaker stays open before one probe is admitted.
275    route_bind_breaker_cooldown: Duration,
276    health_probe_timeout: Duration,
277    /// Central storage policy. When set, each registering module receives its
278    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
279    storage_config: Option<crate::daemon_config::StorageConfig>,
280    /// The machine id established at boot, served on every HELLO_ACK and on
281    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
282    /// changes the file, never this value. `None` serves no id.
283    machine_id: Option<crate::machine_id::MachineId>,
284    admission_facts_carrier_module_id: Option<String>,
285    admission_facts_targets: Option<Vec<String>>,
286    /// Scope records with their sync authorities and tombstones; see
287    /// `crate::scopes`. Shared by clones of this handler, so every connection
288    /// reads and writes one table.
289    scopes: Arc<RwLock<ScopeTable>>,
290    /// Wakes the expiry loop when an accepted scope change may have added a
291    /// deadline, so the loop can wait without ticking while no live scope has
292    /// one. A permit is stored when nothing waits, so no wake is lost.
293    scope_deadline_added: Arc<tokio::sync::Notify>,
294    /// The configured `scope_authority_owners`, kept so a rescan can report a
295    /// changed value as needing a daemon restart; rescan never applies it.
296    scope_authority_owners: Vec<String>,
297    federated_scope_owner: String,
298    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
299    privileged_operator_prompt: PrivilegedOperatorPrompt,
300    /// The local and peer address of each accepted TCP client connection, read
301    /// from the daemon's own socket, so a privileged request can name its caller.
302    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
303    route_openers: Arc<Mutex<HashMap<ConnectionId, RouteOpenerConnection>>>,
304    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
305    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
306    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
307    config_desktop_stamps:
308        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
309    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
310    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
311    pub(crate) operator_apps:
312        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
313    /// One launch entry per app, behind a leaf lock: no other lock is taken
314    /// while it is held. Entries are memory-only, so a daemon or
315    /// installed-service restart drops them and a relaunched daemon never
316    /// mistakes an older process for its own launch.
317    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
318    /// Serializes `app.open` launches: the liveness check in the decision and
319    /// the later publish must not interleave across concurrent calls, or two
320    /// calls could both launch and the second publish would orphan the first
321    /// process. Refusals and `already_running` answers share the same lock;
322    /// `app.open` is rare, so the cost is negligible.
323    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
324    // Portable wire samples exercise dispatch without starting an OS process.
325    #[cfg(test)]
326    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
327    #[cfg(test)]
328    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
329    #[cfg(test)]
330    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
331    #[cfg(test)]
332    pub(crate) config_review_test_replies:
333        std::collections::BTreeMap<String, subc_protocol::config::ConfigReviewReply>,
334    #[cfg(test)]
335    pub(crate) config_review_test_seen: Option<tokio::sync::mpsc::UnboundedSender<String>>,
336    #[cfg(test)]
337    pub(crate) config_review_test_refuse: Arc<std::sync::Mutex<std::collections::BTreeSet<String>>>,
338    #[cfg(test)]
339    pub(crate) config_review_test_fail_once: Arc<std::sync::atomic::AtomicBool>,
340    #[cfg(test)]
341    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
342    #[cfg(test)]
343    recovery_exit_test_completed: Option<fn(u64)>,
344    #[cfg(test)]
345    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
346    #[cfg(test)]
347    recovery_exit_test_quiet_retry: bool,
348    #[cfg(test)]
349    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
350    #[cfg(test)]
351    config_delivery_test_wakes:
352        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
353    #[cfg(all(test, unix))]
354    config_delivery_test_idle:
355        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
356    /// Test-only Windows signature and flash hooks. Production builds carry
357    /// neither: with the publisher unset, the production table never reaches
358    /// verification, and the default attention hook only logs.
359    #[allow(dead_code)]
360    #[cfg(windows)]
361    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
362    #[allow(dead_code)]
363    #[cfg(windows)]
364    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
365    /// Test-only tracking fault hook: makes opening the tracking handle on
366    /// the launched pid fail, so a test can prove an untrackable launch is
367    /// stopped rather than left running.
368    #[allow(dead_code)]
369    #[cfg(windows)]
370    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
371    /// Test-only count of Windows spawn attempts, so a test can prove a
372    /// refused launch started no process. Unit tests only.
373    #[cfg(all(test, windows))]
374    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
375    #[cfg(test)]
376    caller_lookup: Option<TestCallerLookup>,
377    /// The launch nonce each module connection presented at HELLO, which is how
378    /// a `scope.sync` is matched to the owner's current launch.
379    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
380    rescan: Option<SupervisorRescanContext>,
381    connected_clients: ConnectedClients,
382    counters: DaemonCounters,
383    /// Why this daemon serves no local endpoint, when binding one failed. `None`
384    /// when the endpoint is served, and also on a handler that was never told.
385    local_endpoint_unavailable: Option<String>,
386    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
387    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
388    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
389    /// their usual severity (see [`log_requirement_events`]). A handler built
390    /// without one has a flag that is never set.
391    daemon_shutdown: DaemonShutdownFlag,
392    daemon_provenance: DaemonProvenanceFacts,
393    #[cfg(test)]
394    control_dispatch_delay: Option<Duration>,
395    #[cfg(test)]
396    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
397    /// Holds `route.open` after the route.bind is queued to the module and
398    /// before it is marked enqueued, so a test can make the module's reply (or
399    /// a client teardown) land exactly inside that window.
400    #[cfg(test)]
401    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
402    /// Holds a HELLO after its registry entry is reserved and before its
403    /// forwarding endpoint is installed, so a test can read the catalog and
404    /// open routes while the module is registered but not yet routable. A
405    /// blocking barrier because the HELLO handler is synchronous; the test
406    /// runs the HELLO on its own thread.
407    #[cfg(test)]
408    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
409    #[cfg(test)]
410    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
411    #[cfg(test)]
412    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
413    #[cfg(test)]
414    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
415    #[cfg(test)]
416    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
417}
418
419impl fmt::Debug for ControlHandler {
420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421        f.debug_struct("ControlHandler")
422            .field("registry", &self.registry)
423            .field("forwarding", &self.forwarding)
424            .field("process_liveness", &self.process_liveness.is_some())
425            .field("supervisor", &self.supervisor)
426            .field("subc_capabilities", &self.subc_capabilities)
427            .finish()
428    }
429}
430
431impl ControlHandler {
432    pub(crate) fn install_registration_service(
433        &self,
434        router: std::sync::Weak<crate::Router>,
435        auth: crate::server::ServerAuth,
436    ) {
437        self.supervisor.install_registration_service(router, auth);
438    }
439    pub fn new(registry: Arc<Registry>) -> Self {
440        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
441    }
442
443    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
444        let counters = forwarding.counters();
445        // Taken from the forwarding table rather than created here, so that the
446        // breaker a `route.open` consults is the same one a module's
447        // registration resets, however many handlers are built over one table.
448        let route_bind_breakers = forwarding.route_bind_breakers();
449        let route_bind_concurrency = forwarding.route_bind_concurrency();
450        let route_outages = forwarding.route_outages();
451        Self {
452            registry,
453            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
454            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
455            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
456            #[cfg(test)]
457            activity_request_pause: Arc::new(Mutex::new(None)),
458            #[cfg(test)]
459            cleanup_pause: Arc::new(Mutex::new(None)),
460            #[cfg(test)]
461            after_nonce_attestation: Arc::new(Mutex::new(None)),
462            #[cfg(test)]
463            hello_ingress_pause: Arc::new(Mutex::new(None)),
464            #[cfg(test)]
465            agent_commands_pause: Arc::new(Mutex::new(None)),
466            claims: Arc::new(claims::Claims::default()),
467            config_runtime: None,
468            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
469            config_review_admission_is_default: true,
470            activity: None,
471            activity_streams: Arc::new(Mutex::new(HashMap::new())),
472            activity_reservations: Default::default(),
473            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
474            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
475            scope_streams: Arc::new(Mutex::new(HashMap::new())),
476            forwarding,
477            process_liveness: None,
478            supervisor: SupervisorHandle::new(),
479            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
480                env!("CARGO_PKG_VERSION").to_owned(),
481            )),
482            agent_declarations: agent_commands::Queues::default(),
483            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
484            subc_capabilities: Arc::from([
485                CAP_MANIFEST_REGISTRATION.to_string(),
486                CAP_CHANNEL_LIFECYCLE.to_string(),
487                CAP_PING_PONG.to_string(),
488                CAP_SESSION_ATTACH.to_string(),
489                CAP_ADMISSION_FACTS_RELAY.to_string(),
490                CAP_SCOPES_V1.to_string(),
491                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
492                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
493                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
494                PEER_BUILD_CAPABILITY.to_string(),
495                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
496                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
497                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
498                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
499                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
500                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
501                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
502                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
503                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
504                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
505                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
506                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
507            ]),
508            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
509            route_bind_relay_timeouts: BTreeMap::new(),
510            route_bind_breakers,
511            route_bind_concurrency,
512            route_outages,
513            route_refusal_log: Default::default(),
514            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
515            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
516            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
517            storage_config: None,
518            machine_id: None,
519            admission_facts_carrier_module_id: None,
520            admission_facts_targets: None,
521            scopes: Arc::new(RwLock::new(ScopeTable::new(
522                crate::daemon_config::default_scope_authority_owners(),
523            ))),
524            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
525            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
526            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
527            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
528            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
529            route_openers: Arc::new(Mutex::new(HashMap::new())),
530            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
531            observed_peers: Arc::new(Mutex::new(HashMap::new())),
532            captured_peers: Arc::new(Mutex::new(HashMap::new())),
533            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
534            local_connections: Arc::new(Mutex::new(HashSet::new())),
535            operator_app_policy: Default::default(),
536            operator_apps: Arc::new(Mutex::new(HashMap::new())),
537            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
538            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
539            #[cfg(test)]
540            app_open_test_platform: None,
541            #[cfg(test)]
542            app_open_test_launch: None,
543            #[cfg(test)]
544            config_review_test_reply: None,
545            #[cfg(test)]
546            config_review_test_replies: Default::default(),
547            #[cfg(test)]
548            config_review_test_seen: None,
549            #[cfg(test)]
550            config_review_test_refuse: Default::default(),
551            #[cfg(test)]
552            config_review_test_fail_once: Default::default(),
553            #[cfg(test)]
554            recovery_exit_test_after_step: None,
555            #[cfg(test)]
556            recovery_exit_test_completed: None,
557            #[cfg(test)]
558            apply_reconcile_pause: Arc::new(Mutex::new(None)),
559            #[cfg(test)]
560            recovery_exit_test_quiet_retry: false,
561            #[cfg(test)]
562            recovery_exit_test_retry_pause: None,
563            #[cfg(test)]
564            config_delivery_test_wakes: None,
565            #[cfg(all(test, unix))]
566            config_delivery_test_idle: None,
567            #[cfg(windows)]
568            windows_verify: None,
569            #[cfg(windows)]
570            windows_flash: None,
571            #[cfg(windows)]
572            windows_track: None,
573            #[cfg(all(test, windows))]
574            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
575            #[cfg(test)]
576            caller_lookup: None,
577            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
578            rescan: None,
579            connected_clients: ConnectedClients::new(),
580            local_endpoint_unavailable: None,
581            counters,
582            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
583            daemon_shutdown: DaemonShutdownFlag::default(),
584            daemon_provenance: DaemonProvenanceFacts::default(),
585            #[cfg(test)]
586            control_dispatch_delay: None,
587            #[cfg(test)]
588            provenance_probe_override: None,
589            #[cfg(test)]
590            route_bind_relay_sent_hold: None,
591            #[cfg(test)]
592            hello_registry_to_forwarding_hold: None,
593            #[cfg(test)]
594            hello_ack_to_publication_hold: None,
595            #[cfg(test)]
596            hello_before_publication_hold: None,
597            #[cfg(test)]
598            hello_after_launch_check_hold: None,
599            #[cfg(test)]
600            hello_inside_publication_hold: None,
601        }
602    }
603
604    /// Set the central storage policy: registering modules then receive their
605    /// resolved storage descriptor in HELLO_ACK.
606    pub fn with_storage_config(
607        mut self,
608        storage_config: Option<crate::daemon_config::StorageConfig>,
609    ) -> Self {
610        self.storage_config = storage_config;
611        self
612    }
613
614    /// Set the machine id served to every registering module (HELLO_ACK) and on
615    /// `server.describe`.
616    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
617        self.machine_id = machine_id;
618        self
619    }
620
621    /// Configure the exact reserved module and target ids permitted to relay
622    /// opaque admission facts. Config-file loading validates this authority;
623    /// this builder keeps the same policy available to embedded test daemons.
624    pub fn with_admission_facts_config(
625        mut self,
626        carrier_module_id: Option<String>,
627        targets: Option<Vec<String>>,
628    ) -> Self {
629        self.admission_facts_carrier_module_id = carrier_module_id;
630        self.admission_facts_targets = targets;
631        self
632    }
633
634    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
635    /// Replaces the scope table with an empty one under the new list, so call it
636    /// while building the handler, before any module can sync.
637    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
638        self.scopes = Arc::new(RwLock::new(
639            ScopeTable::new(owners.iter().cloned())
640                .with_federated_owner(self.federated_scope_owner.clone()),
641        ));
642        self.scope_authority_owners = owners;
643        self
644    }
645
646    /// Set the exclusive federated owner while building the handler, before syncs.
647    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
648        self.scopes = Arc::new(RwLock::new(
649            ScopeTable::new(self.scope_authority_owners.iter().cloned())
650                .with_federated_owner(owner.clone()),
651        ));
652        self.federated_scope_owner = owner;
653        self
654    }
655
656    /// Set the startup policy before installing the rescan context or serving requests.
657    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
658        self.privileged_operator_prompt = mode;
659        self
660    }
661
662    #[cfg(test)]
663    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
664        self.control_dispatch_delay = Some(delay);
665        self
666    }
667
668    pub fn with_process_liveness(
669        mut self,
670        process_liveness: Arc<dyn ModuleProcessLiveness>,
671    ) -> Self {
672        self.process_liveness = Some(process_liveness);
673        self
674    }
675
676    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
677        self.supervisor = supervisor;
678        if let Some(owner) = &self.config_runtime {
679            self.supervisor.install_binding_retirement(owner);
680        }
681        self.supervisor.set_activity(self.activity.clone());
682        self
683    }
684
685    /// Install the configured module set and its reserved capability bindings.
686    /// Bindings are configuration-scoped and may point at a provider that has not
687    /// been installed yet, so this does not require the bound module to exist.
688    pub fn with_capability_config(
689        self,
690        modules: impl IntoIterator<Item = (String, bool)>,
691        reserved_capabilities: BTreeMap<String, String>,
692    ) -> Self {
693        self.capability_evaluator
694            .configure(modules, reserved_capabilities);
695        self
696    }
697
698    /// Share the supervisor's daemon-shutdown flag with this handler, so
699    /// requirement changes after the daemon has begun its announced shutdown
700    /// are not reported as faults.
701    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
702        self.daemon_shutdown = flag;
703        self
704    }
705
706    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
707        self.connected_clients = connected_clients;
708        self
709    }
710
711    /// Report why this daemon serves no local endpoint, in `server.describe`, so
712    /// an operator can see a bind failure without reading the daemon log.
713    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
714        self.local_endpoint_unavailable = reason;
715        self
716    }
717
718    pub fn forwarding(&self) -> Arc<ForwardingTable> {
719        Arc::clone(&self.forwarding)
720    }
721
722    pub(crate) fn counters(&self) -> DaemonCounters {
723        self.counters.clone()
724    }
725
726    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
727    /// registration-release watch. The signal is what the supervisor waits on
728    /// before spawning a replacement, so it must only fire once forwarding
729    /// teardown is also done (see [`Self::cleanup_connection`] /
730    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
731    /// registry-only path below because publication already owns the spawn lock.
732    fn deregister_connection(
733        &self,
734        connection_id: ConnectionId,
735        reason: RegistrationEndReason,
736    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
737        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
738            spawn.end_primary_registration();
739        }
740        self.registry
741            .deregister_connection_with_reason(connection_id, reason)
742    }
743
744    fn request_refusal_close(
745        &self,
746        connection: ConnectionId,
747        sink: Option<&crate::FrameSink>,
748        reason: CloseReason,
749    ) {
750        if let Some(sink) = sink {
751            sink.terminate_ingress();
752        }
753        if self.claims.close_notifications_enabled() {
754            self.forwarding.request_connection_close(connection, reason);
755        }
756    }
757
758    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
759    ///
760    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
761    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
762    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
763    #[cfg(test)]
764    pub fn handle_control(
765        &self,
766        connection_id: ConnectionId,
767        frame: Frame,
768    ) -> Result<Vec<Frame>, RouterError> {
769        match frame.header.ty {
770            FrameType::Ping => Ok(vec![pong(&frame)?]),
771            FrameType::Hello => self.handle_hello(connection_id, None, frame),
772            FrameType::Goodbye => self.handle_goodbye(connection_id),
773            ty => Ok(vec![control_error_frame(
774                &frame,
775                "unsupported_control_frame",
776                format!("unsupported channel-0 frame {ty:?}"),
777            )?]),
778        }
779    }
780
781    pub async fn handle_control_frame(
782        &self,
783        ctx: &RouteCtx,
784        frame: Frame,
785    ) -> Result<Vec<Frame>, RouterError> {
786        self.handle_control_frame_timed(ctx, frame, None).await
787    }
788
789    #[cfg(any(test, feature = "test-support"))]
790    pub fn with_test_operator_app_policy(
791        mut self,
792        policy: crate::operator_apps::TestOperatorAppPolicy,
793    ) -> Self {
794        self.operator_app_policy = policy.into();
795        self
796    }
797
798    /// Inject the Windows signature check for tests. The injected check
799    /// answers the verified version string or the rejection reason; the
800    /// daemon enforces the floor itself on the returned version.
801    #[cfg(all(windows, any(test, feature = "test-support")))]
802    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
803        self.windows_verify = Some(verify);
804        self
805    }
806
807    /// Record which pids the daemon would flash for `already_running`.
808    #[cfg(all(windows, any(test, feature = "test-support")))]
809    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
810        self.windows_flash = Some(flash);
811        self
812    }
813
814    /// Inject a tracking failure for tests: makes `track_launched_process`
815    /// fail so a test can prove a launch that cannot be tracked is stopped,
816    /// never left running.
817    #[cfg(all(windows, any(test, feature = "test-support")))]
818    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
819        self.windows_track = Some(track);
820        self
821    }
822
823    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
824        self.local_connections
825            .lock()
826            .unwrap_or_else(|p| p.into_inner())
827            .insert(connection);
828    }
829
830    pub(crate) fn record_route_opener(
831        &self,
832        connection: ConnectionId,
833        opener: RouteOpenerConnection,
834    ) {
835        self.route_openers
836            .lock()
837            .unwrap_or_else(|p| p.into_inner())
838            .insert(connection, opener);
839    }
840
841    // Keep the connection-level delivery decision shared with route.bind. The
842    // target's capability opt-in is separate from recognition of the caller.
843    fn connection_operator_app(
844        &self,
845        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
846    ) -> Option<subc_protocol::peer::OperatorApp> {
847        stamp
848            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
849            .map(|stamp| stamp.app.clone())
850    }
851
852    pub(crate) fn record_observed_peer(
853        &self,
854        connection: ConnectionId,
855        peer: subc_os::local_peer::ObservedPeer,
856    ) {
857        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
858        let peer = match peer {
859            OsPeer::Unobserved => ObservedPeer::unobserved(),
860            OsPeer::Observed(peer) => {
861                let observed = match peer.user {
862                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
863                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
864                };
865                observed
866                    .with_exe(
867                        peer.exe
868                            .and_then(|path| path.into_os_string().into_string().ok()),
869                    )
870                    .with_signing_id(peer.signing_id)
871            }
872        };
873        self.observed_peers
874            .lock()
875            .unwrap_or_else(|p| p.into_inner())
876            .insert(connection, peer);
877    }
878
879    pub(crate) fn record_caller_endpoints(
880        &self,
881        connection: ConnectionId,
882        endpoints: Option<(SocketAddr, SocketAddr)>,
883    ) {
884        let mut callers = self
885            .caller_endpoints
886            .lock()
887            .unwrap_or_else(|p| p.into_inner());
888        callers.remove(&connection);
889        if let Some(endpoints) = endpoints {
890            callers.insert(connection, endpoints);
891        }
892    }
893
894    #[cfg(test)]
895    pub(crate) fn with_caller_lookup_for_test(
896        mut self,
897        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
898    ) -> Self {
899        self.caller_lookup = Some(Arc::new(lookup));
900        self
901    }
902
903    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
904        let endpoints = self
905            .caller_endpoints
906            .lock()
907            .unwrap_or_else(|p| p.into_inner())
908            .get(&connection)
909            .copied();
910        #[cfg(test)]
911        let lookup = self.caller_lookup.clone();
912        tokio::task::spawn_blocking(move || {
913            #[cfg(test)]
914            if let Some(lookup) = lookup {
915                return lookup(endpoints);
916            }
917            endpoints
918                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
919                .unwrap_or_default()
920        })
921        .await
922        .unwrap_or_default()
923    }
924
925    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
926        frame.header.channel == 0
927            && frame.header.ty == FrameType::Request
928            && self
929                .forwarding
930                .module_endpoint_for_connection(ctx.connection_id)
931                .is_ok_and(|endpoint| endpoint.is_none())
932            && parse_client_control_request(&frame.body)
933                .ok()
934                .is_some_and(|request| privileged_operation(&request).is_some())
935    }
936
937    pub(crate) async fn handle_control_frame_timed(
938        &self,
939        ctx: &RouteCtx,
940        frame: Frame,
941        dispatch_started_at: Option<StdInstant>,
942    ) -> Result<Vec<Frame>, RouterError> {
943        let first = ctx.egress.first_ingress_frame();
944        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
945            .await
946    }
947
948    pub(crate) async fn handle_control_frame_ingress(
949        &self,
950        ctx: &RouteCtx,
951        frame: Frame,
952        dispatch_started_at: Option<StdInstant>,
953        first: bool,
954    ) -> Result<Vec<Frame>, RouterError> {
955        if ctx.egress.ingress_terminal() {
956            return Ok(Vec::new());
957        }
958        #[cfg(test)]
959        self.claims.record_dispatch(frame.header.corr);
960        let claim_binding = self.claims.binding(ctx.connection_id);
961        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
962            && claim_binding
963                .as_ref()
964                .is_some_and(|binding| binding.prefix_module_id().is_some()))
965        .then(|| self.prefix_hello_attempt(ctx));
966        if claim_binding
967            .as_ref()
968            .is_some_and(|binding| binding.prefix_module_id().is_some())
969        {
970            let registered = self
971                .forwarding
972                .module_endpoint_for_connection(ctx.connection_id)
973                .map_err(RouterError::Forwarding)?
974                .is_some();
975            if !registered && frame.header.ty != FrameType::Hello {
976                return self
977                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
978                    .await;
979            }
980            if registered && frame.header.ty == FrameType::Goodbye {
981                ctx.egress.terminate_ingress();
982                let result = self.handle_goodbye(ctx.connection_id);
983                self.claims.connection_closed(ctx.connection_id);
984                self.request_refusal_close(
985                    ctx.connection_id,
986                    Some(&ctx.egress),
987                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
988                );
989                return result;
990            }
991            if registered && frame.header.ty == FrameType::Request {
992                let allowed =
993                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
994                        matches!(
995                            probe.op.as_str(),
996                            "catalog.update"
997                                | "catalog.update_role_declarations"
998                                | "scope.describe"
999                                | "scope.watch"
1000                                | "supervisor.live_roots"
1001                                | subc_protocol::policy_root::GET_OP
1002                                | "activity.record"
1003                        )
1004                    });
1005                if !allowed {
1006                    return Ok(vec![control_error_frame(
1007                        &frame,
1008                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1009                        "prefix registrations have only brokered module operations",
1010                    )?]);
1011                }
1012            }
1013            if registered
1014                && frame.header.ty == FrameType::Push
1015                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
1016                    .is_ok_and(|probe| probe.op == "route.status")
1017            {
1018                return Ok(vec![control_error_frame(
1019                    &frame,
1020                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1021                    "prefix registrations may push only route.status for routes they serve",
1022                )?]);
1023            }
1024        }
1025        match frame.header.ty {
1026            FrameType::Ping => Ok(vec![pong(&frame)?]),
1027            FrameType::Hello => {
1028                if claim_binding
1029                    .as_ref()
1030                    .is_some_and(|binding| binding.prefix_module_id().is_none())
1031                {
1032                    return self
1033                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
1034                        .await;
1035                }
1036                // Resolved once, here: the blocking HELLO below may outlive this
1037                // reader and run after cleanup has forgotten the channel, and it
1038                // must still be judged as this channel's HELLO.
1039                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
1040                if let Some(spawn) = &channel_spawn {
1041                    spawn.wait_launch().await;
1042                    // Refused launches close the channel. Leave their pending
1043                    // HELLO unanswered instead of racing a reply against shutdown.
1044                    if !spawn.launch_ready() {
1045                        ctx.egress.terminate_ingress();
1046                        return Ok(Vec::new());
1047                    }
1048                    #[cfg(test)]
1049                    self.pause_hello_ingress_for_test().await;
1050                } else if claim_binding.is_none() {
1051                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
1052                        if let (Some(module), Some(nonce)) = (
1053                            hello
1054                                .get("manifest")
1055                                .and_then(|value| value.get("module_id"))
1056                                .and_then(|value| value.as_str()),
1057                            hello.get("launch_nonce").and_then(|value| value.as_str()),
1058                        ) {
1059                            if !self
1060                                .config_runtime
1061                                .as_ref()
1062                                .is_some_and(|owner| owner.module_is_gated(module))
1063                                && !self.supervisor.wait_program_binding(module, nonce).await
1064                            {
1065                                self.request_refusal_close(
1066                                    ctx.connection_id,
1067                                    Some(&ctx.egress),
1068                                    CloseReason::new(
1069                                        "program_refused",
1070                                        "the spawned program binding failed",
1071                                    ),
1072                                );
1073                                return Ok(vec![control_error_frame(
1074                                    &frame,
1075                                    if self
1076                                        .config_runtime
1077                                        .as_ref()
1078                                        .is_some_and(|owner| owner.is_recovering())
1079                                    {
1080                                        "config_gated"
1081                                    } else {
1082                                        "program_refused"
1083                                    },
1084                                    "the spawned program binding failed",
1085                                )?]);
1086                            }
1087                        }
1088                    }
1089                }
1090                let handler = self.clone();
1091                let connection = ctx.connection_id;
1092                let egress = ctx.egress.clone();
1093                let correlation = frame.header.corr;
1094                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
1095                let span = tracing::Span::current();
1096                let hello_binding = claim_binding.clone();
1097                let replies = tokio::task::spawn_blocking(move || {
1098                    tracing::dispatcher::with_default(&dispatcher, || {
1099                        span.in_scope(|| {
1100                            handler.handle_hello_checked(
1101                                connection,
1102                                Some(egress),
1103                                frame,
1104                                true,
1105                                hello_binding,
1106                                channel_spawn,
1107                            )
1108                        })
1109                    })
1110                })
1111                .await
1112                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
1113                #[cfg(test)]
1114                if prefix_attempt.is_some() {
1115                    self.claims.pause_prefix_commit_for_test(false).await;
1116                }
1117                if let Some(attempt) = &mut prefix_attempt {
1118                    let accepted = !replies
1119                        .iter()
1120                        .any(|reply| reply.header.ty == FrameType::Error)
1121                        && self
1122                            .registry
1123                            .get_module_by_connection(ctx.connection_id)
1124                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
1125                            .is_some();
1126                    if accepted {
1127                        attempt.accepted = true;
1128                    } else {
1129                        ctx.egress.terminate_ingress();
1130                        for reply in replies {
1131                            ctx.egress.send_flushed(reply).await?;
1132                        }
1133                        return Ok(Vec::new());
1134                    }
1135                }
1136                Ok(replies)
1137            }
1138            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
1139            FrameType::Cancel => {
1140                // Channel-0 cancellation withdraws approvals and subscriptions
1141                // and fences pending agent declarations;
1142                // successful cancellation has no ordinary reply.
1143                // A config Apply may also own an OS prompt. Cancel that prompt
1144                // before config cancellation can report the request handled.
1145                if self
1146                    .agent_declarations
1147                    .cancel(ctx.connection_id, frame.header.corr)
1148                    || self
1149                        .forwarding
1150                        .operator_confirms()
1151                        .cancel(ctx.connection_id, frame.header.corr)
1152                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
1153                    || self
1154                        .supervisor
1155                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
1156                    || self.cancel_activity_subscription(ctx, &frame)?
1157                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
1158                    || self
1159                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
1160                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
1161                {
1162                    Ok(Vec::new())
1163                } else {
1164                    Ok(vec![control_error_frame(
1165                        &frame,
1166                        "unknown_subscription",
1167                        "no subscription has this correlation id",
1168                    )?])
1169                }
1170            }
1171            FrameType::Request => {
1172                // This additive operation is not part of the existing exhaustive
1173                // module-control enum. Probe the op before decoding that enum.
1174                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
1175                if let Some(probe) = &op {
1176                    self.record_control_usage(ctx.connection_id, &probe.op);
1177                }
1178                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
1179                if let Some(refusal) = self.recovery_request_refusal(
1180                    ctx,
1181                    &frame,
1182                    op.as_ref().map(|probe| probe.op.as_str()),
1183                )? {
1184                    if claim_present {
1185                        self.reclaim_presented_expiry(&frame);
1186                        return self
1187                            .refuse_claim_connection(ctx, &frame, "config_gated")
1188                            .await;
1189                    }
1190                    return Ok(vec![refusal]);
1191                }
1192                if claim_present {
1193                    return self.handle_claim_present(ctx, &frame, first).await;
1194                }
1195                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
1196                    return self.handle_claim_mint(ctx, &frame).await;
1197                }
1198                if let Some(refusal) = self.registration_operation_refusal(
1199                    ctx,
1200                    &frame,
1201                    op.as_ref().map(|probe| probe.op.as_str()),
1202                )? {
1203                    return Ok(vec![refusal]);
1204                }
1205                if let Some(probe) = op.as_ref().filter(|probe| policy_root::is_op(&probe.op)) {
1206                    return self.handle_policy_root(ctx, frame, &probe.op).await;
1207                }
1208                if op
1209                    .as_ref()
1210                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
1211                {
1212                    return self.handle_catalog_watch(ctx, frame);
1213                }
1214                if op
1215                    .as_ref()
1216                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
1217                {
1218                    return self.handle_scope_watch(ctx, frame);
1219                }
1220                if op
1221                    .as_ref()
1222                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
1223                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
1224                        .unwrap_or(false)
1225                {
1226                    return Ok(vec![control_error_frame(
1227                        &frame,
1228                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
1229                        "provider_declarations are fixed at HELLO; restart the module to change them",
1230                    )?]);
1231                }
1232                if let Some(probe) = op
1233                    .as_ref()
1234                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
1235                {
1236                    return self
1237                        .handle_module_config_request(ctx, frame, &probe.op)
1238                        .await;
1239                }
1240                if let Some(probe) = op
1241                    .as_ref()
1242                    .filter(|probe| config_gate::is_config_op(&probe.op))
1243                {
1244                    return self.handle_config_gate_request(ctx, frame, &probe.op).await;
1245                }
1246                if op
1247                    .as_ref()
1248                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
1249                {
1250                    return self.handle_activity_record(ctx, frame).await;
1251                }
1252                if op.as_ref().is_some_and(|probe| {
1253                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
1254                }) {
1255                    // A refusal and a CANCEL that won must not both end the stream.
1256                    let key = (ctx.connection_id, frame.header.corr);
1257                    let replies = self.handle_activity_read(ctx, frame).await?;
1258                    return Ok(self.activity_reservations.settle(key, replies));
1259                }
1260                if op
1261                    .as_ref()
1262                    .is_some_and(|probe| probe.op == "operator.confirm")
1263                {
1264                    return self.handle_operator_confirm(ctx, frame).await;
1265                }
1266                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
1267                    return self
1268                        .observe_control_wait(
1269                            ctx,
1270                            None,
1271                            ops::APP_OPEN,
1272                            self.handle_app_open(ctx, frame),
1273                        )
1274                        .await;
1275                }
1276                if op
1277                    .as_ref()
1278                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
1279                {
1280                    return self.handle_connection_describe(ctx, frame).await;
1281                }
1282                if op
1283                    .as_ref()
1284                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
1285                {
1286                    return self.handle_scope_served_by(ctx.connection_id, frame);
1287                }
1288                if self
1289                    .forwarding
1290                    .module_endpoint_for_connection(ctx.connection_id)
1291                    .map_err(RouterError::Forwarding)?
1292                    .is_some()
1293                {
1294                    if !is_known_module_request_op(&frame.body) {
1295                        return Ok(vec![control_error_frame(
1296                            &frame,
1297                            "unsupported_control_frame",
1298                            "module-originated channel-0 REQUEST is not supported",
1299                        )?]);
1300                    }
1301                    let request = match parse_module_control_request_from_module(&frame.body) {
1302                        Ok(request) => request,
1303                        Err((err, ControlRequestBodyError::UnknownOp)) => {
1304                            return Ok(vec![control_error_frame(
1305                                &frame,
1306                                "unsupported_control_frame",
1307                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
1308                            )?])
1309                        }
1310                        Err((err, ControlRequestBodyError::InvalidBody)) => {
1311                            return Ok(vec![control_error_frame(
1312                                &frame,
1313                                "invalid_control_body",
1314                                format!("malformed module control body: {err}"),
1315                            )?])
1316                        }
1317                    };
1318                    let op = module_control_request_op(&request);
1319                    let corr = frame.header.corr;
1320                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
1321                    if let ModuleControlRequestFromModule::AgentCommands {
1322                        started,
1323                        finished,
1324                        known,
1325                    } = request
1326                    {
1327                        return self
1328                            .agent_declarations
1329                            .enqueue(
1330                                self,
1331                                ctx,
1332                                frame,
1333                                crate::resource_totals::Declaration {
1334                                    started,
1335                                    finished,
1336                                    known,
1337                                },
1338                            )
1339                            .await;
1340                    }
1341                    let result =
1342                        self.handle_module_control_request(ctx.connection_id, frame, request);
1343                    log_slow_control_dispatch(
1344                        dispatch_started_at,
1345                        op,
1346                        ctx.connection_id,
1347                        corr,
1348                        None,
1349                    );
1350                    return result;
1351                }
1352
1353                if is_known_module_request_op(&frame.body) {
1354                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
1355                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
1356                    let code = if is_agents {
1357                        "not_supervised"
1358                    } else if op
1359                        .as_ref()
1360                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
1361                    {
1362                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
1363                    } else {
1364                        "not_registered"
1365                    };
1366                    return Ok(vec![control_error_frame(
1367                        &frame,
1368                        code,
1369                        "module-originated control requests require the module's own registered connection",
1370                    )?]);
1371                }
1372
1373                let request = match parse_client_control_request(&frame.body) {
1374                    Ok(request) => request,
1375                    Err((err, ControlRequestBodyError::UnknownOp)) => {
1376                        return Ok(vec![control_error_frame(
1377                            &frame,
1378                            "unknown_control_op",
1379                            format!("unknown client control op: {err}"),
1380                        )?])
1381                    }
1382                    Err((err, ControlRequestBodyError::InvalidBody)) => {
1383                        return Ok(vec![control_error_frame(
1384                            &frame,
1385                            "invalid_control_body",
1386                            format!("malformed client control body: {err}"),
1387                        )?])
1388                    }
1389                };
1390                let op = client_control_request_op(&request);
1391                let corr = frame.header.corr;
1392                log_control_dispatch_arrival(op, ctx.connection_id, corr);
1393                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
1394                #[cfg(test)]
1395                if let Some(delay) = self.control_dispatch_delay {
1396                    tokio::time::sleep(delay).await;
1397                }
1398                let result = self
1399                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
1400                    .await;
1401                if let Some(timings) = route_open_timings.as_mut() {
1402                    timings.finish();
1403                }
1404                log_slow_control_dispatch(
1405                    dispatch_started_at,
1406                    op,
1407                    ctx.connection_id,
1408                    corr,
1409                    route_open_timings.as_ref(),
1410                );
1411                result
1412            }
1413            FrameType::Push => {
1414                let Some(endpoint) = self
1415                    .forwarding
1416                    .module_endpoint_for_connection(ctx.connection_id)
1417                    .map_err(RouterError::Forwarding)?
1418                else {
1419                    return Ok(vec![control_error_frame(
1420                        &frame,
1421                        "unsupported_control_frame",
1422                        "client-originated channel-0 PUSH is not supported",
1423                    )?]);
1424                };
1425                self.handle_status_update(endpoint, frame)
1426            }
1427            FrameType::Response | FrameType::Error
1428                if self
1429                    .forwarding
1430                    .module_endpoint_for_connection(ctx.connection_id)
1431                    .map_err(RouterError::Forwarding)?
1432                    .is_some() =>
1433            {
1434                self.handle_module_relay_response(ctx.connection_id, frame)
1435            }
1436            ty => Ok(vec![control_error_frame(
1437                &frame,
1438                "unsupported_control_frame",
1439                format!("unsupported channel-0 frame {ty:?}"),
1440            )?]),
1441        }
1442    }
1443
1444    #[cfg(test)]
1445    fn pause_cleanup_for_test(&self, stage: u8) {
1446        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
1447        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
1448            let (_, (reached, release)) = slot.take().unwrap();
1449            drop(slot);
1450            let _ = reached.send(());
1451            let _ = release.recv_timeout(Duration::from_secs(5));
1452        }
1453    }
1454
1455    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
1456    /// right after the nonce is resolved.
1457    #[cfg(all(test, unix, feature = "test-support"))]
1458    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
1459        *self
1460            .after_nonce_attestation
1461            .lock()
1462            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
1463    }
1464
1465    #[cfg(test)]
1466    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
1467        let hook = self
1468            .after_nonce_attestation
1469            .lock()
1470            .unwrap_or_else(|p| p.into_inner())
1471            .take();
1472        if let Some(hook) = hook {
1473            hook();
1474        }
1475    }
1476
1477    pub fn cleanup_connection(
1478        &self,
1479        connection_id: ConnectionId,
1480    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1481        // The server loop joins its offloaded request tasks (route opens,
1482        // privileged requests and activity reads) before this cleanup runs, and
1483        // inline dispatch has ended. Two kinds of work are not joined. Agent
1484        // command declarations run on their queue's detached worker, so the
1485        // queue is closed first: every declaration still queued or validating
1486        // has its commit fence cancelled before anything below can change how
1487        // the connection resolves. A HELLO whose reader was dropped keeps
1488        // running on its blocking thread. It carries the channel spawn its
1489        // reader resolved at ingress instead of re-reading the index forgotten
1490        // below, so it is still judged as that channel's HELLO: the retired
1491        // spawn refuses it before it records anything, and a channel HELLO
1492        // never records a launch nonce, so it cannot leave this connection any
1493        // nonce authority.
1494        self.agent_declarations.close(connection_id);
1495        self.close_catalog_subscriptions(connection_id);
1496        self.close_config_settings_subscriptions(connection_id);
1497        self.close_scope_subscriptions(connection_id);
1498        #[cfg(test)]
1499        self.pause_cleanup_for_test(0);
1500        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1501            spawn.retire_registration_channel();
1502        }
1503        self.supervisor
1504            .forget_registration_connection(connection_id);
1505        #[cfg(test)]
1506        self.pause_cleanup_for_test(1);
1507        self.local_connections
1508            .lock()
1509            .unwrap_or_else(|p| p.into_inner())
1510            .remove(&connection_id);
1511        self.caller_endpoints
1512            .lock()
1513            .unwrap_or_else(|p| p.into_inner())
1514            .remove(&connection_id);
1515        self.route_openers
1516            .lock()
1517            .unwrap_or_else(|p| p.into_inner())
1518            .remove(&connection_id);
1519        self.build_class_warned
1520            .lock()
1521            .unwrap_or_else(|p| p.into_inner())
1522            .remove(&connection_id);
1523        // Retire the capture before its published facts so an in-flight
1524        // verification cannot recreate them after cleanup.
1525        self.captured_peers
1526            .lock()
1527            .unwrap_or_else(|p| p.into_inner())
1528            .remove(&connection_id);
1529        self.observed_peers
1530            .lock()
1531            .unwrap_or_else(|p| p.into_inner())
1532            .remove(&connection_id);
1533        self.config_desktop_stamps
1534            .lock()
1535            .unwrap_or_else(|p| p.into_inner())
1536            .remove(&connection_id);
1537        self.operator_apps
1538            .lock()
1539            .unwrap_or_else(|p| p.into_inner())
1540            .remove(&connection_id);
1541        self.forwarding
1542            .operator_confirms()
1543            .connection_closed(connection_id);
1544        let cleanup = self.cleanup_connection_with_end_reason(
1545            connection_id,
1546            RegistrationEndReason::ConnectionClosed,
1547        );
1548        // A draining writer can still be reached by a route until forwarding
1549        // cleanup finishes. Keep its claim sink visible to launch retirement.
1550        self.claims.connection_closed(connection_id);
1551        cleanup
1552    }
1553
1554    fn cleanup_connection_with_end_reason(
1555        &self,
1556        connection_id: ConnectionId,
1557        requested_reason: RegistrationEndReason,
1558    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1559        #[cfg(test)]
1560        if let Some(pause) = self
1561            .activity_request_pause
1562            .lock()
1563            .unwrap()
1564            .as_ref()
1565            .filter(|pause| pause.connection == connection_id)
1566        {
1567            pause
1568                .cleanup_started
1569                .store(true, std::sync::atomic::Ordering::Release);
1570        }
1571        if let Some(runtime) = &self.config_runtime {
1572            runtime.disconnected(connection_id);
1573        }
1574        self.agent_declarations.close(connection_id);
1575        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
1576            self.registry
1577                .get_module_by_connection(connection_id)?
1578                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
1579                .and_then(|module| module.registration_end_reason().ok().flatten())
1580                .unwrap_or(requested_reason)
1581        } else {
1582            requested_reason
1583        };
1584        let crash_closed = self
1585            .registry
1586            .get_module_by_connection(connection_id)?
1587            .and_then(|registration| {
1588                self.forwarding
1589                    .module_endpoint_for_connection(connection_id)
1590                    .ok()
1591                    .flatten()
1592                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
1593                    .map(|routes| (registration.manifest.module_id, routes))
1594            });
1595        let crash_closed = crash_closed.map(|(module_id, routes)| {
1596            let terminal = match self.supervisor.get(&module_id) {
1597                None => false,
1598                Some(module) => match module.will_recover_after_connection_loss() {
1599                    Ok(will_recover) => !will_recover,
1600                    Err(err) => {
1601                        warn!(
1602                            %module_id,
1603                            error = %err,
1604                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
1605                        );
1606                        false
1607                    }
1608                },
1609            };
1610            // The forwarding table gates all providers at the start of daemon
1611            // shutdown, before their connections are closed. An ordinary
1612            // module disconnect still reports crash if that gate is not set.
1613            let (reason, drained) = match self
1614                .forwarding
1615                .daemon_drain_result_for_connection(connection_id)
1616            {
1617                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
1618                Ok(None) => (RouteCloseReason::Crash, false),
1619                Err(err) => {
1620                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
1621                    (RouteCloseReason::Crash, false)
1622                }
1623            };
1624            (module_id, routes, reason, drained, terminal)
1625        });
1626        let registrations = self.deregister_connection(connection_id, end_reason);
1627        // Read before teardown: the spawn whose registration this connection
1628        // was. Its registration ending is an authority change for it.
1629        let ended_authority = self
1630            .forwarding
1631            .target_authority_for_connection(connection_id)
1632            .ok()
1633            .flatten();
1634        let cleanup = if crash_closed.is_some() {
1635            self.forwarding.cleanup_connection_counted(connection_id)
1636        } else {
1637            // A module connection's teardown needs the count of abandoned
1638            // route.bind relays for its route.closed notice below. Any other
1639            // connection, such as a client's, sends no such notice and needs
1640            // only its routes released, so it uses the route-only wrapper and
1641            // reports zero.
1642            self.forwarding
1643                .cleanup_connection(connection_id)
1644                .map(|released| crate::forwarding::ConnectionCleanup {
1645                    released,
1646                    abandoned_relays: 0,
1647                })
1648        };
1649        // The route.closed push waits for forwarding teardown because only
1650        // teardown knows how many pending route.bind relays it aborted. It still
1651        // goes out before the GOODBYEs for the released routes, and its targets
1652        // were captured above, before teardown removed those routes.
1653        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
1654            let abandoned = cleanup
1655                .as_ref()
1656                .map_or(0, |cleanup| cleanup.abandoned_relays);
1657            send_route_control_pushes(
1658                &self.forwarding,
1659                routes,
1660                ClientControlPush::RouteClosed {
1661                    module_id,
1662                    channels: Vec::new(),
1663                    reason,
1664                    drained,
1665                    abandoned,
1666                    excluded_subscriptions: 0,
1667                    terminal: Some(terminal),
1668                },
1669            );
1670        }
1671        if let Ok(cleanup) = cleanup {
1672            self.emit_route_goodbyes(cleanup.released);
1673        }
1674        if let Some(record) = ended_authority {
1675            self.change_spawn_authority(&record);
1676        }
1677        // Signal the registration-release watch only now that BOTH registry and
1678        // forwarding teardown are done, so a supervisor waiting to spawn a
1679        // replacement never observes release while old routes still exist.
1680        if matches!(&registrations, Ok(r) if !r.is_empty()) {
1681            crate::supervise::notify_registration_release();
1682            self.capability_evaluator.wake_deadline_loop();
1683            self.refresh_capability_requirements();
1684        }
1685        self.supervisor.remove_spawn_subscribers(connection_id);
1686        self.activity_streams
1687            .lock()
1688            .unwrap_or_else(|p| p.into_inner())
1689            .retain(|(id, _), task| {
1690                if *id == connection_id {
1691                    task.abort();
1692                    false
1693                } else {
1694                    true
1695                }
1696            });
1697        // Sync authority dies with its connection, so the owner's next
1698        // connection can take it; the owner's scopes stay as they are.
1699        self.hello_launch_nonces
1700            .lock()
1701            .unwrap_or_else(|poisoned| poisoned.into_inner())
1702            .forget(connection_id);
1703        self.scopes
1704            .write()
1705            .unwrap_or_else(|poisoned| poisoned.into_inner())
1706            .release_connection(connection_id);
1707        registrations
1708    }
1709
1710    pub(crate) fn handle_route_goodbye(
1711        &self,
1712        connection_id: ConnectionId,
1713        route_channel: u16,
1714        route_epoch: u32,
1715    ) -> Result<bool, RouterError> {
1716        debug!(
1717            connection_id = connection_id.get(),
1718            route_channel, route_epoch, "handling route GOODBYE"
1719        );
1720        let RouteRelease::Removed(released_route) = self
1721            .forwarding
1722            .release_client_route(connection_id, route_channel, route_epoch)
1723            .map_err(RouterError::Forwarding)?
1724        else {
1725            return Ok(false);
1726        };
1727        self.emit_route_goodbyes(vec![released_route]);
1728        Ok(true)
1729    }
1730
1731    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
1732        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
1733    }
1734
1735    async fn handle_client_control_request(
1736        &self,
1737        ctx: &RouteCtx,
1738        frame: Frame,
1739        request: ClientControlRequest,
1740        route_open_timings: &mut Option<RouteOpenTimings>,
1741    ) -> Result<Vec<Frame>, RouterError> {
1742        if let Some(owner) = &self.config_runtime {
1743            let module = match &request {
1744                ClientControlRequest::SupervisorRestart { module_id, .. }
1745                | ClientControlRequest::SupervisorReload { module_id }
1746                | ClientControlRequest::SupervisorSwap { module_id, .. }
1747                | ClientControlRequest::SupervisorSetEnabled {
1748                    module_id,
1749                    enabled: true,
1750                } => Some(module_id.as_str()),
1751                _ => None,
1752            };
1753            let rescan = matches!(
1754                &request,
1755                ClientControlRequest::SupervisorRescan { preview: false }
1756                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
1757            );
1758            let held = if module.is_some() || rescan {
1759                let module = module.map(str::to_owned);
1760                owner
1761                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
1762                    .await
1763            } else {
1764                Ok(())
1765            };
1766            if let Err(error) = held {
1767                if error.code != "config_delivery_deferred" {
1768                    let code = if error.code == "store_tampered" {
1769                        "store_tampered"
1770                    } else {
1771                        "config_gated"
1772                    };
1773                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
1774                }
1775            }
1776        }
1777        if let Some(operation) = privileged_operation(&request) {
1778            let caller = self.resolve_caller(ctx.connection_id).await;
1779            let op = client_control_request_op(&request);
1780            let text = prompt_text(operation, &caller);
1781            match self.privileged_operator_prompt {
1782                PrivilegedOperatorPrompt::Log => {
1783                    info!(target: "subc_daemon::privileged_prompt", operation = op,
1784                        target = ?operation, caller = %caller.description(), summary = %text,
1785                        "privileged request would prompt the operator");
1786                }
1787                PrivilegedOperatorPrompt::Enforce => {
1788                    let key =
1789                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1790                    let shortcut =
1791                        self.operator_shortcut_stamp(ctx.connection_id)
1792                            .await
1793                            .map(|stamp| {
1794                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
1795                            });
1796                    let outcome = self
1797                        .forwarding
1798                        .operator_confirms()
1799                        .approve_privileged_with_shortcut(
1800                            ctx,
1801                            &frame,
1802                            op,
1803                            text,
1804                            caller.description(),
1805                            key,
1806                            shortcut,
1807                        )
1808                        .await;
1809                    if outcome.code != "confirmed" {
1810                        return Ok(vec![outcome.frame(&frame)]);
1811                    }
1812                }
1813            }
1814        }
1815        match request {
1816            ClientControlRequest::DaemonShutdownIntent { intent } => {
1817                if intent.as_str() != Some("restart") {
1818                    return Ok(vec![control_error_frame(
1819                        &frame,
1820                        "invalid_params",
1821                        "intent must be 'restart'",
1822                    )?]);
1823                }
1824                // A stamped daemon boots a newer approved generation only from a
1825                // durable restart intent, written here before the daemon exits.
1826                // Failing to write it never blocks the restart: the next start
1827                // then boots the last active generation and the newer one waits.
1828                if let Some(owner) = &self.config_runtime {
1829                    match owner
1830                        .on_blocking(|owner| owner.assign_daemon_restart())
1831                        .await
1832                    {
1833                        Ok(Some(generation)) => {
1834                            info!(
1835                                generation,
1836                                "daemon restart will warm up approved generation"
1837                            )
1838                        }
1839                        Ok(None) => {}
1840                        Err(error) => warn!(
1841                            %error,
1842                            "daemon restart intent not recorded; the next start boots the last active generation"
1843                        ),
1844                    }
1845                }
1846                let response = ClientControlResponse::DaemonShutdownIntent {
1847                    intent: "restart".to_owned(),
1848                    expires_at_ms: self.supervisor.announce_daemon_restart(),
1849                };
1850                Ok(vec![control_response_body_frame(
1851                    &frame,
1852                    &response,
1853                    "ClientControlResponse::DaemonShutdownIntent",
1854                )?])
1855            }
1856            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
1857            ClientControlRequest::PolicyRoot(_)
1858            | ClientControlRequest::PolicyRootSet(_)
1859            | ClientControlRequest::PolicyRootRecover(_) => {
1860                unreachable!("policy root ops dispatch before the client-only path")
1861            }
1862            ClientControlRequest::CatalogList { module_id } => {
1863                self.handle_catalog_list(frame, module_id)
1864            }
1865            ClientControlRequest::RouteOpen {
1866                target,
1867                identity,
1868                consumer_identity,
1869                consumer_capabilities,
1870                role_versions,
1871                busy_refusals,
1872                admission_facts,
1873                scope,
1874                ..
1875            } => {
1876                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
1877                    &frame.body,
1878                ) {
1879                    Ok(extensions) => extensions,
1880                    Err(err) => {
1881                        return Ok(vec![control_error_frame(
1882                            &frame,
1883                            "invalid_control_body",
1884                            format!("malformed route.open extensions: {err}"),
1885                        )?]);
1886                    }
1887                };
1888                self.handle_route_open(
1889                    ctx,
1890                    frame,
1891                    RouteOpenRequest {
1892                        target,
1893                        identity,
1894                        consumer_identity,
1895                        consumer_capabilities,
1896                        role_versions,
1897                        busy_refusals,
1898                        admission_facts,
1899                        scope,
1900                        accepts_close_reasons: extensions.accepts_close_reasons,
1901                    },
1902                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
1903                )
1904                .await
1905            }
1906            ClientControlRequest::RoutePoll {
1907                route_channel,
1908                route_epoch,
1909                kind,
1910            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
1911            ClientControlRequest::SupervisorList {} => {
1912                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
1913                    self.agent_declarations.refuse(
1914                        self,
1915                        ctx,
1916                        control_error_frame(
1917                            &frame,
1918                            "busy",
1919                            "supervisor list work is at capacity; retry",
1920                        )?,
1921                    );
1922                    return Ok(Vec::new());
1923                };
1924                // Filesystem-backed diagnostics must not hold up this connection's reader.
1925                let handler = self.clone();
1926                let sink = ctx.egress.clone();
1927                tokio::spawn(
1928                    async move {
1929                        let _permit = permit;
1930                        let result = handler.handle_supervisor_list(frame.clone()).await;
1931                        let replies = match result {
1932                            Ok(replies) => replies,
1933                            Err(error) => {
1934                                control_error_frame(&frame, "backend_error", error.to_string())
1935                                    .into_iter()
1936                                    .collect()
1937                            }
1938                        };
1939                        for reply in replies {
1940                            if !matches!(
1941                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
1942                                    .await,
1943                                Ok(Ok(()))
1944                            ) {
1945                                break;
1946                            }
1947                        }
1948                    }
1949                    .with_current_subscriber(),
1950                );
1951                Ok(Vec::new())
1952            }
1953            ClientControlRequest::SupervisorSpawnSnapshot {} => {
1954                self.handle_supervisor_spawn_snapshot(frame)
1955            }
1956            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
1957                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
1958            }
1959            ClientControlRequest::SupervisorRestart {
1960                module_id,
1961                drain_timeout_ms,
1962            } => {
1963                self.log_supervisor_request_received(
1964                    ctx,
1965                    frame.header.corr,
1966                    ops::SUPERVISOR_RESTART,
1967                    Some(&module_id),
1968                    None,
1969                )?;
1970                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
1971                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
1972                    .await
1973            }
1974            ClientControlRequest::SupervisorSwap {
1975                module_id,
1976                ready_timeout_ms,
1977            } => {
1978                self.log_supervisor_request_received(
1979                    ctx,
1980                    frame.header.corr,
1981                    ops::SUPERVISOR_SWAP,
1982                    Some(&module_id),
1983                    None,
1984                )?;
1985                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
1986                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
1987                    .await
1988            }
1989            ClientControlRequest::SupervisorReload { module_id } => {
1990                self.log_supervisor_request_received(
1991                    ctx,
1992                    frame.header.corr,
1993                    ops::SUPERVISOR_RELOAD,
1994                    Some(&module_id),
1995                    None,
1996                )?;
1997                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
1998                self.handle_supervisor_reload(frame, module_id, requester)
1999                    .await
2000            }
2001            ClientControlRequest::SupervisorRescan { preview } => {
2002                if !preview {
2003                    self.log_supervisor_request_received(
2004                        ctx,
2005                        frame.header.corr,
2006                        ops::SUPERVISOR_RESCAN,
2007                        None,
2008                        None,
2009                    )?;
2010                }
2011                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2012                let operation = self.handle_supervisor_rescan(
2013                    frame,
2014                    if preview {
2015                        RescanMode::Preview
2016                    } else {
2017                        RescanMode::Execute
2018                    },
2019                    requester,
2020                );
2021                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
2022                    .await
2023            }
2024            ClientControlRequest::SupervisorRescanChecked {
2025                preview,
2026                candidate,
2027                expect,
2028            } => {
2029                self.observe_control_wait(
2030                    ctx,
2031                    None,
2032                    ops::SUPERVISOR_RESCAN,
2033                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
2034                )
2035                .await
2036            }
2037            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2038                self.log_supervisor_request_received(
2039                    ctx,
2040                    frame.header.corr,
2041                    ops::SUPERVISOR_RELEASE_RESERVED,
2042                    Some(&module_id),
2043                    None,
2044                )?;
2045                self.handle_supervisor_release_reserved(frame, module_id)
2046                    .await
2047            }
2048            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2049                self.log_supervisor_request_received(
2050                    ctx,
2051                    frame.header.corr,
2052                    ops::SUPERVISOR_SET_ENABLED,
2053                    Some(&module_id),
2054                    Some(enabled),
2055                )?;
2056                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2057                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
2058                    .await
2059            }
2060            ClientControlRequest::SupervisorHealthProbe { module_id } => {
2061                self.handle_supervisor_health_probe(ctx, frame, module_id)
2062                    .await
2063            }
2064            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
2065            ClientControlRequest::SupervisorRoutes { module_id } => {
2066                self.handle_supervisor_routes(frame, module_id)
2067            }
2068            ClientControlRequest::SupervisorProvenance { module_id } => {
2069                self.handle_supervisor_provenance(ctx, frame, module_id)
2070                    .await
2071            }
2072            ClientControlRequest::SupervisorStderrTail {
2073                module_id,
2074                max_lines,
2075                max_bytes,
2076            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
2077            ClientControlRequest::SupervisorTerminals { module_id } => {
2078                self.handle_supervisor_terminals(ctx, frame, module_id)
2079                    .await
2080            }
2081        }
2082    }
2083
2084    /// Explicit test-only phone policy; daemon configuration cannot select it.
2085    #[cfg(any(test, feature = "test-support"))]
2086    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
2087        self.operator_app_policy.phone_enabled = enabled;
2088        self
2089    }
2090
2091    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
2092        debug!(connection_id = connection_id.get(), "handling GOODBYE");
2093        // GOODBYE ends the connection's logical session even when its socket
2094        // stays open. Use disconnect teardown so verdicts, client notices and
2095        // scope authority are released at the same lifecycle boundary.
2096        self.cleanup_connection_with_end_reason(
2097            connection_id,
2098            RegistrationEndReason::ExplicitGoodbye,
2099        )
2100        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
2101        Ok(Vec::new())
2102    }
2103}
2104
2105impl Default for ControlHandler {
2106    fn default() -> Self {
2107        Self::new(Arc::new(Registry::default()))
2108    }
2109}
2110
2111impl crate::supervise::SwapPromotionObserver for ControlHandler {
2112    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
2113        self.apply_registration_capabilities(registration);
2114    }
2115}
2116
2117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2118enum ControlRequestBodyError {
2119    UnknownOp,
2120    InvalidBody,
2121}
2122
2123#[derive(Debug, Deserialize)]
2124struct ControlOpProbe {
2125    op: String,
2126}
2127
2128fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
2129    debug!(
2130        op = %op,
2131        connection_id = connection_id.get(),
2132        corr,
2133        "control dispatch"
2134    );
2135}
2136
2137fn log_slow_control_dispatch(
2138    dispatch_started_at: Option<StdInstant>,
2139    op: &'static str,
2140    connection_id: ConnectionId,
2141    corr: u64,
2142    route_open_timings: Option<&RouteOpenTimings>,
2143) {
2144    let Some(dispatch_started_at) = dispatch_started_at else {
2145        return;
2146    };
2147    // Use the same monotonic clock as the phase timers and relay deadline.
2148    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
2149    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
2150        if let Some(timings) = route_open_timings {
2151            warn!(
2152                op = %op,
2153                connection_id = connection_id.get(),
2154                corr,
2155                elapsed_ms = elapsed.as_millis() as u64,
2156                module_id = ?timings.module_id,
2157                principal = %timings.principal,
2158                admission_ms = timings.admission.as_millis() as u64,
2159                project_root_ms = timings.project_root.as_millis() as u64,
2160                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
2161                bind_send_ms = timings.bind_send.as_millis() as u64,
2162                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
2163                "slow control dispatch"
2164            );
2165            return;
2166        }
2167        warn!(
2168            op = %op,
2169            connection_id = connection_id.get(),
2170            corr,
2171            elapsed_ms = elapsed.as_millis() as u64,
2172            "slow control dispatch"
2173        );
2174    }
2175}
2176
2177/// A test stand-in for the OS caller lookup, given the recorded endpoints.
2178#[cfg(test)]
2179type TestCallerLookup =
2180    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
2181
2182/// Every new client operation needs an explicit privilege decision here.
2183fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
2184    request.privileged_operation()
2185}
2186
2187trait PrivilegedRequest {
2188    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
2189}
2190
2191impl PrivilegedRequest for ClientControlRequest {
2192    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
2193        let request = self;
2194        match request {
2195        ClientControlRequest::SupervisorRestart { module_id, .. } => {
2196            Some(PrivilegedOperation::Restart { module_id })
2197        }
2198        ClientControlRequest::SupervisorSwap { module_id, .. } => {
2199            Some(PrivilegedOperation::Swap { module_id })
2200        }
2201        ClientControlRequest::SupervisorReload { module_id } => {
2202            Some(PrivilegedOperation::Reload { module_id })
2203        }
2204        ClientControlRequest::SupervisorRescan { preview } => {
2205            if *preview {
2206                None
2207            } else {
2208                Some(PrivilegedOperation::Rescan)
2209            }
2210        }
2211        // Only the well-formed apply asks for approval. A preview changes
2212        // nothing, and any other combination is refused before it touches
2213        // anything, so prompting the operator for it would ask about a request
2214        // that cannot run.
2215        ClientControlRequest::SupervisorRescanChecked {
2216            preview,
2217            candidate,
2218            expect,
2219        } => (!*preview && candidate.is_none() && expect.is_some())
2220            .then_some(PrivilegedOperation::Rescan),
2221        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2222            Some(PrivilegedOperation::SetEnabled {
2223                module_id,
2224                enabled: *enabled,
2225            })
2226        }
2227        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2228            Some(PrivilegedOperation::ReleaseReserved { module_id })
2229        }
2230        ClientControlRequest::ServerDescribe {}
2231        | ClientControlRequest::PolicyRoot(_)
2232        | ClientControlRequest::PolicyRootSet(_)
2233        | ClientControlRequest::PolicyRootRecover(_)
2234        // The announcement uses the same client admission as supervisor.restart,
2235        // but cannot stop anything itself and needs no operator confirmation.
2236        | ClientControlRequest::DaemonShutdownIntent { .. }
2237        | ClientControlRequest::CatalogList { .. }
2238        | ClientControlRequest::RouteOpen { .. }
2239        | ClientControlRequest::RoutePoll { .. }
2240        | ClientControlRequest::SupervisorList {}
2241        | ClientControlRequest::SupervisorHealth {}
2242        | ClientControlRequest::SupervisorHealthProbe { .. }
2243        | ClientControlRequest::SupervisorRoutes { .. }
2244        | ClientControlRequest::SupervisorProvenance { .. }
2245        | ClientControlRequest::SupervisorStderrTail { .. }
2246        | ClientControlRequest::SupervisorTerminals { .. }
2247        | ClientControlRequest::SupervisorSpawnSnapshot {}
2248        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
2249    }
2250    }
2251}
2252
2253fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
2254    match request {
2255        ClientControlRequest::PolicyRoot(_) => subc_protocol::policy_root::GET_OP,
2256        ClientControlRequest::PolicyRootSet(_) => subc_control::policy_root::SET_OP,
2257        ClientControlRequest::PolicyRootRecover(_) => subc_control::policy_root::RECOVER_OP,
2258        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
2259        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
2260        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
2261        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
2262        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
2263        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
2264        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
2265        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
2266        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
2267        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
2268        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
2269        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
2270        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
2271        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
2272        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
2273        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
2274        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
2275        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
2276        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
2277        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
2278        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
2279    }
2280}
2281
2282fn parse_client_control_request(
2283    body: &[u8],
2284) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
2285    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
2286        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
2287            Ok(probe)
2288                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
2289                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
2290            {
2291                ControlRequestBodyError::InvalidBody
2292            }
2293            Ok(_) => ControlRequestBodyError::UnknownOp,
2294            Err(_) => ControlRequestBodyError::InvalidBody,
2295        };
2296        (err, classification)
2297    })
2298}
2299
2300fn pong(frame: &Frame) -> Result<Frame, RouterError> {
2301    Frame::build_with_version(
2302        response_version(frame),
2303        FrameType::Pong,
2304        frame.header.flags,
2305        0,
2306        0,
2307        frame.header.corr,
2308        Vec::new(),
2309    )
2310    .map_err(RouterError::FrameBuild)
2311}
2312
2313pub(crate) fn control_error_frame(
2314    frame: &Frame,
2315    code: &'static str,
2316    message: impl Into<String>,
2317) -> Result<Frame, RouterError> {
2318    control_error_body_frame(
2319        frame,
2320        ErrorBody {
2321            code: code.to_string(),
2322            message: message.into(),
2323            detail: None,
2324        },
2325    )
2326}
2327
2328/// A channel-0 ERROR for a refusal the daemon decided itself: every
2329/// route.open refusal, the drain `module_reloading` and scope-change/end
2330/// bodies, spawn-subscription and supervisor refusals. Carries the
2331/// daemon-origin bit, which is what lets a client treat `module_reloading`
2332/// as proof that its request never reached a module. Response, push,
2333/// goodbye and relay-request frames keep the plain control flags in their
2334/// own builders.
2335pub(crate) fn control_error_body_frame(
2336    frame: &Frame,
2337    error: ErrorBody,
2338) -> Result<Frame, RouterError> {
2339    control_error_frame_with_flags(frame, error, daemon_error_flags())
2340}
2341
2342/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
2343/// refused route.bind answered as a route.open refusal, or a refused
2344/// module-control RPC. Plain control flags — the code and message are
2345/// module-chosen, so the frame must not claim daemon authorship, even when
2346/// the module picks a daemon code like `module_reloading`.
2347fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
2348    control_error_frame_with_flags(frame, error, control_flags())
2349}
2350
2351fn control_error_frame_with_flags(
2352    frame: &Frame,
2353    error: ErrorBody,
2354    flags: Flags,
2355) -> Result<Frame, RouterError> {
2356    let body = serde_json::to_vec(&error).map_err(|err| {
2357        RouterError::backend(
2358            0,
2359            frame.header.corr,
2360            format!("failed to encode control ERROR: {err}"),
2361        )
2362    })?;
2363
2364    Frame::build_with_version(
2365        response_version(frame),
2366        FrameType::Error,
2367        flags,
2368        0,
2369        0,
2370        frame.header.corr,
2371        body,
2372    )
2373    .map_err(RouterError::FrameBuild)
2374}
2375
2376pub(crate) fn control_response_body_frame<T: Serialize>(
2377    frame: &Frame,
2378    reply: &T,
2379    label: &'static str,
2380) -> Result<Frame, RouterError> {
2381    let body = serde_json::to_vec(reply).map_err(|err| {
2382        RouterError::backend(
2383            0,
2384            frame.header.corr,
2385            format!("failed to encode {label}: {err}"),
2386        )
2387    })?;
2388
2389    Frame::build_with_version(
2390        response_version(frame),
2391        FrameType::Response,
2392        control_flags(),
2393        0,
2394        0,
2395        frame.header.corr,
2396        body,
2397    )
2398    .map_err(RouterError::FrameBuild)
2399}
2400
2401fn forwarding_error_code(err: &ForwardingError) -> &'static str {
2402    match err {
2403        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
2404        ForwardingError::NoModuleConnection => "target_unavailable",
2405        ForwardingError::ModuleReloading { .. } => "module_reloading",
2406        ForwardingError::ClientRouteChannelExhausted { .. }
2407        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
2408        ForwardingError::StaleModuleEndpoint
2409        | ForwardingError::UnknownReservation { .. }
2410        | ForwardingError::ConnectionClosing { .. }
2411        | ForwardingError::ClientEgressClosed { .. }
2412        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
2413        // Only a swap candidate's registration can produce this, and it means
2414        // exactly what a second active HELLO for a live id means.
2415        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
2416        ForwardingError::TargetRegistrationChanged(_) => "capability_forbidden",
2417        ForwardingError::RelayDeadlineElapsed => "module_timeout",
2418        ForwardingError::RelayCorrelationExhausted
2419        | ForwardingError::RouteOpenBuild(_)
2420        | ForwardingError::Poisoned => "forwarding_error",
2421    }
2422}
2423
2424fn response_version(frame: &Frame) -> u8 {
2425    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
2426        frame.header.ver
2427    } else {
2428        PROTOCOL_VERSION
2429    }
2430}
2431
2432pub(crate) fn control_flags() -> Flags {
2433    Flags::new(false, Priority::Passive, false)
2434}
2435
2436/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
2437/// channel. The target is the module (a client never saw the route), so this
2438/// takes the module path: delivered late rather than dropped when the module's
2439/// queue is momentarily full, and never closing its connection.
2440fn send_goodbye_target_best_effort(
2441    counters: &DaemonCounters,
2442    target: &GoodbyeTarget,
2443    context: &'static str,
2444) {
2445    let Ok(frame) = Frame::build_with_version(
2446        target.negotiated_ver,
2447        FrameType::Goodbye,
2448        control_flags(),
2449        target.channel,
2450        target.epoch,
2451        0,
2452        Vec::new(),
2453    ) else {
2454        return;
2455    };
2456    crate::forwarding::send_module_route_goodbye(
2457        counters,
2458        &target.sink,
2459        frame,
2460        target.module_id.as_deref(),
2461        context,
2462    );
2463}
2464
2465fn route_close_reason_for_opener(
2466    reason: RouteCloseReason,
2467    accepts_close_reasons: Option<&[String]>,
2468) -> RouteCloseReason {
2469    if reason == RouteCloseReason::AuthorityChanged
2470        && !accepts_close_reasons
2471            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
2472    {
2473        // Older readers forbid reopening for unknown reasons. Reload already
2474        // permits reopening and, like an authority change, requires a new bind.
2475        RouteCloseReason::Reload
2476    } else {
2477        reason
2478    }
2479}
2480
2481pub(crate) fn send_route_control_pushes(
2482    forwarding: &ForwardingTable,
2483    routes: Vec<EndpointRoute>,
2484    push: ClientControlPush,
2485) {
2486    let reason = match &push {
2487        ClientControlPush::RouteClosing { reason, .. }
2488        | ClientControlPush::RouteClosed { reason, .. } => *reason,
2489    };
2490    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
2491    for route in routes {
2492        let recipient_reason =
2493            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
2494        let target = route.goodbye_target;
2495        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
2496            existing.connection_id == target.connection_id && *reason == recipient_reason
2497        }) {
2498            debug_assert_eq!(
2499                existing.negotiated_ver, target.negotiated_ver,
2500                "one connection cannot negotiate multiple frame versions"
2501            );
2502            if !channels.contains(&target.channel) {
2503                channels.push(target.channel);
2504            }
2505            continue;
2506        }
2507        let channel = target.channel;
2508        targets.push((target, recipient_reason, vec![channel]));
2509    }
2510    for (target, recipient_reason, mut channels) in targets {
2511        channels.sort_unstable();
2512        let mut push = push.clone();
2513        match &mut push {
2514            ClientControlPush::RouteClosing {
2515                channels: covered,
2516                reason,
2517                ..
2518            }
2519            | ClientControlPush::RouteClosed {
2520                channels: covered,
2521                reason,
2522                ..
2523            } => {
2524                *covered = channels;
2525                *reason = recipient_reason;
2526            }
2527        }
2528        let body = match serde_json::to_vec(&push) {
2529            Ok(body) => body,
2530            Err(err) => {
2531                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
2532                continue;
2533            }
2534        };
2535        let frame = match Frame::build_with_version(
2536            target.negotiated_ver,
2537            FrameType::Push,
2538            control_flags(),
2539            0,
2540            0,
2541            0,
2542            body.clone(),
2543        ) {
2544            Ok(frame) => frame,
2545            Err(err) => {
2546                warn!(
2547                    route_channel = target.channel,
2548                    error = %err,
2549                    "failed to build route lifecycle control PUSH frame"
2550                );
2551                continue;
2552            }
2553        };
2554        if let Err(err) = target.sink.try_send(frame) {
2555            if target.close_on_delivery_failure() {
2556                warn!(
2557                    target_connection_id = target.connection_id.get(),
2558                    route_channel = target.channel,
2559                    error = %err,
2560                    "route lifecycle control PUSH was not delivered to client; closing target connection"
2561                );
2562                let _ = forwarding.escalate_client_delivery_failure(
2563                    target.connection_id,
2564                    target.channel,
2565                    target.epoch,
2566                    CloseReason::new(
2567                        "route_lifecycle_push_delivery_failed",
2568                        format!(
2569                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
2570                            target.channel
2571                        ),
2572                    ),
2573                    crate::forwarding::UndeliveredFrame {
2574                        module_id: target.module_id.as_deref(),
2575                        sink: &target.sink,
2576                    },
2577                );
2578            }
2579        }
2580    }
2581}
2582
2583#[cfg(test)]
2584#[path = "control/scope_outcome_count_tests.rs"]
2585mod scope_outcome_count_tests;
2586
2587#[cfg(test)]
2588#[path = "control/control_tests.rs"]
2589mod tests;
2590
2591#[cfg(test)]
2592#[path = "control/concurrency_default_exposure_tests.rs"]
2593mod concurrency_default_exposure_tests;