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    #[must_use]
71    pub fn new() -> Self {
72        Self { map: None }
73    }
74
75    /// Insert a type into this `Extensions`.
76    ///
77    /// If a extension of this type already existed, it will
78    /// be returned.
79    ///
80    /// # Example
81    ///
82    /// ```
83    /// # use apalis_core::task::extensions::Extensions;
84    /// let mut ext = Extensions::new();
85    /// assert!(ext.insert(5i32).is_none());
86    /// assert!(ext.insert(4u8).is_none());
87    /// assert_eq!(ext.insert(9i32), Some(5i32));
88    /// ```
89    pub fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
90        self.map
91            .get_or_insert_with(Box::default)
92            .insert(TypeId::of::<T>(), Box::new(val))
93            .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
94    }
95
96    /// Get a reference to a type previously inserted on this `Extensions`.
97    ///
98    /// # Example
99    ///
100    /// ```
101    /// # use apalis_core::task::extensions::Extensions;
102    /// let mut ext = Extensions::new();
103    /// assert!(ext.get::<i32>().is_none());
104    /// ext.insert(5i32);
105    ///
106    /// assert_eq!(ext.get::<i32>(), Some(&5i32));
107    /// ```
108    #[must_use]
109    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
110        self.map
111            .as_ref()
112            .and_then(|map| map.get(&TypeId::of::<T>()))
113            .and_then(|boxed| (**boxed).as_any().downcast_ref())
114    }
115
116    /// Get a checked reference to a type previously inserted on this `Extensions`.
117    ///
118    /// # Example
119    ///
120    /// ```
121    /// # use apalis_core::task::extensions::Extensions;
122    /// let mut ext = Extensions::new();
123    /// assert!(ext.get_checked::<i32>().is_err());
124    /// ext.insert(5i32);
125    ///
126    /// assert_eq!(ext.get_checked::<i32>(), Ok(&5i32));
127    /// ```
128    pub fn get_checked<T: Send + Sync + 'static>(&self) -> Result<&T, MissingDataError> {
129        self.get().ok_or({
130            let type_name = std::any::type_name::<T>();
131            MissingDataError::NotFound(type_name.to_owned())
132        })
133    }
134
135    /// Get a mutable reference to a type previously inserted on this `Extensions`.
136    ///
137    /// # Example
138    ///
139    /// ```
140    /// # use apalis_core::task::extensions::Extensions;
141    /// let mut ext = Extensions::new();
142    /// ext.insert(String::from("Hello"));
143    /// ext.get_mut::<String>().unwrap().push_str(" World");
144    ///
145    /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
146    /// ```
147    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
148        self.map
149            .as_mut()
150            .and_then(|map| map.get_mut(&TypeId::of::<T>()))
151            .and_then(|boxed| (**boxed).as_any_mut().downcast_mut())
152    }
153
154    /// Remove a type from this `Extensions`.
155    ///
156    /// If a extension of this type existed, it will be returned.
157    ///
158    /// # Example
159    ///
160    /// ```
161    /// # use apalis_core::task::extensions::Extensions;
162    /// let mut ext = Extensions::new();
163    /// ext.insert(5i32);
164    /// assert_eq!(ext.remove::<i32>(), Some(5i32));
165    /// assert!(ext.get::<i32>().is_none());
166    /// ```
167    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
168        self.map
169            .as_mut()
170            .and_then(|map| map.remove(&TypeId::of::<T>()))
171            .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
172    }
173
174    /// Clear the `Extensions` of all inserted extensions.
175    ///
176    /// # Example
177    ///
178    /// ```
179    /// # use apalis_core::task::extensions::Extensions;
180    /// let mut ext = Extensions::new();
181    /// ext.insert(5i32);
182    /// ext.clear();
183    ///
184    /// assert!(ext.get::<i32>().is_none());
185    /// ```
186    #[inline]
187    pub fn clear(&mut self) {
188        if let Some(ref mut map) = self.map {
189            map.clear();
190        }
191    }
192
193    /// Check whether the extension set is empty or not.
194    ///
195    /// # Example
196    ///
197    /// ```
198    /// # use apalis_core::task::extensions::Extensions;
199    /// let mut ext = Extensions::new();
200    /// assert!(ext.is_empty());
201    /// ext.insert(5i32);
202    /// assert!(!ext.is_empty());
203    /// ```
204    #[inline]
205    #[must_use]
206    pub fn is_empty(&self) -> bool {
207        self.map.as_ref().map_or(true, |map| map.is_empty())
208    }
209
210    /// Get the number of extensions available.
211    ///
212    /// # Example
213    ///
214    /// ```
215    /// # use apalis_core::task::extensions::Extensions;
216    /// let mut ext = Extensions::new();
217    /// assert_eq!(ext.len(), 0);
218    /// ext.insert(5i32);
219    /// assert_eq!(ext.len(), 1);
220    /// ```
221    #[inline]
222    #[must_use]
223    pub fn len(&self) -> usize {
224        self.map.as_ref().map_or(0, |map| map.len())
225    }
226
227    /// Extends `self` with another `Extensions`.
228    ///
229    /// If an instance of a specific type exists in both, the one in `self` is overwritten with the
230    /// one from `other`.
231    ///
232    /// # Example
233    ///
234    /// ```
235    /// # use apalis_core::task::extensions::Extensions;
236    /// let mut ext_a = Extensions::new();
237    /// ext_a.insert(8u8);
238    /// ext_a.insert(16u16);
239    ///
240    /// let mut ext_b = Extensions::new();
241    /// ext_b.insert(4u8);
242    /// ext_b.insert("hello");
243    ///
244    /// ext_a.extend(ext_b);
245    /// assert_eq!(ext_a.len(), 3);
246    /// assert_eq!(ext_a.get::<u8>(), Some(&4u8));
247    /// assert_eq!(ext_a.get::<u16>(), Some(&16u16));
248    /// assert_eq!(ext_a.get::<&'static str>().copied(), Some("hello"));
249    /// ```
250    pub fn extend(&mut self, other: Self) {
251        if let Some(other) = other.map {
252            if let Some(map) = &mut self.map {
253                map.extend(*other);
254            } else {
255                self.map = Some(other);
256            }
257        }
258    }
259}
260
261impl fmt::Debug for Extensions {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.debug_struct("Extensions").finish()
264    }
265}
266
267trait AnyClone: Any {
268    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync>;
269    fn as_any(&self) -> &dyn Any;
270    fn as_any_mut(&mut self) -> &mut dyn Any;
271    fn into_any(self: Box<Self>) -> Box<dyn Any>;
272}
273
274impl<T: Clone + Send + Sync + 'static> AnyClone for T {
275    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync> {
276        Box::new(self.clone())
277    }
278
279    fn as_any(&self) -> &dyn Any {
280        self
281    }
282
283    fn as_any_mut(&mut self) -> &mut dyn Any {
284        self
285    }
286
287    fn into_any(self: Box<Self>) -> Box<dyn Any> {
288        self
289    }
290}
291
292impl Clone for Box<dyn AnyClone + Send + Sync> {
293    fn clone(&self) -> Self {
294        (**self).clone_box()
295    }
296}
297
298impl<T: Clone + Send + Sync + 'static> MetadataExt<T> for Extensions {
299    type Error = MissingDataError;
300    fn inject(&mut self, value: T) -> Result<(), Self::Error> {
301        self.insert(value);
302        Ok(())
303    }
304    fn extract(&self) -> Result<T, Self::Error> {
305        Ok(self.get_checked::<T>()?.clone())
306    }
307}
308
309#[test]
310fn test_extensions() {
311    #[derive(Clone, Debug, PartialEq)]
312    struct MyType(i32);
313
314    let mut extensions = Extensions::new();
315
316    extensions.insert(5i32);
317    extensions.insert(MyType(10));
318
319    assert_eq!(extensions.get(), Some(&5i32));
320    assert_eq!(extensions.get_mut(), Some(&mut 5i32));
321
322    let ext2 = extensions.clone();
323
324    assert_eq!(extensions.remove::<i32>(), Some(5i32));
325    assert!(extensions.get::<i32>().is_none());
326
327    // clone still has it
328    assert_eq!(ext2.get(), Some(&5i32));
329    assert_eq!(ext2.get(), Some(&MyType(10)));
330
331    assert_eq!(extensions.get::<bool>(), None);
332    assert_eq!(extensions.get(), Some(&MyType(10)));
333}