1use std::any::{Any, TypeId};
4use std::borrow::Cow;
5use std::fmt;
6use std::future::Future;
7use std::sync::Arc;
8
9use crate::lifecycle::LifecycleDef;
10use crate::{
11 BoxError, BoxFuture, CommandSpec, Injectable, IntoModules, KernelError, Lifecycle, Module,
12 ModuleId, ProviderKey, Resolver, Scope,
13};
14
15pub(crate) type Contribution = (TypeId, Arc<dyn Any + Send + Sync>);
17
18pub(crate) type Instance = Arc<dyn Any + Send + Sync>;
20
21pub(crate) type ErasedFactory =
23 Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Instance, KernelError>> + Send + Sync>;
24
25#[derive(Clone)]
27pub(crate) struct ProviderDef {
28 pub(crate) key: ProviderKey,
29 pub(crate) scope: Scope,
30 pub(crate) deps: Vec<ProviderKey>,
31 pub(crate) factory: ErasedFactory,
32 pub(crate) multi: bool,
34}
35
36pub struct ModuleBuilder {
38 pub(crate) id: ModuleId,
39 pub(crate) name: &'static str,
40 pub(crate) global: bool,
41 pub(crate) imports: Vec<Box<dyn Module>>,
42 pub(crate) providers: Vec<ProviderDef>,
43 pub(crate) exports: Vec<ProviderKey>,
44 pub(crate) contributions: Vec<Contribution>,
45 pub(crate) lifecycles: Vec<LifecycleDef>,
46 pub(crate) commands: Vec<CommandSpec>,
47}
48
49impl ModuleBuilder {
50 pub(crate) fn new(id: ModuleId, name: &'static str) -> Self {
51 Self {
52 id,
53 name,
54 global: false,
55 imports: Vec::new(),
56 providers: Vec::new(),
57 exports: Vec::new(),
58 contributions: Vec::new(),
59 lifecycles: Vec::new(),
60 commands: Vec::new(),
61 }
62 }
63
64 pub fn module_id(&self) -> ModuleId {
66 self.id
67 }
68
69 pub fn import(&mut self, module: impl Module) -> &mut Self {
71 self.imports.push(Box::new(module));
72 self
73 }
74
75 pub fn imports(&mut self, modules: impl IntoModules) -> &mut Self {
77 self.imports.extend(modules.into_modules());
78 self
79 }
80
81 pub fn global(&mut self) -> &mut Self {
83 self.global = true;
84 self
85 }
86
87 pub fn provider<T: Injectable>(&mut self) -> &mut Self {
89 self.injectable::<T>(ProviderKey::of::<T>())
90 }
91
92 pub fn provider_named<T: Injectable>(
94 &mut self,
95 name: impl Into<Cow<'static, str>>,
96 ) -> &mut Self {
97 self.injectable::<T>(ProviderKey::named::<T>(name))
98 }
99
100 fn injectable<T: Injectable>(&mut self, key: ProviderKey) -> &mut Self {
101 self.providers.push(ProviderDef {
102 key,
103 scope: T::scope(),
104 deps: T::dependencies(),
105 factory: Arc::new(|r| {
106 Box::pin(async move {
107 T::construct(r)
108 .await
109 .map(|v| Arc::new(Arc::new(v)) as Instance)
110 })
111 }),
112 multi: false,
113 });
114 self
115 }
116
117 pub fn value<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
119 self.value_arc(Arc::new(value))
120 }
121
122 pub fn value_arc<T: ?Sized + Send + Sync + 'static>(&mut self, value: Arc<T>) -> &mut Self {
124 self.providers
125 .push(value_def(ProviderKey::of::<T>(), value));
126 self
127 }
128
129 pub fn factory<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
131 self.providers.push(f.into_def());
132 self
133 }
134
135 pub fn multi<T: ?Sized + Send + Sync + 'static>(&mut self, f: Factory<T>) -> &mut Self {
139 let mut def = f.into_def();
140 def.multi = true;
141 self.providers.push(def);
142 self
143 }
144
145 pub fn exports<T: ?Sized + 'static>(&mut self) -> &mut Self {
147 self.export_key(ProviderKey::of::<T>())
148 }
149
150 pub fn export_key(&mut self, key: ProviderKey) -> &mut Self {
152 self.exports.push(key);
153 self
154 }
155
156 pub fn contribute<C: Send + Sync + 'static>(&mut self, c: C) -> &mut Self {
160 self.contributions.push((TypeId::of::<C>(), Arc::new(c)));
161 self
162 }
163
164 pub fn lifecycle<T: Lifecycle + Send + Sync + 'static>(&mut self) -> &mut Self {
167 self.lifecycles.push(LifecycleDef::of::<T>());
168 self
169 }
170
171 pub fn command(&mut self, cmd: CommandSpec) -> &mut Self {
173 self.commands.push(cmd);
174 self
175 }
176}
177
178impl fmt::Debug for ModuleBuilder {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 f.debug_struct("ModuleBuilder")
181 .field("module", &self.name)
182 .field("global", &self.global)
183 .field("imports", &self.imports.len())
184 .field(
185 "providers",
186 &self
187 .providers
188 .iter()
189 .map(|p| p.key.to_string())
190 .collect::<Vec<_>>(),
191 )
192 .field(
193 "exports",
194 &self
195 .exports
196 .iter()
197 .map(ToString::to_string)
198 .collect::<Vec<_>>(),
199 )
200 .finish()
201 }
202}
203
204pub struct Factory<T: ?Sized> {
208 scope: Scope,
209 deps: Vec<ProviderKey>,
210 name: Option<Cow<'static, str>>,
211 build: BuildFn<T>,
212}
213
214type BuildFn<T> =
216 Arc<dyn Fn(Resolver) -> BoxFuture<'static, Result<Arc<T>, BoxError>> + Send + Sync>;
217
218impl<T: ?Sized + Send + Sync + 'static> Factory<T> {
219 pub fn new<F, Fut>(f: F) -> Self
221 where
222 F: Fn(Resolver) -> Fut + Send + Sync + 'static,
223 Fut: Future<Output = Result<Arc<T>, BoxError>> + Send + 'static,
224 {
225 Self {
226 scope: Scope::Singleton,
227 deps: Vec::new(),
228 name: None,
229 build: Arc::new(move |r| Box::pin(f(r))),
230 }
231 }
232
233 pub fn scope(mut self, s: Scope) -> Self {
235 self.scope = s;
236 self
237 }
238
239 pub fn deps(mut self, d: Vec<ProviderKey>) -> Self {
241 self.deps = d;
242 self
243 }
244
245 pub fn named(mut self, n: impl Into<Cow<'static, str>>) -> Self {
247 self.name = Some(n.into());
248 self
249 }
250
251 pub(crate) fn into_def(self) -> ProviderDef {
252 let key = match self.name {
253 Some(name) => ProviderKey::named::<T>(name),
254 None => ProviderKey::of::<T>(),
255 };
256 let provider = key.to_string();
257 let build = self.build;
258 ProviderDef {
259 key,
260 scope: self.scope,
261 deps: self.deps,
262 factory: Arc::new(move |r| {
263 let fut = build(r);
264 let provider = provider.clone();
265 Box::pin(async move {
266 match fut.await {
267 Ok(value) => Ok(Arc::new(value) as Instance),
268 Err(error) => Err(into_kernel_error(error, provider)),
269 }
270 })
271 }),
272 multi: false,
273 }
274 }
275}
276
277impl<T: ?Sized> fmt::Debug for Factory<T> {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 f.debug_struct("Factory")
280 .field("type", &std::any::type_name::<T>())
281 .field("scope", &self.scope)
282 .field("deps", &self.deps)
283 .field("name", &self.name)
284 .finish()
285 }
286}
287
288pub(crate) fn value_def<T: ?Sized + Send + Sync + 'static>(
290 key: ProviderKey,
291 value: Arc<T>,
292) -> ProviderDef {
293 ProviderDef {
294 key,
295 scope: Scope::Singleton,
296 deps: Vec::new(),
297 factory: Arc::new(move |_| {
298 let instance: Instance = Arc::new(value.clone());
299 Box::pin(async move { Ok(instance) })
300 }),
301 multi: false,
302 }
303}
304
305fn into_kernel_error(error: BoxError, provider: String) -> KernelError {
308 match error.downcast::<KernelError>() {
309 Ok(kernel) => *kernel,
310 Err(source) => KernelError::Construction { provider, source },
311 }
312}