Skip to main content

luxid_core/
container.rs

1//! The service container.
2//!
3//! Lifetimes follow ASP.NET Core's model, which is the proven answer for a
4//! statically typed language: singleton (once per app), scoped (once per
5//! request), transient (every resolution).
6//!
7//! Resolution is by runtime type id — the same trade already taken with
8//! pure-context actions. Two things narrow the blast radius:
9//!
10//! * [`Container::eager_init`] resolves every singleton at boot, so a missing
11//!   or cyclic binding fails at startup naming the type, not on first request.
12//! * Cycles are detected during resolution and reported as a chain rather than
13//!   overflowing the stack.
14
15use std::any::{Any, TypeId};
16use std::cell::RefCell;
17use std::collections::HashMap;
18use std::sync::{Arc, Mutex, RwLock};
19
20use crate::error::{Error, Result};
21
22type Instance = Arc<dyn Any + Send + Sync>;
23type Factory = Arc<dyn Fn(&Container) -> Result<Instance> + Send + Sync>;
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Lifetime {
27    /// One instance for the life of the application.
28    Singleton,
29    /// One instance per request.
30    Scoped,
31    /// A fresh instance on every resolution.
32    Transient,
33}
34
35struct Registration {
36    type_name: &'static str,
37    lifetime: Lifetime,
38    factory: Factory,
39}
40
41thread_local! {
42    /// The chain currently being resolved on this thread, used to turn a
43    /// dependency cycle into a readable error instead of a stack overflow.
44    static RESOLVING: RefCell<Vec<&'static str>> = const { RefCell::new(Vec::new()) };
45}
46
47/// Declarative bindings, assembled in `src/app.rs` and frozen into a
48/// [`Container`] at boot.
49#[derive(Default)]
50pub struct Providers {
51    registrations: HashMap<TypeId, Registration>,
52    order: Vec<TypeId>,
53}
54
55impl Providers {
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// One instance for the whole application.
61    #[must_use]
62    pub fn singleton<T, F>(self, factory: F) -> Self
63    where
64        T: Any + Send + Sync,
65        F: Fn(&Container) -> T + Send + Sync + 'static,
66    {
67        self.register::<T, _>(Lifetime::Singleton, move |c| Ok(factory(c)))
68    }
69
70    /// One instance per request.
71    #[must_use]
72    pub fn scoped<T, F>(self, factory: F) -> Self
73    where
74        T: Any + Send + Sync,
75        F: Fn(&Container) -> T + Send + Sync + 'static,
76    {
77        self.register::<T, _>(Lifetime::Scoped, move |c| Ok(factory(c)))
78    }
79
80    /// A fresh instance on every resolution.
81    #[must_use]
82    pub fn transient<T, F>(self, factory: F) -> Self
83    where
84        T: Any + Send + Sync,
85        F: Fn(&Container) -> T + Send + Sync + 'static,
86    {
87        self.register::<T, _>(Lifetime::Transient, move |c| Ok(factory(c)))
88    }
89
90    /// A singleton whose construction can fail — a pool that must connect, a
91    /// client that must read credentials. The failure surfaces at boot.
92    #[must_use]
93    pub fn try_singleton<T, F>(self, factory: F) -> Self
94    where
95        T: Any + Send + Sync,
96        F: Fn(&Container) -> Result<T> + Send + Sync + 'static,
97    {
98        self.register::<T, _>(Lifetime::Singleton, factory)
99    }
100
101    /// Bind a trait object, so apps and tests can swap implementations:
102    /// `.bind::<dyn Mailer, _>(|c| Arc::new(Smtp::new(c)))`.
103    #[must_use]
104    pub fn bind<I, F>(mut self, factory: F) -> Self
105    where
106        I: ?Sized + Send + Sync + 'static,
107        F: Fn(&Container) -> Arc<I> + Send + Sync + 'static,
108    {
109        let key = TypeId::of::<I>();
110
111        // The instance stored is `Arc<I>` itself, boxed into `Arc<dyn Any>` —
112        // an unsized `I` cannot be downcast to directly.
113        let registration = Registration {
114            type_name: std::any::type_name::<I>(),
115            lifetime: Lifetime::Singleton,
116            factory: Arc::new(move |c: &Container| {
117                let instance: Arc<I> = factory(c);
118                Ok(Arc::new(instance) as Instance)
119            }),
120        };
121
122        if self.registrations.insert(key, registration).is_none() {
123            self.order.push(key);
124        }
125        self
126    }
127
128    fn register<T, F>(mut self, lifetime: Lifetime, factory: F) -> Self
129    where
130        T: Any + Send + Sync,
131        F: Fn(&Container) -> Result<T> + Send + Sync + 'static,
132    {
133        let key = TypeId::of::<T>();
134
135        let registration = Registration {
136            type_name: std::any::type_name::<T>(),
137            lifetime,
138            factory: Arc::new(move |c: &Container| Ok(Arc::new(factory(c)?) as Instance)),
139        };
140
141        if self.registrations.insert(key, registration).is_none() {
142            self.order.push(key);
143        }
144        self
145    }
146
147    /// Freeze into a container. Call [`Container::eager_init`] to validate.
148    pub fn build(self) -> Container {
149        Container {
150            root: Arc::new(Root {
151                registrations: self.registrations,
152                order: self.order,
153                singletons: RwLock::new(HashMap::new()),
154            }),
155            scoped: Arc::new(Mutex::new(HashMap::new())),
156        }
157    }
158}
159
160struct Root {
161    registrations: HashMap<TypeId, Registration>,
162    order: Vec<TypeId>,
163    singletons: RwLock<HashMap<TypeId, Instance>>,
164}
165
166/// A handle onto the application's services. Cheap to clone.
167#[derive(Clone)]
168pub struct Container {
169    root: Arc<Root>,
170    scoped: Arc<Mutex<HashMap<TypeId, Instance>>>,
171}
172
173impl Default for Container {
174    fn default() -> Self {
175        Providers::new().build()
176    }
177}
178
179impl Container {
180    /// A per-request view: same singletons, a fresh scoped cache.
181    pub fn scope(&self) -> Self {
182        Self {
183            root: Arc::clone(&self.root),
184            scoped: Arc::new(Mutex::new(HashMap::new())),
185        }
186    }
187
188    pub fn contains<T: Any + Send + Sync>(&self) -> bool {
189        self.root.registrations.contains_key(&TypeId::of::<T>())
190    }
191
192    pub fn is_empty(&self) -> bool {
193        self.root.registrations.is_empty()
194    }
195
196    pub fn len(&self) -> usize {
197        self.root.registrations.len()
198    }
199
200    /// Resolve a concrete type.
201    pub fn get<T: Any + Send + Sync>(&self) -> Result<Arc<T>> {
202        let instance = self.resolve(TypeId::of::<T>(), std::any::type_name::<T>())?;
203
204        instance.downcast::<T>().map_err(|_| {
205            Error::internal(format!(
206                "`{}` was registered under a different type than it resolves to",
207                std::any::type_name::<T>()
208            ))
209        })
210    }
211
212    /// Resolve a trait object registered with [`Providers::bind`].
213    pub fn get_dyn<I: ?Sized + Send + Sync + 'static>(&self) -> Result<Arc<I>> {
214        let instance = self.resolve(TypeId::of::<I>(), std::any::type_name::<I>())?;
215
216        instance
217            .downcast::<Arc<I>>()
218            .map(|boxed| Arc::clone(&*boxed))
219            .map_err(|_| {
220                Error::internal(format!(
221                    "`{}` was bound as a concrete type; resolve it with `get` instead of `get_dyn`",
222                    std::any::type_name::<I>()
223                ))
224            })
225    }
226
227    /// Resolve every singleton now, in registration order.
228    ///
229    /// Called by `App::run`, so a missing or cyclic binding is a startup
230    /// failure naming the type rather than a 500 at 3am.
231    pub fn eager_init(&self) -> Result<()> {
232        for key in &self.root.order {
233            let registration = &self.root.registrations[key];
234
235            if registration.lifetime == Lifetime::Singleton {
236                self.resolve(*key, registration.type_name)?;
237            }
238        }
239        Ok(())
240    }
241
242    fn resolve(&self, key: TypeId, requested: &'static str) -> Result<Instance> {
243        let Some(registration) = self.root.registrations.get(&key) else {
244            return Err(Error::internal(format!(
245                "no provider bound for `{requested}`. Register it in `providers()`, \
246                 e.g. `.singleton(|_| {requested}::new())`"
247            )));
248        };
249
250        match registration.lifetime {
251            Lifetime::Singleton => {
252                if let Some(existing) = self
253                    .root
254                    .singletons
255                    .read()
256                    .expect("singleton cache is not poisoned")
257                    .get(&key)
258                {
259                    return Ok(Arc::clone(existing));
260                }
261
262                // The factory runs without the lock held: it may resolve other
263                // services, and holding the write lock across that would
264                // deadlock on any diamond dependency.
265                let instance = self.invoke(registration)?;
266
267                let mut singletons = self
268                    .root
269                    .singletons
270                    .write()
271                    .expect("singleton cache is not poisoned");
272
273                // A concurrent resolution may have won the race; prefer the
274                // instance already published so callers agree on identity.
275                Ok(Arc::clone(singletons.entry(key).or_insert(instance)))
276            }
277
278            Lifetime::Scoped => {
279                if let Some(existing) = self
280                    .scoped
281                    .lock()
282                    .expect("scope cache is not poisoned")
283                    .get(&key)
284                {
285                    return Ok(Arc::clone(existing));
286                }
287
288                let instance = self.invoke(registration)?;
289                let mut scoped = self.scoped.lock().expect("scope cache is not poisoned");
290
291                Ok(Arc::clone(scoped.entry(key).or_insert(instance)))
292            }
293
294            Lifetime::Transient => self.invoke(registration),
295        }
296    }
297
298    /// Run a factory with cycle detection.
299    fn invoke(&self, registration: &Registration) -> Result<Instance> {
300        let name = registration.type_name;
301
302        let cycle = RESOLVING.with(|chain| {
303            let mut chain = chain.borrow_mut();
304
305            if chain.contains(&name) {
306                let mut path = chain.clone();
307                path.push(name);
308                return Some(path.join(" → "));
309            }
310
311            chain.push(name);
312            None
313        });
314
315        if let Some(path) = cycle {
316            // Unwind the marker we did not push, then report the whole chain.
317            return Err(Error::internal(format!(
318                "dependency cycle in providers: {path}"
319            )));
320        }
321
322        let outcome = (registration.factory)(self);
323
324        RESOLVING.with(|chain| {
325            chain.borrow_mut().pop();
326        });
327
328        outcome
329    }
330}
331
332impl std::fmt::Debug for Container {
333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        f.debug_struct("Container")
335            .field("registered", &self.root.registrations.len())
336            .finish()
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use std::sync::atomic::{AtomicUsize, Ordering};
344
345    #[derive(Debug)]
346    struct Counter {
347        seq: usize,
348    }
349
350    impl Counter {
351        fn built(counter: &Arc<AtomicUsize>) -> Self {
352            Self {
353                seq: counter.fetch_add(1, Ordering::SeqCst),
354            }
355        }
356    }
357
358    #[derive(Debug)]
359    struct Config {
360        url: String,
361    }
362
363    #[derive(Debug)]
364    struct Pool {
365        url: String,
366    }
367
368    #[derive(Debug)]
369    struct Repo {
370        url: String,
371    }
372
373    trait Mailer: Send + Sync {
374        fn name(&self) -> &'static str;
375    }
376
377    #[derive(Debug)]
378    struct Smtp;
379    impl Mailer for Smtp {
380        fn name(&self) -> &'static str {
381            "smtp"
382        }
383    }
384
385    #[test]
386    fn a_singleton_is_built_once() {
387        let builds = Arc::new(AtomicUsize::new(0));
388        let counter = Arc::clone(&builds);
389
390        let container = Providers::new()
391            .singleton(move |_| Counter::built(&counter))
392            .build();
393
394        let first = container.get::<Counter>().expect("resolves");
395        let second = container.get::<Counter>().expect("resolves");
396
397        assert_eq!(builds.load(Ordering::SeqCst), 1);
398        assert!(Arc::ptr_eq(&first, &second));
399        assert_eq!(first.seq, 0);
400    }
401
402    #[test]
403    fn a_transient_is_built_every_time() {
404        let builds = Arc::new(AtomicUsize::new(0));
405        let counter = Arc::clone(&builds);
406
407        let container = Providers::new()
408            .transient(move |_| Counter::built(&counter))
409            .build();
410
411        let first = container.get::<Counter>().expect("resolves");
412        let second = container.get::<Counter>().expect("resolves");
413
414        assert_eq!(builds.load(Ordering::SeqCst), 2);
415        assert!(!Arc::ptr_eq(&first, &second));
416        assert_eq!((first.seq, second.seq), (0, 1));
417    }
418
419    #[test]
420    fn a_scoped_value_is_shared_within_a_scope_and_fresh_across_scopes() {
421        let builds = Arc::new(AtomicUsize::new(0));
422        let counter = Arc::clone(&builds);
423
424        let container = Providers::new()
425            .scoped(move |_| Counter::built(&counter))
426            .build();
427
428        let request = container.scope();
429        let first = request.get::<Counter>().expect("resolves");
430        let second = request.get::<Counter>().expect("resolves");
431        assert!(Arc::ptr_eq(&first, &second), "same within one request");
432        assert_eq!(builds.load(Ordering::SeqCst), 1);
433
434        let other_request = container.scope();
435        let third = other_request.get::<Counter>().expect("resolves");
436        assert!(!Arc::ptr_eq(&first, &third), "fresh in the next request");
437        assert_eq!((first.seq, third.seq), (0, 1));
438        assert_eq!(builds.load(Ordering::SeqCst), 2);
439    }
440
441    #[test]
442    fn singletons_are_shared_across_scopes() {
443        let builds = Arc::new(AtomicUsize::new(0));
444        let counter = Arc::clone(&builds);
445
446        let container = Providers::new()
447            .singleton(move |_| Counter::built(&counter))
448            .build();
449
450        let a = container.scope().get::<Counter>().expect("resolves");
451        let b = container.scope().get::<Counter>().expect("resolves");
452
453        assert!(Arc::ptr_eq(&a, &b));
454        assert_eq!(builds.load(Ordering::SeqCst), 1);
455    }
456
457    #[test]
458    fn factories_can_resolve_their_own_dependencies() {
459        let container = Providers::new()
460            .singleton(|_| Config {
461                url: "postgres://local".into(),
462            })
463            .singleton(|c| {
464                let config = c.get::<Config>().expect("config is registered");
465                Pool {
466                    url: config.url.clone(),
467                }
468            })
469            .build();
470
471        assert_eq!(
472            container.get::<Pool>().expect("resolves").url,
473            "postgres://local"
474        );
475    }
476
477    #[test]
478    fn a_diamond_dependency_resolves_without_deadlocking() {
479        let container = Providers::new()
480            .singleton(|_| Config { url: "u".into() })
481            .singleton(|c| Pool {
482                url: c.get::<Config>().expect("config").url.clone(),
483            })
484            .singleton(|c| Repo {
485                url: c.get::<Pool>().expect("pool").url.clone(),
486            })
487            .build();
488
489        container.eager_init().expect("graph resolves");
490        assert_eq!(container.get::<Repo>().expect("resolves").url, "u");
491    }
492
493    #[test]
494    fn an_unregistered_type_names_itself_in_the_error() {
495        let container = Providers::new().build();
496        let err = container.get::<Config>().unwrap_err();
497
498        let message = format!("{err}");
499        assert!(message.contains("no provider bound"), "{message}");
500        assert!(message.contains("Config"), "{message}");
501        assert!(message.contains("providers()"), "{message}");
502    }
503
504    #[test]
505    fn eager_init_catches_a_missing_dependency_at_boot() {
506        // Pool depends on Config, which nobody registered.
507        let container = Providers::new()
508            .try_singleton(|c| {
509                c.get::<Config>().map(|config| Pool {
510                    url: config.url.clone(),
511                })
512            })
513            .build();
514
515        let err = container.eager_init().unwrap_err();
516        assert!(format!("{err}").contains("Config"));
517    }
518
519    #[test]
520    fn eager_init_only_builds_singletons() {
521        let builds = Arc::new(AtomicUsize::new(0));
522        let counter = Arc::clone(&builds);
523
524        let container = Providers::new()
525            .scoped(move |_| Counter::built(&counter))
526            .build();
527
528        container.eager_init().expect("nothing eager to build");
529        assert_eq!(builds.load(Ordering::SeqCst), 0);
530    }
531
532    #[test]
533    fn a_dependency_cycle_is_reported_as_a_chain() {
534        let container = Providers::new()
535            .try_singleton(|c| {
536                c.get::<Repo>().map(|repo| Pool {
537                    url: repo.url.clone(),
538                })
539            })
540            .try_singleton(|c| {
541                c.get::<Pool>().map(|pool| Repo {
542                    url: pool.url.clone(),
543                })
544            })
545            .build();
546
547        let err = container.eager_init().unwrap_err();
548        let message = format!("{err}");
549
550        assert!(message.contains("dependency cycle"), "{message}");
551        assert!(message.contains("→"), "{message}");
552    }
553
554    #[test]
555    fn trait_objects_bind_and_resolve() {
556        let container = Providers::new()
557            .bind::<dyn Mailer, _>(|_| Arc::new(Smtp))
558            .build();
559
560        assert_eq!(
561            container.get_dyn::<dyn Mailer>().expect("resolves").name(),
562            "smtp"
563        );
564    }
565
566    #[test]
567    fn resolving_a_bound_trait_with_get_reports_the_right_call() {
568        let container = Providers::new()
569            .bind::<dyn Mailer, _>(|_| Arc::new(Smtp))
570            .build();
571
572        // `Smtp` itself was never registered — only `dyn Mailer` was.
573        assert!(container.get::<Smtp>().is_err());
574    }
575
576    #[test]
577    fn re_registering_a_type_replaces_it_without_duplicating_boot_order() {
578        let container = Providers::new()
579            .singleton(|_| Config {
580                url: "first".into(),
581            })
582            .singleton(|_| Config {
583                url: "second".into(),
584            })
585            .build();
586
587        assert_eq!(container.len(), 1);
588        assert_eq!(container.get::<Config>().expect("resolves").url, "second");
589    }
590}