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    /// Resolves the unnamed provider of `T`.
39    pub async fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Arc<T>, KernelError> {
40        self.get_key::<T>(&ProviderKey::of::<T>()).await
41    }
42
43    /// Resolves the provider of `T` registered under `name`.
44    pub async fn get_named<T: ?Sized + Send + Sync + 'static>(
45        &self,
46        name: &str,
47    ) -> Result<Arc<T>, KernelError> {
48        self.get_key::<T>(&ProviderKey::named::<T>(name.to_owned()))
49            .await
50    }
51
52    /// Resolves every multi-binding of `T` in the app (see
53    /// [`ModuleBuilder::multi`](crate::ModuleBuilder::multi)), in module dependency order.
54    pub async fn get_all<T: ?Sized + Send + Sync + 'static>(
55        &self,
56    ) -> Result<Vec<Arc<T>>, KernelError> {
57        let key = ProviderKey::of::<T>();
58        let mut all = Vec::new();
59        for &index in self.inner.graph.multi_of(key.type_id()) {
60            all.push(self.resolve_as::<T>(index, &key).await?);
61        }
62        Ok(all)
63    }
64
65    /// A handle that resolves the unnamed provider of `T` on its first
66    /// [`get`](Lazy::get). It adds no edge to the dependency graph, so it
67    /// breaks cycles; resolve it after boot, not inside a constructor.
68    pub fn lazy<T: ?Sized + Send + Sync + 'static>(&self) -> Lazy<T> {
69        Lazy::new(&self.inner, self.module, self.scope.clone())
70    }
71
72    /// A handle to the whole app.
73    pub fn app(&self) -> AppContext {
74        AppContext::from_inner(self.inner.clone())
75    }
76
77    /// The module whose visibility this resolver uses.
78    pub fn module(&self) -> ModuleId {
79        self.module
80    }
81
82    async fn get_key<T: ?Sized + Send + Sync + 'static>(
83        &self,
84        key: &ProviderKey,
85    ) -> Result<Arc<T>, KernelError> {
86        let index = self.lookup(key)?;
87        self.resolve_as::<T>(index, key).await
88    }
89
90    /// Resolves provider `index`, whose key is `key`, as an `Arc<T>`.
91    pub(crate) async fn resolve_as<T: ?Sized + Send + Sync + 'static>(
92        &self,
93        index: usize,
94        key: &ProviderKey,
95    ) -> Result<Arc<T>, KernelError> {
96        let instance = self.resolve_index(index).await?;
97        downcast::<T>(&instance, key)
98    }
99
100    fn lookup(&self, key: &ProviderKey) -> Result<usize, KernelError> {
101        let graph = &self.inner.graph;
102        match graph.lookup(self.module_index, key) {
103            Some(Visible::One(index)) => Ok(*index),
104            found => Err(graph.unresolved(
105                found,
106                self.module_index,
107                self.module.name(),
108                key,
109                self.required_by(),
110            )),
111        }
112    }
113
114    /// What is asking for a provider, for error messages.
115    fn required_by(&self) -> String {
116        match self.stack.frames().next() {
117            Some(frame) => format!("`{}`", self.key_of(frame.provider)),
118            None => "a direct resolver call".to_owned(),
119        }
120    }
121
122    fn key_of(&self, index: usize) -> &ProviderKey {
123        &self.inner.graph.providers[index].def.key
124    }
125
126    /// Resolves a provider by index, honouring its scope.
127    pub(crate) async fn resolve_index(&self, index: usize) -> Result<Instance, KernelError> {
128        let node = &self.inner.graph.providers[index];
129        let singleton_cell = &self.inner.singletons[index];
130        if node.def.scope == Scope::Singleton
131            && let Some(instance) = singleton_cell.get()
132        {
133            return Ok(instance.clone());
134        }
135        // Checked before touching any cell: re-entering a cell that is being
136        // initialised by this very resolution chain would deadlock.
137        if let Some(path) = self.stack.cycle_through(index) {
138            return Err(KernelError::ProviderCycle {
139                path: path
140                    .into_iter()
141                    .map(|p| self.key_of(p).to_string())
142                    .collect(),
143            });
144        }
145        match node.def.scope {
146            Scope::Singleton => {
147                // Singletons never see the request scope, so they cannot capture request state.
148                let child = self.child(index, None);
149                singleton_cell
150                    .get_or_try_init(|| (node.def.factory)(child))
151                    .await
152                    .cloned()
153            }
154            Scope::Request => {
155                if let Some(singleton) = self.stack.frames().find(|f| self.is_singleton(f.provider))
156                {
157                    let graph = &self.inner.graph;
158                    return Err(KernelError::ScopeInversion {
159                        module: graph.modules[graph.providers[singleton.provider].module].name,
160                        singleton: self.key_of(singleton.provider).to_string(),
161                        request_scoped: node.def.key.to_string(),
162                    });
163                }
164                let Some(scope) = &self.scope else {
165                    return Err(KernelError::MissingRequestScope {
166                        provider: node.def.key.to_string(),
167                    });
168                };
169                let cell = scope.cell(app_identity(&self.inner), index);
170                let child = self.child(index, Some(scope.clone()));
171                cell.get_or_try_init(|| (node.def.factory)(child))
172                    .await
173                    .cloned()
174            }
175            Scope::Transient => (node.def.factory)(self.child(index, self.scope.clone())).await,
176        }
177    }
178
179    fn is_singleton(&self, index: usize) -> bool {
180        self.inner.graph.providers[index].def.scope == Scope::Singleton
181    }
182
183    /// The resolver handed to the factory of provider `index`: the owning
184    /// module's visibility, one more frame on the stack.
185    fn child(&self, index: usize, scope: Option<RequestScope>) -> Resolver {
186        let owner = self.inner.graph.providers[index].module;
187        Resolver {
188            inner: self.inner.clone(),
189            module: self.inner.graph.modules[owner].id,
190            module_index: Some(owner),
191            scope,
192            stack: self.stack.push(index),
193        }
194    }
195}
196
197impl fmt::Debug for Resolver {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        f.debug_struct("Resolver")
200            .field("module", &self.module.name())
201            .field("request_scoped", &self.scope.is_some())
202            .finish_non_exhaustive()
203    }
204}
205
206/// Extracts the `Arc<T>` stored in an instance.
207fn downcast<T: ?Sized + Send + Sync + 'static>(
208    instance: &Instance,
209    key: &ProviderKey,
210) -> Result<Arc<T>, KernelError> {
211    instance
212        .downcast_ref::<Arc<T>>()
213        .cloned()
214        .ok_or_else(|| KernelError::Construction {
215            provider: key.to_string(),
216            source: format!(
217                "internal error: instance is not an `Arc<{}>`",
218                std::any::type_name::<T>()
219            )
220            .into(),
221        })
222}
223
224/// The providers currently being constructed, innermost first (a persistent list).
225#[derive(Clone, Default)]
226struct Stack(Option<Arc<Frame>>);
227
228struct Frame {
229    provider: usize,
230    parent: Option<Arc<Frame>>,
231}
232
233impl Stack {
234    fn push(&self, provider: usize) -> Stack {
235        Stack(Some(Arc::new(Frame {
236            provider,
237            parent: self.0.clone(),
238        })))
239    }
240
241    fn frames(&self) -> impl Iterator<Item = &Frame> {
242        std::iter::successors(self.0.as_deref(), |frame| frame.parent.as_deref())
243    }
244
245    /// If `provider` is already being constructed, the cycle from its first
246    /// construction back to itself (`[A, B, A]`).
247    fn cycle_through(&self, provider: usize) -> Option<Vec<usize>> {
248        let mut path: Vec<usize> = Vec::new();
249        for frame in self.frames() {
250            path.push(frame.provider);
251            if frame.provider == provider {
252                path.reverse();
253                path.push(provider);
254                return Some(path);
255            }
256        }
257        None
258    }
259}