Skip to main content

navree_kernel/
container.rs

1//! The container: the validated graph plus memoized singleton instances, and
2//! the per-unit-of-work [`RequestScope`] cache.
3
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::{Arc, Mutex, PoisonError};
7
8use tokio::sync::OnceCell;
9use tokio_util::sync::CancellationToken;
10use tokio_util::task::TaskTracker;
11
12use crate::CommandSpec;
13use crate::builder::Instance;
14use crate::graph::Graph;
15
16/// Shared state behind [`AppContext`](crate::AppContext) and every [`Resolver`](crate::Resolver).
17pub(crate) struct AppInner {
18    pub(crate) graph: Graph,
19    /// One cell per provider; only singleton providers use theirs.
20    pub(crate) singletons: Vec<OnceCell<Instance>>,
21    pub(crate) shutdown: CancellationToken,
22    pub(crate) tracker: TaskTracker,
23    /// The command the app was booted to run, if any.
24    pub(crate) command: Option<CommandSpec>,
25}
26
27impl AppInner {
28    pub(crate) fn new(
29        graph: Graph,
30        shutdown: CancellationToken,
31        command: Option<CommandSpec>,
32    ) -> Self {
33        let singletons = graph.providers.iter().map(|_| OnceCell::new()).collect();
34        Self {
35            graph,
36            singletons,
37            shutdown,
38            tracker: TaskTracker::new(),
39            command,
40        }
41    }
42}
43
44/// Identifies one app in a [`RequestScope`] cache.
45pub(crate) fn app_identity(inner: &Arc<AppInner>) -> usize {
46    Arc::as_ptr(inner).addr()
47}
48
49/// The cache of one unit of work (an HTTP request, a job run, a command, ...):
50/// request-scoped providers are built at most once per `RequestScope`.
51/// Clones share the same cache.
52#[derive(Clone, Default)]
53pub struct RequestScope {
54    cells: Arc<Mutex<ScopeCells>>,
55}
56
57/// Memoization cells keyed by (app identity, provider index).
58type ScopeCells = HashMap<(usize, usize), Arc<OnceCell<Instance>>>;
59
60impl RequestScope {
61    /// A fresh, empty scope.
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    /// The memoization cell of provider `provider` of app `app`.
67    pub(crate) fn cell(&self, app: usize, provider: usize) -> Arc<OnceCell<Instance>> {
68        let mut cells = self.cells.lock().unwrap_or_else(PoisonError::into_inner);
69        cells.entry((app, provider)).or_default().clone()
70    }
71}
72
73impl fmt::Debug for RequestScope {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        let len = self.cells.lock().map_or(0, |cells| cells.len());
76        f.debug_struct("RequestScope")
77            .field("cached", &len)
78            .finish()
79    }
80}