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