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/// # Examples
41///
42/// ```
43/// use dptree::di::DependencyMap;
44/// use std::sync::Arc;
45///
46/// let mut container = DependencyMap::new();
47/// container.insert(5_i32);
48/// container.insert("abc");
49///
50/// assert_eq!(container.get(), Arc::new(5_i32));
51/// assert_eq!(container.get(), Arc::new("abc"));
52///
53/// // If a type of a value already exists within the container, it will be replaced.
54/// let old_value = container.insert(10_i32).unwrap();
55///
56/// assert_eq!(old_value, Arc::new(5_i32));
57/// assert_eq!(container.get(), Arc::new(10_i32));
58/// ```
59///
60/// When a value is not found within the container, it will panic:
61///
62/// ```should_panic
63/// use dptree::di::DependencyMap;
64/// use std::sync::Arc;
65///
66/// let mut container = DependencyMap::new();
67/// container.insert(10i32);
68/// container.insert(true);
69/// container.insert("static str");
70///
71/// // `alloc::string::String` was requested, but not provided. Available types:
72/// //     `i32`
73/// //     `&str`
74/// //     `bool`
75/// let string: Arc<String> = container.get();
76/// ```
77#[derive(Default, Clone, Debug)]
78pub struct DependencyMap {
79    pub(crate) map: BTreeMap<TypeId, Dependency>,
80}
81
82#[derive(Clone)]
83pub(crate) struct Dependency {
84    pub(crate) type_name: &'static str,
85    inner: Arc<dyn Any + Send + Sync>,
86}
87
88impl Debug for Dependency {
89    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("Dependency").field("type_name", &self.type_name).finish_non_exhaustive()
91    }
92}
93
94impl PartialEq for DependencyMap {
95    fn eq(&self, other: &Self) -> bool {
96        let keys1 = self.map.keys();
97        let keys2 = other.map.keys();
98        keys1.len() == keys2.len() && keys1.zip(keys2).all(|(k1, k2)| k1 == k2)
99    }
100}
101
102impl DependencyMap {
103    pub fn new() -> Self {
104        Self::default()
105    }
106
107    /// Inserts a value into the container.
108    ///
109    /// If the container do not has this type present, `None` is returned.
110    /// Otherwise, the value is updated, and the old value is returned.
111    pub fn insert<T: Send + Sync + 'static>(&mut self, item: T) -> Option<Arc<T>> {
112        self.map
113            .insert(
114                TypeId::of::<T>(),
115                Dependency { type_name: std::any::type_name::<T>(), inner: Arc::new(item) },
116            )
117            .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
118    }
119
120    /// Inserts all dependencies from another container into itself.
121    pub fn insert_container(&mut self, container: Self) {
122        self.map.extend(container.map);
123    }
124
125    /// Removes a value from the container.
126    ///
127    /// If the container do not has this type present, `None` is returned.
128    /// Otherwise, the value is removed and returned.
129    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<Arc<T>> {
130        self.map
131            .remove(&TypeId::of::<T>())
132            .map(|dep| dep.inner.downcast().expect("Values are stored by `TypeId`"))
133    }
134
135    /// Retrieves the value of type `V` from this container.
136    ///
137    /// ## Panics
138    ///
139    /// If the container has no value of type `V`.
140    pub fn get<V>(&self) -> Arc<V>
141    where
142        V: Send + Sync + 'static,
143    {
144        self.map
145            .get(&TypeId::of::<V>())
146            .unwrap_or_else(|| {
147                panic!(
148                    "`{}` was requested, but not provided. Available types:\n{}",
149                    std::any::type_name::<V>(),
150                    self.available_types()
151                )
152            })
153            .clone()
154            .inner
155            .downcast::<V>()
156            .expect("Checked by `unwrap_or_else`")
157    }
158
159    /// Tries to get a value from the container; does not panic.
160    pub fn try_get<V: Send + Sync + 'static>(&self) -> Option<Arc<V>> {
161        self.map
162            .get(&TypeId::of::<V>())
163            .cloned()
164            .map(|v| v.inner.downcast().expect("Values are stored by `TypeId`"))
165    }
166
167    fn available_types(&self) -> String {
168        let mut list = String::new();
169
170        for dep in self.map.values() {
171            writeln!(list, "    `{}`", dep.type_name).unwrap();
172        }
173
174        list
175    }
176}
177
178/// Converts functions into [`CompiledFn`].
179///
180/// For a function to be convertible into [`CompiledFn`], it must be of 0-12
181/// arguments and return [`Future`].
182pub trait Injectable<Output, FnArgs>
183where
184    Output: 'static,
185{
186    fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output>;
187
188    /// Returns the set of types that this function depends on. Used only for
189    /// run-time "type checking".
190    fn input_types() -> BTreeSet<Type>;
191
192    /// Returns the map of obligations of this function.
193    ///
194    /// The map contains all types from [`Self::input_types`] as keys, each one
195    /// corresponding to the current [`Location::caller`].
196    ///
197    /// [`Location::caller`]: std::panic::Location::caller
198    #[track_caller]
199    fn obligations() -> BTreeMap<Type, &'static Location<'static>> {
200        let location = Location::caller();
201        Self::input_types().into_iter().map(|ty| (ty, location)).collect()
202    }
203}
204
205/// A function with all dependencies satisfied.
206#[cfg(not(target_arch = "wasm32"))]
207pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + Send + Sync + 'a>;
208#[cfg(target_arch = "wasm32")]
209pub type CompiledFn<'a, Output> = Arc<dyn Fn() -> BoxFuture<'a, Output> + 'a>;
210
211/// Turns a synchronous function into a type that implements [`Injectable`].
212pub struct Asyncify<F>(pub F);
213
214macro_rules! impl_into_di {
215    ($($generic:ident),*) => {
216        impl<Func, Output, Fut, $($generic),*> Injectable<Output, ($($generic,)*)> for Func
217        where
218            Func: Fn($($generic),*) -> Fut + MaybeSend + MaybeSync + 'static,
219            Fut: Future<Output = Output> + MaybeSend + 'static,
220            Output: 'static,
221            $($generic: Clone + Send + Sync + 'static),*
222        {
223            #[allow(non_snake_case)]
224            #[allow(unused_variables)]
225            fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
226                Arc::new(move || {
227                    $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
228                    let fut = self( $( $generic ),* );
229                    Box::pin(fut)
230                })
231            }
232
233            fn input_types() -> BTreeSet<Type> {
234                BTreeSet::from_iter(vec![
235                    $(Type::of::<$generic>()),*
236                ])
237            }
238        }
239
240        impl<Func, Output, $($generic),*> Injectable<Output, ($($generic,)*)> for Asyncify<Func>
241        where
242            Func: Fn($($generic),*) -> Output + MaybeSend + MaybeSync + 'static,
243            Output: MaybeSend + 'static,
244            $($generic: Clone + Send + Sync + 'static),*
245        {
246            #[allow(non_snake_case)]
247            #[allow(unused_variables)]
248            fn inject<'a>(&'a self, container: &'a DependencyMap) -> CompiledFn<'a, Output> {
249                let Asyncify(this) = self;
250                Arc::new(move || {
251                    $(let $generic = std::borrow::Borrow::<$generic>::borrow(&container.get()).clone();)*
252                    let out = this( $( $generic ),* );
253                    Box::pin(ready(out))
254                })
255            }
256
257            fn input_types() -> BTreeSet<Type> {
258                BTreeSet::from_iter(vec![
259                    $(Type::of::<$generic>()),*
260                ])
261            }
262        }
263    };
264}
265
266impl_into_di!();
267impl_into_di!(T1);
268impl_into_di!(T1, T2);
269impl_into_di!(T1, T2, T3);
270impl_into_di!(T1, T2, T3, T4);
271impl_into_di!(T1, T2, T3, T4, T5);
272impl_into_di!(T1, T2, T3, T4, T5, T6);
273impl_into_di!(T1, T2, T3, T4, T5, T6, T7);
274impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8);
275impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
276impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
277impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
278impl_into_di!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
279
280/// Constructs [`DependencyMap`] with a list of dependencies.
281///
282/// # Examples
283///
284/// ```
285/// use dptree::di::DependencyMap;
286///
287/// let map = dptree::deps![123, "abc", true];
288///
289/// let i: i32 = *map.get();
290/// let str: &str = *map.get();
291/// let b: bool = *map.get();
292///
293/// assert!(i == 123);
294/// assert!(str == "abc");
295/// assert!(b == true);
296/// ```
297#[macro_export]
298macro_rules! deps {
299    ($($dep:expr),* $(,)?) => {
300        {
301            // In the case if this macro receives zero arguments.
302            #[allow(unused_mut)]
303            let mut map = $crate::di::DependencyMap::new();
304            $(map.insert($dep);)*
305            map
306        }
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    crate::cross_test! {
315        fn get() {
316            let mut map = DependencyMap::new();
317            map.insert(42i32);
318            map.insert("hello world");
319            map.insert_container(deps![true]);
320
321            assert_eq!(map.get(), Arc::new(42i32));
322            assert_eq!(map.get(), Arc::new("hello world"));
323            assert_eq!(map.get(), Arc::new(true));
324        }
325
326        fn try_get() {
327            let mut map = DependencyMap::new();
328            assert_eq!(map.try_get::<i32>(), None);
329            map.insert(42i32);
330            assert_eq!(map.try_get(), Some(Arc::new(42i32)));
331            assert_eq!(map.try_get::<f32>(), None);
332        }
333
334        fn same_keys() {
335            let mut map_bool1 = DependencyMap::new();
336            let mut map_bool2 = DependencyMap::new();
337            let map_empty = DependencyMap::new();
338
339            map_bool1.insert(false);
340            map_bool2.insert(true);
341
342            assert_eq!(map_bool1, map_bool2);
343            assert_ne!(map_bool1, map_empty);
344            assert_ne!(map_bool2, map_empty);
345        }
346    }
347}