1#![forbid(unsafe_code)]
2
3pub mod activity;
4mod agent_commands;
5pub mod config;
6mod control_ops;
7mod live_upgrade;
8pub use agent_commands::AgentCommandsError;
9#[cfg(any(test, feature = "test-support"))]
10use live_upgrade::connection_serve_future_with_options;
11use live_upgrade::register_connection;
12#[cfg(test)]
13use live_upgrade::registration_channel_exit_code;
14pub use live_upgrade::ResumeScopeSync;
15pub use subc_protocol::session::{AgentCommandFinished, AgentCommandRoot};
16pub mod consumer;
17mod operator_app;
18pub mod policy_cache;
19#[cfg(any(test, feature = "test-support"))]
20mod stand_in;
21#[cfg(feature = "test-support")]
22pub mod test_support;
23pub use activity::*;
24pub use consumer::{
25 is_retryable_route_open_code, AppOpenError, CallError, CallOptions, CallReply, CancelHandle,
26 CancelOutcome, CatalogList, CatalogSubscription, CloseRouteOptions, ConfigApplyResponse,
27 ConfigEdit, ConfigEditAction, ConfigFileError, ConfigFileErrorLayer, ConfigModule,
28 ConfigModulesResponse, ConfigPlanRefusal, ConfigPlanView, ConfigSchemaResponse,
29 ConfigSettingsLayer, ConfigShowResponse, ConfigStatus, ConfigSubscription, ConfigThrough,
30 ConfigWatchEvent, ConnectionFacts, ConnectionState, ConsumerCapabilityError, ConsumerError,
31 ConsumerOptions, ControlPush, CorrelationId, Digest, HealthProbeResponse, NotSentCause,
32 OutcomeUnknownCause, PendingReply, PushEvent, RequestBody, RequestReservation, RetryBackoff,
33 ReverseRequestContext, ReverseRequestError, ReverseRequestRegistrationError,
34 ReverseRequestRegistry, RouteCloseDisposition, RouteCloseReason, RouteEndReason,
35 RouteOpenTarget, RouteOpenTargetKind, RoutePollResult, ScopeBindProofRefusal, ScopeSelector,
36 ServerDescription, SpawnStreamError, SpawnSubscription, StderrTailResponse, SubcConsumer,
37 SubscribeOptions, Subscription, SubscriptionClosed, SubscriptionEnd, SupervisorAck,
38 SupervisorEntry, SupervisorHealthResponse, SupervisorListResponse,
39 SupervisorProvenanceResponse, ACCEPTED_CLOSE_REASONS, DEFAULT_CALL_TIMEOUT,
40 DEFAULT_LIVENESS_PROBE_WINDOW, DEFAULT_ROUTE_RETRY_DEADLINE, SPAWN_CURSOR_INCARNATION_MISMATCH,
41 SPAWN_CURSOR_TOO_OLD, SPAWN_SUBSCRIBER_LAGGED,
42};
43pub use operator_app::{operator_app_candidates, operator_app_path, OperatorAppPathError};
44pub use policy_cache::{
45 PolicyResolveError, PolicyResolver, PolicyResolverConfig, PolicyResolverFootprint,
46 PolicyVerdict, ProjectRef, Subject, DEFAULT_POLICY_RESOLVER_MODULE_ID,
47};
48pub use subc_control::{AppOpenReply, AppOpenStatus, CatalogOrigin, CatalogWatchResponse};
49pub use subc_control::{
50 ScopeRef, ScopeWatchEvent, ScopeWatchPush, ScopeWatchResponse, ScopeWatchSelector,
51 ScopeWatchState, ScopeWatchStatus,
52};
53
54mod module_subscription;
55pub use module_subscription::ScopeSubscription;
56
57use std::{
58 collections::{BTreeMap, HashMap, VecDeque},
59 env,
60 error::Error,
61 ffi::OsString,
62 fmt,
63 future::Future,
64 io,
65 panic::{catch_unwind, AssertUnwindSafe},
66 path::{Path, PathBuf},
67 pin::Pin,
68 sync::{
69 atomic::{AtomicBool, AtomicU64, Ordering},
70 Arc, Mutex,
71 },
72 time::{Duration, SystemTime, UNIX_EPOCH},
73};
74
75pub use async_trait::async_trait;
76pub use subc_control::{CatalogEntry, ConsumerIdentity};
77mod scope_served_by;
78pub use scope_served_by::{ScopeServedByAnswer, ScopeServedByReply};
79pub mod registration;
80mod route_authorize;
81pub use route_authorize::{
82 RouteAuthorizeExpected, RouteAuthorizeOutcome, RouteAuthorizeResponse, RouteAuthorizeScope,
83};
84mod request_pools;
85pub use registration::ClaimError;
86use request_pools::{wait_for_permit, DispatchPools, PermitWaitOutcome, WaitingRequest};
87pub use request_pools::{RequestClass, RequestPool, RequestPoolSnapshot, RequestPools};
88pub use subc_os::launch_nonce;
95use subc_protocol::{
96 call_mode::derive_call_mode,
97 error_codes,
98 manifest::ModuleManifest,
99 scope::{
100 ScopeEnd, ScopeEndResult, ScopeEnded, ScopeRecord, ScopeRecordResult, ScopeStamp,
101 ScopeStatus, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP, SCOPE_SYNC_OP,
102 },
103 session::{
104 ModuleControlCommand, ModuleControlRequest, ModuleControlRequestFromModule,
105 ModuleControlResponse, ModuleControlResponseToModule, OperatorConfirmKind,
106 OperatorConfirmReply, OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK,
107 MODULE_TO_SUBC_OP_CATALOG_UPDATE, MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS,
108 },
109 BindIdentity, ErrorBody, Flags, Frame, FrameBuildError, FrameType, ModuleHelloAckBody,
110 ModuleHelloBody, Principal, Priority, RouteTarget, PROTOCOL_VERSION, SUBC_MODULE_ID_ENV,
111};
112pub use subc_protocol::{
113 call_mode::{CallMode, CALL_MODES_CAPABILITY},
114 manifest::{
115 build_provenance, CapabilityDeclarations, CapabilityNeed, CapabilityRequirement,
116 ExecutionMode, LaunchNonceSource, ManifestProvenance, ProvenanceFormError, ProviderRole,
117 Tool, PROVENANCE_SENTINELS,
118 },
119 session::{HealthReport, HealthStatus},
120 AdmissionClass, MachineId, SUBC_PROTOCOL_CRATE_VERSION,
121};
122pub use subc_transport::connection_file::{
123 discover, discovery_candidates, Discovered, DiscoveryError,
124};
125
126use subc_transport::{
127 authenticate_client, connection_file, read_frame, write_frame, AuthError, ConnectionFileError,
128 FrameIoError,
129};
130use tokio::{
131 io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufWriter},
132 net::TcpStream,
133 sync::{mpsc, oneshot},
134 time::{timeout, timeout_at, Instant},
135};
136use tokio_util::{
137 sync::{CancellationToken, WaitForCancellationFuture},
138 task::TaskTracker,
139};
140
141const AUTH_DEADLINE: Duration = Duration::from_secs(2);
142const CATALOG_UPDATE_TIMEOUT: Duration = Duration::from_secs(10);
143const OPERATOR_CONFIRM_TIMEOUT: Duration = Duration::from_secs(290);
144const OPERATOR_CONFIRM_OP: &str = "operator.confirm";
145const EGRESS_BUFFER: usize = 64;
146const HANDLER_TASK_CAPACITY: usize = 64;
147const DISPATCH_SATURATION_WAIT: Duration = Duration::from_secs(2);
150const HELLO_CORR: u64 = 1;
151const DEFAULT_WRITER_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
152const DRAINING_HOOK_START_LIMIT: Duration = Duration::from_secs(2);
160static NEXT_MODULE_CONNECTION_TOKEN: AtomicU64 = AtomicU64::new(1);
161const DETACHED_CONNECTION_TOKEN: u64 = 0;
165
166type RequestKey = (u16, u32, u64);
167type InFlight = Arc<Mutex<HashMap<RequestKey, CancellationToken>>>;
168
169#[derive(Clone, Copy)]
175pub struct RouteHandle {
176 pub channel: u16,
177 pub epoch: u32,
178 connection_token: u64,
179 reverse_request_registry_id: u64,
180}
181
182impl RouteHandle {
183 pub fn detached(channel: u16, epoch: u32) -> Self {
197 Self::new(channel, epoch, DETACHED_CONNECTION_TOKEN)
198 }
199
200 pub(crate) fn new(channel: u16, epoch: u32, connection_token: u64) -> Self {
201 Self {
202 channel,
203 epoch,
204 connection_token,
205 reverse_request_registry_id: 0,
206 }
207 }
208
209 pub(crate) fn new_consumer(
210 channel: u16,
211 epoch: u32,
212 connection_token: u64,
213 reverse_requests: ReverseRequestRegistry,
214 ) -> Self {
215 reverse_requests.seal();
216 Self {
217 channel,
218 epoch,
219 connection_token,
220 reverse_request_registry_id: consumer::install_reverse_request_registry(
221 reverse_requests,
222 ),
223 }
224 }
225
226 pub(crate) fn connection_token(self) -> u64 {
227 self.connection_token
228 }
229
230 pub fn on_request<F, Fut>(
231 &self,
232 method_family: impl Into<String>,
233 handler: F,
234 ) -> Result<(), ReverseRequestRegistrationError>
235 where
236 F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
237 Fut: Future<Output = Vec<u8>> + Send + 'static,
238 {
239 consumer::route_reverse_request_registry(self.reverse_request_registry_id)?
240 .on_request(method_family, handler)
241 }
242
243 pub fn on_request_fallible<F, Fut>(
244 &self,
245 method_family: impl Into<String>,
246 handler: F,
247 ) -> Result<(), ReverseRequestRegistrationError>
248 where
249 F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
250 Fut: Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static,
251 {
252 consumer::route_reverse_request_registry(self.reverse_request_registry_id)?
253 .on_request_fallible(method_family, handler)
254 }
255
256 pub(crate) fn reverse_request_registry_id(self) -> u64 {
257 self.reverse_request_registry_id
258 }
259}
260
261impl PartialEq for RouteHandle {
262 fn eq(&self, other: &Self) -> bool {
263 self.channel == other.channel
264 && self.epoch == other.epoch
265 && self.connection_token == other.connection_token
266 }
267}
268
269impl Eq for RouteHandle {}
270
271impl std::hash::Hash for RouteHandle {
272 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
273 std::hash::Hash::hash(&self.channel, state);
274 std::hash::Hash::hash(&self.epoch, state);
275 std::hash::Hash::hash(&self.connection_token, state);
276 }
277}
278
279impl fmt::Debug for RouteHandle {
280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 f.debug_struct("RouteHandle")
282 .field("channel", &self.channel)
283 .field("epoch", &self.epoch)
284 .finish_non_exhaustive()
285 }
286}
287#[derive(Debug, Clone, PartialEq, Eq)]
289pub struct LiveRootsSnapshot {
290 pub roots: Vec<subc_protocol::session::LiveRoot>,
291 pub unknown_root_bindings: u64,
292 pub total_bindings: u64,
293}
294
295#[derive(Debug, Clone, PartialEq, Eq)]
300#[non_exhaustive]
301pub struct ScopeSyncReply {
302 pub generation: u64,
304 pub results: Vec<ScopeRecordResult>,
308 pub ended: Vec<ScopeEnded>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
317#[non_exhaustive]
318pub struct ScopeApplyReply {
319 pub generation: u64,
321 pub results: Vec<ScopeRecordResult>,
323 pub end_results: Vec<ScopeEndResult>,
326 pub ended: Vec<ScopeEnded>,
329}
330
331#[derive(Debug, Clone, PartialEq, Eq)]
334#[non_exhaustive]
335pub struct ScopeDescribeReply {
336 pub status: ScopeStatus,
337 pub scope_epoch: Option<u64>,
339 pub daemon_incarnation: String,
342 pub owner_synced: bool,
344 pub owner_configured: bool,
346 pub scope: Option<ScopeStamp>,
350}
351
352#[derive(Debug, serde::Deserialize)]
355#[serde(untagged)]
356enum ModuleControlReply {
357 Control(Box<ModuleControlResponseToModule>),
358 RouteAuthorize(RouteAuthorizeResponse),
359}
360
361impl ModuleControlReply {
362 fn control(self) -> Result<ModuleControlResponseToModule, CatalogUpdateError> {
363 match self {
364 Self::Control(reply) => Ok(*reply),
365 other => Err(CatalogUpdateError::Protocol(format!(
366 "unexpected module control response: {other:?}"
367 ))),
368 }
369 }
370}
371
372type CatalogUpdateReply = oneshot::Sender<Result<ModuleControlReply, CatalogUpdateError>>;
373type CatalogUpdateWaiter = oneshot::Receiver<Result<ModuleControlReply, CatalogUpdateError>>;
374type CatalogUpdateRequest = (u64, mpsc::Sender<Frame>, CatalogUpdateWaiter);
375type OperatorConfirmRequestWaiter = (u64, mpsc::Sender<Frame>, oneshot::Receiver<Frame>);
376
377pub type ModuleServeFuture = Pin<Box<dyn Future<Output = Result<(), SubcModuleError>> + Send>>;
379
380#[derive(Clone)]
381struct RequestDispatcher {
382 in_flight: InFlight,
383 control_slots: Arc<tokio::sync::Semaphore>,
384 pools: Arc<DispatchPools>,
387 draining_hooks: Arc<Mutex<Vec<oneshot::Receiver<()>>>>,
392 undecodable_push_logged: Arc<AtomicBool>,
395 failure: Arc<Mutex<Option<SubcModuleError>>>,
396 failed: CancellationToken,
397 tasks: TaskTracker,
398 aborts: Arc<Mutex<Vec<tokio::task::AbortHandle>>>,
399 data_tasks: TaskTracker,
400 data_aborts: Arc<Mutex<Vec<tokio::task::AbortHandle>>>,
401 undelivered_replies: Arc<AtomicU64>,
402}
403
404impl RequestDispatcher {
405 #[cfg(test)]
408 fn new() -> Self {
409 Self::with_pools(Arc::new(DispatchPools::new(RequestPools::new())))
410 }
411
412 fn with_pools(pools: Arc<DispatchPools>) -> Self {
413 Self {
414 in_flight: Arc::new(Mutex::new(HashMap::new())),
415 control_slots: Arc::new(tokio::sync::Semaphore::new(16)),
416 pools,
417 draining_hooks: Arc::new(Mutex::new(Vec::new())),
418 undecodable_push_logged: Arc::new(AtomicBool::new(false)),
419 failure: Arc::new(Mutex::new(None)),
420 failed: CancellationToken::new(),
421 tasks: TaskTracker::new(),
422 aborts: Arc::new(Mutex::new(Vec::new())),
423 data_tasks: TaskTracker::new(),
424 data_aborts: Arc::new(Mutex::new(Vec::new())),
425 undelivered_replies: Arc::new(AtomicU64::new(0)),
426 }
427 }
428
429 fn fail(&self, error: SubcModuleError) {
430 let mut failure = self.failure.lock().unwrap_or_else(|e| e.into_inner());
431 if failure.is_none() {
432 *failure = Some(error);
433 }
434 self.failed.cancel();
435 }
436
437 fn take_failure(&self) -> Option<SubcModuleError> {
438 self.failure
439 .lock()
440 .unwrap_or_else(|e| e.into_inner())
441 .take()
442 }
443
444 fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
445 let task = self.tasks.spawn(future);
446 let mut aborts = self.aborts.lock().unwrap_or_else(|e| e.into_inner());
447 aborts.retain(|task| !task.is_finished());
448 aborts.push(task.abort_handle());
449 }
450
451 fn abort_all(&self) {
452 live_upgrade::abort_tasks(&self.aborts);
453 live_upgrade::abort_tasks(&self.data_aborts);
454 }
455
456 fn fold_health(&self, mut report: HealthReport) -> HealthReport {
457 if let Some(saturation) = self.pools.saturation() {
458 if report.status == HealthStatus::Ok {
459 report.status = HealthStatus::Degraded;
460 }
461 report.detail = Some(match report.detail {
462 Some(detail) => format!("{saturation}; {detail}"),
463 None => saturation,
464 });
465 }
466 report
467 }
468
469 async fn wait_for_draining_hooks_to_start(&self) {
473 let started = std::mem::take(
474 &mut *self
475 .draining_hooks
476 .lock()
477 .unwrap_or_else(|poisoned| poisoned.into_inner()),
478 );
479 let deadline = tokio::time::Instant::now() + DRAINING_HOOK_START_LIMIT;
480 for hook in started {
481 if tokio::time::timeout_at(deadline, hook).await.is_err() {
484 return;
485 }
486 }
487 }
488
489 fn cancel_all(&self) {
494 self.pools.close();
495 let cancelled = match self.in_flight.lock() {
496 Ok(guard) => guard.values().cloned().collect::<Vec<_>>(),
497 Err(poisoned) => poisoned.into_inner().values().cloned().collect(),
498 };
499 for cancellation in cancelled {
500 cancellation.cancel();
501 }
502 }
503}
504
505#[derive(Clone)]
507pub struct ModuleHandle {
508 generations: Arc<live_upgrade::Generations>,
509}
510
511#[derive(Debug, Clone, PartialEq, Eq)]
513#[non_exhaustive]
514pub struct DrainNotice {
515 pub reason: RouteCloseReason,
516 pub deadline: SystemTime,
517 pub accepting: bool,
519}
520
521#[derive(Debug)]
523#[non_exhaustive]
524pub enum DrainReadyError {
525 Unsupported,
526 Refused(Box<ErrorBody>),
527 ConnectionClosed,
528 Timeout,
529 Protocol(String),
530}
531
532impl fmt::Display for DrainReadyError {
533 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
534 match self {
535 Self::Unsupported => f.write_str("daemon does not support accepting drains"),
536 Self::Refused(body) => {
537 write!(f, "drain ready refused: {} ({})", body.message, body.code)
538 }
539 Self::ConnectionClosed => {
540 f.write_str("connection closed before drain ready acknowledgement")
541 }
542 Self::Timeout => f.write_str("drain ready acknowledgement timed out"),
543 Self::Protocol(message) => write!(f, "invalid drain ready reply: {message}"),
544 }
545 }
546}
547
548impl std::error::Error for DrainReadyError {}
549
550impl ModuleHandle {
551 pub async fn drain_ready(&self) -> Result<(), DrainReadyError> {
555 use subc_protocol::session::{ModuleDrainReady, ACCEPTING_DRAIN_CAPABILITY};
556
557 let shared = self.shared();
558 if !shared
559 .daemon_capabilities
560 .iter()
561 .any(|cap| cap == ACCEPTING_DRAIN_CAPABILITY)
562 {
563 return Err(DrainReadyError::Unsupported);
564 }
565 let body = serde_json::to_vec(&ModuleDrainReady::Ready {})
566 .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
567 let (corr, writer, rx) = {
568 let mut inner = shared.lock_inner();
569 if inner.closed {
570 return Err(DrainReadyError::ConnectionClosed);
571 }
572 let writer = inner
573 .writer
574 .clone()
575 .ok_or(DrainReadyError::ConnectionClosed)?;
576 let corr =
577 next_module_control_corr(&mut inner).ok_or(DrainReadyError::ConnectionClosed)?;
578 let (tx, rx) = oneshot::channel();
579 inner.pending_drain_ready.insert(corr, tx);
580 (corr, writer, rx)
581 };
582 struct Waiter<'a>(&'a ModuleHandleShared, u64);
583 impl Drop for Waiter<'_> {
584 fn drop(&mut self) {
585 self.0.lock_inner().pending_drain_ready.remove(&self.1);
586 }
587 }
588 let _waiter = Waiter(&shared, corr);
589 let frame = Frame::build_with_version(
590 shared.negotiated_ver,
591 FrameType::Request,
592 control_flags(),
593 0,
594 0,
595 corr,
596 body,
597 )
598 .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
599 let reply = timeout(CATALOG_UPDATE_TIMEOUT, async {
600 shared
601 .queue_request(&writer, frame)
602 .await
603 .map_err(|err| match err {
604 CatalogUpdateError::Rejected(body) => DrainReadyError::Refused(Box::new(body)),
605 _ => DrainReadyError::ConnectionClosed,
606 })?;
607 rx.await.map_err(|_| DrainReadyError::ConnectionClosed)
608 })
609 .await
610 .map_err(|_| DrainReadyError::Timeout)??;
611 match reply.header.ty {
612 FrameType::Response => {
613 serde_json::from_slice::<ModuleDrainReady>(&reply.body)
614 .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
615 self.fence_consumer_dials();
616 Ok(())
617 }
618 FrameType::Error => {
619 let body = serde_json::from_slice(&reply.body)
620 .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
621 Err(DrainReadyError::Refused(Box::new(body)))
622 }
623 ty => Err(DrainReadyError::Protocol(format!(
624 "unexpected terminal frame: {ty:?}"
625 ))),
626 }
627 }
628}
629
630struct ModuleHandleShared {
631 registration: registration::Session,
632 negotiated_ver: u8,
633 daemon_capabilities: Vec<String>,
634 supports_catalog_update: bool,
635 supports_role_declarations_update: bool,
636 supports_live_roots: bool,
637 supports_agent_commands: bool,
638 supports_scope_sync: bool,
639 supports_scope_apply: bool,
640 supports_scope_describe: bool,
641 supports_scope_watch: bool,
642 supports_route_authorize: bool,
643 supports_operator_confirm: bool,
644 supports_activity: bool,
645 connection_runtime: tokio::runtime::Handle,
646 connection_token: u64,
647 live_routes: Mutex<HashMap<u16, RouteHandle>>,
648 dropped_route_frames: AtomicU64,
649 close_token: CancellationToken,
650 upgrade_notice: CancellationToken,
651 dispatch_pools: Mutex<Arc<DispatchPools>>,
654 catalog_send: tokio::sync::Mutex<()>,
655 config: config::Session,
656 served_control_ops: std::sync::OnceLock<Vec<String>>,
657 inner: Mutex<ModuleHandleState>,
658}
659
660struct ModuleHandleState {
661 pending_control_streams: HashMap<u64, module_subscription::ControlStreamSender>,
662 pending_claim_calls: HashMap<u64, oneshot::Sender<Frame>>,
663 writer: Option<mpsc::Sender<Frame>>,
664 next_corr: Option<u64>,
665 pending_catalog_updates: HashMap<u64, CatalogUpdateReply>,
666 pending_operator_confirms: HashMap<u64, oneshot::Sender<Frame>>,
667 pending_activity_records: HashMap<u64, oneshot::Sender<Frame>>,
668 pending_scope_served_by: HashMap<u64, oneshot::Sender<Frame>>,
669 pending_config_calls: HashMap<u64, oneshot::Sender<Frame>>,
670 pending_agent_commands: HashMap<u64, oneshot::Sender<Frame>>,
671 pending_drain_ready: HashMap<u64, oneshot::Sender<Frame>>,
672 current_provides: Option<Vec<ProviderRole>>,
673 catalog_changes: VecDeque<CatalogChange>,
674 upgrade: live_upgrade::UpgradeState,
675 closed: bool,
676}
677
678struct CatalogChange {
679 corr: u64,
680 update: CatalogManifestChange,
681 outcome: Option<CatalogChangeOutcome>,
682}
683
684enum CatalogManifestChange {
685 Catalog {
686 provides: Vec<ProviderRole>,
687 capabilities: Option<CapabilityDeclarations>,
688 ready: Option<bool>,
689 },
690 RoleDeclarations(BTreeMap<String, serde_json::Map<String, serde_json::Value>>),
691}
692
693enum CatalogChangeOutcome {
694 AcceptedCatalog,
695 AcceptedRoleDeclarations,
696 Rejected,
697 Unknown,
698}
699
700struct CatalogUpdateGuard {
701 shared: Arc<ModuleHandleShared>,
702 corr: u64,
703}
704
705impl Drop for CatalogUpdateGuard {
706 fn drop(&mut self) {
707 self.shared.remove_pending_catalog_update(self.corr);
708 }
709}
710
711impl ModuleHandle {
712 fn new(
713 ack: &ModuleHelloAckBody,
714 writer: mpsc::Sender<Frame>,
715 connection_token: u64,
716 close_token: CancellationToken,
717 connection_runtime: tokio::runtime::Handle,
718 ) -> Self {
719 Self {
720 generations: Arc::new(live_upgrade::Generations::new(
721 ack,
722 Arc::new(ModuleHandleShared::new(
723 ack,
724 writer,
725 connection_token,
726 close_token,
727 connection_runtime,
728 )),
729 )),
730 }
731 }
732}
733
734impl ModuleHandleShared {
735 fn new(
736 ack: &ModuleHelloAckBody,
737 writer: mpsc::Sender<Frame>,
738 connection_token: u64,
739 close_token: CancellationToken,
740 connection_runtime: tokio::runtime::Handle,
741 ) -> Self {
742 Self {
743 registration: registration::Session::default(),
744 negotiated_ver: ack.negotiated_ver,
745 daemon_capabilities: ack.subc_capabilities.clone(),
746 supports_catalog_update: ack
747 .subc_ops
748 .iter()
749 .any(|op| op == MODULE_TO_SUBC_OP_CATALOG_UPDATE),
750 supports_role_declarations_update: ack
751 .subc_ops
752 .iter()
753 .any(|op| op == MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS),
754 supports_live_roots: ack.subc_ops.iter().any(|op| op == "supervisor.live_roots"),
755 supports_agent_commands: ack
756 .subc_ops
757 .iter()
758 .any(|op| op == "supervisor.agent_commands"),
759 supports_scope_sync: ack.subc_ops.iter().any(|op| op == SCOPE_SYNC_OP),
760 supports_scope_apply: ack.subc_ops.iter().any(|op| op == SCOPE_APPLY_OP),
761 supports_scope_describe: ack.subc_ops.iter().any(|op| op == SCOPE_DESCRIBE_OP),
762 supports_scope_watch: ack
763 .subc_ops
764 .iter()
765 .any(|op| op == subc_control::ops::SCOPE_WATCH),
766 supports_route_authorize: ack
767 .subc_ops
768 .iter()
769 .any(|op| op == subc_protocol::scope::ROUTE_AUTHORIZE_OP),
770 supports_operator_confirm: ack.subc_ops.iter().any(|op| op == OPERATOR_CONFIRM_OP),
771 supports_activity: ack
772 .subc_capabilities
773 .iter()
774 .any(|capability| capability == ACTIVITY_LEDGER_CAPABILITY),
775 connection_runtime,
776 connection_token,
777 live_routes: Mutex::new(HashMap::new()),
778 dropped_route_frames: AtomicU64::new(0),
779 close_token,
780 upgrade_notice: CancellationToken::new(),
781 dispatch_pools: Mutex::new(Arc::new(DispatchPools::new(RequestPools::new()))),
782 catalog_send: tokio::sync::Mutex::new(()),
783 config: config::Session::default(),
784 served_control_ops: std::sync::OnceLock::new(),
785 inner: Mutex::new(ModuleHandleState {
786 pending_control_streams: HashMap::new(),
787 pending_claim_calls: HashMap::new(),
788 writer: Some(writer),
789 next_corr: Some(HELLO_CORR + 1),
790 pending_catalog_updates: HashMap::new(),
791 pending_operator_confirms: HashMap::new(),
792 pending_activity_records: HashMap::new(),
793 pending_scope_served_by: HashMap::new(),
794 pending_config_calls: HashMap::new(),
795 pending_agent_commands: HashMap::new(),
796 pending_drain_ready: HashMap::new(),
797 current_provides: None,
798 catalog_changes: VecDeque::new(),
799 upgrade: live_upgrade::UpgradeState::default(),
800 closed: false,
801 }),
802 }
803 }
804}
805
806impl ModuleHandle {
807 pub fn machine_id(&self) -> Option<&MachineId> {
815 self.generations.metadata().machine_id.as_ref()
816 }
817
818 pub fn daemon_capabilities(&self) -> &[String] {
823 &self.generations.metadata().capabilities
824 }
825
826 pub fn storage(&self) -> Option<&serde_json::Value> {
829 self.generations.metadata().storage.as_ref()
830 }
831
832 pub fn daemon_supports(&self, capability: &str) -> bool {
843 let shared = self.shared();
844 shared
845 .daemon_capabilities
846 .iter()
847 .any(|advertised| advertised == capability)
848 }
849
850 pub fn closed(&self) -> impl Future<Output = ()> + Send + 'static {
855 let shared = self.shared();
856 shared.close_token.clone().cancelled_owned()
857 }
858
859 pub fn is_closed(&self) -> bool {
861 let shared = self.shared();
862 shared.close_token.is_cancelled()
863 }
864
865 pub async fn catalog_update(
870 &self,
871 provides: Vec<ProviderRole>,
872 ) -> Result<(), CatalogUpdateError> {
873 self.catalog_update_inner(Some(provides), None, None).await
874 }
875
876 pub async fn update_role_declarations(
884 &self,
885 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
886 ) -> Result<(), CatalogUpdateError> {
887 let shared = self.shared();
888 shared.check_upgrade_fence()?;
889 if !shared.supports_role_declarations_update {
890 return Err(CatalogUpdateError::NotSupported);
891 }
892 let body = serde_json::to_vec(
893 &ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations {
894 role_declarations: serde_json::to_value(&role_declarations)
895 .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?,
896 },
897 )
898 .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
899 let send_guard = shared.catalog_send.lock().await;
900 let (corr, writer, rx) = shared.begin_catalog_update()?;
901 let _pending = CatalogUpdateGuard {
902 shared: shared.clone(),
903 corr,
904 };
905 let frame = Frame::build_with_version(
906 shared.negotiated_ver,
907 FrameType::Request,
908 control_flags(),
909 0,
910 0,
911 corr,
912 body,
913 )
914 .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
915 shared
916 .queue_catalog_change(
917 &writer,
918 frame,
919 CatalogManifestChange::RoleDeclarations(role_declarations),
920 )
921 .await?;
922 drop(send_guard);
923 match timeout(CATALOG_UPDATE_TIMEOUT, rx).await {
924 Ok(Ok(Ok(reply))) => match reply.control()? {
925 ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {} => Ok(()),
926 _ => Err(CatalogUpdateError::Protocol(
927 "unexpected catalog.update_role_declarations response".into(),
928 )),
929 },
930 Ok(Ok(Err(err))) => Err(err),
931 Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
932 Err(_) => Err(CatalogUpdateError::Timeout),
933 }
934 }
935
936 pub async fn catalog_update_with_capabilities(
942 &self,
943 provides: Vec<ProviderRole>,
944 capabilities: CapabilityDeclarations,
945 ) -> Result<(), CatalogUpdateError> {
946 self.catalog_update_inner(Some(provides), Some(capabilities), None)
947 .await
948 }
949
950 pub async fn set_ready(&self, ready: bool) -> Result<(), CatalogUpdateError> {
962 self.catalog_update_inner(None, None, Some(ready)).await
963 }
964
965 async fn catalog_update_inner(
966 &self,
967 provides: Option<Vec<ProviderRole>>,
968 capabilities: Option<CapabilityDeclarations>,
969 ready: Option<bool>,
970 ) -> Result<(), CatalogUpdateError> {
971 let shared = self.shared();
972 shared.check_upgrade_fence()?;
973 if !shared.supports_catalog_update {
974 return Err(CatalogUpdateError::NotSupported);
975 }
976
977 let send_guard = shared.catalog_send.lock().await;
980 let provides = match provides {
981 Some(provides) => provides,
982 None => {
983 let inner = shared.lock_inner();
984 if inner.closed {
985 return Err(CatalogUpdateError::ConnectionClosed);
986 }
987 inner
988 .current_provides
989 .as_ref()
990 .filter(|_| {
991 !inner.catalog_changes.iter().any(|change| {
992 matches!(change.update, CatalogManifestChange::Catalog { .. })
993 })
994 })
995 .cloned()
996 .ok_or_else(|| {
997 CatalogUpdateError::Protocol(
998 "current provider roles are unknown or a catalog update is in flight"
999 .into(),
1000 )
1001 })?
1002 }
1003 };
1004 let body = serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
1005 provides: provides.clone(),
1006 capabilities: capabilities.clone(),
1007 ready,
1008 })
1009 .map_err(|err| {
1010 CatalogUpdateError::Protocol(format!(
1011 "failed to encode catalog.update request body: {err}"
1012 ))
1013 })?;
1014 let (corr, writer, rx) = shared.begin_catalog_update()?;
1015 let _pending = CatalogUpdateGuard {
1016 shared: shared.clone(),
1017 corr,
1018 };
1019 let frame = Frame::build_with_version(
1020 shared.negotiated_ver,
1021 FrameType::Request,
1022 control_flags(),
1023 0,
1024 0,
1025 corr,
1026 body,
1027 )
1028 .map_err(|err| {
1029 shared.remove_pending_catalog_update(corr);
1030 CatalogUpdateError::Protocol(format!(
1031 "failed to build catalog.update request frame: {err}"
1032 ))
1033 })?;
1034
1035 shared
1036 .queue_catalog_change(
1037 &writer,
1038 frame,
1039 CatalogManifestChange::Catalog {
1040 provides,
1041 capabilities,
1042 ready,
1043 },
1044 )
1045 .await?;
1046 drop(send_guard);
1047
1048 match timeout(CATALOG_UPDATE_TIMEOUT, async {
1049 rx.await
1050 .map(|reply| reply.and_then(ModuleControlReply::control))
1051 })
1052 .await
1053 {
1054 Ok(Ok(Ok(ModuleControlResponseToModule::CatalogUpdate {}))) => Ok(()),
1055 Ok(Ok(Ok(_))) => Err(CatalogUpdateError::Protocol(
1056 "unexpected catalog.update response".into(),
1057 )),
1058 Ok(Ok(Err(err))) => Err(err),
1059 Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
1060 Err(_) => {
1061 shared.remove_pending_catalog_update(corr);
1062 Err(CatalogUpdateError::Timeout)
1063 }
1064 }
1065 }
1066
1067 pub async fn live_roots(&self) -> Result<LiveRootsSnapshot, CatalogUpdateError> {
1069 let shared = self.shared();
1070 shared.check_upgrade_fence()?;
1071 if !shared.supports_live_roots {
1072 return Err(CatalogUpdateError::NotSupported);
1073 }
1074 let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {})
1075 .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
1076 let (corr, writer, rx) = shared.begin_catalog_update()?;
1077 let frame = Frame::build_with_version(
1078 shared.negotiated_ver,
1079 FrameType::Request,
1080 control_flags(),
1081 0,
1082 0,
1083 corr,
1084 body,
1085 )
1086 .map_err(|err| {
1087 shared.remove_pending_catalog_update(corr);
1088 CatalogUpdateError::Protocol(err.to_string())
1089 })?;
1090 if let Err(error) = shared.queue_request(&writer, frame).await {
1091 shared.remove_pending_catalog_update(corr);
1092 return Err(error);
1093 }
1094 match timeout(CATALOG_UPDATE_TIMEOUT, async {
1095 rx.await
1096 .map(|reply| reply.and_then(ModuleControlReply::control))
1097 })
1098 .await
1099 {
1100 Ok(Ok(Ok(ModuleControlResponseToModule::LiveRoots {
1101 roots,
1102 unknown_root_bindings,
1103 total_bindings,
1104 }))) => Ok(LiveRootsSnapshot {
1105 roots,
1106 unknown_root_bindings,
1107 total_bindings,
1108 }),
1109 Ok(Ok(Ok(_))) => Err(CatalogUpdateError::Protocol(
1110 "unexpected live_roots response".into(),
1111 )),
1112 Ok(Ok(Err(err))) => Err(err),
1113 Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
1114 Err(_) => {
1115 shared.remove_pending_catalog_update(corr);
1116 Err(CatalogUpdateError::Timeout)
1117 }
1118 }
1119 }
1120
1121 pub async fn scope_sync(
1137 &self,
1138 generation: u64,
1139 scopes: Vec<ScopeRecord>,
1140 ) -> Result<ScopeSyncReply, ScopeCallError> {
1141 let shared = self.shared();
1142 live_upgrade::ScopeRequest::check_fence(&shared)?;
1143 if !shared.supports_scope_sync {
1144 return Err(ScopeCallError::NotSupported { op: SCOPE_SYNC_OP });
1145 }
1146 let request = ModuleControlRequestFromModule::ScopeSync { generation, scopes };
1147 let reply = live_upgrade::ScopeRequest::call(&shared, SCOPE_SYNC_OP, &request).await?;
1148 live_upgrade::ScopeRequest::decode_sync(reply)
1149 }
1150
1151 pub async fn scope_apply(
1162 &self,
1163 generation: u64,
1164 upsert: Vec<ScopeRecord>,
1165 end: Vec<ScopeEnd>,
1166 ) -> Result<ScopeApplyReply, ScopeCallError> {
1167 let shared = self.shared();
1168 live_upgrade::ScopeRequest::check_fence(&shared)?;
1169 if !shared.supports_scope_apply {
1170 return Err(ScopeCallError::NotSupported { op: SCOPE_APPLY_OP });
1171 }
1172 let request = ModuleControlRequestFromModule::ScopeApply {
1173 generation,
1174 upsert,
1175 end,
1176 };
1177 match live_upgrade::ScopeRequest::call(&shared, SCOPE_APPLY_OP, &request)
1178 .await?
1179 .control()
1180 .map_err(ScopeCallError::from_control_error)?
1181 {
1182 ModuleControlResponseToModule::ScopeApply {
1183 generation,
1184 results,
1185 end_results,
1186 ended,
1187 } => Ok(ScopeApplyReply {
1188 generation,
1189 results,
1190 end_results,
1191 ended,
1192 }),
1193 other => Err(ScopeCallError::Protocol(format!(
1194 "unexpected {SCOPE_APPLY_OP} response: {other:?}"
1195 ))),
1196 }
1197 }
1198
1199 pub async fn scope_describe(
1207 &self,
1208 owner: Principal,
1209 scope_ref: String,
1210 ) -> Result<ScopeDescribeReply, ScopeCallError> {
1211 let shared = self.shared();
1212 live_upgrade::ScopeRequest::check_fence(&shared)?;
1213 if !shared.supports_scope_describe {
1214 return Err(ScopeCallError::NotSupported {
1215 op: SCOPE_DESCRIBE_OP,
1216 });
1217 }
1218 let request = ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref };
1219 match live_upgrade::ScopeRequest::call(&shared, SCOPE_DESCRIBE_OP, &request)
1220 .await?
1221 .control()
1222 .map_err(ScopeCallError::from_control_error)?
1223 {
1224 ModuleControlResponseToModule::ScopeDescribe {
1225 status,
1226 scope_epoch,
1227 daemon_incarnation,
1228 owner_synced,
1229 owner_configured,
1230 scope,
1231 } => Ok(ScopeDescribeReply {
1232 status,
1233 scope_epoch,
1234 daemon_incarnation,
1235 owner_synced,
1236 owner_configured,
1237 scope,
1238 }),
1239 other => Err(ScopeCallError::Protocol(format!(
1240 "unexpected {SCOPE_DESCRIBE_OP} response: {other:?}"
1241 ))),
1242 }
1243 }
1244
1245 pub async fn confirm_operator(
1257 &self,
1258 summary: &str,
1259 caller_route: &RouteHandle,
1260 ) -> Result<(), OperatorConfirmError> {
1261 self.confirm_operator_with_deadline(summary, caller_route, OPERATOR_CONFIRM_TIMEOUT)
1262 .await
1263 }
1264
1265 pub async fn confirm_operation(
1286 &self,
1287 summary: &str,
1288 caller_route: &RouteHandle,
1289 operation: &str,
1290 ) -> Result<(), OperatorConfirmError> {
1291 if operation.is_empty() {
1292 return Err(OperatorConfirmError::OperationInvalid);
1293 }
1294 self.confirm_operation_with_deadline(
1295 summary,
1296 caller_route,
1297 operation,
1298 OPERATOR_CONFIRM_TIMEOUT,
1299 )
1300 .await
1301 }
1302
1303 pub async fn confirm_enrollment(
1321 &self,
1322 summary: &str,
1323 caller_route: &RouteHandle,
1324 ) -> Result<(), OperatorConfirmError> {
1325 self.confirm_inner(
1326 summary,
1327 caller_route,
1328 Some(OperatorConfirmKind::Enrollment),
1329 None,
1330 OPERATOR_CONFIRM_TIMEOUT,
1331 )
1332 .await
1333 }
1334
1335 pub(crate) async fn confirm_operator_with_deadline(
1336 &self,
1337 summary: &str,
1338 caller_route: &RouteHandle,
1339 duration: Duration,
1340 ) -> Result<(), OperatorConfirmError> {
1341 self.confirm_inner(summary, caller_route, None, None, duration)
1342 .await
1343 }
1344
1345 async fn confirm_operation_with_deadline(
1346 &self,
1347 summary: &str,
1348 caller_route: &RouteHandle,
1349 operation: &str,
1350 duration: Duration,
1351 ) -> Result<(), OperatorConfirmError> {
1352 self.confirm_inner(
1353 summary,
1354 caller_route,
1355 Some(OperatorConfirmKind::Operation),
1356 Some(operation.to_owned()),
1357 duration,
1358 )
1359 .await
1360 }
1361
1362 async fn confirm_inner(
1363 &self,
1364 summary: &str,
1365 caller_route: &RouteHandle,
1366 kind: Option<OperatorConfirmKind>,
1367 operation: Option<String>,
1368 duration: Duration,
1369 ) -> Result<(), OperatorConfirmError> {
1370 let shared = self.shared();
1371 if caller_route.connection_token() != shared.connection_token {
1372 return Err(OperatorConfirmError::NotPermitted);
1373 }
1374 if !shared.supports_operator_confirm {
1375 return Err(OperatorConfirmError::Unsupported);
1376 }
1377 let deadline = Instant::now() + duration;
1380 let body = serde_json::to_vec(
1381 &OperatorConfirmRequest::new(summary, caller_route.channel, caller_route.epoch)
1382 .with_kind(kind)
1383 .with_operation(operation),
1384 )
1385 .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1386 let (corr, writer, rx) = shared.begin_operator_confirm()?;
1387 let mut guard = OperatorConfirmGuard {
1388 shared: Arc::clone(&shared),
1389 runtime: shared.connection_runtime.clone(),
1390 writer: writer.clone(),
1391 corr,
1392 accepted: false,
1393 armed: true,
1394 };
1395 let frame = Frame::build_with_version(
1396 shared.negotiated_ver,
1397 FrameType::Request,
1398 control_flags(),
1399 0,
1400 0,
1401 corr,
1402 body,
1403 )
1404 .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1405 tokio::select! {
1406 result = timeout_at(deadline, shared.queue_request(&writer, frame)) => {
1407 result.map_err(|_| OperatorConfirmError::PresenceUnavailable)?
1408 .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1409 }
1410 _ = shared.close_token.cancelled() => {
1411 return Err(OperatorConfirmError::PresenceUnavailable);
1412 }
1413 }
1414 guard.accepted = true;
1415 let reply = timeout_at(deadline, rx)
1416 .await
1417 .map_err(|_| OperatorConfirmError::PresenceUnavailable)?
1418 .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1419 guard.armed = false;
1420 match reply.header.ty {
1421 FrameType::Response => {
1422 match serde_json::from_slice::<OperatorConfirmReply>(&reply.body) {
1423 Ok(body) if body.outcome == "confirmed" => Ok(()),
1424 _ => Err(OperatorConfirmError::PresenceUnavailable),
1425 }
1426 }
1427 FrameType::Error => match serde_json::from_slice::<ErrorBody>(&reply.body) {
1428 Ok(body) => Err(match body.code.as_str() {
1429 error_codes::OPERATOR_DECLINED => {
1430 let detail = body.detail.as_ref();
1431 if detail
1432 .and_then(|detail| detail.get("reason"))
1433 .and_then(serde_json::Value::as_str)
1434 == Some("backoff")
1435 {
1436 OperatorConfirmError::Backoff {
1437 retry_after_ms: detail
1438 .and_then(|detail| detail.get("retry_after_ms"))
1439 .and_then(serde_json::Value::as_u64),
1440 }
1441 } else {
1442 OperatorConfirmError::Declined
1443 }
1444 }
1445 error_codes::OPERATOR_PRESENCE_UNAVAILABLE
1446 if body
1447 .detail
1448 .as_ref()
1449 .and_then(|detail| detail.get("reason"))
1450 .and_then(serde_json::Value::as_str)
1451 == Some("unsupported_platform") =>
1452 {
1453 OperatorConfirmError::PresenceUnsupportedPlatform
1454 }
1455 error_codes::OPERATOR_SUMMARY_INVALID => OperatorConfirmError::SummaryInvalid,
1456 error_codes::OPERATOR_REQUEST_NOT_PERMITTED | "not_registered" => {
1457 OperatorConfirmError::NotPermitted
1458 }
1459 "unsupported_control_frame" => OperatorConfirmError::Unsupported,
1460 _ => OperatorConfirmError::PresenceUnavailable,
1461 }),
1462 Err(_) => Err(OperatorConfirmError::PresenceUnavailable),
1463 },
1464 _ => Err(OperatorConfirmError::PresenceUnavailable),
1465 }
1466 }
1467
1468 pub async fn push(
1470 &self,
1471 handle: &RouteHandle,
1472 body: Vec<u8>,
1473 admission_class: Option<AdmissionClass>,
1474 ) -> Result<(), SubcModuleError> {
1475 let shared = self.shared();
1476 self.validate_route(*handle)?;
1477 let writer = shared
1478 .lock_inner()
1479 .writer
1480 .clone()
1481 .ok_or(SubcModuleError::WriterClosed)?;
1482 let frame = Frame::build_with_version(
1483 shared.negotiated_ver,
1484 FrameType::Push,
1485 data_flags().with_admission_class(admission_class.unwrap_or(AdmissionClass::Normal)),
1486 handle.channel,
1487 handle.epoch,
1488 0,
1489 body,
1490 )
1491 .map_err(SubcModuleError::FrameBuild)?;
1492 shared
1493 .queue_request(&writer, frame)
1494 .await
1495 .map_err(|_| SubcModuleError::WriterClosed)
1496 }
1497
1498 pub fn dropped_route_frames(&self) -> u64 {
1500 let shared = self.shared();
1501 shared.dropped_route_frames.load(Ordering::Relaxed)
1502 }
1503
1504 fn validate_route(&self, handle: RouteHandle) -> Result<(), SubcModuleError> {
1505 let shared = self.shared();
1506 if handle.connection_token() != shared.connection_token {
1507 return Err(SubcModuleError::StaleRouteHandle(handle));
1508 }
1509 let routes = shared
1510 .live_routes
1511 .lock()
1512 .map_err(|_| SubcModuleError::InFlightPoisoned)?;
1513 if routes.get(&handle.channel) == Some(&handle) {
1514 Ok(())
1515 } else {
1516 Err(SubcModuleError::StaleRouteHandle(handle))
1517 }
1518 }
1519
1520 fn install_route(&self, handle: RouteHandle) -> Result<(), SubcModuleError> {
1521 let shared = self.shared();
1522 shared
1523 .live_routes
1524 .lock()
1525 .map_err(|_| SubcModuleError::InFlightPoisoned)?
1526 .insert(handle.channel, handle);
1527 Ok(())
1528 }
1529
1530 fn installed_route(&self, channel: u16) -> Result<Option<RouteHandle>, SubcModuleError> {
1531 let shared = self.shared();
1532 let route = shared
1533 .live_routes
1534 .lock()
1535 .map_err(|_| SubcModuleError::InFlightPoisoned)?
1536 .get(&channel)
1537 .copied();
1538 Ok(route)
1539 }
1540
1541 fn remove_route(&self, handle: RouteHandle) -> Result<bool, SubcModuleError> {
1542 let shared = self.shared();
1543 let mut routes = shared
1544 .live_routes
1545 .lock()
1546 .map_err(|_| SubcModuleError::InFlightPoisoned)?;
1547 if routes.get(&handle.channel) == Some(&handle) {
1548 routes.remove(&handle.channel);
1549 Ok(true)
1550 } else {
1551 Ok(false)
1552 }
1553 }
1554
1555 fn validate_ingress(&self, channel: u16, epoch: u32) -> Result<bool, SubcModuleError> {
1556 let shared = self.shared();
1557 let handle = RouteHandle::new(channel, epoch, shared.connection_token);
1558 let valid = shared
1559 .live_routes
1560 .lock()
1561 .map_err(|_| SubcModuleError::InFlightPoisoned)?
1562 .get(&channel)
1563 == Some(&handle);
1564 if !valid {
1565 shared.dropped_route_frames.fetch_add(1, Ordering::Relaxed);
1566 }
1567 Ok(valid)
1568 }
1569
1570 fn route_handle(&self, channel: u16, epoch: u32) -> RouteHandle {
1571 let shared = self.shared();
1572 RouteHandle::new(channel, epoch, shared.connection_token)
1573 }
1574
1575 fn handle_control_reply(&self, frame: Frame) -> bool {
1576 let shared = self.shared();
1577 let Some(frame) = self.handle_control_stream_frame(frame) else {
1578 return true;
1579 };
1580 if let Some(reply) = shared
1581 .lock_inner()
1582 .pending_drain_ready
1583 .remove(&frame.header.corr)
1584 {
1585 let _ = reply.send(frame);
1586 return true;
1587 }
1588 let claim_reply = shared
1589 .lock_inner()
1590 .pending_claim_calls
1591 .remove(&frame.header.corr);
1592 if let Some(reply) = claim_reply {
1593 let _ = reply.send(frame);
1594 return true;
1595 }
1596 let config_reply = shared
1597 .lock_inner()
1598 .pending_config_calls
1599 .remove(&frame.header.corr);
1600 if let Some(reply) = config_reply {
1601 let _ = reply.send(frame);
1602 return true;
1603 }
1604 if let Some(reply) = shared
1605 .lock_inner()
1606 .pending_agent_commands
1607 .remove(&frame.header.corr)
1608 {
1609 let _ = reply.send(frame);
1610 return true;
1611 }
1612 let served_by_reply = shared
1613 .lock_inner()
1614 .pending_scope_served_by
1615 .remove(&frame.header.corr);
1616 if let Some(reply) = served_by_reply {
1617 let _ = reply.send(frame);
1618 return true;
1619 }
1620 let activity_reply = shared
1621 .lock_inner()
1622 .pending_activity_records
1623 .remove(&frame.header.corr);
1624 if let Some(reply) = activity_reply {
1625 let _ = reply.send(frame);
1626 return true;
1627 }
1628 let operator_reply = shared
1629 .lock_inner()
1630 .pending_operator_confirms
1631 .remove(&frame.header.corr);
1632 if let Some(reply) = operator_reply {
1633 let _ = reply.send(frame);
1634 return true;
1635 }
1636 let Some(reply) = shared.take_pending_catalog_update(frame.header.corr) else {
1637 return false;
1638 };
1639 let result = match frame.header.ty {
1640 FrameType::Response => serde_json::from_slice::<ModuleControlReply>(&frame.body)
1641 .map_err(|err| {
1642 CatalogUpdateError::Protocol(format!(
1643 "invalid module control response body: {err}"
1644 ))
1645 }),
1646 FrameType::Error => match serde_json::from_slice::<ErrorBody>(&frame.body) {
1647 Ok(body) => Err(match body.code.as_str() {
1648 "catalog_update_frozen_field" => CatalogUpdateError::FrozenField(body),
1649 "not_registered" => CatalogUpdateError::NotRegistered(body),
1650 _ => CatalogUpdateError::Rejected(body),
1651 }),
1652 Err(err) => Err(CatalogUpdateError::Protocol(format!(
1653 "invalid catalog.update error body: {err}"
1654 ))),
1655 },
1656 ty => Err(CatalogUpdateError::Protocol(format!(
1657 "unexpected catalog.update terminal frame: {ty:?}"
1658 ))),
1659 };
1660 let outcome = match &result {
1661 Ok(ModuleControlReply::Control(reply)) => match reply.as_ref() {
1662 ModuleControlResponseToModule::CatalogUpdate {} => {
1663 CatalogChangeOutcome::AcceptedCatalog
1664 }
1665 ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {} => {
1666 CatalogChangeOutcome::AcceptedRoleDeclarations
1667 }
1668 _ => CatalogChangeOutcome::Unknown,
1669 },
1670 Err(CatalogUpdateError::FrozenField(_))
1671 | Err(CatalogUpdateError::NotRegistered(_))
1672 | Err(CatalogUpdateError::Rejected(_)) => CatalogChangeOutcome::Rejected,
1673 _ => CatalogChangeOutcome::Unknown,
1674 };
1675 shared.finish_catalog_change(frame.header.corr, outcome);
1676 let _ = reply.send(result);
1677 true
1678 }
1679
1680 fn close_connection(&self) {
1681 let shared = self.shared();
1682 shared.close_connection();
1683 }
1684}
1685
1686impl ModuleHandleShared {
1687 fn begin_catalog_update(&self) -> Result<CatalogUpdateRequest, CatalogUpdateError> {
1688 self.begin_control_call(false)
1689 }
1690
1691 fn begin_control_call(
1692 &self,
1693 resume_sync: bool,
1694 ) -> Result<CatalogUpdateRequest, CatalogUpdateError> {
1695 let mut inner = self.lock_inner();
1696 if !resume_sync && inner.upgrade.fenced() {
1697 return Err(CatalogUpdateError::Rejected(live_upgrade::upgrade_refusal()));
1698 }
1699 if inner.closed {
1700 return Err(CatalogUpdateError::ConnectionClosed);
1701 }
1702 let Some(writer) = inner.writer.clone() else {
1703 drop(inner);
1704 self.close_connection();
1705 return Err(CatalogUpdateError::ConnectionClosed);
1706 };
1707 let Some(corr) = next_module_control_corr(&mut inner) else {
1708 drop(inner);
1709 self.close_connection();
1710 return Err(CatalogUpdateError::ConnectionClosed);
1711 };
1712 let (tx, rx) = oneshot::channel();
1713 inner.pending_catalog_updates.insert(corr, tx);
1714 Ok((corr, writer, rx))
1715 }
1716
1717 fn begin_operator_confirm(&self) -> Result<OperatorConfirmRequestWaiter, OperatorConfirmError> {
1718 let mut inner = self.lock_inner();
1719 if inner.closed || inner.upgrade.fenced() {
1720 return Err(OperatorConfirmError::PresenceUnavailable);
1721 }
1722 let Some(writer) = inner.writer.clone() else {
1723 drop(inner);
1724 self.close_connection();
1725 return Err(OperatorConfirmError::PresenceUnavailable);
1726 };
1727 let Some(corr) = next_module_control_corr(&mut inner) else {
1728 drop(inner);
1729 self.close_connection();
1730 return Err(OperatorConfirmError::PresenceUnavailable);
1731 };
1732 let (tx, rx) = oneshot::channel();
1733 inner.pending_operator_confirms.insert(corr, tx);
1734 Ok((corr, writer, rx))
1735 }
1736
1737 fn take_pending_catalog_update(&self, corr: u64) -> Option<CatalogUpdateReply> {
1738 self.lock_inner().pending_catalog_updates.remove(&corr)
1739 }
1740
1741 fn remove_pending_catalog_update(&self, corr: u64) {
1742 let removed = self
1743 .lock_inner()
1744 .pending_catalog_updates
1745 .remove(&corr)
1746 .is_some();
1747 if removed {
1748 self.finish_catalog_change(corr, CatalogChangeOutcome::Unknown);
1749 }
1750 }
1751
1752 fn finish_catalog_change(&self, corr: u64, outcome: CatalogChangeOutcome) {
1753 let mut inner = self.lock_inner();
1754 if let Some(change) = inner
1755 .catalog_changes
1756 .iter_mut()
1757 .find(|change| change.corr == corr)
1758 {
1759 change.outcome = Some(outcome);
1760 }
1761 while inner
1764 .catalog_changes
1765 .front()
1766 .is_some_and(|change| change.outcome.is_some())
1767 {
1768 let change = inner.catalog_changes.pop_front().expect("completed change");
1769 match (change.outcome.expect("completed outcome"), change.update) {
1770 (
1771 CatalogChangeOutcome::AcceptedCatalog,
1772 CatalogManifestChange::Catalog {
1773 provides,
1774 capabilities,
1775 ready,
1776 },
1777 ) => {
1778 inner.current_provides = Some(provides.clone());
1779 inner.upgrade.update_manifest(|manifest| {
1780 manifest.provides = provides;
1781 if capabilities.is_some() {
1782 manifest.capabilities = capabilities;
1783 }
1784 if ready.is_some() {
1785 manifest.ready = ready;
1786 }
1787 });
1788 }
1789 (
1790 CatalogChangeOutcome::AcceptedRoleDeclarations,
1791 CatalogManifestChange::RoleDeclarations(declarations),
1792 ) => {
1793 inner
1794 .upgrade
1795 .update_manifest(|manifest| manifest.role_declarations = declarations);
1796 }
1797 (
1798 CatalogChangeOutcome::Unknown | CatalogChangeOutcome::AcceptedRoleDeclarations,
1799 CatalogManifestChange::Catalog { .. },
1800 ) => inner.current_provides = None,
1801 _ => {}
1802 }
1803 }
1804 }
1805
1806 fn close_connection(&self) {
1807 let pending = {
1808 let mut inner = self.lock_inner();
1809 if inner.closed {
1810 return;
1811 }
1812 inner.closed = true;
1813 inner.writer = None;
1814 inner.catalog_changes.clear();
1815 self.close_token.cancel();
1816 inner.pending_operator_confirms.clear();
1818 inner.pending_activity_records.clear();
1819 inner.pending_scope_served_by.clear();
1820 inner.pending_drain_ready.clear();
1821 inner.pending_config_calls.clear();
1822 inner.pending_agent_commands.clear();
1823 inner.pending_claim_calls.clear();
1824 inner.pending_control_streams.clear();
1825 inner
1826 .pending_catalog_updates
1827 .drain()
1828 .map(|(_, reply)| reply)
1829 .collect::<Vec<_>>()
1830 };
1831 self.clear_live_routes();
1832 for reply in pending {
1833 let _ = reply.send(Err(CatalogUpdateError::ConnectionClosed));
1834 }
1835 }
1836
1837 fn clear_live_routes(&self) {
1838 if let Ok(mut routes) = self.live_routes.lock() {
1839 routes.clear();
1840 }
1841 }
1842
1843 fn lock_inner(&self) -> std::sync::MutexGuard<'_, ModuleHandleState> {
1844 self.inner
1845 .lock()
1846 .unwrap_or_else(|poisoned| poisoned.into_inner())
1847 }
1848}
1849
1850fn next_module_control_corr(inner: &mut ModuleHandleState) -> Option<u64> {
1851 let corr = inner.next_corr?;
1852 inner.next_corr = corr.checked_add(1);
1853 Some(corr)
1854}
1855
1856struct OperatorConfirmGuard {
1857 shared: Arc<ModuleHandleShared>,
1858 runtime: tokio::runtime::Handle,
1859 writer: mpsc::Sender<Frame>,
1860 corr: u64,
1861 accepted: bool,
1862 armed: bool,
1863}
1864
1865impl Drop for OperatorConfirmGuard {
1866 fn drop(&mut self) {
1867 if !self.armed {
1868 return;
1869 }
1870 self.shared
1871 .lock_inner()
1872 .pending_operator_confirms
1873 .remove(&self.corr);
1874 if !self.accepted {
1875 return;
1876 }
1877 let Ok(cancel) = Frame::build_with_version(
1878 self.shared.negotiated_ver,
1879 FrameType::Cancel,
1880 control_flags(),
1881 0,
1882 0,
1883 self.corr,
1884 Vec::new(),
1885 ) else {
1886 return;
1887 };
1888 match self.writer.try_send(cancel) {
1889 Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
1890 Err(mpsc::error::TrySendError::Full(cancel)) => {
1891 let writer = self.writer.clone();
1895 self.runtime.spawn(async move {
1896 let _ = writer.send(cancel).await;
1897 });
1898 }
1899 }
1900 }
1901}
1902
1903#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1908#[non_exhaustive]
1909pub enum OperatorConfirmError {
1910 Declined,
1911 Backoff {
1914 retry_after_ms: Option<u64>,
1915 },
1916 PresenceUnavailable,
1921 PresenceUnsupportedPlatform,
1933 SummaryInvalid,
1934 OperationInvalid,
1940 NotPermitted,
1941 Unsupported,
1942}
1943
1944impl fmt::Display for OperatorConfirmError {
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 f.write_str(match self {
1947 Self::Declined => "operator declined the write",
1948 Self::Backoff { retry_after_ms: None } => {
1949 "operator confirmation refused without asking: a recent decline holds new prompts for a short time"
1950 }
1951 Self::PresenceUnavailable => "operator confirmation is unavailable",
1952 Self::PresenceUnsupportedPlatform => {
1953 "operator confirmation has no prompt on this platform"
1954 }
1955 Self::SummaryInvalid => "operator confirmation summary is invalid",
1956 Self::OperationInvalid => "operator confirmation operation is invalid",
1957 Self::NotPermitted => "operator confirmation is not permitted for this route",
1958 Self::Unsupported => "daemon does not support operator confirmation",
1959 Self::Backoff {
1960 retry_after_ms: Some(_),
1961 } => return write!(
1962 f,
1963 "operator confirmation refused without asking: a recent decline holds new prompts for {} s",
1964 self.backoff_seconds().expect("backoff retry duration is present")
1965 ),
1966 })
1967 }
1968}
1969
1970impl OperatorConfirmError {
1971 fn backoff_seconds(&self) -> Option<u64> {
1972 match self {
1973 Self::Backoff {
1974 retry_after_ms: Some(milliseconds),
1975 } => Some(milliseconds / 1_000 + u64::from(!milliseconds.is_multiple_of(1_000))),
1976 _ => None,
1977 }
1978 }
1979}
1980
1981impl Error for OperatorConfirmError {}
1982
1983#[derive(Debug)]
1988pub enum CatalogUpdateError {
1989 NotSupported,
1990 FrozenField(ErrorBody),
1991 NotRegistered(ErrorBody),
1992 Rejected(ErrorBody),
1993 Timeout,
1994 ConnectionClosed,
1995 Protocol(String),
1996}
1997
1998impl fmt::Display for CatalogUpdateError {
1999 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2000 match self {
2001 Self::NotSupported => write!(
2002 f,
2003 "daemon HELLO_ACK did not advertise catalog.update support"
2004 ),
2005 Self::FrozenField(body) => {
2006 write!(f, "catalog.update rejected frozen field: {}", body.message)
2007 }
2008 Self::NotRegistered(body) => write!(
2009 f,
2010 "catalog.update requires a registered module: {}",
2011 body.message
2012 ),
2013 Self::Rejected(body) => write!(
2014 f,
2015 "catalog.update rejected by subc: {} ({})",
2016 body.code, body.message
2017 ),
2018 Self::Timeout => write!(f, "catalog.update timed out waiting for an ACK"),
2019 Self::ConnectionClosed => {
2020 write!(f, "subc connection closed before catalog.update completed")
2021 }
2022 Self::Protocol(message) => write!(f, "catalog.update protocol error: {message}"),
2023 }
2024 }
2025}
2026
2027impl Error for CatalogUpdateError {}
2028
2029#[derive(Debug, Clone, PartialEq, Eq)]
2038#[non_exhaustive]
2039pub enum ScopeCallError {
2040 NotSupported { op: &'static str },
2043 Refused { code: String, message: String },
2049 Timeout,
2051 ConnectionClosed,
2053 Protocol(String),
2055}
2056
2057impl ScopeCallError {
2058 pub fn code(&self) -> Option<&str> {
2060 match self {
2061 Self::Refused { code, .. } => Some(code),
2062 _ => None,
2063 }
2064 }
2065
2066 fn from_control_error(err: CatalogUpdateError) -> Self {
2071 match err {
2072 CatalogUpdateError::FrozenField(body)
2073 | CatalogUpdateError::NotRegistered(body)
2074 | CatalogUpdateError::Rejected(body) => Self::Refused {
2075 code: body.code,
2076 message: body.message,
2077 },
2078 CatalogUpdateError::Timeout => Self::Timeout,
2079 CatalogUpdateError::ConnectionClosed => Self::ConnectionClosed,
2080 CatalogUpdateError::Protocol(message) => Self::Protocol(message),
2081 CatalogUpdateError::NotSupported => {
2084 Self::Protocol("unexpected NotSupported from the control reply table".into())
2085 }
2086 }
2087 }
2088}
2089
2090impl fmt::Display for ScopeCallError {
2091 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2092 match self {
2093 Self::NotSupported { op } => {
2094 write!(f, "daemon HELLO_ACK did not advertise {op} support")
2095 }
2096 Self::Refused { code, message } => {
2097 write!(f, "subc refused the request: {code} ({message})")
2098 }
2099 Self::Timeout => write!(f, "timed out waiting for the daemon's reply"),
2100 Self::ConnectionClosed => {
2101 write!(f, "subc connection closed before the daemon replied")
2102 }
2103 Self::Protocol(message) => write!(f, "scope call protocol error: {message}"),
2104 }
2105 }
2106}
2107
2108impl Error for ScopeCallError {}
2109
2110#[async_trait]
2159pub trait ModuleHandler: Send + Sync + 'static {
2160 async fn handle(&self, ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome;
2165
2166 async fn on_hello_ack(&self, _ack: &ModuleHelloAckBody) {}
2169
2170 async fn resume_scope_sync(&self, _handle: &ModuleHandle) -> Option<ResumeScopeSync> {
2174 None
2175 }
2176
2177 async fn on_reconnected(
2181 &self,
2182 _handle: &ModuleHandle,
2183 _scope_sync: Option<Result<ScopeSyncReply, ScopeCallError>>,
2184 ) {
2185 }
2186
2187 fn control_ops(&self) -> Vec<String> {
2193 Vec::new()
2194 }
2195
2196 async fn on_control_request(
2209 &self,
2210 _op: &str,
2211 _body: serde_json::Value,
2212 _cancel: CancellationToken,
2213 ) -> Result<serde_json::Value, ErrorBody> {
2214 Err(ErrorBody::new(
2215 "unsupported_op",
2216 "no control handler implemented",
2217 ))
2218 }
2219
2220 fn config_declaration(&self) -> Option<config::ConfigDeclareRequest> {
2224 None
2225 }
2226
2227 async fn config_review(
2230 &self,
2231 _request: config::ConfigReviewRequest,
2232 ) -> config::ConfigReviewReply {
2233 config::ConfigReviewReply::new(
2234 vec![],
2235 vec![config::ConfigReviewRefusal::new(
2236 "value_invalid",
2237 vec![],
2238 vec!["module has no config review implementation".into()],
2239 )],
2240 )
2241 }
2242
2243 async fn config_apply(&self, _view: config::ConfigView) -> Result<(), Vec<String>> {
2247 Err(vec!["module has no config apply implementation".into()])
2248 }
2249
2250 async fn config_files(&self) {}
2253
2254 async fn on_config_state(&self, _state: config::ConfigState) {}
2256
2257 async fn on_config_error(&self, error: config::ConfigError) {
2260 tracing::warn!(%error, "module configuration request failed");
2261 }
2262
2263 async fn on_project_config_error(&self, _project_id: String, error: config::ConfigError) {
2267 self.on_config_error(error).await;
2268 }
2269
2270 async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
2272 BindDecision::accept()
2273 }
2274
2275 async fn on_bound(&self, _handle: &RouteHandle) {}
2277
2278 async fn health(&self) -> HealthReport {
2308 HealthReport {
2321 detail: Some("no health implementation; inherited default".to_string()),
2322 ..HealthReport::ok()
2323 }
2324 }
2325
2326 async fn on_route_gone(&self, _handle: &RouteHandle) {}
2328
2329 fn request_pools(&self) -> RequestPools {
2361 RequestPools::new()
2362 }
2363
2364 async fn on_draining(&self, _reason: RouteCloseReason, _deadline: SystemTime) {}
2382
2383 async fn on_draining_notice(&self, notice: DrainNotice) {
2386 self.on_draining(notice.reason, notice.deadline).await;
2387 }
2388
2389 async fn on_connection_end(&self, _end: ConnectionEnd) {}
2396}
2397
2398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2403#[non_exhaustive]
2404pub enum ConnectionEnd {
2405 Goodbye,
2407 Eof,
2409 Reset,
2412 Closed,
2414}
2415
2416impl ConnectionEnd {
2417 pub fn as_str(self) -> &'static str {
2419 match self {
2420 Self::Goodbye => "goodbye",
2421 Self::Eof => "eof",
2422 Self::Reset => "reset",
2423 Self::Closed => "closed",
2424 }
2425 }
2426}
2427
2428impl std::fmt::Display for ConnectionEnd {
2429 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2430 f.write_str(self.as_str())
2431 }
2432}
2433
2434#[derive(Debug, Clone, PartialEq)]
2436pub enum HandlerOutcome {
2437 Response(Vec<u8>),
2439 Error { code: String, message: String },
2441 ErrorWithDetail {
2443 code: String,
2444 message: String,
2445 detail: serde_json::Value,
2446 },
2447 Streamed,
2450}
2451
2452#[derive(Clone)]
2455pub struct RequestCtx {
2456 handle: RouteHandle,
2457 corr: u64,
2458 ver: u8,
2459 egress: mpsc::Sender<Frame>,
2460 module_handle: ModuleHandle,
2461 cancelled: CancellationToken,
2462 binary_reply: Arc<AtomicBool>,
2463 request_flags: Flags,
2464 request_body: Arc<[u8]>,
2465 open: Arc<tokio::sync::Mutex<bool>>,
2470}
2471
2472impl RequestCtx {
2473 pub fn module_handle(&self) -> ModuleHandle {
2475 self.module_handle.clone()
2476 }
2477
2478 pub fn request_payload(
2483 &self,
2484 ) -> Result<Option<(serde_json::Value, &[u8])>, subc_protocol::framed_body::FramedBodyError>
2485 {
2486 if !self.request_flags.is_binary() {
2487 return Ok(None);
2488 }
2489 subc_protocol::framed_body::decode(&self.request_body).map(Some)
2490 }
2491
2492 pub fn route_handle(&self) -> RouteHandle {
2494 self.handle
2495 }
2496
2497 pub fn corr(&self) -> u64 {
2499 self.corr
2500 }
2501
2502 pub fn mark_binary_reply(&self) {
2514 self.binary_reply.store(true, Ordering::Relaxed);
2515 }
2516
2517 pub async fn emit(&self, body: Vec<u8>) -> Result<(), SubcModuleError> {
2520 self.emit_with_admission(body, None).await
2521 }
2522
2523 pub async fn push(&self, body: Vec<u8>) -> Result<(), SubcModuleError> {
2533 let open = self.open.lock().await;
2534 if !*open || self.cancelled.is_cancelled() {
2535 return Err(SubcModuleError::RequestEnded);
2536 }
2537 self.send_frame(FrameType::Push, data_flags(), body).await
2538 }
2539
2540 pub async fn emit_with_admission(
2542 &self,
2543 body: Vec<u8>,
2544 admission_class: Option<AdmissionClass>,
2545 ) -> Result<(), SubcModuleError> {
2546 self.module_handle.validate_route(self.handle)?;
2547 if self.cancelled.is_cancelled() {
2548 return Ok(());
2549 }
2550 self.send_frame(
2551 FrameType::StreamData,
2552 data_flags().with_admission_class(admission_class.unwrap_or(AdmissionClass::Normal)),
2553 body,
2554 )
2555 .await
2556 }
2557
2558 pub fn cancelled(&self) -> WaitForCancellationFuture<'_> {
2562 self.cancelled.cancelled()
2563 }
2564
2565 pub fn cancellation_token(&self) -> CancellationToken {
2567 self.cancelled.clone()
2568 }
2569
2570 async fn send_frame(
2571 &self,
2572 frame_type: FrameType,
2573 flags: Flags,
2574 body: Vec<u8>,
2575 ) -> Result<(), SubcModuleError> {
2576 self.module_handle.validate_route(self.handle)?;
2577 let (frame_type, flags, body) = bounded_terminal(frame_type, flags, body)?;
2578 let frame = Frame::build_with_version(
2579 self.ver,
2580 frame_type,
2581 flags,
2582 self.handle.channel,
2583 self.handle.epoch,
2584 self.corr,
2585 body,
2586 )
2587 .map_err(SubcModuleError::FrameBuild)?;
2588 send_outbound(&self.egress, frame).await
2589 }
2590}
2591
2592fn checked_increment(counter: &AtomicU64) -> Option<u64> {
2597 let mut current = counter.load(Ordering::Relaxed);
2598 loop {
2599 let next = current.checked_add(1)?;
2600 match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
2601 Ok(previous) => return Some(previous),
2602 Err(actual) => current = actual,
2603 }
2604 }
2605}
2606
2607#[derive(Debug, Clone)]
2614#[non_exhaustive]
2615pub struct RouteBindRequest {
2616 pub handle: RouteHandle,
2617 pub target: RouteTarget,
2618 pub identity: BindIdentity,
2619 pub principal: Option<Principal>,
2620 pub consumer_capabilities: Option<Vec<String>>,
2627 pub role_versions: Option<std::collections::BTreeMap<String, String>>,
2634 pub admission_facts: Option<serde_json::Value>,
2636 pub scope: Option<ScopeStamp>,
2645 pub call_mode: CallMode,
2648 pub peer: subc_protocol::peer::RouteBindPeer,
2676}
2677
2678impl RouteBindRequest {
2679 pub fn new(handle: RouteHandle, target: RouteTarget, identity: BindIdentity) -> Self {
2684 Self {
2685 handle,
2686 target,
2687 identity,
2688 principal: None,
2689 consumer_capabilities: None,
2690 role_versions: None,
2691 admission_facts: None,
2692 scope: None,
2693 call_mode: derive_call_mode(None),
2694 peer: subc_protocol::peer::RouteBindPeer::new(),
2695 }
2696 }
2697
2698 pub fn with_peer(mut self, peer: subc_protocol::peer::RouteBindPeer) -> Self {
2701 self.peer = peer;
2702 self
2703 }
2704
2705 pub fn peer_build(&self) -> Option<&str> {
2708 self.peer.peer_build.as_deref()
2709 }
2710
2711 pub fn with_principal(mut self, principal: Principal) -> Self {
2713 self.principal = Some(principal);
2714 self
2715 }
2716
2717 pub fn with_consumer_capabilities(mut self, consumer_capabilities: Vec<String>) -> Self {
2719 self.consumer_capabilities = Some(consumer_capabilities);
2720 self
2721 }
2722
2723 pub fn with_role_versions(
2725 mut self,
2726 role_versions: std::collections::BTreeMap<String, String>,
2727 ) -> Self {
2728 self.role_versions = Some(role_versions);
2729 self
2730 }
2731
2732 pub fn with_admission_facts(mut self, admission_facts: serde_json::Value) -> Self {
2734 self.admission_facts = Some(admission_facts);
2735 self
2736 }
2737
2738 pub fn with_scope(mut self, scope: ScopeStamp) -> Self {
2741 self.call_mode = derive_call_mode(Some(&scope));
2742 self.scope = Some(scope);
2743 self
2744 }
2745
2746 pub fn with_call_mode(mut self, call_mode: CallMode) -> Self {
2748 self.call_mode = call_mode;
2749 self
2750 }
2751}
2752
2753#[derive(Debug, Clone)]
2755pub struct BindDecision {
2756 kind: BindDecisionKind,
2757}
2758
2759impl BindDecision {
2760 pub fn accept() -> Self {
2762 Self {
2763 kind: BindDecisionKind::Accept,
2764 }
2765 }
2766
2767 pub fn reject(code: impl Into<String>, message: impl Into<String>) -> Self {
2769 Self {
2770 kind: BindDecisionKind::Reject {
2771 code: code.into(),
2772 message: message.into(),
2773 detail: None,
2774 },
2775 }
2776 }
2777
2778 pub fn reject_with_detail(
2785 code: impl Into<String>,
2786 message: impl Into<String>,
2787 detail: serde_json::Value,
2788 ) -> Self {
2789 Self {
2790 kind: BindDecisionKind::Reject {
2791 code: code.into(),
2792 message: message.into(),
2793 detail: Some(detail),
2794 },
2795 }
2796 }
2797}
2798
2799#[derive(Debug, Clone)]
2800enum BindDecisionKind {
2801 Accept,
2802 Reject {
2803 code: String,
2804 message: String,
2805 detail: Option<serde_json::Value>,
2806 },
2807}
2808
2809pub async fn serve<H>(manifest: ModuleManifest, handler: H) -> Result<(), SubcModuleError>
2818where
2819 H: ModuleHandler,
2820{
2821 ServeOptions::default().serve(manifest, handler).await
2822}
2823
2824#[derive(Clone, Debug, Default)]
2828pub struct ModuleStopHandle {
2829 token: CancellationToken,
2830}
2831
2832impl ModuleStopHandle {
2833 pub fn new() -> Self {
2834 Self::default()
2835 }
2836
2837 pub fn stop(&self) {
2840 self.token.cancel();
2841 }
2842}
2843
2844#[derive(Clone, Debug)]
2847#[non_exhaustive]
2848pub struct ServeOptions {
2849 registration_channel: bool,
2850 prefix_child: bool,
2851 writer_drain_timeout: Duration,
2852 stop_handle: ModuleStopHandle,
2853 live_upgrade: bool,
2854 connection_file: Option<PathBuf>,
2855}
2856
2857impl Default for ServeOptions {
2858 fn default() -> Self {
2859 Self {
2860 writer_drain_timeout: DEFAULT_WRITER_DRAIN_TIMEOUT,
2861 registration_channel: false,
2862 prefix_child: false,
2863 stop_handle: ModuleStopHandle::new(),
2864 live_upgrade: false,
2865 connection_file: None,
2866 }
2867 }
2868}
2869
2870impl ServeOptions {
2871 pub fn with_writer_drain_timeout(mut self, timeout: Duration) -> Self {
2881 self.writer_drain_timeout = timeout;
2882 self
2883 }
2884
2885 pub fn with_stop_handle(mut self, handle: ModuleStopHandle) -> Self {
2888 self.stop_handle = handle;
2889 self
2890 }
2891
2892 pub async fn serve<H: ModuleHandler>(
2894 self,
2895 mut manifest: ModuleManifest,
2896 handler: H,
2897 ) -> Result<(), SubcModuleError> {
2898 let connection_file = parse_subc_arg(env::args_os().skip(1))?;
2899 if let Some(module_id) = module_id_from_env()? {
2900 manifest.module_id = module_id;
2901 }
2902 self.serve_with(&connection_file, manifest, handler).await
2903 }
2904
2905 pub async fn serve_with<H: ModuleHandler>(
2907 self,
2908 connection_file: &Path,
2909 manifest: ModuleManifest,
2910 handler: H,
2911 ) -> Result<(), SubcModuleError> {
2912 if let Some((_handle, future)) = self
2913 .serve_with_handle(connection_file, manifest, handler)
2914 .await?
2915 {
2916 future.await?;
2917 }
2918 Ok(())
2919 }
2920
2921 pub async fn serve_from_env_with_handle<H: ModuleHandler>(
2935 self,
2936 mut manifest: ModuleManifest,
2937 handler: H,
2938 ) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
2939 let connection_file = parse_subc_arg(env::args_os().skip(1))?;
2940 if let Some(module_id) = module_id_from_env()? {
2941 manifest.module_id = module_id;
2942 }
2943 self.serve_with_handle(&connection_file, manifest, handler)
2944 .await
2945 }
2946
2947 pub async fn serve_with_handle<H: ModuleHandler>(
2959 self,
2960 connection_file: &Path,
2961 manifest: ModuleManifest,
2962 handler: H,
2963 ) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
2964 prepare_connection(connection_file, manifest, handler, self).await
2965 }
2966}
2967
2968pub async fn serve_from_env_with_handle<H>(
2983 manifest: ModuleManifest,
2984 handler: H,
2985) -> Result<(ModuleHandle, ModuleServeFuture), SubcModuleError>
2986where
2987 H: ModuleHandler,
2988{
2989 ServeOptions::default()
2990 .serve_from_env_with_handle(manifest, handler)
2991 .await?
2992 .ok_or(SubcModuleError::ConnectionClosedBeforeHelloAck)
2993}
2994
2995pub async fn serve_with<H>(
2998 connection_file: &Path,
2999 manifest: ModuleManifest,
3000 handler: H,
3001) -> Result<(), SubcModuleError>
3002where
3003 H: ModuleHandler,
3004{
3005 ServeOptions::default()
3006 .serve_with(connection_file, manifest, handler)
3007 .await
3008}
3009
3010pub async fn serve_with_handle<H>(
3013 connection_file: &Path,
3014 manifest: ModuleManifest,
3015 handler: H,
3016) -> Result<(ModuleHandle, ModuleServeFuture), SubcModuleError>
3017where
3018 H: ModuleHandler,
3019{
3020 ServeOptions::default()
3021 .serve_with_handle(connection_file, manifest, handler)
3022 .await?
3023 .ok_or(SubcModuleError::ConnectionClosedBeforeHelloAck)
3024}
3025
3026async fn prepare_connection<H: ModuleHandler>(
3027 connection_file: &Path,
3028 manifest: ModuleManifest,
3029 handler: H,
3030 mut options: ServeOptions,
3031) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
3032 if options.live_upgrade {
3033 options.connection_file = Some(connection_file.to_owned());
3034 }
3035 options.registration_channel = registration::adopt(&manifest.module_id)?;
3036 let stream = tokio::select! {
3037 biased;
3038 () = options.stop_handle.token.cancelled() => return Ok(None),
3039 stream = async {
3040 let claim = if registration::supervised() && !options.registration_channel {
3041 registration::prefix_claim(&manifest.module_id).await
3042 .map_err(|error| registration::serve_claim_error(&manifest.module_id, error))?
3043 } else {
3044 None
3045 };
3046 let mut stream = connect_to_subc(connection_file, options.registration_channel).await?;
3047 if let Some(claim) = claim {
3048 registration::present_claim(&mut stream, claim, AUTH_DEADLINE).await
3049 .map_err(|error| registration::serve_claim_error(&manifest.module_id, error))?;
3050 options.prefix_child = true;
3051 }
3052 Ok::<_, SubcModuleError>(stream)
3053 } => stream?,
3054 };
3055 register_connection(stream, manifest, handler, options).await
3056}
3057
3058#[cfg(any(test, feature = "test-support"))]
3061fn connection_serve_future<R, H>(
3062 read_half: R,
3063 tx: mpsc::Sender<Frame>,
3064 handler: Arc<H>,
3065 handle: ModuleHandle,
3066 writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3067) -> ModuleServeFuture
3068where
3069 R: AsyncRead + Unpin + Send + 'static,
3070 H: ModuleHandler,
3071{
3072 connection_serve_future_with_options(
3073 read_half,
3074 tx,
3075 handler,
3076 handle,
3077 writer,
3078 ServeOptions::default(),
3079 None,
3080 )
3081}
3082
3083async fn module_loop<R, H>(
3084 mut reader: R,
3085 egress: &mpsc::Sender<Frame>,
3086 handler: Arc<H>,
3087 module_handle: ModuleHandle,
3088 dispatcher: &RequestDispatcher,
3089 stop: &ModuleStopHandle,
3090) -> Result<ConnectionEnd, SubcModuleError>
3091where
3092 R: AsyncRead + Unpin,
3093 H: ModuleHandler,
3094{
3095 serve_frames(
3096 &mut reader,
3097 egress,
3098 &handler,
3099 &module_handle,
3100 dispatcher,
3101 stop,
3102 )
3103 .await
3104}
3105
3106async fn serve_frames<R, H>(
3107 reader: &mut R,
3108 egress: &mpsc::Sender<Frame>,
3109 handler: &Arc<H>,
3110 module_handle: &ModuleHandle,
3111 dispatcher: &RequestDispatcher,
3112 stop: &ModuleStopHandle,
3113) -> Result<ConnectionEnd, SubcModuleError>
3114where
3115 R: AsyncRead + Unpin,
3116 H: ModuleHandler,
3117{
3118 let shared = module_handle.shared();
3119 loop {
3120 let read = tokio::select! {
3121 biased;
3122 () = dispatcher.failed.cancelled() => return Err(dispatcher.take_failure().expect("failure signalled")),
3123 () = stop.token.cancelled() => return Ok(ConnectionEnd::Closed),
3124 () = shared.close_token.cancelled() => return Ok(ConnectionEnd::Closed),
3125 read = read_frame(reader) => read,
3126 };
3127 let frame = match read {
3128 Ok(Some(frame)) => frame,
3129 Ok(None) => return Ok(ConnectionEnd::Eof),
3131 Err(FrameIoError::Io(error)) if is_disconnect(&error) => {
3134 return Ok(ConnectionEnd::Reset);
3135 }
3136 Err(err) => return Err(SubcModuleError::FrameIo(err)),
3137 };
3138 if !handle_frame(
3139 frame,
3140 egress,
3141 Arc::clone(handler),
3142 dispatcher.clone(),
3143 module_handle.clone(),
3144 )
3145 .await?
3146 {
3147 return Ok(ConnectionEnd::Goodbye);
3149 }
3150 }
3151}
3152
3153async fn handle_frame<H>(
3154 frame: Frame,
3155 egress: &mpsc::Sender<Frame>,
3156 handler: Arc<H>,
3157 dispatcher: RequestDispatcher,
3158 module_handle: ModuleHandle,
3159) -> Result<bool, SubcModuleError>
3160where
3161 H: ModuleHandler,
3162{
3163 if frame.header.channel != 0
3164 && !module_handle.validate_ingress(frame.header.channel, frame.header.epoch)?
3165 {
3166 return Ok(true);
3167 }
3168 match frame.header.ty {
3169 FrameType::Ping if frame.header.channel == 0 => {
3170 let pong = Frame::build_with_version(
3171 frame.header.ver,
3172 FrameType::Pong,
3173 frame.header.flags,
3174 0,
3175 0,
3176 frame.header.corr,
3177 Vec::new(),
3178 )
3179 .map_err(SubcModuleError::FrameBuild)?;
3180 send_outbound(egress, pong).await?;
3181 Ok(true)
3182 }
3183 FrameType::Goodbye if frame.header.channel == 0 => Ok(false),
3184 FrameType::Goodbye => {
3185 let handle = module_handle.route_handle(frame.header.channel, frame.header.epoch);
3186 if module_handle.remove_route(handle)? {
3187 cancel_handle(&dispatcher.in_flight, handle)?;
3188 handler.on_route_gone(&handle).await;
3189 }
3190 Ok(true)
3191 }
3192 FrameType::Response if frame.header.channel == 0 => {
3193 let _ = module_handle.handle_control_reply(frame);
3194 Ok(true)
3195 }
3196 FrameType::Error | FrameType::StreamData | FrameType::StreamEnd
3197 if frame.header.channel == 0 =>
3198 {
3199 let _ = module_handle.handle_control_reply(frame);
3200 Ok(true)
3201 }
3202 FrameType::Cancel => {
3203 handle_cancel(frame, &dispatcher.in_flight)?;
3204 Ok(true)
3205 }
3206 FrameType::Request if frame.header.channel == 0 => {
3207 handle_control_request(frame, egress, handler, dispatcher, module_handle.clone())
3208 .await?;
3209 Ok(true)
3210 }
3211 FrameType::Request => {
3212 spawn_data_request(frame, egress.clone(), handler, dispatcher, module_handle)?;
3213 Ok(true)
3214 }
3215 FrameType::Push if frame.header.channel == 0 => {
3216 if config::changed(&frame, &module_handle) {
3217 return Ok(true);
3218 }
3219 handle_control_push(&frame, handler, &dispatcher, &module_handle);
3220 Ok(true)
3221 }
3222 _ => Ok(true),
3223 }
3224}
3225
3226fn handle_control_push<H>(
3228 frame: &Frame,
3229 handler: Arc<H>,
3230 dispatcher: &RequestDispatcher,
3231 module_handle: &ModuleHandle,
3232) where
3233 H: ModuleHandler,
3234{
3235 match serde_json::from_slice::<ModuleControlCommand>(&frame.body) {
3236 Ok(ModuleControlCommand::Draining {
3237 reason,
3238 deadline_ms,
3239 }) => {
3240 let accepting = matches!(
3241 serde_json::from_slice(&frame.body),
3242 Ok(subc_protocol::session::AcceptingDrainCommand::Draining {
3243 accepting: true,
3244 ..
3245 })
3246 );
3247 if !accepting {
3248 module_handle.fence_consumer_dials();
3249 }
3250 let started = spawn_draining_hook(
3251 handler,
3252 DrainNotice {
3253 reason: sdk_route_close_reason(reason),
3254 deadline: drain_deadline(deadline_ms),
3255 accepting,
3256 },
3257 dispatcher,
3258 );
3259 dispatcher
3260 .draining_hooks
3261 .lock()
3262 .unwrap_or_else(|poisoned| poisoned.into_inner())
3263 .push(started);
3264 }
3265 Ok(ModuleControlCommand::Upgrading { reconnect_by_ms }) => {
3266 module_handle.announce_upgrade(reconnect_by_ms)
3267 }
3268 Err(error) => {
3269 if !dispatcher
3270 .undecodable_push_logged
3271 .swap(true, Ordering::Relaxed)
3272 {
3273 let op = serde_json::from_slice::<serde_json::Value>(&frame.body)
3274 .ok()
3275 .and_then(|body| body.get("op")?.as_str().map(str::to_string));
3276 tracing::warn!(
3277 op = op.as_deref().unwrap_or("<none>"),
3278 error = %error,
3279 "ignoring a channel-0 push from subc that this SDK cannot decode; \
3280 further undecodable pushes on this connection are ignored without logging"
3281 );
3282 }
3283 }
3284 }
3285}
3286
3287fn spawn_draining_hook<H>(
3291 handler: Arc<H>,
3292 notice: DrainNotice,
3293 dispatcher: &RequestDispatcher,
3294) -> oneshot::Receiver<()>
3295where
3296 H: ModuleHandler,
3297{
3298 let (started_tx, started_rx) = oneshot::channel();
3299 dispatcher.spawn(async move {
3300 let mut hook = handler.on_draining_notice(notice);
3301 let mut started_tx = Some(started_tx);
3302 std::future::poll_fn(|cx| {
3303 let poll = hook.as_mut().poll(cx);
3304 if let Some(started) = started_tx.take() {
3305 let _ = started.send(());
3306 }
3307 poll
3308 })
3309 .await;
3310 });
3311 started_rx
3312}
3313
3314fn sdk_route_close_reason(reason: subc_protocol::RouteCloseReason) -> RouteCloseReason {
3318 match serde_json::to_value(reason) {
3319 Ok(serde_json::Value::String(wire)) => RouteCloseReason::from_wire(&wire),
3320 _ => RouteCloseReason::Unknown(format!("{reason:?}")),
3321 }
3322}
3323
3324fn drain_deadline(deadline_ms: u64) -> SystemTime {
3328 UNIX_EPOCH
3329 .checked_add(Duration::from_millis(deadline_ms))
3330 .unwrap_or_else(SystemTime::now)
3331}
3332
3333fn spawn_data_request<H>(
3334 frame: Frame,
3335 egress: mpsc::Sender<Frame>,
3336 handler: Arc<H>,
3337 dispatcher: RequestDispatcher,
3338 module_handle: ModuleHandle,
3339) -> Result<(), SubcModuleError>
3340where
3341 H: ModuleHandler,
3342{
3343 let handle = module_handle.route_handle(frame.header.channel, frame.header.epoch);
3344 let corr = frame.header.corr;
3345 let cancellation = CancellationToken::new();
3346 {
3347 let mut guard = lock_in_flight(&dispatcher.in_flight)?;
3348 guard.insert((handle.channel, handle.epoch, corr), cancellation.clone());
3349 }
3350
3351 let ctx = RequestCtx {
3352 handle,
3353 corr,
3354 ver: frame.header.ver,
3355 egress,
3356 module_handle,
3357 cancelled: cancellation,
3358 binary_reply: Arc::new(AtomicBool::new(false)),
3359 request_flags: frame.header.flags,
3360 request_body: Arc::from(frame.body.as_slice()),
3361 open: Arc::new(tokio::sync::Mutex::new(true)),
3362 };
3363 let body = frame.body;
3364 let in_flight = Arc::clone(&dispatcher.in_flight);
3365 let (pool, op) = dispatcher.pools.classify(&body);
3368 let pool = pool.clone();
3369 let wait = pool.start_waiting((handle.channel, handle.epoch, corr));
3370 dispatcher.clone().spawn_data(async move {
3371 let waiting = WaitingRequest {
3372 op,
3373 channel: handle.channel,
3374 corr,
3375 };
3376 let permit = match wait_for_permit(&pool, wait, waiting, &ctx.cancelled).await {
3377 PermitWaitOutcome::Acquired(permit) => Some(permit),
3378 PermitWaitOutcome::Cancelled => None,
3381 PermitWaitOutcome::Closed => {
3382 dispatcher
3384 .undelivered_replies
3385 .fetch_add(1, Ordering::Relaxed);
3386 if let Ok(mut guard) = in_flight.lock() {
3387 guard.remove(&(handle.channel, handle.epoch, corr));
3388 }
3389 return;
3390 }
3391 };
3392 let outcome = if permit.is_none() || ctx.cancelled.is_cancelled() {
3395 Ok(HandlerOutcome::Error {
3396 code: "cancelled".to_string(),
3397 message: "request cancelled".to_string(),
3398 })
3399 } else {
3400 catch_handler_panic(async { handler.handle(ctx.clone(), body).await }).await
3401 };
3402 let panicked = outcome.is_err();
3403 let outcome = outcome.unwrap_or_else(|()| HandlerOutcome::Error {
3404 code: "internal".to_string(),
3405 message: "module handler panicked".to_string(),
3406 });
3407 match send_handler_outcome(&ctx, outcome).await {
3408 Err(SubcModuleError::StaleRouteHandle(_)) if !panicked => {}
3412 Err(error) => {
3413 if matches!(error, SubcModuleError::WriterClosed) {
3414 dispatcher
3415 .undelivered_replies
3416 .fetch_add(1, Ordering::Relaxed);
3417 }
3418 dispatcher.fail(error);
3419 }
3420 Ok(()) if panicked => dispatcher.fail(SubcModuleError::HandlerPanic),
3421 Ok(()) => {}
3422 }
3423 if let Ok(mut guard) = in_flight.lock() {
3424 guard.remove(&(handle.channel, handle.epoch, corr));
3425 }
3426 });
3427 Ok(())
3428}
3429
3430fn spawn_health_request<H>(
3431 frame: Frame,
3432 egress: mpsc::Sender<Frame>,
3433 handler: Arc<H>,
3434 dispatcher: RequestDispatcher,
3435) -> Result<(), SubcModuleError>
3436where
3437 H: ModuleHandler,
3438{
3439 let channel = frame.header.channel;
3440 let epoch = frame.header.epoch;
3441 let corr = frame.header.corr;
3442 let ver = frame.header.ver;
3443 let cancellation = CancellationToken::new();
3444 {
3445 let mut guard = lock_in_flight(&dispatcher.in_flight)?;
3446 guard.insert((channel, epoch, corr), cancellation.clone());
3447 }
3448
3449 let in_flight = Arc::clone(&dispatcher.in_flight);
3450 dispatcher.clone().spawn(async move {
3451 if !cancellation.is_cancelled() {
3454 let result = async {
3455 let report = catch_handler_panic(async { handler.health().await }).await;
3456 let panicked = report.is_err();
3457 let (ty, body) = match report {
3458 Ok(report) => (
3459 FrameType::Response,
3460 serde_json::to_vec(&ModuleControlResponse::from(
3461 dispatcher.fold_health(report),
3462 ))?,
3463 ),
3464 Err(()) => (
3465 FrameType::Error,
3466 serde_json::to_vec(&ErrorBody::new("internal", "module handler panicked"))?,
3467 ),
3468 };
3469 let (ty, flags, body) = bounded_terminal(ty, control_flags(), body)?;
3470 let frame = Frame::build_with_version(ver, ty, flags, channel, epoch, corr, body)
3471 .map_err(SubcModuleError::FrameBuild)?;
3472 send_outbound(&egress, frame).await?;
3473 if panicked {
3474 return Err(SubcModuleError::HandlerPanic);
3475 }
3476 Ok(())
3477 }
3478 .await;
3479 if let Err(error) = result {
3480 if matches!(error, SubcModuleError::WriterClosed) {
3481 dispatcher
3482 .undelivered_replies
3483 .fetch_add(1, Ordering::Relaxed);
3484 }
3485 dispatcher.fail(error);
3486 }
3487 }
3488 if let Ok(mut guard) = in_flight.lock() {
3489 guard.remove(&(channel, epoch, corr));
3490 }
3491 });
3492 Ok(())
3493}
3494
3495async fn send_handler_outcome(
3496 ctx: &RequestCtx,
3497 outcome: HandlerOutcome,
3498) -> Result<(), SubcModuleError> {
3499 let mut open = ctx.open.lock().await;
3501 *open = false;
3502 match outcome {
3503 HandlerOutcome::Response(body) => {
3504 let flags = Flags::new(
3505 ctx.binary_reply.load(Ordering::Relaxed),
3506 Priority::Interactive,
3507 false,
3508 );
3509 ctx.send_frame(FrameType::Response, flags, body).await
3510 }
3511 HandlerOutcome::Error { code, message } => {
3512 let body = serde_json::to_vec(&ErrorBody::new(code, message))
3513 .map_err(SubcModuleError::Json)?;
3514 ctx.send_frame(FrameType::Error, data_flags(), body).await
3515 }
3516 HandlerOutcome::ErrorWithDetail {
3517 code,
3518 message,
3519 detail,
3520 } => {
3521 let body = serde_json::to_vec(&ErrorBody::new(code, message).with_detail(detail))
3522 .map_err(SubcModuleError::Json)?;
3523 ctx.send_frame(FrameType::Error, data_flags(), body).await
3524 }
3525 HandlerOutcome::Streamed => {
3526 ctx.send_frame(FrameType::StreamEnd, data_flags(), Vec::new())
3527 .await
3528 }
3529 }
3530}
3531
3532async fn catch_handler_panic<F: Future>(future: F) -> Result<F::Output, ()> {
3535 let mut future = std::pin::pin!(future);
3536 std::future::poll_fn(
3537 |cx| match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
3538 Ok(poll) => poll.map(Ok),
3539 Err(_) => std::task::Poll::Ready(Err(())),
3540 },
3541 )
3542 .await
3543}
3544
3545fn bounded_terminal(
3546 ty: FrameType,
3547 flags: Flags,
3548 body: Vec<u8>,
3549) -> Result<(FrameType, Flags, Vec<u8>), SubcModuleError> {
3550 let size = subc_protocol::HEADER_LEN + body.len();
3551 let limit = subc_protocol::MAX_DELIVERED_FRAME_LEN;
3552 if matches!(ty, FrameType::Response | FrameType::Error) && size > limit {
3553 let body = serde_json::to_vec(
3554 &ErrorBody::new("frame_too_large", "module reply exceeds frame limit")
3555 .with_detail(serde_json::json!({ "size": size, "limit": limit })),
3556 )?;
3557 return Ok((FrameType::Error, flags, body));
3559 }
3560 Ok((ty, flags, body))
3561}
3562
3563fn handle_cancel(frame: Frame, in_flight: &InFlight) -> Result<(), SubcModuleError> {
3564 let guard = lock_in_flight(in_flight)?;
3565 if let Some(cancellation) =
3566 guard.get(&(frame.header.channel, frame.header.epoch, frame.header.corr))
3567 {
3568 cancellation.cancel();
3569 }
3570 Ok(())
3571}
3572
3573fn cancel_handle(in_flight: &InFlight, handle: RouteHandle) -> Result<(), SubcModuleError> {
3574 let cancelled = {
3575 let mut guard = lock_in_flight(in_flight)?;
3576 let keys = guard
3577 .keys()
3578 .copied()
3579 .filter(|(channel, epoch, _)| *channel == handle.channel && *epoch == handle.epoch)
3580 .collect::<Vec<_>>();
3581 keys.into_iter()
3582 .filter_map(|key| guard.remove(&key))
3583 .collect::<Vec<_>>()
3584 };
3585 for cancellation in cancelled {
3586 cancellation.cancel();
3587 }
3588 Ok(())
3589}
3590
3591async fn handle_control_request<H>(
3592 frame: Frame,
3593 egress: &mpsc::Sender<Frame>,
3594 handler: Arc<H>,
3595 dispatcher: RequestDispatcher,
3596 module_handle: ModuleHandle,
3597) -> Result<(), SubcModuleError>
3598where
3599 H: ModuleHandler,
3600{
3601 if control_ops::request(
3602 &frame,
3603 egress,
3604 Arc::clone(&handler),
3605 &dispatcher,
3606 &module_handle,
3607 )
3608 .await?
3609 {
3610 return Ok(());
3611 }
3612 if config::review(
3613 &frame,
3614 egress,
3615 Arc::clone(&handler),
3616 &dispatcher,
3617 &module_handle,
3618 ) {
3619 return Ok(());
3620 }
3621 let request = match serde_json::from_slice::<ModuleControlRequest>(&frame.body) {
3627 Ok(request) => request,
3628 Err(error) => {
3629 let body = serde_json::to_vec(&ErrorBody::new(
3630 "invalid_request",
3631 format!("control request could not be decoded by this module: {error}"),
3632 ))
3633 .map_err(SubcModuleError::Json)?;
3634 let refusal = Frame::build_with_version(
3635 frame.header.ver,
3636 FrameType::Error,
3637 control_flags(),
3638 0,
3639 0,
3640 frame.header.corr,
3641 body,
3642 )
3643 .map_err(SubcModuleError::FrameBuild)?;
3644 send_outbound(egress, refusal).await?;
3645 return Ok(());
3646 }
3647 };
3648 match request {
3649 ModuleControlRequest::RouteBind {
3650 route_channel,
3651 epoch,
3652 target,
3653 identity,
3654 principal,
3655 consumer_capabilities,
3656 role_versions,
3657 admission_facts,
3658 scope,
3659 call_mode,
3660 } => {
3661 if let Some(stale) = module_handle.installed_route(route_channel)? {
3668 if epoch <= stale.epoch {
3669 let body = serde_json::to_vec(&ErrorBody::new(
3670 "route_rejected",
3671 format!(
3672 "route.bind epoch {epoch} does not supersede installed epoch {} on channel {route_channel}",
3673 stale.epoch
3674 ),
3675 ))
3676 .map_err(SubcModuleError::Json)?;
3677 let reject = Frame::build_with_version(
3678 frame.header.ver,
3679 FrameType::Error,
3680 control_flags(),
3681 0,
3682 0,
3683 frame.header.corr,
3684 body,
3685 )
3686 .map_err(SubcModuleError::FrameBuild)?;
3687 send_outbound(egress, reject).await?;
3688 return Ok(());
3689 }
3690 if module_handle.remove_route(stale)? {
3691 cancel_handle(&dispatcher.in_flight, stale)?;
3692 handler.on_route_gone(&stale).await;
3693 }
3694 }
3695 let handle = module_handle.route_handle(route_channel, epoch);
3696 let peer =
3700 match serde_json::from_slice::<subc_protocol::peer::RouteBindPeer>(&frame.body) {
3701 Ok(peer) => peer,
3702 Err(error) => {
3703 tracing::warn!(
3704 channel = route_channel,
3705 epoch,
3706 %error,
3707 "route.bind peer keys did not decode; treating them as absent"
3708 );
3709 subc_protocol::peer::RouteBindPeer::new()
3710 }
3711 };
3712 let req = RouteBindRequest {
3713 handle,
3714 target,
3715 identity,
3716 principal,
3717 consumer_capabilities,
3718 role_versions,
3719 admission_facts,
3720 call_mode: call_mode.unwrap_or_else(|| derive_call_mode(scope.as_ref())),
3721 scope,
3722 peer,
3723 };
3724 let decision = handler.on_bind(&req).await;
3725 match decision.kind {
3726 BindDecisionKind::Accept => {
3727 let response = match serde_json::to_vec(&ModuleControlResponse::RouteBindAck {})
3728 .map_err(SubcModuleError::Json)
3729 .and_then(|body| {
3730 Frame::build_with_version(
3731 frame.header.ver,
3732 FrameType::Response,
3733 control_flags(),
3734 0,
3735 0,
3736 frame.header.corr,
3737 body,
3738 )
3739 .map_err(SubcModuleError::FrameBuild)
3740 }) {
3741 Ok(response) => response,
3742 Err(err) => {
3743 handler.on_route_gone(&handle).await;
3744 return Err(err);
3745 }
3746 };
3747 if let Err(err) = send_outbound(egress, response).await {
3748 handler.on_route_gone(&handle).await;
3749 return Err(err);
3750 }
3751 if let Err(err) = module_handle.install_route(handle) {
3752 handler.on_route_gone(&handle).await;
3753 return Err(err);
3754 }
3755 handler.on_bound(&handle).await;
3756 }
3757 BindDecisionKind::Reject {
3758 code,
3759 message,
3760 detail,
3761 } => {
3762 let body = match detail {
3763 Some(detail) => ErrorBody::new(code, message).with_detail(detail),
3764 None => ErrorBody::new(code, message),
3765 };
3766 let result = serde_json::to_vec(&body)
3767 .map_err(SubcModuleError::Json)
3768 .and_then(|body| {
3769 Frame::build_with_version(
3770 frame.header.ver,
3771 FrameType::Error,
3772 control_flags(),
3773 0,
3774 0,
3775 frame.header.corr,
3776 body,
3777 )
3778 .map_err(SubcModuleError::FrameBuild)
3779 });
3780 let result = match result {
3781 Ok(response) => send_outbound(egress, response).await,
3782 Err(err) => Err(err),
3783 };
3784 handler.on_route_gone(&handle).await;
3785 result?;
3786 }
3787 }
3788 }
3789 ModuleControlRequest::HealthCheck {} => {
3790 spawn_health_request(frame, egress.clone(), handler, dispatcher)?;
3791 }
3792 }
3793 Ok(())
3794}
3795
3796async fn expect_hello_ack<R>(reader: &mut R) -> Result<ModuleHelloAckBody, SubcModuleError>
3797where
3798 R: AsyncRead + Unpin,
3799{
3800 let Some(frame) = read_frame(reader).await.map_err(SubcModuleError::FrameIo)? else {
3801 return Err(SubcModuleError::ConnectionClosedBeforeHelloAck);
3802 };
3803 match frame.header.ty {
3804 FrameType::HelloAck => serde_json::from_slice(&frame.body).map_err(SubcModuleError::Json),
3805 FrameType::Error => {
3806 let body =
3807 serde_json::from_slice::<ErrorBody>(&frame.body).map_err(SubcModuleError::Json)?;
3808 Err(SubcModuleError::HelloRejected { body })
3809 }
3810 ty => Err(SubcModuleError::UnexpectedHelloAck { ty }),
3811 }
3812}
3813
3814pub trait ModuleStream: AsyncRead + AsyncWrite + Unpin + Send {}
3816impl<T: AsyncRead + AsyncWrite + Unpin + Send> ModuleStream for T {}
3817
3818async fn connect_to_subc(
3819 connection_file_path: &Path,
3820 registration_channel: bool,
3821) -> Result<Box<dyn ModuleStream>, SubcModuleError> {
3822 let conn = connection_file::read_for_client(connection_file_path).map_err(|source| {
3823 SubcModuleError::ConnectionFile {
3824 path: connection_file_path.to_path_buf(),
3825 source,
3826 }
3827 })?;
3828 if let Some(mut stream) = if registration_channel {
3829 registration::take_stream()?
3830 } else {
3831 None
3832 } {
3833 authenticate_client(&mut stream, &conn, AUTH_DEADLINE)
3834 .await
3835 .map_err(|source| SubcModuleError::Auth {
3836 path: connection_file_path.to_path_buf(),
3837 endpoint: "registration channel".into(),
3838 source,
3839 })?;
3840 return Ok(stream);
3841 }
3842 let endpoint = conn
3843 .endpoints
3844 .first()
3845 .ok_or_else(|| SubcModuleError::NoEndpoint {
3846 path: connection_file_path.to_path_buf(),
3847 })?;
3848 let endpoint_label = format!("{}:{}", endpoint.host, endpoint.port);
3849 let mut stream = connect_endpoint(&endpoint.host, endpoint.port)
3850 .await
3851 .map_err(|source| SubcModuleError::Connect {
3852 path: connection_file_path.to_path_buf(),
3853 endpoint: endpoint_label.clone(),
3854 source,
3855 })?;
3856 let _ = stream.set_nodelay(true);
3866 authenticate_client(&mut stream, &conn, AUTH_DEADLINE)
3867 .await
3868 .map_err(|source| SubcModuleError::Auth {
3869 path: connection_file_path.to_path_buf(),
3870 endpoint: endpoint_label,
3871 source,
3872 })?;
3873 Ok(Box::new(stream))
3874}
3875
3876async fn connect_endpoint(host: &str, port: u16) -> io::Result<TcpStream> {
3877 let host = host
3878 .strip_prefix('[')
3879 .and_then(|h| h.strip_suffix(']'))
3880 .unwrap_or(host);
3881 TcpStream::connect((host, port)).await
3882}
3883
3884async fn send_goodbye(tx: &mpsc::Sender<Frame>) -> Result<(), SubcModuleError> {
3885 let frame = Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 0, Vec::new())
3886 .map_err(SubcModuleError::FrameBuild)?;
3887 send_outbound(tx, frame).await
3888}
3889
3890fn is_disconnect(error: &io::Error) -> bool {
3891 matches!(
3892 error.kind(),
3893 io::ErrorKind::ConnectionReset
3894 | io::ErrorKind::ConnectionAborted
3895 | io::ErrorKind::BrokenPipe
3896 )
3897}
3898
3899fn writer_ended(
3900 result: Result<Result<(), WriterFailure>, tokio::task::JoinError>,
3901) -> SubcModuleError {
3902 match result {
3903 Ok(Ok(())) => SubcModuleError::WriterClosed,
3904 Ok(Err(error)) => SubcModuleError::FrameIo(error.error),
3905 Err(error) => SubcModuleError::WriterTask(error),
3906 }
3907}
3908
3909fn writer_connection_end(
3910 result: Result<Result<(), WriterFailure>, tokio::task::JoinError>,
3911) -> Result<ConnectionEnd, SubcModuleError> {
3912 match writer_ended(result) {
3913 SubcModuleError::FrameIo(FrameIoError::Io(error)) if is_disconnect(&error) => {
3914 Ok(ConnectionEnd::Reset)
3915 }
3916 error => Err(error),
3917 }
3918}
3919
3920async fn finish_writer(
3921 mut writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3922 deadline: Instant,
3923) -> (Result<(), SubcModuleError>, usize) {
3924 match timeout_at(deadline, &mut writer).await {
3925 Ok(Ok(Ok(()))) => (Ok(()), 0),
3926 Ok(Ok(Err(failure))) => (
3927 Err(SubcModuleError::FrameIo(failure.error)),
3928 failure.undelivered_replies,
3929 ),
3930 Ok(Err(error)) => (Err(SubcModuleError::WriterTask(error)), 0),
3931 Err(_) => {
3932 writer.abort();
3933 let _ = writer.await;
3934 (Ok(()), 0)
3935 }
3936 }
3937}
3938
3939struct WriterFailure {
3940 error: FrameIoError,
3941 undelivered_replies: usize,
3942}
3943
3944async fn finish_writer_and_drain<R>(
3949 writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3950 reader: &mut R,
3951 deadline: Instant,
3952) -> (Result<(), SubcModuleError>, usize)
3953where
3954 R: AsyncRead + Unpin,
3955{
3956 let flushed = finish_writer(writer, deadline).await;
3957 if flushed.0.is_ok() {
3958 drain_until_peer_closes(reader, deadline).await;
3959 }
3960 flushed
3961}
3962
3963async fn drain_until_peer_closes<R>(reader: &mut R, deadline: Instant)
3981where
3982 R: AsyncRead + Unpin,
3983{
3984 if Instant::now() >= deadline {
3985 return;
3986 }
3987 let mut discard = [0u8; 4096];
3988 let _ = timeout_at(deadline, async {
3989 while let Ok(read) = reader.read(&mut discard).await {
3990 if read == 0 {
3991 break;
3992 }
3993 }
3994 })
3995 .await;
3996}
3997
3998fn is_reply(frame: &Frame) -> bool {
3999 matches!(
4000 frame.header.ty,
4001 FrameType::Response | FrameType::Error | FrameType::StreamEnd
4002 )
4003}
4004
4005async fn drain_writer<W>(write_half: W, mut rx: mpsc::Receiver<Frame>) -> Result<(), WriterFailure>
4006where
4007 W: AsyncWrite + Unpin,
4008{
4009 let mut writer = BufWriter::new(write_half);
4010 let mut pending_replies = 0;
4011 let result = async {
4012 while let Some(frame) = rx.recv().await {
4013 pending_replies += usize::from(is_reply(&frame));
4014 write_frame(&mut writer, &frame).await?;
4015 while let Ok(frame) = rx.try_recv() {
4016 pending_replies += usize::from(is_reply(&frame));
4017 write_frame(&mut writer, &frame).await?;
4018 }
4019 writer.flush().await.map_err(FrameIoError::Io)?;
4020 pending_replies = 0;
4021 }
4022 writer.flush().await.map_err(FrameIoError::Io)?;
4023 let _ = writer.shutdown().await;
4032 Ok(())
4033 }
4034 .await;
4035 result.map_err(|error| {
4036 rx.close();
4037 while let Ok(frame) = rx.try_recv() {
4038 pending_replies += usize::from(is_reply(&frame));
4039 }
4040 WriterFailure {
4041 error,
4042 undelivered_replies: pending_replies,
4043 }
4044 })
4045}
4046
4047async fn send_outbound(egress: &mpsc::Sender<Frame>, frame: Frame) -> Result<(), SubcModuleError> {
4048 egress
4049 .send(frame)
4050 .await
4051 .map_err(|_| SubcModuleError::WriterClosed)
4052}
4053
4054fn parse_subc_arg(args: impl IntoIterator<Item = OsString>) -> Result<PathBuf, SubcModuleError> {
4055 let mut args = args.into_iter();
4056 while let Some(arg) = args.next() {
4057 if arg == "--subc" {
4058 let value = args.next().ok_or(SubcModuleError::MissingSubcValue)?;
4059 return Ok(PathBuf::from(value));
4060 }
4061 if let Some(raw) = arg.to_str().and_then(|arg| arg.strip_prefix("--subc=")) {
4062 if raw.is_empty() {
4063 return Err(SubcModuleError::MissingSubcValue);
4064 }
4065 return Ok(PathBuf::from(raw));
4066 }
4067 }
4068 Err(SubcModuleError::MissingSubcArg)
4069}
4070
4071fn module_id_from_env() -> Result<Option<String>, SubcModuleError> {
4072 match env::var(SUBC_MODULE_ID_ENV) {
4073 Ok(value) if !value.trim().is_empty() => Ok(Some(value)),
4074 Ok(_) => Err(SubcModuleError::EmptyModuleIdEnv),
4075 Err(env::VarError::NotPresent) => Ok(None),
4076 Err(env::VarError::NotUnicode(value)) => {
4077 Err(SubcModuleError::NonUnicodeModuleIdEnv { value })
4078 }
4079 }
4080}
4081
4082fn lock_in_flight(
4083 in_flight: &InFlight,
4084) -> Result<std::sync::MutexGuard<'_, HashMap<RequestKey, CancellationToken>>, SubcModuleError> {
4085 in_flight
4086 .lock()
4087 .map_err(|_| SubcModuleError::InFlightPoisoned)
4088}
4089
4090fn control_flags() -> Flags {
4091 Flags::new(false, Priority::Passive, false)
4092}
4093
4094fn data_flags() -> Flags {
4095 Flags::new(false, Priority::Interactive, false)
4096}
4097
4098#[derive(Debug)]
4099#[non_exhaustive]
4100pub enum SubcModuleError {
4101 InvalidControlOp(String),
4103 DuplicateControlCorrelation(u64),
4105 RegistrationChannel(io::Error),
4106 MissingSubcArg,
4107 MissingSubcValue,
4108 EmptyModuleIdEnv,
4109 NonUnicodeModuleIdEnv {
4110 value: OsString,
4111 },
4112 ConnectionFile {
4113 path: PathBuf,
4114 source: ConnectionFileError,
4115 },
4116 NoEndpoint {
4117 path: PathBuf,
4118 },
4119 Connect {
4120 path: PathBuf,
4121 endpoint: String,
4122 source: io::Error,
4123 },
4124 Auth {
4125 path: PathBuf,
4126 endpoint: String,
4127 source: AuthError,
4128 },
4129 FrameIo(FrameIoError),
4130 FrameBuild(FrameBuildError),
4131 Json(serde_json::Error),
4132 WriterClosed,
4133 HandlerPanic,
4135 StaleRouteHandle(RouteHandle),
4136 ConnectionTokenExhausted,
4137 WriterTask(tokio::task::JoinError),
4138 InFlightPoisoned,
4139 ConnectionClosedBeforeHelloAck,
4140 UnexpectedHelloAck {
4141 ty: FrameType,
4142 },
4143 HelloRejected {
4144 body: ErrorBody,
4145 },
4146 LaunchNonce(launch_nonce::LaunchNonceError),
4149 RequestEnded,
4152}
4153
4154impl fmt::Display for SubcModuleError {
4155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4156 match self {
4157 Self::InvalidControlOp(op) => {
4158 write!(f, "invalid or reserved control operation: {op:?}")
4159 }
4160 Self::DuplicateControlCorrelation(corr) => {
4161 write!(f, "duplicate in-flight control correlation: {corr}")
4162 }
4163 Self::RegistrationChannel(error) => write!(f, "registration channel: {error}"),
4164 Self::MissingSubcArg => write!(f, "missing required --subc <connection-file> argument"),
4165 Self::MissingSubcValue => write!(f, "--subc requires a connection-file path value"),
4166 Self::EmptyModuleIdEnv => write!(f, "{SUBC_MODULE_ID_ENV} must not be empty when set"),
4167 Self::NonUnicodeModuleIdEnv { value } => write!(
4168 f,
4169 "{SUBC_MODULE_ID_ENV} must be valid UTF-8, got '{}'",
4170 value.to_string_lossy()
4171 ),
4172 Self::ConnectionFile { path, source } => write!(
4173 f,
4174 "failed to read subc connection file '{}': {source}",
4175 path.display()
4176 ),
4177 Self::NoEndpoint { path } => write!(
4178 f,
4179 "subc connection file '{}' has no endpoints",
4180 path.display()
4181 ),
4182 Self::Connect {
4183 path,
4184 endpoint,
4185 source,
4186 } => write!(
4187 f,
4188 "failed to connect to subc endpoint {endpoint} from '{}': {source}",
4189 path.display()
4190 ),
4191 Self::Auth {
4192 path,
4193 endpoint,
4194 source,
4195 } => write!(
4196 f,
4197 "failed to authenticate to subc endpoint {endpoint} from '{}': {source}",
4198 path.display()
4199 ),
4200 Self::FrameIo(err) => fmt::Display::fmt(err, f),
4201 Self::FrameBuild(err) => write!(f, "frame build error: {err}"),
4202 Self::Json(err) => write!(f, "JSON error: {err}"),
4203 Self::WriterClosed => write!(f, "module writer task closed"),
4204 Self::HandlerPanic => write!(f, "module handler panicked"),
4205 Self::StaleRouteHandle(handle) => write!(f, "stale route handle: {handle:?}"),
4206 Self::ConnectionTokenExhausted => write!(f, "module connection token exhausted"),
4207 Self::WriterTask(err) => write!(f, "module writer task failed: {err}"),
4208 Self::InFlightPoisoned => write!(f, "in-flight registry lock poisoned"),
4209 Self::ConnectionClosedBeforeHelloAck => write!(f, "connection closed before HELLO_ACK"),
4210 Self::UnexpectedHelloAck { ty } => write!(f, "expected HELLO_ACK, got {ty:?}"),
4211 Self::HelloRejected { body } => write!(
4212 f,
4213 "HELLO rejected by subc: {} ({})",
4214 body.code, body.message
4215 ),
4216 Self::LaunchNonce(err) => write!(f, "launch nonce unavailable: {err}"),
4217 Self::RequestEnded => write!(f, "request already cancelled or answered"),
4218 }
4219 }
4220}
4221
4222impl Error for SubcModuleError {
4223 fn source(&self) -> Option<&(dyn Error + 'static)> {
4224 match self {
4225 Self::RegistrationChannel(error) => Some(error),
4226 Self::ConnectionFile { source, .. } => Some(source),
4227 Self::Connect { source, .. } => Some(source),
4228 Self::Auth { source, .. } => Some(source),
4229 Self::FrameIo(err) => Some(err),
4230 Self::FrameBuild(err) => Some(err),
4231 Self::Json(err) => Some(err),
4232 Self::LaunchNonce(err) => Some(err),
4233 Self::WriterTask(err) => Some(err),
4234 Self::MissingSubcArg
4235 | Self::InvalidControlOp(_)
4236 | Self::DuplicateControlCorrelation(_)
4237 | Self::MissingSubcValue
4238 | Self::EmptyModuleIdEnv
4239 | Self::NonUnicodeModuleIdEnv { .. }
4240 | Self::NoEndpoint { .. }
4241 | Self::WriterClosed
4242 | Self::HandlerPanic
4243 | Self::StaleRouteHandle(_)
4244 | Self::ConnectionTokenExhausted
4245 | Self::InFlightPoisoned
4246 | Self::ConnectionClosedBeforeHelloAck
4247 | Self::UnexpectedHelloAck { .. }
4248 | Self::HelloRejected { .. }
4249 | Self::RequestEnded => None,
4250 }
4251 }
4252}
4253
4254impl From<serde_json::Error> for SubcModuleError {
4255 fn from(err: serde_json::Error) -> Self {
4256 Self::Json(err)
4257 }
4258}
4259
4260#[cfg(test)]
4261mod call_mode_tests;
4262
4263#[cfg(test)]
4264mod tests {
4265 use std::sync::atomic::{AtomicUsize, Ordering};
4266
4267 use serde_json::json;
4268
4269 use subc_protocol::manifest::{Concurrency, ExecutionMode, IdentityScope, Tool};
4270 use tokio::sync::Semaphore;
4271 use tokio::time::{advance, timeout};
4272
4273 use super::*;
4274
4275 struct EchoHandler;
4276
4277 #[async_trait]
4278 impl ModuleHandler for EchoHandler {
4279 async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
4280 HandlerOutcome::Response(body)
4281 }
4282 }
4283
4284 struct BlockingHandler {
4285 entered: Arc<AtomicUsize>,
4286 release: Semaphore,
4287 report: HealthReport,
4288 }
4289
4290 #[async_trait]
4291 impl ModuleHandler for BlockingHandler {
4292 async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
4293 self.entered.fetch_add(1, Ordering::SeqCst);
4294 self.release.acquire().await.unwrap().forget();
4295 HandlerOutcome::Streamed
4296 }
4297
4298 async fn health(&self) -> HealthReport {
4299 self.report.clone()
4300 }
4301 }
4302
4303 fn health_request(corr: u64) -> Frame {
4304 Frame::build(
4305 FrameType::Request,
4306 control_flags(),
4307 0,
4308 0,
4309 corr,
4310 serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).unwrap(),
4311 )
4312 .unwrap()
4313 }
4314
4315 fn data_request(channel: u16, corr: u64) -> Frame {
4316 Frame::build(
4317 FrameType::Request,
4318 data_flags(),
4319 channel,
4320 1,
4321 corr,
4322 b"opaque".to_vec(),
4323 )
4324 .unwrap()
4325 }
4326
4327 fn catalog_update_response(corr: u64) -> Frame {
4328 Frame::build(
4329 FrameType::Response,
4330 control_flags(),
4331 0,
4332 0,
4333 corr,
4334 serde_json::to_vec(&ModuleControlResponseToModule::CatalogUpdate {}).unwrap(),
4335 )
4336 .unwrap()
4337 }
4338
4339 fn test_module_handle(subc_ops: &[&str]) -> (ModuleHandle, mpsc::Receiver<Frame>) {
4340 let (tx, rx) = mpsc::channel(4);
4341 let ack = ModuleHelloAckBody {
4342 resume_token: None,
4343 negotiated_ver: PROTOCOL_VERSION,
4344 subc_ops: subc_ops.iter().map(|op| (*op).to_string()).collect(),
4345 subc_capabilities: Vec::new(),
4346 storage: None,
4347 machine_id: None,
4348 };
4349 (
4350 ModuleHandle::new(
4351 &ack,
4352 tx,
4353 1,
4354 CancellationToken::new(),
4355 tokio::runtime::Handle::current(),
4356 ),
4357 rx,
4358 )
4359 }
4360
4361 #[tokio::test]
4362 async fn accepting_drain_ready_requires_negotiation_and_uses_channel_zero() {
4363 let (legacy, mut silent) = test_module_handle(&[]);
4364 assert!(matches!(
4365 legacy.drain_ready().await,
4366 Err(DrainReadyError::Unsupported)
4367 ));
4368 assert!(silent.try_recv().is_err());
4369
4370 let (tx, mut rx) = mpsc::channel(1);
4371 let handle = ModuleHandle::new(
4372 &ModuleHelloAckBody {
4373 resume_token: None,
4374 negotiated_ver: PROTOCOL_VERSION,
4375 subc_ops: vec!["module.drain_ready".into()],
4376 subc_capabilities: vec!["accepting-drain/v1".into()],
4377 storage: None,
4378 machine_id: None,
4379 },
4380 tx,
4381 1,
4382 CancellationToken::new(),
4383 tokio::runtime::Handle::current(),
4384 );
4385 let (result, ()) = tokio::join!(handle.drain_ready(), async {
4386 let request = rx.recv().await.unwrap();
4387 assert_eq!(
4388 (
4389 request.header.ty,
4390 request.header.channel,
4391 request.header.epoch
4392 ),
4393 (FrameType::Request, 0, 0)
4394 );
4395 assert_eq!(request.body, br#"{"op":"module.drain_ready"}"#);
4396 assert!(handle.handle_control_reply(control_reply(
4397 FrameType::Response,
4398 request.header.corr,
4399 request.body
4400 )));
4401 });
4402 result.unwrap();
4403 }
4404
4405 #[test]
4406 fn module_handle_exposes_the_acked_machine_id_and_none_otherwise() {
4407 let runtime = tokio::runtime::Runtime::new().unwrap();
4408 let handle_for = |machine_id: Option<&str>| {
4409 let (tx, _rx) = mpsc::channel(1);
4410 let ack = ModuleHelloAckBody {
4411 resume_token: None,
4412 negotiated_ver: PROTOCOL_VERSION,
4413 subc_ops: Vec::new(),
4414 subc_capabilities: Vec::new(),
4415 storage: None,
4416 machine_id: machine_id.map(str::to_owned),
4417 };
4418 ModuleHandle::new(
4419 &ack,
4420 tx,
4421 1,
4422 CancellationToken::new(),
4423 runtime.handle().clone(),
4424 )
4425 };
4426 assert_eq!(
4427 handle_for(Some("0123456789abcdef0123456789abcdef"))
4428 .machine_id()
4429 .map(MachineId::as_str),
4430 Some("0123456789abcdef0123456789abcdef")
4431 );
4432 assert_eq!(handle_for(None).machine_id(), None);
4434 assert_eq!(handle_for(Some("not-a-machine-id")).machine_id(), None);
4435 }
4436
4437 fn test_provider_role(tool_names: &[&str]) -> ProviderRole {
4438 ProviderRole::ToolProvider {
4439 tools: tool_names
4440 .iter()
4441 .map(|name| Tool {
4442 name: (*name).to_string(),
4443 description: None,
4444 execution_mode: ExecutionMode::Pure,
4445 schema: json!({"type": "object"}),
4446 })
4447 .collect(),
4448 identity_scope: vec![IdentityScope::Project],
4449 concurrency: Concurrency::ModuleManaged,
4450 emits_push: false,
4451 sub_supervises: false,
4452 }
4453 }
4454
4455 #[tokio::test]
4456 async fn catalog_update_fails_fast_when_hello_ack_does_not_advertise_support() {
4457 let (handle, mut rx) = test_module_handle(&[]);
4458
4459 let error = handle
4460 .catalog_update(vec![test_provider_role(&["a"])])
4461 .await
4462 .unwrap_err();
4463 assert!(matches!(error, CatalogUpdateError::NotSupported));
4464 assert!(matches!(
4465 handle.set_ready(true).await,
4466 Err(CatalogUpdateError::NotSupported)
4467 ));
4468 assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
4469 }
4470
4471 #[tokio::test]
4472 async fn catalog_update_demuxes_multiple_in_flight_requests() {
4473 let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4474 let first_handle = handle.clone();
4475 let second_handle = handle.clone();
4476 let first = tokio::spawn(async move {
4477 first_handle
4478 .catalog_update(vec![test_provider_role(&["a"])])
4479 .await
4480 });
4481 let second = tokio::spawn(async move {
4482 second_handle
4483 .catalog_update(vec![test_provider_role(&["b"])])
4484 .await
4485 });
4486
4487 let first_frame = timeout(Duration::from_secs(1), rx.recv())
4488 .await
4489 .unwrap()
4490 .unwrap();
4491 let second_frame = timeout(Duration::from_secs(1), rx.recv())
4492 .await
4493 .unwrap()
4494 .unwrap();
4495 assert_eq!(first_frame.header.ty, FrameType::Request);
4496 assert_eq!(first_frame.header.channel, 0);
4497 assert_eq!(second_frame.header.ty, FrameType::Request);
4498 assert_eq!(second_frame.header.channel, 0);
4499 assert_ne!(first_frame.header.corr, second_frame.header.corr);
4500
4501 let (earlier, later) =
4502 if json_body(&first_frame.body)["provides"] == json!([test_provider_role(&["a"])]) {
4503 (first, second)
4504 } else {
4505 (second, first)
4506 };
4507 assert!(handle.handle_control_reply(catalog_update_response(second_frame.header.corr)));
4508 assert!(later.await.unwrap().is_ok());
4509 assert!(handle.handle_control_reply(catalog_update_response(first_frame.header.corr)));
4510 assert!(earlier.await.unwrap().is_ok());
4511
4512 let expected = json_body(&second_frame.body)["provides"].clone();
4513 let (result, ()) = tokio::join!(handle.set_ready(true), async {
4514 let frame = rx.recv().await.unwrap();
4515 assert_eq!(json_body(&frame.body)["provides"], expected);
4516 assert_eq!(json_body(&frame.body)["ready"], true);
4517 handle.handle_control_reply(catalog_update_response(frame.header.corr));
4518 });
4519 result.unwrap();
4520 }
4521
4522 fn json_body(body: &[u8]) -> serde_json::Value {
4523 serde_json::from_slice(body).unwrap()
4524 }
4525
4526 #[tokio::test]
4527 async fn role_declarations_update_requires_its_own_advertised_op() {
4528 for ops in [vec![], vec![MODULE_TO_SUBC_OP_CATALOG_UPDATE]] {
4529 let (handle, mut rx) = test_module_handle(&ops);
4530 assert!(matches!(
4531 handle.update_role_declarations(BTreeMap::new()).await,
4532 Err(CatalogUpdateError::NotSupported)
4533 ));
4534 assert!(matches!(
4535 rx.try_recv(),
4536 Err(mpsc::error::TryRecvError::Empty)
4537 ));
4538 }
4539 }
4540
4541 #[tokio::test]
4542 async fn role_declarations_update_sends_map_and_preserves_refusal() {
4543 let (handle, mut rx) =
4544 test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS]);
4545 let initial_roles = vec![test_provider_role(&["original"])];
4546 handle.shared().lock_inner().current_provides = Some(initial_roles.clone());
4547 for declarations in [
4548 json!({"media-provider/v1": {"engines": ["image"]}}),
4549 json!({}),
4550 ] {
4551 let map = serde_json::from_value(declarations.clone()).unwrap();
4552 let (result, ()) = tokio::join!(handle.update_role_declarations(map), async {
4553 let frame = rx.recv().await.unwrap();
4554 assert_eq!(frame.header.ty, FrameType::Request);
4555 assert_eq!(frame.header.channel, 0);
4556 assert_eq!(
4557 json_body(&frame.body),
4558 json!({"op": "catalog.update_role_declarations", "role_declarations": declarations})
4559 );
4560 handle.handle_control_reply(control_reply(
4561 FrameType::Response,
4562 frame.header.corr,
4563 serde_json::to_vec(&json!({"op": "catalog.update_role_declarations"})).unwrap(),
4564 ));
4565 });
4566 result.unwrap();
4567 }
4568 let (result, ()) = tokio::join!(handle.update_role_declarations(BTreeMap::new()), async {
4569 let frame = rx.recv().await.unwrap();
4570 handle.handle_control_reply(control_reply(FrameType::Error, frame.header.corr,
4571 serde_json::to_vec(&json!({"code": "invalid_role_declarations", "message": "role_declarations key must use capability-name grammar"})).unwrap()));
4572 });
4573 let Err(CatalogUpdateError::Rejected(body)) = result else {
4574 panic!("expected typed refusal")
4575 };
4576 assert_eq!(body.code, "invalid_role_declarations");
4577 assert_eq!(
4578 body.message,
4579 "role_declarations key must use capability-name grammar"
4580 );
4581 assert_eq!(
4582 handle.shared().lock_inner().current_provides,
4583 Some(initial_roles)
4584 );
4585 }
4586
4587 async fn ack_catalog_update(
4588 handle: &ModuleHandle,
4589 rx: &mut mpsc::Receiver<Frame>,
4590 provides: &[ProviderRole],
4591 ready: Option<bool>,
4592 capabilities: Option<&CapabilityDeclarations>,
4593 ) {
4594 let frame = rx.recv().await.unwrap();
4595 let mut expected = json!({"op": "catalog.update", "provides": provides});
4596 if let Some(ready) = ready {
4597 expected["ready"] = json!(ready);
4598 }
4599 if let Some(capabilities) = capabilities {
4600 expected["capabilities"] = json!(capabilities);
4601 }
4602 assert_eq!(json_body(&frame.body), expected);
4603 let mut wire = format!(
4604 r#"{{"op":"catalog.update","provides":{}"#,
4605 serde_json::to_string(provides).unwrap()
4606 );
4607 if let Some(capabilities) = capabilities {
4608 wire.push_str(&format!(
4609 r#","capabilities":{}"#,
4610 serde_json::to_string(capabilities).unwrap()
4611 ));
4612 }
4613 if let Some(ready) = ready {
4614 wire.push_str(&format!(r#","ready":{ready}"#));
4615 }
4616 wire.push('}');
4617 assert_eq!(frame.body, wire.as_bytes());
4618 assert!(handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4619 }
4620
4621 #[tokio::test]
4622 async fn catalog_update_set_ready_preserves_registered_and_replaced_roles() {
4623 let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4624 let initial = vec![test_provider_role(&["initial", "second"])];
4625 handle.shared().lock_inner().current_provides = Some(initial.clone());
4626 let (result, ()) = tokio::join!(
4627 handle.set_ready(true),
4628 ack_catalog_update(&handle, &mut rx, &initial, Some(true), None)
4629 );
4630 result.unwrap();
4631
4632 let replaced = vec![test_provider_role(&["replacement"])];
4633 let (result, ()) = tokio::join!(
4634 handle.catalog_update(replaced.clone()),
4635 ack_catalog_update(&handle, &mut rx, &replaced, None, None)
4636 );
4637 result.unwrap();
4638 let (result, ()) = tokio::join!(
4639 handle.set_ready(false),
4640 ack_catalog_update(&handle, &mut rx, &replaced, Some(false), None)
4641 );
4642 result.unwrap();
4643
4644 let attested = vec![test_provider_role(&["attested"])];
4645 let capabilities = CapabilityDeclarations {
4646 provides: vec!["test.capability".into()],
4647 requires: Vec::new(),
4648 must_never_reach: Vec::new(),
4649 };
4650 let (result, ()) = tokio::join!(
4651 handle.catalog_update_with_capabilities(attested.clone(), capabilities.clone()),
4652 ack_catalog_update(&handle, &mut rx, &attested, None, Some(&capabilities))
4653 );
4654 result.unwrap();
4655 let (result, ()) = tokio::join!(
4656 handle.set_ready(true),
4657 ack_catalog_update(&handle, &mut rx, &attested, Some(true), None)
4658 );
4659 result.unwrap();
4660 }
4661
4662 #[tokio::test]
4663 async fn catalog_update_set_ready_refuses_unknown_or_in_flight_roles() {
4664 let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4665 assert!(matches!(
4666 handle.set_ready(true).await,
4667 Err(CatalogUpdateError::Protocol(_))
4668 ));
4669 assert!(rx.try_recv().is_err());
4670
4671 let updating = handle.clone();
4672 let update = tokio::spawn(async move {
4673 updating
4674 .catalog_update(vec![test_provider_role(&["new"])])
4675 .await
4676 });
4677 let frame = rx.recv().await.unwrap();
4678 assert!(matches!(
4679 handle.set_ready(true).await,
4680 Err(CatalogUpdateError::Protocol(_))
4681 ));
4682 assert!(rx.try_recv().is_err());
4683 update.abort();
4684 assert!(update.await.unwrap_err().is_cancelled());
4685 assert!(!handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4686 assert!(matches!(
4687 handle.set_ready(true).await,
4688 Err(CatalogUpdateError::Protocol(_))
4689 ));
4690
4691 let roles = vec![test_provider_role(&["recovered"])];
4692 let (result, ()) = tokio::join!(
4693 handle.catalog_update(roles.clone()),
4694 ack_catalog_update(&handle, &mut rx, &roles, None, None)
4695 );
4696 result.unwrap();
4697 let (result, ()) = tokio::join!(
4698 handle.set_ready(true),
4699 ack_catalog_update(&handle, &mut rx, &roles, Some(true), None)
4700 );
4701 result.unwrap();
4702 }
4703
4704 #[tokio::test(start_paused = true)]
4705 async fn catalog_update_set_ready_timeout_does_not_replay_stale_roles() {
4706 let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4707 handle.shared().lock_inner().current_provides = Some(vec![test_provider_role(&["old"])]);
4708 assert!(matches!(
4709 handle
4710 .catalog_update(vec![test_provider_role(&["new"])])
4711 .await,
4712 Err(CatalogUpdateError::Timeout)
4713 ));
4714 let frame = rx.recv().await.unwrap();
4715 assert!(!handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4716 assert!(matches!(
4717 handle.set_ready(true).await,
4718 Err(CatalogUpdateError::Protocol(_))
4719 ));
4720 assert!(rx.try_recv().is_err());
4721 }
4722
4723 #[tokio::test]
4724 async fn catalog_update_set_ready_rejection_retains_last_accepted_roles() {
4725 let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4726 let initial = vec![test_provider_role(&["kept"])];
4727 handle.shared().lock_inner().current_provides = Some(initial.clone());
4728 let (result, ()) = tokio::join!(
4729 handle.catalog_update(vec![test_provider_role(&["rejected"])]),
4730 async {
4731 let frame = rx.recv().await.unwrap();
4732 handle.handle_control_reply(control_reply(
4733 FrameType::Error,
4734 frame.header.corr,
4735 br#"{"code":"catalog_update_frozen_field","message":"frozen"}"#.to_vec(),
4736 ));
4737 }
4738 );
4739 assert!(matches!(result, Err(CatalogUpdateError::FrozenField(_))));
4740 let (result, ()) = tokio::join!(
4741 handle.set_ready(true),
4742 ack_catalog_update(&handle, &mut rx, &initial, Some(true), None)
4743 );
4744 result.unwrap();
4745 }
4746
4747 fn control_reply(ty: FrameType, corr: u64, body: Vec<u8>) -> Frame {
4748 Frame::build(ty, control_flags(), 0, 0, corr, body).unwrap()
4749 }
4750
4751 async fn authorize_for_test(
4752 handle: &ModuleHandle,
4753 ) -> Result<RouteAuthorizeResponse, ScopeCallError> {
4754 handle
4755 .route_authorize(
4756 Principal::Direct,
4757 RouteAuthorizeScope::new(
4758 Principal::Reserved {
4759 module_id: "owner".into(),
4760 },
4761 "stored-scope",
4762 7,
4763 ),
4764 "target".into(),
4765 RouteAuthorizeExpected::new(
4766 subc_protocol::scope::ScopeKind::Head,
4767 &subc_protocol::scope::ScopeAttributes::default(),
4768 ),
4769 )
4770 .await
4771 }
4772
4773 #[tokio::test]
4774 async fn route_authorize_requires_advertised_operation() {
4775 let (tx, mut rx) = mpsc::channel(4);
4776 let ack = ModuleHelloAckBody {
4777 resume_token: None,
4778 negotiated_ver: PROTOCOL_VERSION,
4779 subc_ops: vec![],
4780 subc_capabilities: vec![subc_protocol::scope::ROUTE_AUTHORIZE_CAPABILITY.into()],
4782 storage: None,
4783 machine_id: None,
4784 };
4785 let handle = ModuleHandle::new(
4786 &ack,
4787 tx,
4788 1,
4789 CancellationToken::new(),
4790 tokio::runtime::Handle::current(),
4791 );
4792 let result = timeout(Duration::from_millis(100), authorize_for_test(&handle))
4793 .await
4794 .expect("an unsupported operation must return without sending or awaiting a reply");
4795 assert_eq!(
4796 result,
4797 Err(ScopeCallError::NotSupported {
4798 op: subc_protocol::scope::ROUTE_AUTHORIZE_OP,
4799 })
4800 );
4801 assert!(
4802 rx.try_recv().is_err(),
4803 "unsupported calls must send nothing"
4804 );
4805 }
4806
4807 #[tokio::test]
4808 async fn route_authorize_decodes_every_answer_and_permission_refusal() {
4809 use RouteAuthorizeOutcome::*;
4810 let (handle, mut rx) = test_module_handle(&[subc_protocol::scope::ROUTE_AUTHORIZE_OP]);
4811 for (wire, outcome, code) in [
4812 ("authorized", Authorized, None),
4813 ("scope_ended", ScopeEnded, Some("scope_not_live")),
4814 ("indeterminate", Indeterminate, Some("scope_not_synced")),
4815 ("epoch_changed", EpochChanged, Some("scope_ended")),
4816 ("claim_changed", ClaimChanged, None),
4817 (
4818 "proof_required",
4819 ProofRequired,
4820 Some("scope_bind_proof_required"),
4821 ),
4822 ("not_authorized", NotAuthorized, Some("scope_not_carrier")),
4823 ("target_absent", TargetAbsent, None),
4824 ] {
4825 let caller = handle.clone();
4826 let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4827 let request = rx.recv().await.unwrap();
4828 assert_eq!(request.header.ty, FrameType::Request);
4829 assert_eq!(request.header.channel, 0);
4830 assert_eq!(request.header.ver, PROTOCOL_VERSION);
4831 assert_eq!(
4832 serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
4833 serde_json::json!({
4834 "op": "route.authorize", "principal": {"kind": "direct"},
4835 "scope": {"owner": {"kind": "reserved", "module_id": "owner"},
4836 "ref": "stored-scope", "epoch": 7},
4837 "target": "target", "expected": {"kind": "head"}
4838 })
4839 );
4840 let content_version = (outcome == Authorized).then_some("sha256:content");
4841 let mut body = serde_json::json!({
4842 "op": "route.authorize", "outcome": wire, "message": "judgment"
4843 });
4844 if let Some(code) = code {
4845 body["route_open_code"] = code.into();
4846 }
4847 if let Some(version) = content_version {
4848 body["content_version"] = version.into();
4849 }
4850 assert!(handle.handle_control_reply(control_reply(
4851 FrameType::Response,
4852 request.header.corr,
4853 serde_json::to_vec(&body).unwrap(),
4854 )));
4855 let reply = pending.await.unwrap().unwrap();
4856 assert_eq!(reply.outcome, outcome);
4857 assert_eq!(reply.message, "judgment");
4858 assert_eq!(reply.route_open_code.as_deref(), code);
4859 assert_eq!(reply.content_version.as_deref(), content_version);
4860 }
4861
4862 for (code, message) in [
4863 ("route_authorize_not_permitted", "not the configured owner"),
4864 ("not_registered", "connection is not registered"),
4865 ("unexpected", "a future daemon call refusal"),
4866 ] {
4867 let caller = handle.clone();
4868 let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4869 let request = rx.recv().await.unwrap();
4870 assert!(handle.handle_control_reply(control_reply(
4871 FrameType::Error,
4872 request.header.corr,
4873 serde_json::to_vec(&serde_json::json!({"code": code, "message": message})).unwrap(),
4874 )));
4875 assert_eq!(
4876 pending.await.unwrap(),
4877 Err(ScopeCallError::Refused {
4878 code: code.into(),
4879 message: message.into(),
4880 })
4881 );
4882 }
4883 }
4884
4885 #[tokio::test]
4886 async fn route_authorize_rejects_malformed_and_unexpected_replies() {
4887 let (handle, mut rx) = test_module_handle(&[subc_protocol::scope::ROUTE_AUTHORIZE_OP]);
4888 for (ty, body) in [
4889 (FrameType::Response, r#"{"op":"catalog.update"}"#),
4890 (
4891 FrameType::Response,
4892 r#"{"op":"route.authorize","outcome":"authorized"}"#,
4893 ),
4894 (
4895 FrameType::Response,
4896 r#"{"op":"route.authorize","outcome":"future","message":"new"}"#,
4897 ),
4898 (FrameType::Error, "not json"),
4899 (FrameType::Request, "{}"),
4900 ] {
4901 let caller = handle.clone();
4902 let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4903 let request = rx.recv().await.unwrap();
4904 assert!(handle.handle_control_reply(control_reply(
4905 ty,
4906 request.header.corr,
4907 body.as_bytes().to_vec(),
4908 )));
4909 assert!(
4910 matches!(pending.await.unwrap(), Err(ScopeCallError::Protocol(_))),
4911 "{body}"
4912 );
4913 }
4914 }
4915
4916 #[tokio::test]
4917 async fn scope_served_by_requires_capability_and_decodes_open_replies() {
4918 let (unsupported, mut rx) = test_module_handle(&[subc_control::SCOPE_SERVED_BY_OP]);
4919 assert_eq!(
4920 unsupported
4921 .scope_served_by("s".into(), 1, "tool".into())
4922 .await,
4923 Err(ScopeCallError::NotSupported {
4924 op: subc_control::SCOPE_SERVED_BY_OP
4925 })
4926 );
4927 assert!(rx.try_recv().is_err());
4928 let (tx, mut rx) = mpsc::channel(4);
4929 let ack = ModuleHelloAckBody {
4930 resume_token: None,
4931 negotiated_ver: PROTOCOL_VERSION,
4932 subc_ops: vec![],
4933 subc_capabilities: vec![subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.into()],
4934 storage: None,
4935 machine_id: None,
4936 };
4937 let handle = ModuleHandle::new(
4938 &ack,
4939 tx,
4940 1,
4941 CancellationToken::new(),
4942 tokio::runtime::Handle::current(),
4943 );
4944 for answer in ["served", "not_served", "unknown", "future"] {
4945 let caller = handle.clone();
4946 let pending =
4947 tokio::spawn(
4948 async move { caller.scope_served_by("s".into(), 7, "tool".into()).await },
4949 );
4950 let request = rx.recv().await.unwrap();
4951 let decoded: subc_control::ScopeServedByRequest =
4952 serde_json::from_slice(&request.body).unwrap();
4953 assert_eq!(
4954 (
4955 decoded.scope_ref.as_str(),
4956 decoded.scope_epoch,
4957 decoded.module_id.as_str()
4958 ),
4959 ("s", 7, "tool")
4960 );
4961 assert!(handle.handle_control_reply(control_reply(FrameType::Response, request.header.corr,
4962 serde_json::to_vec(&serde_json::json!({"op":"scope.served_by", "answer":answer, "daemon_incarnation":"d"})).unwrap())));
4963 let reply = pending.await.unwrap().unwrap();
4964 assert_eq!(reply.daemon_incarnation, "d");
4965 assert_eq!(serde_json::to_value(reply.answer).unwrap(), answer);
4966 }
4967 let caller = handle.clone();
4968 let pending =
4969 tokio::spawn(async move { caller.scope_served_by("s".into(), 7, "tool".into()).await });
4970 let request = rx.recv().await.unwrap();
4971 assert!(handle.handle_control_reply(control_reply(
4972 FrameType::Error,
4973 request.header.corr,
4974 serde_json::to_vec(&serde_json::json!({"code":"not_registered", "message":"gone"}))
4975 .unwrap()
4976 )));
4977 assert_eq!(
4978 pending.await.unwrap().unwrap_err().code(),
4979 Some("not_registered")
4980 );
4981 }
4982
4983 fn owner() -> Principal {
4984 Principal::Reserved {
4985 module_id: "owner".to_string(),
4986 }
4987 }
4988
4989 mod scope_watch {
4990 use super::*;
4991 include!("module_subscription_tests.rs");
4992 }
4993
4994 #[tokio::test]
4998 async fn scope_ops_fail_fast_when_hello_ack_does_not_advertise_them() {
4999 let (handle, mut rx) = test_module_handle(&[]);
5000 assert_eq!(
5001 handle.scope_sync(1, Vec::new()).await.unwrap_err(),
5002 ScopeCallError::NotSupported { op: SCOPE_SYNC_OP }
5003 );
5004 assert_eq!(
5005 handle
5006 .scope_describe(owner(), "s".to_string())
5007 .await
5008 .unwrap_err(),
5009 ScopeCallError::NotSupported {
5010 op: SCOPE_DESCRIBE_OP
5011 }
5012 );
5013 assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5014
5015 let (describe_only, mut rx) = test_module_handle(&[SCOPE_DESCRIBE_OP]);
5016 assert_eq!(
5017 describe_only.scope_sync(1, Vec::new()).await.unwrap_err(),
5018 ScopeCallError::NotSupported { op: SCOPE_SYNC_OP }
5019 );
5020 assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5021
5022 let (sync_only, mut rx) = test_module_handle(&[SCOPE_SYNC_OP]);
5023 assert_eq!(
5024 sync_only
5025 .scope_describe(owner(), "s".to_string())
5026 .await
5027 .unwrap_err(),
5028 ScopeCallError::NotSupported {
5029 op: SCOPE_DESCRIBE_OP
5030 }
5031 );
5032 assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5033 }
5034
5035 #[tokio::test]
5036 async fn scope_apply_sends_nothing_without_its_own_advertised_op() {
5037 for ops in [&[][..], &[SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP][..]] {
5038 let (handle, mut rx) = test_module_handle(ops);
5039 assert_eq!(
5040 handle.scope_apply(2, Vec::new(), Vec::new()).await,
5041 Err(ScopeCallError::NotSupported { op: SCOPE_APPLY_OP })
5042 );
5043 assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5044 }
5045 }
5046
5047 #[tokio::test]
5048 async fn scope_apply_sends_the_delta_and_preserves_per_entry_outcomes() {
5049 let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5050 let apply = tokio::spawn({
5051 let handle = handle.clone();
5052 async move {
5053 handle
5054 .scope_apply(
5055 2,
5056 vec![ScopeRecord::new(
5057 "run",
5058 1,
5059 subc_protocol::scope::ScopeKind::Ephemeral,
5060 )
5061 .with_expires_at_ms(Some(12345))
5062 .with_workdir(Some("/session/folder".into()))
5063 .with_project_id(Some("project:1".into()))],
5064 vec![ScopeEnd::new("old", 3), ScopeEnd::new("missing", 1)],
5065 )
5066 .await
5067 }
5068 });
5069 let request = timeout(Duration::from_secs(1), rx.recv())
5070 .await
5071 .unwrap()
5072 .unwrap();
5073 assert_eq!(request.header.ty, FrameType::Request);
5074 assert_eq!(request.header.channel, 0);
5075 assert_eq!(
5076 serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
5077 serde_json::json!({
5078 "op": "scope.apply", "generation": 2,
5079 "upsert": [{"ref": "run", "scope_epoch": 1, "kind": "ephemeral", "expires_at_ms": 12345,
5080 "workdir": "/session/folder", "project_id": "project:1"}],
5081 "end": [{"ref": "old", "scope_epoch": 3}, {"ref": "missing", "scope_epoch": 1}]
5082 })
5083 );
5084 let body = serde_json::to_vec(&serde_json::json!({
5085 "op": "scope.apply", "generation": 2,
5086 "results": [{"ref": "run", "scope_epoch": 1, "outcome": "refused", "code": "scope_expired"}],
5087 "end_results": [
5088 {"ref": "old", "scope_epoch": 3, "outcome": "ended"},
5089 {"ref": "missing", "scope_epoch": 1, "outcome": "not_live"}
5090 ],
5091 "ended": [{"ref": "old", "scope_epoch": 3}]
5092 }))
5093 .unwrap();
5094 assert!(handle.handle_control_reply(control_reply(
5095 FrameType::Response,
5096 request.header.corr,
5097 body
5098 )));
5099 let reply = apply.await.unwrap().unwrap();
5100 assert_eq!(reply.generation, 2);
5101 assert_eq!(reply.results.len(), 1);
5102 assert_eq!(reply.results[0].scope_ref, "run");
5103 assert_eq!(
5104 reply.results[0].outcome,
5105 subc_protocol::scope::ScopeRecordOutcome::Refused
5106 );
5107 assert_eq!(reply.results[0].code.as_deref(), Some("scope_expired"));
5108 assert_eq!(reply.end_results.len(), 2);
5109 assert_eq!(reply.end_results[0].scope_ref, "old");
5110 assert_eq!(reply.end_results[0].scope_epoch, 3);
5111 assert_eq!(
5112 reply.end_results[0].outcome,
5113 subc_protocol::scope::ScopeEndOutcome::Ended
5114 );
5115 assert_eq!(reply.end_results[1].scope_ref, "missing");
5116 assert_eq!(
5117 reply.end_results[1].outcome,
5118 subc_protocol::scope::ScopeEndOutcome::NotLive
5119 );
5120 assert_eq!(reply.ended.len(), 1);
5121 assert_eq!(reply.ended[0].scope_ref, "old");
5122 assert_eq!(reply.ended[0].scope_epoch, 3);
5123 }
5124
5125 #[tokio::test]
5126 async fn scope_apply_rejects_a_reply_for_another_op() {
5127 let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5128 let apply = tokio::spawn({
5129 let handle = handle.clone();
5130 async move { handle.scope_apply(2, Vec::new(), Vec::new()).await }
5131 });
5132 let request = timeout(Duration::from_secs(1), rx.recv())
5133 .await
5134 .unwrap()
5135 .unwrap();
5136 let body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeSync {
5137 generation: 2,
5138 results: Vec::new(),
5139 ended: Vec::new(),
5140 })
5141 .unwrap();
5142 assert!(handle.handle_control_reply(control_reply(
5143 FrameType::Response,
5144 request.header.corr,
5145 body
5146 )));
5147 assert!(matches!(
5148 apply.await.unwrap(),
5149 Err(ScopeCallError::Protocol(_))
5150 ));
5151 }
5152
5153 #[tokio::test]
5154 async fn scope_apply_preserves_whole_call_refusal_codes() {
5155 let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5156 for code in [
5157 subc_protocol::error_codes::SCOPE_SYNC_REQUIRED,
5158 subc_protocol::error_codes::SCOPE_SYNC_STALE,
5159 subc_protocol::error_codes::SCOPE_SYNC_NOT_AUTHORITY,
5160 "not_registered",
5161 ] {
5162 let apply = tokio::spawn({
5163 let handle = handle.clone();
5164 async move { handle.scope_apply(2, Vec::new(), Vec::new()).await }
5165 });
5166 let request = timeout(Duration::from_secs(1), rx.recv())
5167 .await
5168 .unwrap()
5169 .unwrap();
5170 let body = serde_json::to_vec(&ErrorBody::new(code, "why")).unwrap();
5171 assert!(handle.handle_control_reply(control_reply(
5172 FrameType::Error,
5173 request.header.corr,
5174 body
5175 )));
5176 let error = apply.await.unwrap().unwrap_err();
5177 assert_eq!(
5178 error,
5179 ScopeCallError::Refused {
5180 code: code.to_string(),
5181 message: "why".to_string()
5182 }
5183 );
5184 assert_eq!(error.code(), Some(code));
5185 }
5186 }
5187
5188 #[tokio::test]
5190 async fn a_scope_reply_of_another_op_is_a_protocol_error() {
5191 let (handle, mut rx) = test_module_handle(&[SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP]);
5192 let sync = tokio::spawn({
5193 let handle = handle.clone();
5194 async move { handle.scope_sync(1, Vec::new()).await }
5195 });
5196 let request = timeout(Duration::from_secs(1), rx.recv())
5197 .await
5198 .unwrap()
5199 .unwrap();
5200 let describe_body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeDescribe {
5201 status: ScopeStatus::NotLive,
5202 scope_epoch: None,
5203 daemon_incarnation: "i".to_string(),
5204 owner_synced: false,
5205 owner_configured: false,
5206 scope: None,
5207 })
5208 .unwrap();
5209 assert!(handle.handle_control_reply(control_reply(
5210 FrameType::Response,
5211 request.header.corr,
5212 describe_body
5213 )));
5214 assert!(matches!(
5215 sync.await.unwrap(),
5216 Err(ScopeCallError::Protocol(_))
5217 ));
5218
5219 let describe = tokio::spawn({
5220 let handle = handle.clone();
5221 async move { handle.scope_describe(owner(), "s".to_string()).await }
5222 });
5223 let request = timeout(Duration::from_secs(1), rx.recv())
5224 .await
5225 .unwrap()
5226 .unwrap();
5227 let sync_body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeSync {
5228 generation: 1,
5229 results: Vec::new(),
5230 ended: Vec::new(),
5231 })
5232 .unwrap();
5233 assert!(handle.handle_control_reply(control_reply(
5234 FrameType::Response,
5235 request.header.corr,
5236 sync_body
5237 )));
5238 assert!(matches!(
5239 describe.await.unwrap(),
5240 Err(ScopeCallError::Protocol(_))
5241 ));
5242 }
5243
5244 #[tokio::test]
5248 async fn a_scope_error_frame_keeps_the_daemons_code_and_message() {
5249 let (handle, mut rx) = test_module_handle(&[SCOPE_SYNC_OP]);
5250 for code in [
5251 subc_protocol::error_codes::SCOPE_SYNC_STALE,
5252 subc_protocol::error_codes::SCOPE_SYNC_NOT_AUTHORITY,
5253 "not_registered",
5254 ] {
5255 let sync = tokio::spawn({
5256 let handle = handle.clone();
5257 async move { handle.scope_sync(1, Vec::new()).await }
5258 });
5259 let request = timeout(Duration::from_secs(1), rx.recv())
5260 .await
5261 .unwrap()
5262 .unwrap();
5263 let body = serde_json::to_vec(&ErrorBody::new(code, "why")).unwrap();
5264 assert!(handle.handle_control_reply(control_reply(
5265 FrameType::Error,
5266 request.header.corr,
5267 body
5268 )));
5269 let error = sync.await.unwrap().unwrap_err();
5270 assert_eq!(
5271 error,
5272 ScopeCallError::Refused {
5273 code: code.to_string(),
5274 message: "why".to_string()
5275 }
5276 );
5277 assert_eq!(error.code(), Some(code));
5278 }
5279 }
5280
5281 #[tokio::test]
5285 async fn an_undecodable_control_request_is_refused_and_the_module_keeps_serving() {
5286 let (tx, mut rx) = mpsc::channel(4);
5287 let handler = Arc::new(EchoHandler);
5288 let dispatcher = RequestDispatcher::new();
5289 let (module_handle, _unused_rx) = test_module_handle(&[]);
5290 let mut body: serde_json::Value =
5293 serde_json::from_slice(&route_bind_frame(9, 1, 41).body).unwrap();
5294 body["scope"] = serde_json::json!({
5295 "owner": { "kind": "reserved", "module_id": "prefrontal-core" },
5296 "ref": "s",
5297 "scope_epoch": 1,
5298 "kind": "head",
5299 "attributes": { "a_field_from_a_newer_daemon": "x" },
5300 "owner_authorized": true
5301 });
5302 let body = serde_json::to_vec(&body).unwrap();
5303 let bind = Frame::build(FrameType::Request, control_flags(), 0, 0, 41, body).unwrap();
5304
5305 let kept_serving = handle_frame(
5306 bind,
5307 &tx,
5308 Arc::clone(&handler),
5309 dispatcher.clone(),
5310 module_handle.clone(),
5311 )
5312 .await
5313 .expect("an undecodable control request must not end the module");
5314 assert!(kept_serving);
5315 let refusal = timeout(Duration::from_secs(1), rx.recv())
5316 .await
5317 .unwrap()
5318 .unwrap();
5319 assert_eq!(refusal.header.ty, FrameType::Error);
5320 assert_eq!(refusal.header.corr, 41);
5321 let error: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
5322 assert_eq!(error.code, "invalid_request");
5323 assert!(
5326 error.message.contains("a_field_from_a_newer_daemon"),
5327 "{}",
5328 error.message
5329 );
5330
5331 assert!(
5332 handle_frame(health_request(42), &tx, handler, dispatcher, module_handle)
5333 .await
5334 .unwrap()
5335 );
5336 let health = timeout(Duration::from_secs(1), rx.recv())
5337 .await
5338 .unwrap()
5339 .unwrap();
5340 assert_eq!(health.header.ty, FrameType::Response);
5341 assert_eq!(health.header.corr, 42);
5342 }
5343
5344 #[tokio::test]
5345 async fn default_health_check_answers_ok() {
5346 let (tx, mut rx) = mpsc::channel(4);
5347 let handler = Arc::new(EchoHandler);
5348 let dispatcher = RequestDispatcher::new();
5349 let (module_handle, _unused_rx) = test_module_handle(&[]);
5350
5351 assert!(
5352 handle_frame(health_request(77), &tx, handler, dispatcher, module_handle)
5353 .await
5354 .unwrap()
5355 );
5356
5357 let response = timeout(Duration::from_secs(1), rx.recv())
5358 .await
5359 .unwrap()
5360 .unwrap();
5361 assert_eq!(response.header.ty, FrameType::Response);
5362 assert_eq!(response.header.channel, 0);
5363 assert_eq!(response.header.corr, 77);
5364
5365 let parsed = serde_json::from_slice::<ModuleControlResponse>(&response.body).unwrap();
5370 let ModuleControlResponse::HealthCheck { status, detail, .. } = parsed else {
5371 panic!("expected a health.check response");
5372 };
5373 assert_eq!(status, HealthStatus::Ok);
5376 assert!(
5380 detail
5381 .as_deref()
5382 .is_some_and(|d| d.contains("no health implementation")),
5383 "the inherited default must identify itself, got {detail:?}"
5384 );
5385 }
5386
5387 struct DispatchHarness {
5388 tx: mpsc::Sender<Frame>,
5389 rx: mpsc::Receiver<Frame>,
5390 handler: Arc<BlockingHandler>,
5391 dispatcher: RequestDispatcher,
5392 module_handle: ModuleHandle,
5393 }
5394
5395 impl DispatchHarness {
5396 fn new(report: HealthReport) -> Self {
5397 let (tx, rx) = mpsc::channel(HANDLER_TASK_CAPACITY + 4);
5398 let (module_handle, _unused_rx) = test_module_handle(&[]);
5399 module_handle
5400 .install_route(RouteHandle::new(7, 1, 1))
5401 .unwrap();
5402 Self {
5403 tx,
5404 rx,
5405 handler: Arc::new(BlockingHandler {
5406 entered: Arc::new(AtomicUsize::new(0)),
5407 release: Semaphore::new(0),
5408 report,
5409 }),
5410 dispatcher: RequestDispatcher::new(),
5411 module_handle,
5412 }
5413 }
5414
5415 async fn request(&self, corr: u64) {
5416 handle_frame(
5417 data_request(7, corr),
5418 &self.tx,
5419 Arc::clone(&self.handler),
5420 self.dispatcher.clone(),
5421 self.module_handle.clone(),
5422 )
5423 .await
5424 .unwrap();
5425 }
5426
5427 async fn wait_for_entered(&self, count: usize) {
5428 timeout(Duration::from_secs(1), async {
5429 while self.handler.entered.load(Ordering::SeqCst) != count {
5430 tokio::task::yield_now().await;
5431 }
5432 })
5433 .await
5434 .expect("data handlers should acquire the available slots");
5435 }
5436
5437 async fn saturate(&self) {
5438 for corr in 1..=HANDLER_TASK_CAPACITY as u64 {
5439 self.request(corr).await;
5440 }
5441 self.wait_for_entered(HANDLER_TASK_CAPACITY).await;
5442 self.request(HANDLER_TASK_CAPACITY as u64 + 1).await;
5443 tokio::task::yield_now().await;
5444 assert_eq!(self.dispatcher.pools.default.permits.available_permits(), 0);
5445 assert_eq!(
5446 self.dispatcher.pools.default.waiting.lock().unwrap().len(),
5447 1
5448 );
5449 assert_eq!(
5450 self.handler.entered.load(Ordering::SeqCst),
5451 HANDLER_TASK_CAPACITY
5452 );
5453 }
5454
5455 async fn health(&mut self, corr: u64) -> HealthReport {
5456 handle_frame(
5457 health_request(corr),
5458 &self.tx,
5459 Arc::clone(&self.handler),
5460 self.dispatcher.clone(),
5461 self.module_handle.clone(),
5462 )
5463 .await
5464 .unwrap();
5465 let frame = timeout(Duration::from_millis(100), self.rx.recv())
5466 .await
5467 .expect("health.check must answer within 100 ms while data slots are busy")
5468 .unwrap();
5469 assert_eq!(frame.header.ty, FrameType::Response);
5470 assert_eq!(frame.header.channel, 0);
5471 assert_eq!(frame.header.corr, corr);
5472 serde_json::from_slice::<ModuleControlResponse>(&frame.body)
5473 .unwrap()
5474 .health_report()
5475 .unwrap()
5476 }
5477
5478 async fn release(&mut self, count: usize) {
5479 self.handler.release.add_permits(count);
5480 for _ in 0..count {
5481 let frame = timeout(Duration::from_secs(1), self.rx.recv())
5482 .await
5483 .unwrap()
5484 .unwrap();
5485 assert_eq!(frame.header.ty, FrameType::StreamEnd);
5486 assert_eq!(frame.header.channel, 7);
5487 }
5488 assert!(self
5489 .dispatcher
5490 .pools
5491 .default
5492 .waiting
5493 .lock()
5494 .unwrap()
5495 .is_empty());
5496 assert!(self.dispatcher.in_flight.lock().unwrap().is_empty());
5497 assert_eq!(
5498 self.dispatcher.pools.default.permits.available_permits(),
5499 HANDLER_TASK_CAPACITY
5500 );
5501 }
5502 }
5503
5504 #[tokio::test(start_paused = true)]
5505 async fn health_check_answers_degraded_under_saturation_and_recovers() {
5506 let own_report = HealthReport {
5507 status: HealthStatus::Ok,
5508 detail: Some("module gauges healthy".to_string()),
5509 metrics: Some(json!({"transforms": 64})),
5510 };
5511 let mut harness = DispatchHarness::new(own_report.clone());
5512 harness.saturate().await;
5513 assert_eq!(harness.health(899).await, own_report);
5515 advance(Duration::from_millis(7300)).await;
5518 let report = harness.health(900).await;
5519 assert_eq!(report.status, HealthStatus::Degraded);
5520 assert_eq!(report.metrics, own_report.metrics);
5521 assert_eq!(
5522 report.detail.as_deref(),
5523 Some("request dispatch saturated: 64/64 in use, oldest waiting 7.3 s; module gauges healthy")
5524 );
5525
5526 harness.release(HANDLER_TASK_CAPACITY + 1).await;
5527 assert_eq!(harness.health(901).await, own_report);
5528 }
5529
5530 #[tokio::test(start_paused = true)]
5531 async fn health_check_preserves_failing_under_saturation() {
5532 let mut harness = DispatchHarness::new(HealthReport {
5533 status: HealthStatus::Failing,
5534 detail: Some("module dispatch heartbeat stale".to_string()),
5535 metrics: Some(json!({"heartbeat_age_s": 12})),
5536 });
5537 harness.saturate().await;
5538 advance(Duration::from_millis(7300)).await;
5539 let report = harness.health(900).await;
5540 assert_eq!(report.status, HealthStatus::Failing);
5541 assert_eq!(report.metrics, Some(json!({"heartbeat_age_s": 12})));
5542 assert_eq!(
5543 report.detail.as_deref(),
5544 Some("request dispatch saturated: 64/64 in use, oldest waiting 7.3 s; module dispatch heartbeat stale")
5545 );
5546 harness.release(HANDLER_TASK_CAPACITY + 1).await;
5547 }
5548
5549 #[tokio::test(start_paused = true)]
5550 async fn health_check_passes_module_report_through_with_free_permits() {
5551 for status in [
5552 HealthStatus::Ok,
5553 HealthStatus::Degraded,
5554 HealthStatus::Failing,
5555 ] {
5556 let own_report = HealthReport {
5557 status,
5558 detail: Some("module's own assessment".to_string()),
5559 metrics: Some(json!({"gauge": 42})),
5560 };
5561 let mut harness = DispatchHarness::new(own_report.clone());
5562 harness.request(1).await;
5563 harness.wait_for_entered(1).await;
5564 advance(Duration::from_millis(7300)).await;
5565 assert_eq!(harness.health(900).await, own_report);
5566 harness.release(1).await;
5567 }
5568 }
5569
5570 struct CorrBlockingHandler {
5571 entered: Arc<Mutex<Vec<u64>>>,
5572 release_first: Arc<Semaphore>,
5573 }
5574
5575 #[async_trait]
5576 impl ModuleHandler for CorrBlockingHandler {
5577 async fn handle(&self, ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5578 let corr = ctx.corr();
5579 self.entered.lock().unwrap().push(corr);
5580 if corr == 1 {
5581 self.release_first.acquire().await.unwrap().forget();
5582 }
5583 HandlerOutcome::Response(Vec::new())
5584 }
5585 }
5586
5587 #[tokio::test]
5591 async fn cancelled_capacity_queued_data_request_is_answered_without_waiting_for_a_slot() {
5592 let (tx, mut rx) = mpsc::channel(4);
5593 let entered = Arc::new(Mutex::new(Vec::new()));
5594 let release_first = Arc::new(Semaphore::new(0));
5595 let handler = Arc::new(CorrBlockingHandler {
5596 entered: Arc::clone(&entered),
5597 release_first: Arc::clone(&release_first),
5598 });
5599 let dispatcher = RequestDispatcher::with_pools(Arc::new(
5600 DispatchPools::with_default_limit(1, RequestPools::new()),
5601 ));
5602 let (module_handle, _unused_rx) = test_module_handle(&[]);
5603 module_handle
5604 .install_route(RouteHandle::new(7, 1, 1))
5605 .unwrap();
5606
5607 handle_frame(
5608 data_request(7, 1),
5609 &tx,
5610 Arc::clone(&handler),
5611 dispatcher.clone(),
5612 module_handle.clone(),
5613 )
5614 .await
5615 .unwrap();
5616 timeout(Duration::from_secs(1), async {
5617 while entered.lock().unwrap().as_slice() != [1] {
5618 tokio::task::yield_now().await;
5619 }
5620 })
5621 .await
5622 .unwrap();
5623
5624 handle_frame(
5625 data_request(7, 2),
5626 &tx,
5627 Arc::clone(&handler),
5628 dispatcher.clone(),
5629 module_handle.clone(),
5630 )
5631 .await
5632 .unwrap();
5633 timeout(Duration::from_secs(1), async {
5634 while !dispatcher
5635 .in_flight
5636 .lock()
5637 .unwrap()
5638 .contains_key(&(7, 1, 2))
5639 {
5640 tokio::task::yield_now().await;
5641 }
5642 })
5643 .await
5644 .unwrap();
5645 handle_frame(
5646 Frame::build(FrameType::Cancel, data_flags(), 7, 1, 2, Vec::new()).unwrap(),
5647 &tx,
5648 Arc::clone(&handler),
5649 dispatcher.clone(),
5650 module_handle,
5651 )
5652 .await
5653 .unwrap();
5654 assert!(
5655 dispatcher
5656 .in_flight
5657 .lock()
5658 .unwrap()
5659 .get(&(7, 1, 2))
5660 .unwrap()
5661 .is_cancelled(),
5662 "cancel must land while the second request waits for handler capacity"
5663 );
5664
5665 let cancelled = timeout(Duration::from_secs(1), rx.recv())
5668 .await
5669 .expect("a request cancelled while waiting must be answered without waiting for a slot")
5670 .unwrap();
5671 assert_eq!(cancelled.header.ty, FrameType::Error);
5672 assert_eq!(cancelled.header.channel, 7);
5673 assert_eq!(cancelled.header.epoch, 1);
5674 assert_eq!(cancelled.header.corr, 2);
5675 assert_eq!(
5676 serde_json::from_slice::<ErrorBody>(&cancelled.body).unwrap(),
5677 ErrorBody {
5678 code: "cancelled".to_string(),
5679 message: "request cancelled".to_string(),
5680 detail: None,
5681 }
5682 );
5683 timeout(Duration::from_secs(1), async {
5684 while dispatcher
5685 .in_flight
5686 .lock()
5687 .unwrap()
5688 .contains_key(&(7, 1, 2))
5689 {
5690 tokio::task::yield_now().await;
5691 }
5692 })
5693 .await
5694 .unwrap();
5695 assert_eq!(dispatcher.pools.default.permits.available_permits(), 0);
5696 assert!(dispatcher.pools.default.waiting.lock().unwrap().is_empty());
5697 assert_eq!(*entered.lock().unwrap(), vec![1]);
5698
5699 release_first.add_permits(1);
5700 let response = timeout(Duration::from_secs(1), rx.recv())
5701 .await
5702 .unwrap()
5703 .unwrap();
5704 assert_eq!(response.header.ty, FrameType::Response);
5705 assert_eq!(response.header.corr, 1);
5706 timeout(Duration::from_secs(1), async {
5707 while !dispatcher.in_flight.lock().unwrap().is_empty() {
5708 tokio::task::yield_now().await;
5709 }
5710 })
5711 .await
5712 .unwrap();
5713 assert_eq!(*entered.lock().unwrap(), vec![1]);
5714 assert_eq!(dispatcher.pools.default.permits.available_permits(), 1);
5715 assert!(timeout(Duration::from_millis(50), rx.recv()).await.is_err());
5716 }
5717
5718 #[tokio::test]
5719 async fn cancelled_terminal_is_not_sent_after_route_teardown() {
5720 let (tx, mut rx) = mpsc::channel(1);
5721 let (module_handle, _unused_rx) = test_module_handle(&[]);
5722 let handle = RouteHandle::new(7, 1, 1);
5723 module_handle.install_route(handle).unwrap();
5724 let ctx = RequestCtx {
5725 handle,
5726 corr: 2,
5727 ver: PROTOCOL_VERSION,
5728 egress: tx,
5729 module_handle: module_handle.clone(),
5730 cancelled: CancellationToken::new(),
5731 binary_reply: Arc::new(AtomicBool::new(false)),
5732 request_flags: Flags::new(false, Priority::Interactive, false),
5733 request_body: Arc::from([]),
5734 open: Arc::new(tokio::sync::Mutex::new(true)),
5735 };
5736 assert!(module_handle.remove_route(handle).unwrap());
5737
5738 let result = send_handler_outcome(
5739 &ctx,
5740 HandlerOutcome::Error {
5741 code: "cancelled".to_string(),
5742 message: "request cancelled".to_string(),
5743 },
5744 )
5745 .await;
5746
5747 assert!(matches!(
5748 result,
5749 Err(SubcModuleError::StaleRouteHandle(stale)) if stale == handle
5750 ));
5751 assert!(rx.try_recv().is_err());
5752 }
5753
5754 #[tokio::test]
5755 async fn push_rides_the_call_correlation_until_the_terminal_frame() {
5756 let (tx, mut rx) = mpsc::channel(4);
5757 let (module_handle, _unused_rx) = test_module_handle(&[]);
5758 let handle = RouteHandle::new(7, 1, 1);
5759 module_handle.install_route(handle).unwrap();
5760 let ctx = RequestCtx {
5761 handle,
5762 corr: 9,
5763 ver: PROTOCOL_VERSION,
5764 egress: tx,
5765 module_handle: module_handle.clone(),
5766 cancelled: CancellationToken::new(),
5767 binary_reply: Arc::new(AtomicBool::new(false)),
5768 request_flags: Flags::new(false, Priority::Interactive, false),
5769 request_body: Arc::from([]),
5770 open: Arc::new(tokio::sync::Mutex::new(true)),
5771 };
5772 let keepalive = ctx.clone();
5774
5775 keepalive
5776 .push(br#"{"kind":"keepalive"}"#.to_vec())
5777 .await
5778 .unwrap();
5779 let push = rx.try_recv().unwrap();
5780 assert_eq!(push.header.ty, FrameType::Push);
5781 assert_eq!(
5782 (push.header.channel, push.header.epoch, push.header.corr),
5783 (7, 1, 9)
5784 );
5785 assert_eq!(push.body, br#"{"kind":"keepalive"}"#);
5786
5787 send_handler_outcome(&ctx, HandlerOutcome::Response(b"{}".to_vec()))
5788 .await
5789 .unwrap();
5790 assert_eq!(rx.try_recv().unwrap().header.ty, FrameType::Response);
5791
5792 assert!(matches!(
5793 keepalive.push(b"{}".to_vec()).await,
5794 Err(SubcModuleError::RequestEnded)
5795 ));
5796 assert!(rx.try_recv().is_err());
5797 }
5798
5799 #[tokio::test]
5800 async fn push_is_refused_once_the_request_is_cancelled() {
5801 let (tx, mut rx) = mpsc::channel(4);
5802 let (module_handle, _unused_rx) = test_module_handle(&[]);
5803 let handle = RouteHandle::new(7, 1, 1);
5804 module_handle.install_route(handle).unwrap();
5805 let cancelled = CancellationToken::new();
5806 let ctx = RequestCtx {
5807 handle,
5808 corr: 9,
5809 ver: PROTOCOL_VERSION,
5810 egress: tx,
5811 module_handle,
5812 cancelled: cancelled.clone(),
5813 binary_reply: Arc::new(AtomicBool::new(false)),
5814 request_flags: Flags::new(false, Priority::Interactive, false),
5815 request_body: Arc::from([]),
5816 open: Arc::new(tokio::sync::Mutex::new(true)),
5817 };
5818 cancelled.cancel();
5819
5820 assert!(matches!(
5821 ctx.push(b"{}".to_vec()).await,
5822 Err(SubcModuleError::RequestEnded)
5823 ));
5824 assert!(rx.try_recv().is_err());
5825 }
5826
5827 struct CountingHandler {
5828 calls: Arc<AtomicUsize>,
5829 }
5830
5831 #[async_trait]
5832 impl ModuleHandler for CountingHandler {
5833 async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5834 self.calls.fetch_add(1, Ordering::SeqCst);
5835 HandlerOutcome::Response(Vec::new())
5836 }
5837 }
5838
5839 #[tokio::test]
5840 async fn endpoint_validation_drops_stale_request_before_handler_dispatch() {
5841 let (tx, mut rx) = mpsc::channel(4);
5842 let calls = Arc::new(AtomicUsize::new(0));
5843 let handler = Arc::new(CountingHandler {
5844 calls: Arc::clone(&calls),
5845 });
5846 let dispatcher = RequestDispatcher::new();
5847 let (module_handle, _unused_rx) = test_module_handle(&[]);
5848 module_handle
5849 .install_route(RouteHandle::new(7, 2, 1))
5850 .unwrap();
5851 let stale = Frame::build(FrameType::Request, data_flags(), 7, 1, 55, Vec::new()).unwrap();
5852
5853 assert!(
5854 handle_frame(stale, &tx, handler, dispatcher, module_handle.clone())
5855 .await
5856 .unwrap()
5857 );
5858 tokio::task::yield_now().await;
5859 assert_eq!(calls.load(Ordering::SeqCst), 0);
5860 assert_eq!(module_handle.dropped_route_frames(), 1);
5861 assert!(rx.try_recv().is_err());
5862 }
5863
5864 struct BindOrderingHandler {
5865 module_handle: ModuleHandle,
5866 bind_emit_rejected: Arc<AtomicUsize>,
5867 bound: Arc<AtomicUsize>,
5868 cleanup: Arc<AtomicUsize>,
5869 }
5870
5871 #[async_trait]
5872 impl ModuleHandler for BindOrderingHandler {
5873 async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5874 HandlerOutcome::Response(Vec::new())
5875 }
5876
5877 async fn on_bind(&self, req: &RouteBindRequest) -> BindDecision {
5878 if matches!(
5879 self.module_handle
5880 .push(&req.handle, b"too-early".to_vec(), None)
5881 .await,
5882 Err(SubcModuleError::StaleRouteHandle(_))
5883 ) {
5884 self.bind_emit_rejected.fetch_add(1, Ordering::SeqCst);
5885 }
5886 BindDecision::accept()
5887 }
5888
5889 async fn on_bound(&self, handle: &RouteHandle) {
5890 self.bound.fetch_add(1, Ordering::SeqCst);
5891 self.module_handle
5892 .push(handle, b"bound".to_vec(), Some(AdmissionClass::Expedite))
5893 .await
5894 .unwrap();
5895 }
5896
5897 async fn on_route_gone(&self, _handle: &RouteHandle) {
5898 self.cleanup.fetch_add(1, Ordering::SeqCst);
5899 }
5900 }
5901
5902 fn route_bind_frame(channel: u16, epoch: u32, corr: u64) -> Frame {
5903 let body = serde_json::to_vec(&ModuleControlRequest::RouteBind {
5904 route_channel: channel,
5905 epoch,
5906 target: RouteTarget::ToolProvider {
5907 module_id: "provider".to_string(),
5908 },
5909 identity: BindIdentity::new("test".to_string(), "bind".to_string()),
5910 principal: None,
5911 consumer_capabilities: None,
5912 role_versions: None,
5913 admission_facts: None,
5914 scope: None,
5915 call_mode: None,
5916 })
5917 .unwrap();
5918 Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
5919 }
5920
5921 #[tokio::test]
5922 async fn on_bound_runs_only_after_ack_queue_and_handle_install() {
5923 let (module_handle, mut rx) = test_module_handle(&[]);
5924 let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
5925 let bind_emit_rejected = Arc::new(AtomicUsize::new(0));
5926 let bound = Arc::new(AtomicUsize::new(0));
5927 let cleanup = Arc::new(AtomicUsize::new(0));
5928 let handler = Arc::new(BindOrderingHandler {
5929 module_handle: module_handle.clone(),
5930 bind_emit_rejected: Arc::clone(&bind_emit_rejected),
5931 bound: Arc::clone(&bound),
5932 cleanup: Arc::clone(&cleanup),
5933 });
5934
5935 assert!(handle_frame(
5936 route_bind_frame(8, 4, 90),
5937 &tx,
5938 handler,
5939 RequestDispatcher::new(),
5940 module_handle.clone(),
5941 )
5942 .await
5943 .unwrap());
5944 assert_eq!(bind_emit_rejected.load(Ordering::SeqCst), 1);
5945 assert_eq!(bound.load(Ordering::SeqCst), 1);
5946 assert_eq!(cleanup.load(Ordering::SeqCst), 0);
5947
5948 let ack = rx.recv().await.unwrap();
5949 let push = rx.recv().await.unwrap();
5950 assert_eq!(ack.header.ty, FrameType::Response);
5951 assert_eq!(ack.header.channel, 0);
5952 assert_eq!(push.header.ty, FrameType::Push);
5953 assert_eq!((push.header.channel, push.header.epoch), (8, 4));
5954 assert_eq!(
5955 push.header.flags.admission_class(),
5956 Some(AdmissionClass::Expedite)
5957 );
5958
5959 let captured = RouteHandle::new(8, 4, 1);
5960 assert!(module_handle.remove_route(captured).unwrap());
5961 let stale = module_handle
5962 .push(&captured, Vec::new(), None)
5963 .await
5964 .unwrap_err();
5965 assert!(matches!(stale, SubcModuleError::StaleRouteHandle(_)));
5966 assert!(rx.try_recv().is_err());
5967 }
5968
5969 struct RejectingHandler {
5970 bound: Arc<AtomicUsize>,
5971 cleanup: Arc<AtomicUsize>,
5972 }
5973
5974 #[async_trait]
5975 impl ModuleHandler for RejectingHandler {
5976 async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5977 HandlerOutcome::Response(Vec::new())
5978 }
5979
5980 async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
5981 BindDecision::reject("no", "rejected")
5982 }
5983
5984 async fn on_bound(&self, _handle: &RouteHandle) {
5985 self.bound.fetch_add(1, Ordering::SeqCst);
5986 }
5987
5988 async fn on_route_gone(&self, _handle: &RouteHandle) {
5989 self.cleanup.fetch_add(1, Ordering::SeqCst);
5990 }
5991 }
5992
5993 #[tokio::test]
5994 async fn rejected_bind_cleans_up_without_installing_or_calling_on_bound() {
5995 let (module_handle, mut rx) = test_module_handle(&[]);
5996 let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
5997 let bound = Arc::new(AtomicUsize::new(0));
5998 let cleanup = Arc::new(AtomicUsize::new(0));
5999 let handler = Arc::new(RejectingHandler {
6000 bound: Arc::clone(&bound),
6001 cleanup: Arc::clone(&cleanup),
6002 });
6003 handle_frame(
6004 route_bind_frame(6, 3, 91),
6005 &tx,
6006 handler,
6007 RequestDispatcher::new(),
6008 module_handle.clone(),
6009 )
6010 .await
6011 .unwrap();
6012 let refusal = rx.recv().await.unwrap();
6013 assert_eq!(refusal.header.ty, FrameType::Error);
6014 assert_eq!(refusal.body, br#"{"code":"no","message":"rejected"}"#);
6016 assert_eq!(bound.load(Ordering::SeqCst), 0);
6017 assert_eq!(cleanup.load(Ordering::SeqCst), 1);
6018 assert!(matches!(
6019 module_handle.validate_route(RouteHandle::new(6, 3, 1)),
6020 Err(SubcModuleError::StaleRouteHandle(_))
6021 ));
6022 }
6023
6024 struct BusyHandler;
6025
6026 #[async_trait]
6027 impl ModuleHandler for BusyHandler {
6028 async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6029 HandlerOutcome::Response(Vec::new())
6030 }
6031
6032 async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
6033 BindDecision::reject_with_detail(
6034 "bind_busy",
6035 "a read is still running on this root",
6036 serde_json::json!({"reason": "reader", "retry_after_ms": 2000}),
6037 )
6038 }
6039 }
6040
6041 #[tokio::test]
6042 async fn rejected_bind_carries_its_detail_to_the_daemon() {
6043 let (module_handle, mut rx) = test_module_handle(&[]);
6044 let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
6045 handle_frame(
6046 route_bind_frame(6, 3, 92),
6047 &tx,
6048 Arc::new(BusyHandler),
6049 RequestDispatcher::new(),
6050 module_handle.clone(),
6051 )
6052 .await
6053 .unwrap();
6054 let refusal = rx.recv().await.unwrap();
6055 assert_eq!(refusal.header.ty, FrameType::Error);
6056 let body: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
6057 assert_eq!(body.code, "bind_busy");
6058 assert_eq!(
6059 body.detail,
6060 Some(serde_json::json!({"reason": "reader", "retry_after_ms": 2000}))
6061 );
6062 }
6063
6064 struct RebindCountingHandler {
6065 bound: Arc<AtomicUsize>,
6066 cleanup: Arc<AtomicUsize>,
6067 }
6068
6069 #[async_trait]
6070 impl ModuleHandler for RebindCountingHandler {
6071 async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6072 HandlerOutcome::Response(Vec::new())
6073 }
6074
6075 async fn on_bound(&self, _handle: &RouteHandle) {
6076 self.bound.fetch_add(1, Ordering::SeqCst);
6077 }
6078
6079 async fn on_route_gone(&self, _handle: &RouteHandle) {
6080 self.cleanup.fetch_add(1, Ordering::SeqCst);
6081 }
6082 }
6083
6084 #[tokio::test]
6090 async fn rebind_on_installed_channel_replaces_on_higher_epoch_only() {
6091 let (module_handle, mut rx) = test_module_handle(&[]);
6092 let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
6093 let bound = Arc::new(AtomicUsize::new(0));
6094 let cleanup = Arc::new(AtomicUsize::new(0));
6095 let handler = Arc::new(RebindCountingHandler {
6096 bound: Arc::clone(&bound),
6097 cleanup: Arc::clone(&cleanup),
6098 });
6099
6100 handle_frame(
6102 route_bind_frame(8, 4, 90),
6103 &tx,
6104 Arc::clone(&handler),
6105 RequestDispatcher::new(),
6106 module_handle.clone(),
6107 )
6108 .await
6109 .unwrap();
6110 assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Response);
6111 assert_eq!(
6112 (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6113 (1, 0)
6114 );
6115
6116 handle_frame(
6118 route_bind_frame(8, 4, 91),
6119 &tx,
6120 Arc::clone(&handler),
6121 RequestDispatcher::new(),
6122 module_handle.clone(),
6123 )
6124 .await
6125 .unwrap();
6126 let reject = rx.recv().await.unwrap();
6127 assert_eq!(reject.header.ty, FrameType::Error);
6128 assert_eq!(
6129 (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6130 (1, 0)
6131 );
6132 module_handle
6133 .validate_route(RouteHandle::new(8, 4, 1))
6134 .expect("epoch-4 install must survive the rejected rebind");
6135
6136 handle_frame(
6138 route_bind_frame(8, 3, 92),
6139 &tx,
6140 Arc::clone(&handler),
6141 RequestDispatcher::new(),
6142 module_handle.clone(),
6143 )
6144 .await
6145 .unwrap();
6146 assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Error);
6147 assert_eq!(
6148 (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6149 (1, 0)
6150 );
6151
6152 handle_frame(
6155 route_bind_frame(8, 5, 93),
6156 &tx,
6157 Arc::clone(&handler),
6158 RequestDispatcher::new(),
6159 module_handle.clone(),
6160 )
6161 .await
6162 .unwrap();
6163 assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Response);
6164 assert_eq!(
6165 (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6166 (2, 1)
6167 );
6168 assert!(matches!(
6169 module_handle.validate_route(RouteHandle::new(8, 4, 1)),
6170 Err(SubcModuleError::StaleRouteHandle(_))
6171 ));
6172 module_handle
6173 .validate_route(RouteHandle::new(8, 5, 1))
6174 .expect("epoch-5 install must be live after implicit replace");
6175 }
6176
6177 #[tokio::test]
6178 async fn module_control_corr_is_monotonic_and_exhausts_without_wrap() {
6179 let (module_handle, _rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
6180 let shared = module_handle.shared();
6181 let mut inner = shared.lock_inner();
6182 inner.next_corr = Some(u64::MAX);
6183 assert_eq!(next_module_control_corr(&mut inner), Some(u64::MAX));
6184 assert_eq!(next_module_control_corr(&mut inner), None);
6185 }
6186}
6187
6188#[cfg(test)]
6191mod module_close_tests {
6192 use std::time::Instant;
6193
6194 use tokio::{io::DuplexStream, sync::Notify};
6195
6196 use super::stand_in::{serve_against_stand_in_with_ops, Served};
6197 use super::*;
6198
6199 #[derive(Clone, Copy)]
6201 enum Hold {
6202 UntilCancelled,
6204 IgnoringCancellation,
6206 }
6207
6208 struct HoldingHandler {
6209 hold: Hold,
6210 entered: Arc<Notify>,
6211 token: Arc<Mutex<Option<CancellationToken>>>,
6212 }
6213
6214 #[async_trait]
6215 impl ModuleHandler for HoldingHandler {
6216 async fn handle(&self, ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6217 *self.token.lock().unwrap() = Some(ctx.cancellation_token());
6218 self.entered.notify_one();
6219 match self.hold {
6220 Hold::UntilCancelled => {
6221 ctx.cancelled().await;
6222 HandlerOutcome::Error {
6223 code: "cancelled".to_string(),
6224 message: "request cancelled".to_string(),
6225 }
6226 }
6227 Hold::IgnoringCancellation => std::future::pending().await,
6228 }
6229 }
6230 }
6231
6232 async fn serve_against_stand_in<H: ModuleHandler>(handler: H) -> Served {
6234 serve_against_stand_in_with_ops(|_| handler, &[]).await
6235 }
6236
6237 async fn send(daemon: &mut DuplexStream, frame: Frame) {
6238 write_frame(daemon, &frame).await.unwrap();
6239 daemon.flush().await.unwrap();
6240 }
6241
6242 async fn hold_one_request(served: &mut Served, entered: &Notify) {
6245 let bind = serde_json::to_vec(&ModuleControlRequest::RouteBind {
6246 route_channel: 7,
6247 epoch: 1,
6248 target: RouteTarget::ToolProvider {
6249 module_id: "close-test".to_string(),
6250 },
6251 identity: BindIdentity::new("test".to_string(), "close".to_string()),
6252 principal: None,
6253 consumer_capabilities: None,
6254 role_versions: None,
6255 admission_facts: None,
6256 scope: None,
6257 call_mode: None,
6258 })
6259 .unwrap();
6260 send(
6261 &mut served.daemon,
6262 Frame::build(FrameType::Request, control_flags(), 0, 0, 2, bind).unwrap(),
6263 )
6264 .await;
6265 loop {
6266 let frame = read_frame(&mut served.daemon).await.unwrap().unwrap();
6267 if frame.header.channel == 0 && frame.header.corr == 2 {
6268 assert_eq!(
6269 frame.header.ty,
6270 FrameType::Response,
6271 "route.bind must be acked"
6272 );
6273 break;
6274 }
6275 }
6276 send(
6277 &mut served.daemon,
6278 Frame::build(FrameType::Request, data_flags(), 7, 1, 10, b"hold".to_vec()).unwrap(),
6279 )
6280 .await;
6281 timeout(Duration::from_secs(2), entered.notified())
6282 .await
6283 .expect("the handler must receive the request");
6284 }
6285
6286 fn goodbye() -> Frame {
6287 Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 0, Vec::new()).unwrap()
6288 }
6289
6290 fn holding(
6291 hold: Hold,
6292 ) -> (
6293 HoldingHandler,
6294 Arc<Notify>,
6295 Arc<Mutex<Option<CancellationToken>>>,
6296 ) {
6297 let entered = Arc::new(Notify::new());
6298 let token = Arc::new(Mutex::new(None));
6299 let handler = HoldingHandler {
6300 hold,
6301 entered: Arc::clone(&entered),
6302 token: Arc::clone(&token),
6303 };
6304 (handler, entered, token)
6305 }
6306
6307 #[tokio::test]
6308 async fn goodbye_cancels_an_open_request_and_the_serve_future_completes() {
6309 let (handler, entered, token) = holding(Hold::UntilCancelled);
6310 let mut served = serve_against_stand_in(handler).await;
6311 hold_one_request(&mut served, &entered).await;
6312
6313 let started = Instant::now();
6314 send(&mut served.daemon, goodbye()).await;
6315 let result = timeout(Duration::from_secs(5), &mut served.serve)
6316 .await
6317 .expect("a held request must not keep the serve future alive after GOODBYE");
6318 result.unwrap().unwrap();
6319 assert!(
6320 token.lock().unwrap().as_ref().unwrap().is_cancelled(),
6321 "GOODBYE must cancel the request's token"
6322 );
6323 assert!(
6326 started.elapsed() < DEFAULT_WRITER_DRAIN_TIMEOUT,
6327 "closing took {:?}",
6328 started.elapsed()
6329 );
6330 }
6331
6332 #[tokio::test]
6333 async fn a_handler_ignoring_cancellation_cannot_keep_the_serve_future_alive() {
6334 let (handler, entered, _token) = holding(Hold::IgnoringCancellation);
6335 let mut served = serve_against_stand_in(handler).await;
6336 hold_one_request(&mut served, &entered).await;
6337
6338 let started = Instant::now();
6339 send(&mut served.daemon, goodbye()).await;
6340 let result = timeout(
6341 DEFAULT_WRITER_DRAIN_TIMEOUT + Duration::from_secs(3),
6342 &mut served.serve,
6343 )
6344 .await
6345 .expect("the writer drain must be bounded");
6346 result.unwrap().unwrap();
6347 assert!(started.elapsed() >= DEFAULT_WRITER_DRAIN_TIMEOUT);
6348 }
6349
6350 #[tokio::test]
6351 async fn closed_resolves_after_goodbye() {
6352 let served = serve_against_stand_in(EchoHandler).await;
6353 let mut served = served;
6354 assert!(!served.handle.is_closed());
6355 let closed = served.handle.closed();
6356 send(&mut served.daemon, goodbye()).await;
6357 timeout(Duration::from_secs(2), closed)
6358 .await
6359 .expect("closed() must resolve after GOODBYE");
6360 assert!(served.handle.is_closed());
6361 }
6362
6363 #[tokio::test]
6364 async fn closed_resolves_after_eof() {
6365 let Served {
6366 daemon,
6367 handle,
6368 serve: _serve,
6369 } = serve_against_stand_in(EchoHandler).await;
6370 assert!(!handle.is_closed());
6371 drop(daemon);
6372 timeout(Duration::from_secs(2), handle.closed())
6373 .await
6374 .expect("closed() must resolve after EOF");
6375 assert!(handle.is_closed());
6376 }
6377
6378 struct EchoHandler;
6379
6380 #[async_trait]
6381 impl ModuleHandler for EchoHandler {
6382 async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6383 HandlerOutcome::Response(body)
6384 }
6385 }
6386
6387 #[derive(Clone, Default)]
6390 struct EndRecorder(Arc<Mutex<Vec<ConnectionEnd>>>);
6391
6392 #[async_trait]
6393 impl ModuleHandler for EndRecorder {
6394 async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6395 HandlerOutcome::Response(body)
6396 }
6397 async fn on_connection_end(&self, end: ConnectionEnd) {
6398 self.0.lock().unwrap().push(end);
6399 }
6400 }
6401
6402 async fn reported_end(recorder: &EndRecorder, served: &mut Served) -> Vec<ConnectionEnd> {
6403 timeout(Duration::from_secs(5), &mut served.serve)
6404 .await
6405 .expect("serving must end")
6406 .unwrap()
6407 .unwrap();
6408 recorder.0.lock().unwrap().clone()
6409 }
6410
6411 #[tokio::test]
6412 async fn a_daemon_goodbye_is_reported_as_goodbye() {
6413 let recorder = EndRecorder::default();
6414 let mut served = serve_against_stand_in(recorder.clone()).await;
6415 send(&mut served.daemon, goodbye()).await;
6416 assert_eq!(
6417 reported_end(&recorder, &mut served).await,
6418 vec![ConnectionEnd::Goodbye]
6419 );
6420 }
6421
6422 #[tokio::test]
6423 async fn a_daemon_closing_without_goodbye_is_reported_as_eof() {
6424 let recorder = EndRecorder::default();
6425 let mut served = serve_against_stand_in(recorder.clone()).await;
6426 served.daemon.shutdown().await.unwrap();
6427 assert_eq!(
6428 reported_end(&recorder, &mut served).await,
6429 vec![ConnectionEnd::Eof]
6430 );
6431 }
6432
6433 #[derive(Debug, Clone, PartialEq)]
6435 enum Seen {
6436 Draining(RouteCloseReason, SystemTime),
6437 End(ConnectionEnd),
6438 }
6439
6440 #[derive(Clone, Default)]
6443 struct DrainRecorder {
6444 seen: Arc<Mutex<Vec<Seen>>>,
6445 park: bool,
6446 }
6447
6448 #[async_trait]
6449 impl ModuleHandler for DrainRecorder {
6450 async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6451 HandlerOutcome::Response(body)
6452 }
6453 async fn on_draining(&self, reason: RouteCloseReason, deadline: SystemTime) {
6454 self.seen
6455 .lock()
6456 .unwrap()
6457 .push(Seen::Draining(reason, deadline));
6458 if self.park {
6459 std::future::pending::<()>().await;
6460 }
6461 }
6462 async fn on_connection_end(&self, end: ConnectionEnd) {
6463 self.seen.lock().unwrap().push(Seen::End(end));
6464 }
6465 }
6466
6467 fn control_push(body: &[u8]) -> Frame {
6468 Frame::build(FrameType::Push, control_flags(), 0, 0, 0, body.to_vec()).unwrap()
6469 }
6470
6471 fn draining_push(reason: subc_protocol::RouteCloseReason, deadline_ms: u64) -> Frame {
6472 control_push(
6473 &serde_json::to_vec(&ModuleControlCommand::Draining {
6474 reason,
6475 deadline_ms,
6476 })
6477 .unwrap(),
6478 )
6479 }
6480
6481 #[tokio::test]
6482 async fn accepting_drain_notice_exposes_the_marker_only_on_that_notice() {
6483 struct Recorder(Arc<Mutex<Vec<bool>>>);
6484
6485 #[async_trait]
6486 impl ModuleHandler for Recorder {
6487 async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6488 HandlerOutcome::Response(body)
6489 }
6490
6491 async fn on_draining_notice(&self, notice: DrainNotice) {
6492 self.0.lock().unwrap().push(notice.accepting);
6493 }
6494 }
6495
6496 let recorded = Arc::new(Mutex::new(Vec::new()));
6497 let mut served = serve_against_stand_in(Recorder(recorded.clone())).await;
6498 send(&mut served.daemon, control_push(br#"{"op":"module.draining","reason":"restart","deadline_ms":1000,"accepting":true}"#)).await;
6499 ping_is_answered(&mut served, 90).await;
6500 send(
6501 &mut served.daemon,
6502 draining_push(subc_protocol::RouteCloseReason::Restart, 1000),
6503 )
6504 .await;
6505 send(&mut served.daemon, goodbye()).await;
6506 timeout(Duration::from_secs(5), &mut served.serve)
6507 .await
6508 .unwrap()
6509 .unwrap()
6510 .unwrap();
6511 assert_eq!(*recorded.lock().unwrap(), [true, false]);
6512 }
6513
6514 async fn ping_is_answered(served: &mut Served, corr: u64) {
6517 send(
6518 &mut served.daemon,
6519 Frame::build(FrameType::Ping, control_flags(), 0, 0, corr, Vec::new()).unwrap(),
6520 )
6521 .await;
6522 let pong = timeout(Duration::from_secs(2), read_frame(&mut served.daemon))
6523 .await
6524 .expect("the module must answer PING")
6525 .unwrap()
6526 .expect("the module must not close the connection");
6527 assert_eq!(pong.header.ty, FrameType::Pong);
6528 assert_eq!(pong.header.corr, corr);
6529 }
6530
6531 #[tokio::test]
6535 async fn a_drain_notice_calls_on_draining_before_the_goodbye_that_follows_it() {
6536 let recorder = DrainRecorder::default();
6537 let mut served = serve_against_stand_in(recorder.clone()).await;
6538 let deadline_ms = 4_102_444_800_000;
6541 write_frame(
6542 &mut served.daemon,
6543 &draining_push(subc_protocol::RouteCloseReason::Restart, deadline_ms),
6544 )
6545 .await
6546 .unwrap();
6547 write_frame(&mut served.daemon, &goodbye()).await.unwrap();
6548 served.daemon.flush().await.unwrap();
6549
6550 timeout(Duration::from_secs(5), &mut served.serve)
6551 .await
6552 .expect("serving must end after GOODBYE")
6553 .unwrap()
6554 .unwrap();
6555 assert_eq!(
6556 *recorder.seen.lock().unwrap(),
6557 vec![
6558 Seen::Draining(
6559 RouteCloseReason::Restart,
6560 UNIX_EPOCH + Duration::from_millis(deadline_ms)
6561 ),
6562 Seen::End(ConnectionEnd::Goodbye),
6563 ]
6564 );
6565 }
6566
6567 #[tokio::test]
6570 async fn a_drain_hook_that_never_returns_does_not_stop_the_frame_reader() {
6571 let recorder = DrainRecorder {
6572 park: true,
6573 ..DrainRecorder::default()
6574 };
6575 let mut served = serve_against_stand_in(recorder.clone()).await;
6576 send(
6577 &mut served.daemon,
6578 draining_push(subc_protocol::RouteCloseReason::Reload, 1),
6579 )
6580 .await;
6581 ping_is_answered(&mut served, 41).await;
6582 assert!(matches!(
6583 recorder.seen.lock().unwrap().as_slice(),
6584 [Seen::Draining(RouteCloseReason::Reload, _)]
6585 ));
6586
6587 send(&mut served.daemon, goodbye()).await;
6588 timeout(Duration::from_secs(5), &mut served.serve)
6589 .await
6590 .expect("a parked drain hook must not keep the serve future alive")
6591 .unwrap()
6592 .unwrap();
6593 }
6594
6595 #[tokio::test]
6599 async fn an_undecodable_channel_zero_push_is_ignored_and_the_connection_stays_up() {
6600 let recorder = DrainRecorder::default();
6601 let mut served = serve_against_stand_in(recorder.clone()).await;
6602 send(
6603 &mut served.daemon,
6604 control_push(br#"{"op":"module.some_future_command","x":1}"#),
6605 )
6606 .await;
6607 send(&mut served.daemon, control_push(b"not json")).await;
6608 send(
6609 &mut served.daemon,
6610 control_push(br#"{"op":"module.draining","reason":"restart"}"#),
6611 )
6612 .await;
6613 ping_is_answered(&mut served, 42).await;
6614 assert!(!served.handle.is_closed());
6615 assert!(!served.serve.is_finished());
6616 assert!(recorder.seen.lock().unwrap().is_empty());
6617 }
6618
6619 #[tokio::test]
6620 async fn a_module_closing_its_own_connection_is_reported_as_closed() {
6621 let recorder = EndRecorder::default();
6622 let mut served = serve_against_stand_in(recorder.clone()).await;
6623 served.handle.close_connection();
6624 assert_eq!(
6625 reported_end(&recorder, &mut served).await,
6626 vec![ConnectionEnd::Closed]
6627 );
6628 }
6629}
6630
6631#[cfg(test)]
6632mod operator_confirm_tests;
6633
6634#[cfg(test)]
6635mod binary_reply_tests;
6636
6637#[cfg(test)]
6638mod serve_lifecycle_tests;
6639
6640#[cfg(test)]
6641mod request_pool_tests;
6642
6643#[cfg(test)]
6644mod detailed_error_body_tests {
6645 use serde_json::json;
6646
6647 use subc_protocol::ErrorBody;
6648
6649 #[test]
6653 fn detailed_error_body_keeps_code_message_and_detail() {
6654 let body = ErrorBody::new("bad_request", "invalid envelope")
6655 .with_detail(json!({"reason": "missing_server"}));
6656
6657 assert_eq!(
6658 serde_json::to_value(body).unwrap(),
6659 json!({
6660 "code": "bad_request",
6661 "message": "invalid envelope",
6662 "detail": {"reason": "missing_server"},
6663 })
6664 );
6665 }
6666
6667 #[test]
6670 fn detail_less_error_body_is_byte_identical_to_the_pre_detail_wire() {
6671 let old_wire = r#"{"code":"cancelled","message":"caller cancelled"}"#;
6672 let parsed: ErrorBody = serde_json::from_str(old_wire).unwrap();
6673 assert_eq!(parsed.detail, None);
6674 assert_eq!(serde_json::to_string(&parsed).unwrap(), old_wire);
6675 }
6676}
6677
6678static RETAINED_LAUNCH_NONCE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
6681
6682pub fn retain_launch_nonce_for_hello(launch_nonce: String) -> Result<(), String> {
6685 RETAINED_LAUNCH_NONCE
6686 .set(launch_nonce)
6687 .map_err(|_| "launch nonce was already retained for this process".to_string())
6688}
6689
6690fn retained_launch_nonce() -> Option<String> {
6691 RETAINED_LAUNCH_NONCE.get().cloned()
6692}
6693
6694pub fn launch_nonce_source() -> Option<LaunchNonceSource> {
6700 launch_nonce()
6701 .ok()
6702 .flatten()
6703 .map(|nonce| LaunchNonceSource::from_wire_name(nonce.source().as_str()))
6704}
6705
6706fn stamp_launch_nonce_source(manifest: &mut ModuleManifest, sent: Option<&str>) {
6714 let Some(provenance) = manifest.provenance.as_mut() else {
6715 return;
6716 };
6717 if provenance.launch_nonce_source.is_some() {
6718 return;
6719 }
6720 if let Ok(Some(nonce)) = launch_nonce() {
6721 let launched = registration::is_launched_module(&manifest.module_id).unwrap_or(false);
6724 if launched && (registration::supervised() || sent == Some(nonce.value())) {
6725 provenance.launch_nonce_source =
6726 Some(LaunchNonceSource::from_wire_name(nonce.source().as_str()));
6727 }
6728 }
6729}
6730
6731#[cfg(test)]
6732mod checked_increment_tests {
6733 use super::checked_increment;
6734 use std::sync::atomic::{AtomicU64, Ordering};
6735
6736 #[test]
6737 fn returns_the_previous_value_and_stops_at_the_maximum() {
6738 let counter = AtomicU64::new(7);
6739 assert_eq!(checked_increment(&counter), Some(7));
6740 assert_eq!(counter.load(Ordering::Relaxed), 8);
6741
6742 let full = AtomicU64::new(u64::MAX);
6743 assert_eq!(checked_increment(&full), None);
6744 assert_eq!(
6745 full.load(Ordering::Relaxed),
6746 u64::MAX,
6747 "an exhausted counter is left unchanged"
6748 );
6749 }
6750}