1use 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
11pub 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 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}