Skip to main content

apalis_core/task/
extensions.rs

1//! A type-safe container for storing protocol extensions.
2//!
3//! The `Extensions` struct provides a type map for storing arbitrary data associated with a request or response.
4//! Each extension is stored by its type, allowing for safe retrieval and mutation without explicit casting.
5//!
6//! # Features
7//! - Insert, get, mutate, and remove extensions by type.
8//! - Efficient storage: avoids allocating a map unless needed.
9//! - Type-safe API: prevents type mismatches at runtime.
10//! - Cloneable: supports cloning the entire extensions set.
11//! - Extensible: merge extensions from other instances.
12//!
13//! # Example
14//! ```
15//! use apalis_core::task::extensions::Extensions;
16//!
17//! let mut ext = Extensions::new();
18//! ext.insert(42u32);
19//! assert_eq!(ext.get::<u32>(), Some(&42u32));
20//! ext.remove::<u32>();
21//! assert!(ext.get::<u32>().is_none());
22//! ```
23//! Extracted from the [http](https://github.com/hyperium/http/blob/master/src/extensions.rs) crate with modifications to fit our use case
24use std::any::{Any, TypeId};
25use std::collections::HashMap;
26use std::fmt;
27use std::hash::{BuildHasherDefault, Hasher};
28
29use crate::task::data::MissingDataError;
30
31type AnyMap = HashMap<TypeId, Box<dyn AnyClone + Send + Sync>, BuildHasherDefault<IdHasher>>;
32
33// With TypeIds as keys, there's no need to hash them. They are already hashes
34// themselves, coming from the compiler. The IdHasher just holds the u64 of
35// the TypeId, and then returns it, instead of doing any bit fiddling.
36#[derive(Default)]
37struct IdHasher(u64);
38
39impl Hasher for IdHasher {
40    fn write(&mut self, _: &[u8]) {
41        unreachable!("TypeId calls write_u64");
42    }
43
44    #[inline]
45    fn write_u64(&mut self, id: u64) {
46        self.0 = id;
47    }
48
49    #[inline]
50    fn finish(&self) -> u64 {
51        self.0
52    }
53}
54
55/// A type map of typed task extensions.
56///
57/// `Extensions` can be used by `Task` to store
58/// extra data derived from the underlying execution.
59#[derive(Clone, Default)]
60pub struct Extensions {
61    // If extensions are never used, no need to carry around an empty HashMap.
62    // That's 3 words. Instead, this is only 1 word.
63    map: Option<Box<AnyMap>>,
64}
65
66impl Extensions {
67    /// Create an empty `Extensions`.
68    #[inline]
69    #[must_use]
70    pub fn new() -> Self {
71        Self { map: None }
72    }
73
74    /// Insert a type into this `Extensions`.
75    ///
76    /// If an extension of this type already existed, it will
77    /// be returned.
78    ///
79    /// # Example
80    ///
81    /// ```
82    /// # use apalis_core::task::extensions::Extensions;
83    /// let mut ext = Extensions::new();
84    /// assert!(ext.insert(5i32).is_none());
85    /// assert!(ext.insert(4u8).is_none());
86    /// assert_eq!(ext.insert(9i32), Some(5i32));
87    /// ```
88    pub fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
89        self.map
90            .get_or_insert_with(Box::default)
91            .insert(TypeId::of::<T>(), Box::new(val))
92            .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
93    }
94
95    /// Get a reference to a type previously inserted on this `Extensions`.
96    ///
97    /// # Example
98    ///
99    /// ```
100    /// # use apalis_core::task::extensions::Extensions;
101    /// let mut ext = Extensions::new();
102    /// assert!(ext.get::<i32>().is_none());
103    /// ext.insert(5i32);
104    ///
105    /// assert_eq!(ext.get::<i32>(), Some(&5i32));
106    /// ```
107    #[must_use]
108    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
109        self.map
110            .as_ref()
111            .and_then(|map| map.get(&TypeId::of::<T>()))
112            .and_then(|boxed| (**boxed).as_any().downcast_ref())
113    }
114
115    /// Get a checked reference to a type previously inserted on this `Extensions`.
116    ///
117    /// # Example
118    ///
119    /// ```
120    /// # use apalis_core::task::extensions::Extensions;
121    /// let mut ext = Extensions::new();
122    /// assert!(ext.get_checked::<i32>().is_err());
123    /// ext.insert(5i32);
124    ///
125    /// assert_eq!(ext.get_checked::<i32>(), Ok(&5i32));
126    /// ```
127    pub fn get_checked<T: Send + Sync + 'static>(&self) -> Result<&T, MissingDataError> {
128        self.get().ok_or({
129            let type_name = std::any::type_name::<T>();
130            MissingDataError::NotFound(type_name.to_owned())
131        })
132    }
133
134    /// Get a mutable reference to a type previously inserted on this `Extensions`.
135    ///
136    /// # Example
137    ///
138    /// ```
139    /// # use apalis_core::task::extensions::Extensions;
140    /// let mut ext = Extensions::new();
141    /// ext.insert(String::from("Hello"));
142    /// ext.get_mut::<String>().unwrap().push_str(" World");
143    ///
144    /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
145    /// ```
146    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
147        self.map
148            .as_mut()
149            .and_then(|map| map.get_mut(&TypeId::of::<T>()))
150            .and_then(|boxed| (**boxed).as_any_mut().downcast_mut())
151    }
152
153    /// Remove a type from this `Extensions`.
154    ///
155    /// If a extension of this type existed, it will be returned.
156    ///
157    /// # Example
158    ///
159    /// ```
160    /// # use apalis_core::task::extensions::Extensions;
161    /// let mut ext = Extensions::new();
162    /// ext.insert(5i32);
163    /// assert_eq!(ext.remove::<i32>(), Some(5i32));
164    /// assert!(ext.get::<i32>().is_none());
165    /// ```
166    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
167        self.map
168            .as_mut()
169            .and_then(|map| map.remove(&TypeId::of::<T>()))
170            .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
171    }
172
173    /// Clear the `Extensions` of all inserted extensions.
174    ///
175    /// # Example
176    ///
177    /// ```
178    /// # use apalis_core::task::extensions::Extensions;
179    /// let mut ext = Extensions::new();
180    /// ext.insert(5i32);
181    /// ext.clear();
182    ///
183    /// assert!(ext.get::<i32>().is_none());
184    /// ```
185    #[inline]
186    pub fn clear(&mut self) {
187        if let Some(ref mut map) = self.map {
188            map.clear();
189        }
190    }
191
192    /// Check whether the extension set is empty or not.
193    ///
194    /// # Example
195    ///
196    /// ```
197    /// # use apalis_core::task::extensions::Extensions;
198    /// let mut ext = Extensions::new();
199    /// assert!(ext.is_empty());
200    /// ext.insert(5i32);
201    /// assert!(!ext.is_empty());
202    /// ```
203    #[inline]
204    #[must_use]
205    pub fn is_empty(&self) -> bool {
206        self.map.as_ref().is_none_or(|map| map.is_empty())
207    }
208
209    /// Get the number of extensions available.
210    ///
211    /// # Example
212    ///
213    /// ```
214    /// # use apalis_core::task::extensions::Extensions;
215    /// let mut ext = Extensions::new();
216    /// assert_eq!(ext.len(), 0);
217    /// ext.insert(5i32);
218    /// assert_eq!(ext.len(), 1);
219    /// ```
220    #[inline]
221    #[must_use]
222    pub fn len(&self) -> usize {
223        self.map.as_ref().map_or(0, |map| map.len())
224    }
225
226    /// Extends `self` with another `Extensions`.
227    ///
228    /// If an instance of a specific type exists in both, the one in `self` is overwritten with the
229    /// one from `other`.
230    ///
231    /// # Example
232    ///
233    /// ```
234    /// # use apalis_core::task::extensions::Extensions;
235    /// let mut ext_a = Extensions::new();
236    /// ext_a.insert(8u8);
237    /// ext_a.insert(16u16);
238    ///
239    /// let mut ext_b = Extensions::new();
240    /// ext_b.insert(4u8);
241    /// ext_b.insert("hello");
242    ///
243    /// ext_a.extend(ext_b);
244    /// assert_eq!(ext_a.len(), 3);
245    /// assert_eq!(ext_a.get::<u8>(), Some(&4u8));
246    /// assert_eq!(ext_a.get::<u16>(), Some(&16u16));
247    /// assert_eq!(ext_a.get::<&'static str>().copied(), Some("hello"));
248    /// ```
249    pub fn extend(&mut self, other: Self) {
250        if let Some(other) = other.map {
251            if let Some(map) = &mut self.map {
252                map.extend(*other);
253            } else {
254                self.map = Some(other);
255            }
256        }
257    }
258
259    /// Get a mutable reference to the value of type `T`,
260    /// inserting `value` if it does not already exist.
261    ///
262    /// # Example
263    ///
264    /// ```
265    /// # use apalis_core::task::extensions::Extensions;
266    /// let mut ext = Extensions::new();
267    ///
268    /// let value = ext.get_or_insert(String::from("Hello"));
269    /// value.push_str(" World");
270    ///
271    /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
272    /// ```
273    pub fn get_or_insert<T>(&mut self, value: T) -> &mut T
274    where
275        T: Clone + Send + Sync + 'static,
276    {
277        self.get_or_insert_with(|| value)
278    }
279
280    /// Get a mutable reference to the value of type `T`,
281    /// inserting the result of `f` if it does not already exist.
282    ///
283    /// # Example
284    ///
285    /// ```
286    /// # use apalis_core::task::extensions::Extensions;
287    /// let mut ext = Extensions::new();
288    ///
289    /// let value = ext.get_or_insert_with(|| String::from("Hello"));
290    /// value.push_str(" World");
291    ///
292    /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
293    /// ```
294    pub fn get_or_insert_with<T, F>(&mut self, f: F) -> &mut T
295    where
296        T: Clone + Send + Sync + 'static,
297        F: FnOnce() -> T,
298    {
299        if self.get::<T>().is_none() {
300            self.insert(f());
301        }
302
303        self.get_mut::<T>().expect("value was just inserted")
304    }
305}
306
307impl fmt::Debug for Extensions {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        f.debug_struct("Extensions").finish()
310    }
311}
312
313trait AnyClone: Any {
314    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync>;
315    fn as_any(&self) -> &dyn Any;
316    fn as_any_mut(&mut self) -> &mut dyn Any;
317    fn into_any(self: Box<Self>) -> Box<dyn Any>;
318}
319
320impl<T: Clone + Send + Sync + 'static> AnyClone for T {
321    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync> {
322        Box::new(self.clone())
323    }
324
325    fn as_any(&self) -> &dyn Any {
326        self
327    }
328
329    fn as_any_mut(&mut self) -> &mut dyn Any {
330        self
331    }
332
333    fn into_any(self: Box<Self>) -> Box<dyn Any> {
334        self
335    }
336}
337
338impl Clone for Box<dyn AnyClone + Send + Sync> {
339    fn clone(&self) -> Self {
340        (**self).clone_box()
341    }
342}
343
344#[test]
345fn test_extensions() {
346    #[derive(Clone, Debug, PartialEq)]
347    struct MyType(i32);
348
349    let mut extensions = Extensions::new();
350
351    extensions.insert(5i32);
352    extensions.insert(MyType(10));
353
354    assert_eq!(extensions.get(), Some(&5i32));
355    assert_eq!(extensions.get_mut(), Some(&mut 5i32));
356
357    let ext2 = extensions.clone();
358
359    assert_eq!(extensions.remove::<i32>(), Some(5i32));
360    assert!(extensions.get::<i32>().is_none());
361
362    // clone still has it
363    assert_eq!(ext2.get(), Some(&5i32));
364    assert_eq!(ext2.get(), Some(&MyType(10)));
365
366    assert_eq!(extensions.get::<bool>(), None);
367    assert_eq!(extensions.get(), Some(&MyType(10)));
368}