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