runtime_rs/state.rs
1use tokio_util::sync::CancellationToken;
2
3#[cfg(feature = "events")]
4use crate::LifecycleBus;
5#[cfg(feature = "registry")]
6use crate::Registry;
7
8/// Shared application state passed to providers and runtime tasks.
9///
10/// Applications keep ownership of their real state. Put config handles,
11/// typed services, caches, event buses, and domain state wherever they belong;
12/// this trait only says how the runtime observes process shutdown.
13///
14/// The recommended shape is a cheap cloneable handle around a private `Inner`.
15/// This keeps state clones cheap while letting `registry_ref()` and `events()`
16/// return ordinary references:
17///
18/// ```text
19/// use std::sync::Arc;
20/// use tokio_util::sync::CancellationToken;
21/// use runtime_rs::{LifecycleBus, Registry, SharedState};
22///
23/// #[derive(Clone)]
24/// pub struct AppState(Arc<Inner>);
25///
26/// struct Inner {
27/// shutdown_token: CancellationToken,
28/// registry: Registry<AppState>,
29/// events: LifecycleBus,
30/// }
31///
32/// impl SharedState for AppState {
33/// fn shutdown_token(&self) -> CancellationToken {
34/// self.0.shutdown_token.clone()
35/// }
36///
37/// fn registry_ref(&self) -> &Registry<Self> {
38/// &self.0.registry
39/// }
40///
41/// fn events(&self) -> &LifecycleBus {
42/// &self.0.events
43/// }
44/// }
45/// ```
46pub trait SharedState: Clone + Send + Sync + 'static {
47 fn shutdown_token(&self) -> CancellationToken;
48
49 fn initiate_shutdown(&self) {
50 self.shutdown_token().cancel();
51 }
52
53 fn is_shutting_down(&self) -> bool {
54 self.shutdown_token().is_cancelled()
55 }
56
57 #[cfg(feature = "registry")]
58 fn registry_ref(&self) -> &Registry<Self>;
59
60 #[cfg(feature = "events")]
61 fn events(&self) -> &LifecycleBus;
62}