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;
30use crate::task::metadata::MetadataExt;
31
32type AnyMap = HashMap<TypeId, Box<dyn AnyClone + Send + Sync>, BuildHasherDefault<IdHasher>>;
33
34// With TypeIds as keys, there's no need to hash them. They are already hashes
35// themselves, coming from the compiler. The IdHasher just holds the u64 of
36// the TypeId, and then returns it, instead of doing any bit fiddling.
37#[derive(Default)]
38struct IdHasher(u64);
39
40impl Hasher for IdHasher {
41    fn write(&mut self, _: &[u8]) {
42        unreachable!("TypeId calls write_u64");
43    }
44
45    #[inline]
46    fn write_u64(&mut self, id: u64) {
47        self.0 = id;
48    }
49
50    #[inline]
51    fn finish(&self) -> u64 {
52        self.0
53    }
54}
55
56/// A type map of protocol extensions.
57///
58/// `Extensions` can be used by `Request` and `Response` to store
59/// extra data derived from the underlying protocol.
60#[derive(Clone, Default)]
61pub struct Extensions {
62    // If extensions are never used, no need to carry around an empty HashMap.
63    // That's 3 words. Instead, this is only 1 word.
64    map: Option<Box<AnyMap>>,
65}
66
67impl Extensions {
68    /// Create an empty `Extensions`.
69    #[inline]
70    pub fn new() -> Extensions {
71        Extensions { map: None }
72    }
73
74    /// Insert a type into this `Extensions`.
75    ///
76    /// If a 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    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
108        self.map
109            .as_ref()
110            .and_then(|map| map.get(&TypeId::of::<T>()))
111            .and_then(|boxed| (**boxed).as_any().downcast_ref())
112    }
113
114    /// Get a checked reference to a type previously inserted on this `Extensions`.
115    ///
116    /// # Example
117    ///
118    /// ```
119    /// # use apalis_core::task::extensions::Extensions;
120    /// let mut ext = Extensions::new();
121    /// assert!(ext.get_checked::<i32>().is_err());
122    /// ext.insert(5i32);
123    ///
124    /// assert_eq!(ext.get_checked::<i32>(), Ok(&5i32));
125    /// ```
126    pub fn get_checked<T: Send + Sync + 'static>(&self) -> Result<&T, MissingDataError> {
127        self.get().ok_or({
128            let type_name = std::any::type_name::<T>();
129            MissingDataError::NotFound(type_name.to_owned())
130        })
131    }
132
133    /// Get a mutable reference to a type previously inserted on this `Extensions`.
134    ///
135    /// # Example
136    ///
137    /// ```
138    /// # use apalis_core::task::extensions::Extensions;
139    /// let mut ext = Extensions::new();
140    /// ext.insert(String::from("Hello"));
141    /// ext.get_mut::<String>().unwrap().push_str(" World");
142    ///
143    /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
144    /// ```
145    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
146        self.map
147            .as_mut()
148            .and_then(|map| map.get_mut(&TypeId::of::<T>()))
149            .and_then(|boxed| (**boxed).as_any_mut().downcast_mut())
150    }
151
152    /// Remove a type from this `Extensions`.
153    ///
154    /// If a extension of this type existed, it will be returned.
155    ///
156    /// # Example
157    ///
158    /// ```
159    /// # use apalis_core::task::extensions::Extensions;
160    /// let mut ext = Extensions::new();
161    /// ext.insert(5i32);
162    /// assert_eq!(ext.remove::<i32>(), Some(5i32));
163    /// assert!(ext.get::<i32>().is_none());
164    /// ```
165    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
166        self.map
167            .as_mut()
168            .and_then(|map| map.remove(&TypeId::of::<T>()))
169            .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
170    }
171
172    /// Clear the `Extensions` of all inserted extensions.
173    ///
174    /// # Example
175    ///
176    /// ```
177    /// # use apalis_core::task::extensions::Extensions;
178    /// let mut ext = Extensions::new();
179    /// ext.insert(5i32);
180    /// ext.clear();
181    ///
182    /// assert!(ext.get::<i32>().is_none());
183    /// ```
184    #[inline]
185    pub fn clear(&mut self) {
186        if let Some(ref mut map) = self.map {
187            map.clear();
188        }
189    }
190
191    /// Check whether the extension set is empty or not.
192    ///
193    /// # Example
194    ///
195    /// ```
196    /// # use apalis_core::task::extensions::Extensions;
197    /// let mut ext = Extensions::new();
198    /// assert!(ext.is_empty());
199    /// ext.insert(5i32);
200    /// assert!(!ext.is_empty());
201    /// ```
202    #[inline]
203    pub fn is_empty(&self) -> bool {
204        self.map.as_ref().map_or(true, |map| map.is_empty())
205    }
206
207    /// Get the number of extensions available.
208    ///
209    /// # Example
210    ///
211    /// ```
212    /// # use apalis_core::task::extensions::Extensions;
213    /// let mut ext = Extensions::new();
214    /// assert_eq!(ext.len(), 0);
215    /// ext.insert(5i32);
216    /// assert_eq!(ext.len(), 1);
217    /// ```
218    #[inline]
219    pub fn len(&self) -> usize {
220        self.map.as_ref().map_or(0, |map| map.len())
221    }
222
223    /// Extends `self` with another `Extensions`.
224    ///
225    /// If an instance of a specific type exists in both, the one in `self` is overwritten with the
226    /// one from `other`.
227    ///
228    /// # Example
229    ///
230    /// ```
231    /// # use apalis_core::task::extensions::Extensions;
232    /// let mut ext_a = Extensions::new();
233    /// ext_a.insert(8u8);
234    /// ext_a.insert(16u16);
235    ///
236    /// let mut ext_b = Extensions::new();
237    /// ext_b.insert(4u8);
238    /// ext_b.insert("hello");
239    ///
240    /// ext_a.extend(ext_b);
241    /// assert_eq!(ext_a.len(), 3);
242    /// assert_eq!(ext_a.get::<u8>(), Some(&4u8));
243    /// assert_eq!(ext_a.get::<u16>(), Some(&16u16));
244    /// assert_eq!(ext_a.get::<&'static str>().copied(), Some("hello"));
245    /// ```
246    pub fn extend(&mut self, other: Self) {
247        if let Some(other) = other.map {
248            if let Some(map) = &mut self.map {
249                map.extend(*other);
250            } else {
251                self.map = Some(other);
252            }
253        }
254    }
255}
256
257impl fmt::Debug for Extensions {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.debug_struct("Extensions").finish()
260    }
261}
262
263trait AnyClone: Any {
264    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync>;
265    fn as_any(&self) -> &dyn Any;
266    fn as_any_mut(&mut self) -> &mut dyn Any;
267    fn into_any(self: Box<Self>) -> Box<dyn Any>;
268}
269
270impl<T: Clone + Send + Sync + 'static> AnyClone for T {
271    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync> {
272        Box::new(self.clone())
273    }
274
275    fn as_any(&self) -> &dyn Any {
276        self
277    }
278
279    fn as_any_mut(&mut self) -> &mut dyn Any {
280        self
281    }
282
283    fn into_any(self: Box<Self>) -> Box<dyn Any> {
284        self
285    }
286}
287
288impl Clone for Box<dyn AnyClone + Send + Sync> {
289    fn clone(&self) -> Self {
290        (**self).clone_box()
291    }
292}
293
294impl<T: Clone + Send + Sync + 'static> MetadataExt<T> for Extensions {
295    type Error = MissingDataError;
296    fn inject(&mut self, value: T) -> Result<(), Self::Error> {
297        self.insert(value);
298        Ok(())
299    }
300    fn extract(&self) -> Result<T, Self::Error> {
301        Ok(self.get_checked::<T>()?.clone())
302    }
303}
304
305#[test]
306fn test_extensions() {
307    #[derive(Clone, Debug, PartialEq)]
308    struct MyType(i32);
309
310    let mut extensions = Extensions::new();
311
312    extensions.insert(5i32);
313    extensions.insert(MyType(10));
314
315    assert_eq!(extensions.get(), Some(&5i32));
316    assert_eq!(extensions.get_mut(), Some(&mut 5i32));
317
318    let ext2 = extensions.clone();
319
320    assert_eq!(extensions.remove::<i32>(), Some(5i32));
321    assert!(extensions.get::<i32>().is_none());
322
323    // clone still has it
324    assert_eq!(ext2.get(), Some(&5i32));
325    assert_eq!(ext2.get(), Some(&MyType(10)));
326
327    assert_eq!(extensions.get::<bool>(), None);
328    assert_eq!(extensions.get(), Some(&MyType(10)));
329}