Skip to main content

navree_kernel/
lifecycle.rs

1//! The [`Lifecycle`] trait: hooks run at boot and at shutdown.
2
3use std::sync::Arc;
4
5use crate::{AppContext, BoxError, BoxFuture, KernelError, ProviderKey, Resolver};
6
7/// Hooks implemented by a provider and registered with
8/// [`ModuleBuilder::lifecycle`](crate::ModuleBuilder::lifecycle).
9///
10/// At boot, after every singleton is built, `on_init` runs for every
11/// registered provider in module dependency order, then `on_bootstrap` in the
12/// same order. At shutdown, `on_shutdown` runs in reverse order.
13pub trait Lifecycle: Send + Sync + 'static {
14    /// Runs once all singletons exist.
15    fn on_init(&self, _ctx: AppContext) -> BoxFuture<'_, Result<(), BoxError>> {
16        Box::pin(async { Ok(()) })
17    }
18
19    /// Runs after every `on_init` succeeded.
20    fn on_bootstrap(&self, _ctx: AppContext) -> BoxFuture<'_, Result<(), BoxError>> {
21        Box::pin(async { Ok(()) })
22    }
23
24    /// Runs during graceful shutdown, after tracked tasks have drained.
25    fn on_shutdown(&self, _ctx: AppContext) -> BoxFuture<'_, Result<(), BoxError>> {
26        Box::pin(async { Ok(()) })
27    }
28}
29
30/// Resolves a registered lifecycle provider as `Arc<dyn Lifecycle>`.
31pub(crate) type LifecycleResolve = Arc<
32    dyn Fn(Resolver) -> BoxFuture<'static, Result<Arc<dyn Lifecycle>, KernelError>> + Send + Sync,
33>;
34
35/// A `lifecycle::<T>()` registration.
36#[derive(Clone)]
37pub(crate) struct LifecycleDef {
38    pub(crate) key: ProviderKey,
39    pub(crate) resolve: LifecycleResolve,
40}
41
42impl LifecycleDef {
43    pub(crate) fn of<T: Lifecycle>() -> Self {
44        Self {
45            key: ProviderKey::of::<T>(),
46            resolve: Arc::new(|r| {
47                Box::pin(async move { r.get::<T>().await.map(|hooks| hooks as Arc<dyn Lifecycle>) })
48            }),
49        }
50    }
51}