Skip to main content

navree_kernel/
lazy.rs

1//! [`Lazy`]: a provider handle resolved on first use.
2
3use std::fmt;
4use std::sync::{Arc, Weak};
5
6use tokio::sync::OnceCell;
7
8use crate::container::{AppInner, RequestScope};
9use crate::{KernelError, ModuleId, ProviderKey, Resolver};
10
11/// A handle to the unnamed provider of `T`, resolved (with the visibility of
12/// the module that created it) on the first [`get`](Lazy::get) and then cached.
13///
14/// Created by [`Resolver::lazy`]. It is not a dependency edge, so it is the
15/// escape hatch for provider cycles. It holds the app weakly, so it does not
16/// keep a dropped app alive.
17pub struct Lazy<T: ?Sized> {
18    app: Weak<AppInner>,
19    module: ModuleId,
20    scope: Option<RequestScope>,
21    cell: OnceCell<Arc<T>>,
22}
23
24impl<T: ?Sized + Send + Sync + 'static> Lazy<T> {
25    pub(crate) fn new(app: &Arc<AppInner>, module: ModuleId, scope: Option<RequestScope>) -> Self {
26        Self {
27            app: Arc::downgrade(app),
28            module,
29            scope,
30            cell: OnceCell::new(),
31        }
32    }
33
34    /// Resolves the provider on first call; later calls return the same `Arc`.
35    pub async fn get(&self) -> Result<Arc<T>, KernelError> {
36        self.cell
37            .get_or_try_init(|| async {
38                let app = self
39                    .app
40                    .upgrade()
41                    .ok_or_else(|| KernelError::Construction {
42                        provider: ProviderKey::of::<T>().to_string(),
43                        source: "the app that created this lazy handle has been dropped".into(),
44                    })?;
45                Resolver::new(app, self.module, self.scope.clone())
46                    .get::<T>()
47                    .await
48            })
49            .await
50            .cloned()
51    }
52}
53
54impl<T: ?Sized> fmt::Debug for Lazy<T> {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.debug_struct("Lazy")
57            .field("type", &std::any::type_name::<T>())
58            .field("module", &self.module.name())
59            .field("resolved", &self.cell.initialized())
60            .finish()
61    }
62}