Skip to main content

navree_kernel/
resolver.rs

1//! [`Resolver`]: resolves providers as seen from one module.
2
3use std::fmt;
4use std::sync::Arc;
5
6use crate::builder::Instance;
7use crate::container::{AppInner, RequestScope, app_identity};
8use crate::graph::Visible;
9use crate::{AppContext, KernelError, Lazy, ModuleId, ProviderKey, Scope};
10
11/// Resolves providers with the visibility of one module: its own providers,
12/// the exports of the modules it imports and the exports of global modules.
13///
14/// Every provider constructor receives a `Resolver` for the module that owns
15/// the provider. It carries the optional [`RequestScope`] and the resolution
16/// stack used to detect cycles and scope inversions at runtime.
17#[derive(Clone)]
18pub struct Resolver {
19    pub(crate) inner: Arc<AppInner>,
20    module: ModuleId,
21    module_index: Option<usize>,
22    scope: Option<RequestScope>,
23    stack: Stack,
24}
25
26impl Resolver {
27    pub(crate) fn new(inner: Arc<AppInner>, module: ModuleId, scope: Option<RequestScope>) -> Self {
28        let module_index = inner.graph.module_of(module);
29        Self {
30            inner,
31            module,
32            module_index,
33            scope,
34            stack: Stack::default(),
35        }
36    }
37
38    /// This resolver, with `stack` as the providers being constructed.
39    pub(crate) fn continuing(mut self, stack: Stack) -> Self {
40        self.stack = stack;
41        self
42    }
43
44    /// Resolves the unnamed provider of `T`.
45    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Arc<T>, KernelError> {
46        self.get_key::<T>(&ProviderKey::of::<T>()).await
47    }
48
49    /// Resolves the provider of `T` registered under `name`.
50    pub async fn get_named<T: ?Sized + Send + Sync + 'static>(
51        &self,
52        name: &str,
53    ) -> Result<Arc<T>, KernelError> {
54        self.get_key::<T>(&ProviderKey::named::<T>(name.to_owned()))
55            .await
56    }
57
58    /// Resolves every multi-binding of `T` in the app (see
59    /// [`ModuleBuilder::multi`](crate::ModuleBuilder::multi)), in module dependency order.
60    pub async fn get_all<T: ?Sized + Send + Sync + 'static>(
61        &self,
62    ) -> Result<Vec<Arc<T>>, KernelError> {
63        let key = ProviderKey::of::<T>();
64        let mut all = Vec::new();
65        for &index in self.inner.graph.multi_of(key.type_id()) {
66            all.push(self.resolve_as::<T>(index, &key).await?);
67        }
68        Ok(all)
69    }
70
71    /// A handle that resolves the unnamed provider of `T` on its first
72    /// [`get`](Lazy::get). It adds no edge to the dependency graph, so it
73    /// breaks cycles; resolve it after boot, not inside a constructor.
74    pub fn lazy<T: ?Sized + Send + Sync + 'static>(&self) -> Lazy<T> {
75        Lazy::new(&self.inner, self.module, self.scope.clone())
76    }
77
78    /// A handle to the whole app.
79    pub fn app(&self) -> AppContext {
80        AppContext::from_inner(self.inner.clone())
81    }
82
83    /// The module whose visibility this resolver uses.
84    pub fn module(&self) -> ModuleId {
85        self.module
86    }
87
88    async fn get_key<T: ?Sized + Send + Sync + 'static>(
89        &self,
90        key: &ProviderKey,
91    ) -> Result<Arc<T>, KernelError> {
92        let index = self.lookup(key)?;
93        self.resolve_as::<T>(index, key).await
94    }
95
96    /// Resolves provider `index`, whose key is `key`, as an `Arc<T>`.
97    pub(crate) async fn resolve_as<T: ?Sized + Send + Sync + 'static>(
98        &self,
99        index: usize,
100        key: &ProviderKey,
101    ) -> Result<Arc<T>, KernelError> {
102        let instance = self.resolve_index(index).await?;
103        downcast::<T>(&instance, key)
104    }
105
106    fn lookup(&self, key: &ProviderKey) -> Result<usize, KernelError> {
107        let graph = &self.inner.graph;
108        match graph.lookup(self.module_index, key) {
109            Some(Visible::One(index)) => Ok(*index),
110            found => Err(graph.unresolved(
111                found,
112                self.module_index,
113                self.module.name(),
114                key,
115                self.required_by(),
116            )),
117        }
118    }
119
120    /// What is asking for a provider, for error messages.
121    fn required_by(&self) -> String {
122        match self.stack.frames().next() {
123            Some(frame) => format!("`{}`", self.key_of(frame.provider)),
124            None => "a direct resolver call".to_owned(),
125        }
126    }
127
128    fn key_of(&self, index: usize) -> &ProviderKey {
129        &self.inner.graph.providers[index].def.key
130    }
131
132    /// Resolves a provider by index, honouring its scope.
133    pub(crate) async fn resolve_index(&self, index: usize) -> Result<Instance, KernelError> {
134        let node = &self.inner.graph.providers[index];
135        let singleton_cell = &self.inner.singletons[index];
136        if node.def.scope == Scope::Singleton
137            && let Some(instance) = singleton_cell.get()
138        {
139            return Ok(instance.clone());
140        }
141        // Checked before touching any cell: re-entering a cell that is being
142        // initialised by this very resolution chain would deadlock.
143        if let Some(path) = self.stack.cycle_through(index) {
144            return Err(KernelError::ProviderCycle {
145                path: path
146                    .into_iter()
147                    .map(|p| self.key_of(p).to_string())
148                    .collect(),
149            });
150        }
151        match node.def.scope {
152            Scope::Singleton => {
153                // Singletons never see the request scope, so they cannot capture request state.
154                let child = self.child(index, None);
155                singleton_cell
156                    .get_or_try_init(|| (node.def.factory)(child))
157                    .await
158                    .cloned()
159            }
160            Scope::Request => {
161                if let Some(singleton) = self.stack.frames().find(|f| self.is_singleton(f.provider))
162                {
163                    let graph = &self.inner.graph;
164                    return Err(KernelError::ScopeInversion {
165                        module: graph.modules[graph.providers[singleton.provider].module].name,
166                        singleton: self.key_of(singleton.provider).to_string(),
167                        request_scoped: node.def.key.to_string(),
168                    });
169                }
170                let Some(scope) = &self.scope else {
171                    return Err(KernelError::MissingRequestScope {
172                        provider: node.def.key.to_string(),
173                    });
174                };
175                let cell = scope.cell(app_identity(&self.inner), index);
176                let child = self.child(index, Some(scope.clone()));
177                cell.get_or_try_init(|| (node.def.factory)(child))
178                    .await
179                    .cloned()
180            }
181            Scope::Transient => (node.def.factory)(self.child(index, self.scope.clone())).await,
182        }
183    }
184
185    fn is_singleton(&self, index: usize) -> bool {
186        self.inner.graph.providers[index].def.scope == Scope::Singleton
187    }
188
189    /// The resolver handed to the factory of provider `index`: the owning
190    /// module's visibility, one more frame on the stack.
191    fn child(&self, index: usize, scope: Option<RequestScope>) -> Resolver {
192        let owner = self.inner.graph.providers[index].module;
193        Resolver {
194            inner: self.inner.clone(),
195            module: self.inner.graph.modules[owner].id,
196            module_index: Some(owner),
197            scope,
198            stack: self.stack.push(index),
199        }
200    }
201}
202
203impl fmt::Debug for Resolver {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.debug_struct("Resolver")
206            .field("module", &self.module.name())
207            .field("request_scoped", &self.scope.is_some())
208            .finish_non_exhaustive()
209    }
210}
211
212/// A handle to the whole app whose resolutions continue `resolver`'s chain:
213/// asking it for a singleton that is being built on the way to the caller
214/// (the provider whose factory holds `resolver`, or one that asked for that
215/// provider) is a [`KernelError::ProviderCycle`] naming the chain, where
216/// [`AppContext::get`] would wait for ever. Only the singletons of the chain
217/// are carried, and each is built once the app has booted, so a handle kept
218/// past the boot resolves as any other.
219///
220/// Not public API: what Navree's driver kinds hand a driver's factory.
221#[doc(hidden)]
222pub fn app_in_chain(resolver: &Resolver) -> AppContext {
223    let mut singletons: Vec<usize> = resolver
224        .stack
225        .frames()
226        .map(|frame| frame.provider)
227        .filter(|&provider| resolver.is_singleton(provider))
228        .collect();
229    // Innermost first: pushed from the outermost, they keep that order.
230    singletons.reverse();
231    let chain = singletons
232        .into_iter()
233        .fold(Stack::default(), |chain, provider| chain.push(provider));
234    AppContext::in_chain(resolver.inner.clone(), chain)
235}
236
237/// Extracts the `Arc<T>` stored in an instance.
238fn downcast<T: ?Sized + Send + Sync + 'static>(
239    instance: &Instance,
240    key: &ProviderKey,
241) -> Result<Arc<T>, KernelError> {
242    instance
243        .downcast_ref::<Arc<T>>()
244        .cloned()
245        .ok_or_else(|| KernelError::Construction {
246            provider: key.to_string(),
247            source: format!(
248                "internal error: instance is not an `Arc<{}>`",
249                std::any::type_name::<T>()
250            )
251            .into(),
252        })
253}
254
255/// The providers currently being constructed, innermost first (a persistent list).
256#[derive(Clone, Default)]
257pub(crate) struct Stack(Option<Arc<Frame>>);
258
259struct Frame {
260    provider: usize,
261    parent: Option<Arc<Frame>>,
262}
263
264impl Stack {
265    fn push(&self, provider: usize) -> Stack {
266        Stack(Some(Arc::new(Frame {
267            provider,
268            parent: self.0.clone(),
269        })))
270    }
271
272    fn frames(&self) -> impl Iterator<Item = &Frame> {
273        std::iter::successors(self.0.as_deref(), |frame| frame.parent.as_deref())
274    }
275
276    /// If `provider` is already being constructed, the cycle from its first
277    /// construction back to itself (`[A, B, A]`).
278    fn cycle_through(&self, provider: usize) -> Option<Vec<usize>> {
279        let mut path: Vec<usize> = Vec::new();
280        for frame in self.frames() {
281            path.push(frame.provider);
282            if frame.provider == provider {
283                path.reverse();
284                path.push(provider);
285                return Some(path);
286            }
287        }
288        None
289    }
290}