Skip to main content

dptree/
di.rs

1//! An implementation of [dependency injection].
2//!
3//! If you do not know what is dependency injection (DI), please read [this
4//! discussion on StackOverflow], then come back. The only difference is that in
5//! `dptree`, we inject objects into function-handlers, not into objects.
6//!
7//! Currently, the only container is [`DependencyMap`]. It implements the DI
8//! pattern completely, but be careful: it can panic when you do not provide
9//! necessary types. Most the times, it is profitable to use
10//! [`crate::type_check`] to make sure that all types are provided _before_
11//! executing a particular handler.
12//!
13//! [dependency injection]: https://en.wikipedia.org/wiki/Dependency_injection
14//! [this discussion on StackOverflow]: https://stackoverflow.com/questions/130794/what-is-dependency-injection
15
16use futures::future::ready;
17
18use crate::send::{BoxFuture, MaybeSend, MaybeSync};
19
20use std::{
21    any::{Any, TypeId},
22    collections::{BTreeMap, BTreeSet},
23    fmt::{Debug, Formatter, Write},
24    future::Future,
25    iter::FromIterator,
26    panic::Location,
27    sync::Arc,
28};
29
30use crate::Type;
31
32/// A DI container with multiple dependencies.
33///
34/// This DI container stores types by their corresponding type identifiers. It
35/// cannot prove at compile-time that a type of a requested value exists within
36/// the container, so if you do not provide necessary types but they were
37/// requested, it will panic. However, you can use [`crate::type_check`] to make
38/// sure that all types are provided _before_ executing a particular handler.
39///
40/// Lookup uses the exact type inserted. If your handler takes
41/// `Arc<dyn MyTrait + Send + Sync>`, coerce the pointer to that type before
42/// inserting it. Inserting an `Arc<Concrete>` instead registers `Arc<Concrete>`,
43/// even if `Concrete` implements `MyTrait`.
44///
45/// ```
46/// use dptree::di::DependencyMap;
47/// use std::sync::Arc;
48///
49/// trait MyTrait {}
50/// impl MyTrait for u16 {}
51///
52/// let data: Arc<dyn MyTrait + Send + Sync> = Arc::new(42_u16);
53/// let mut container = DependencyMap::new();
54/// container.insert(data);
55/// assert!(container.try_get::<Arc<dyn MyTrait + Send + Sync>>().is_some());
56/// assert!(container.try_get::<Arc<u16>>().is_none());
57/// ```
58///
59/// # Examples
60///
61/// ```
62/// use dptree::di::DependencyMap;
63/// use std::sync::Arc;
64///
65/// let mut container = DependencyMap::new();
66/// container.insert(5_i32);
67/// container.insert("abc");
68///
69/// assert_eq!(container.get(), Arc::new(5_i32));
70/// assert_eq!(container.get(), Arc::new("abc"));
71///
72/// // If a type of a value already exists within the container, it will be replaced.
73/// let old_value = container.insert(10_i32).unwrap();
74///
75/// assert_eq!(old_value, Arc::new(5_i32));
76/// assert_eq!(container.get(), Arc::new(10_i32));
77/// ```
78///
79/// Dependency values must implement `Send + Sync + 'static` on all targets,
80/// including `wasm32`. A handler can capture an `Rc` on `wasm32`, but cannot
81/// store it in the dependency map or inject it as a handler argument.
82///
83/// ```compile_fail
84/// use dptree::di::DependencyMap;
85/// use std::rc::Rc;
86///
87/// DependencyMap::new().insert(Rc::new(42));
88/// ```
89///
90/// Maps do not implement `PartialEq`: the erased dependency values cannot
91/// generally be compared. Use [`Self::same_types`] to compare their type sets.
92///
93/// ```compile_fail
94/// use dptree::deps;
95///
96/// assert_eq!(deps![false], deps![true]);
97/// ```
98///
99/// When a value is not found within the container, it will panic:
100///
101/// ```should_panic
102/// use dptree::di::DependencyMap;
103/// use std::sync::Arc;
104///
105/// let mut container = DependencyMap::new();
106/// container.insert(10i32);
107/// container.insert(true);
108/// container.insert("static str");
109///
110/// // `alloc::string::String` was requested, but not provided. Available types:
111/// //     `i32`
112/// //     `&str`
113/// //     `bool`
114/// let string: Arc<String> = container.get();
115/// ```
116#[derive(Default, Clone, Debug)]
117pub struct DependencyMap {
118    pub(crate) map: BTreeMap<TypeId, Dependency>,
119}
120
121#[derive(Clone)]
122pub(crate) struct Dependency {
123    pub(crate) type_name: &'static str,
124    inner: Arc<dyn Any + Send + Sync>,
125}
126
127impl Debug for Dependency {
128    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
129        f.debug_struct("Dependency").field("type_name", &self.type_name).finish_non_exhaustive()
130    }
131}
132
133impl DependencyMap {
134    /// Returns whether both maps contain exactly the same dependency types.
135    ///
136    /// Values are not compared. Use [`Self::get`] or [`Self::try_get`] to
137    /// compare individual values using their own equality implementations.
138    #[must_use]
139    pub fn same_types(&self, other: &Self) -> bool {
140        self.map.keys().eq(other.map.keys())
141    }
142
143    pub fn new() -> Self {
144        Self::default()
145    }
146
147    /// Inserts a value into the container.
148    ///
149    /// If the container do not has this type present, `None` is returned.
150    /// Otherwise, the value is updated, and the old value is returned.
151    pub fn insert<T: Send + Sync + 'static>(&mut self, item: T) -> Option<Arc<T>> {
152        self.map
153            .insert(
154                TypeId::of::<T>(),
155                Dependency { type_name: std::any::type_name::<T>(), inner: Arc::new(item) },
156            )
157            .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
158    }
159
160    /// Inserts all dependencies from another container into itself.
161    pub fn insert_container(&mut self, container: Self) {
162        self.map.extend(container.map);
163    }
164
165    /// Removes a value from the container.
166    ///
167    /// If the container do not has this type present, `None` is returned.
168    /// Otherwise, the value is removed and returned.
169    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {
170        self.map
171            .remove(&TypeId::of::<T>())
172            .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
173    }
174
175    /// Retrieves the value of type `V` from this container.
176    ///
177    /// ## Panics
178    ///
179    /// If the container has no value of type `V`.
180    pub fn get<V>(&self) -> Arc<V>
181    where
182        V: Send + Sync + 'static,
183    {
184        self.map
185            .get(&TypeId::of::<V>())
186            .unwrap_or_else(|| {
187                panic!(
188                    "`{}` was requested, but not provided. Available types:\n{}",
189                    std::any::type_name::<V>(),
190                    self.available_types()
191                )
192            })
193            .clone()
194            .inner
195            .downcast::<V>()
196            .expect("Checked by `unwrap_or_else`")
197    }
198
199    /// Tries to get a value from the container; does not panic.
200    pub fn try_get<V: Send + Sync + 'static>(&self) -> Option<Arc<V>> {
201        self.map
202            .get(&TypeId::of::<V>())
203            .cloned()
204            .map(|v| v.inner.downcast().expect("Values are stored by `TypeId`"))
205    }
206
207    fn available_types(&self) -> String {
208        let mut list = String::new();
209
210        for dep in self.map.values() {
211            writeln!(list, "    `{}`", dep.type_name).unwrap();
212        }
213
214        list
215    }
216}
217
218/// Converts functions into [`CompiledFn`].
219///
220/// For a function to be convertible into [`CompiledFn`], it must be of 0-12
221/// arguments and return [`Future`].
222pub trait Injectable<Output, FnArgs>
223where
224    Output: 'static,
225{
226    fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output>;
227
228    /// Returns the set of types that this function depends on. Used only for
229    /// run-time "type checking".
230    fn input_types() -> BTreeSet<Type>;
231
232    /// Returns the map of obligations of this function.
233    ///
234    /// The map contains all types from [`Self::input_types`] as keys, each one
235    /// corresponding to the current [`Location::caller`].
236    ///
237    /// [`Location::caller`]: std::panic::Location::caller
238    #[track_caller]
239    fn obligations() -> BTreeMap<Type, &'static Location<'static>> {
240        let location = Location::caller();
241        Self::input_types().into_iter().map(|ty| (ty, location)).collect()
242    }
243}
244
245/// A function with all dependencies satisfied.
246#[cfg(not(target_arch = "wasm32"))]
247pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + Send + Sync + 'a>;
248#[cfg(target_arch = "wasm32")]
249pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + 'a>;
250
251/// Turns a synchronous function into a type that implements [`Injectable`].
252pub struct Asyncify<F>(pub F);
253
254macro_rules! impl_into_di {
255    ($($generic:ident),*) => {
256        impl<Func, Output, Fut, $($generic),*> Injectable<Output, ($($generic,)*)> for Func
257        where
258            Func: Fn($($generic),*) -> Fut + MaybeSend + MaybeSync + 'static,
259            Fut: Future<Output = Output> + MaybeSend + 'static,
260            Output: 'static,
261            $($generic: Clone + Send + Sync + 'static),*
262        {
263            #[allow(non_snake_case)]
264            #[allow(unused_variables)]
265            fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
266                Arc::new(move || {
267                    $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
268                    let fut = self( $( $generic ),* );
269                    Box::pin(fut)
270                })
271            }
272
273            fn input_types() -> BTreeSet<Type> {
274                BTreeSet::from_iter(vec![
275                    $(Type::of::<$generic>()),*
276                ])
277            }
278        }
279
280        impl<Func, Output, $($generic),*> Injectable<Output, ($($generic,)*)> for Asyncify<Func>
281        where
282            Func: Fn($($generic),*) -> Output + MaybeSend + MaybeSync + 'static,
283            Output: MaybeSend + 'static,
284            $($generic: Clone + Send + Sync + 'static),*
285        {
286            #[allow(non_snake_case)]
287            #[allow(unused_variables)]
288            fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
289                let Asyncify(this) = self;
290                Arc::new(move || {
291                    $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
292                    let out = this( $( $generic ),* );
293                    Box::pin(ready(out))
294                })
295            }
296
297            fn input_types() -> BTreeSet<Type> {
298                BTreeSet::from_iter(vec![
299                    $(Type::of::<$generic>()),*
300                ])
301            }
302        }
303    };
304}
305
306impl_into_di!();
307impl_into_di!(T1);
308impl_into_di!(T1, T2);
309impl_into_di!(T1, T2, T3);
310impl_into_di!(T1, T2, T3, T4);
311impl_into_di!(T1, T2, T3, T4, T5);
312impl_into_di!(T1, T2, T3, T4, T5, T6);
313impl_into_di!(T1, T2, T3, T4, T5, T6, T7);
314impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8);
315impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
316impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
317impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
318impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
319
320/// Constructs [`DependencyMap`] with a list of dependencies.
321///
322/// # Examples
323///
324/// ```
325/// use dptree::di::DependencyMap;
326///
327/// let map = dptree::deps![123, "abc", true];
328///
329/// let i: i32 = *map.get();
330/// let str: &str = *map.get();
331/// let b: bool = *map.get();
332///
333/// assert!(i == 123);
334/// assert!(str == "abc");
335/// assert!(b == true);
336/// ```
337#[macro_export]
338macro_rules! deps {
339    ($($dep:expr),* $(,)?) => {
340        {
341            // In the case if this macro receives zero arguments.
342            #[allow(unused_mut)]
343            let mut map = $crate::di::DependencyMap::new();
344            $(map.insert($dep);)*
345            map
346        }
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    crate::cross_test! {
355        fn get() {
356            let mut map = DependencyMap::new();
357            map.insert(42i32);
358            map.insert("hello world");
359            map.insert_container(deps![true]);
360
361            assert_eq!(map.get(), Arc::new(42i32));
362            assert_eq!(map.get(), Arc::new("hello world"));
363            assert_eq!(map.get(), Arc::new(true));
364        }
365
366        fn try_get() {
367            let mut map = DependencyMap::new();
368            assert_eq!(map.try_get::<i32>(), None);
369            map.insert(42i32);
370            assert_eq!(map.try_get(), Some(Arc::new(42i32)));
371            assert_eq!(map.try_get::<f32>(), None);
372        }
373
374        fn same_types_ignores_values() {
375            let mut map_bool1 = DependencyMap::new();
376            let mut map_bool2 = DependencyMap::new();
377            let map_empty = DependencyMap::new();
378
379            map_bool1.insert(false);
380            map_bool2.insert(true);
381
382            assert!(map_bool1.same_types(&map_bool2));
383            assert_ne!(map_bool1.get::<bool>(), map_bool2.get::<bool>());
384            assert!(!map_bool1.same_types(&map_empty));
385            assert!(!map_bool2.same_types(&deps![0_i32]));
386        }
387    }
388}