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