Skip to main content

hyperlane_core/context/
impl.rs

1use super::*;
2
3/// Implementation of `Default` trait for `Context`.
4impl Default for Context {
5    /// Creates a default `Context` instance.
6    ///
7    /// # Returns
8    ///
9    /// - `Context` - A new context with default values and a static default server.
10    #[inline(always)]
11    fn default() -> Self {
12        Self {
13            request: Request::default(),
14            response: Response::default(),
15            route_params: RouteParams::default(),
16            attributes: ThreadSafeAttributeStore::default(),
17        }
18    }
19}
20
21/// Implementation of `PartialEq` trait for `Context`.
22impl PartialEq for Context {
23    /// Compares two `Context` instances for equality.
24    ///
25    /// # Arguments
26    ///
27    /// - `&Self` - The first `Context` instance.
28    /// - `&Self` - The second `Context` instance.
29    ///
30    /// # Returns
31    ///
32    /// - `bool` - True if the instances are equal, otherwise false.
33    #[inline(always)]
34    fn eq(&self, other: &Self) -> bool {
35        self.get_request() == other.get_request()
36            && self.get_response() == other.get_response()
37            && self.get_route_params() == other.get_route_params()
38            && self.get_attributes().len() == other.get_attributes().len()
39    }
40}
41
42/// Implementation of `Eq` trait for `Context`.
43impl Eq for Context {}
44
45/// Implementation of `From` trait for converting `usize` address into `&Context`.
46impl From<usize> for &'static Context {
47    /// Converts a memory address into a reference to `Context`.
48    ///
49    /// # Arguments
50    ///
51    /// - `usize` - The memory address of the `Context` instance.
52    ///
53    /// # Returns
54    ///
55    /// - `&'static Context` - A reference to the `Context` at the given address.
56    ///
57    /// # Safety
58    ///
59    /// - The address is guaranteed to be a valid `Context` instance
60    ///   that was previously converted from a reference and is managed by the runtime.
61    #[inline(always)]
62    fn from(address: usize) -> &'static Context {
63        unsafe { &*(address as *const Context) }
64    }
65}
66
67/// Implementation of `From` trait for converting `usize` address into `&mut Context`.
68impl<'a> From<usize> for &'a mut Context {
69    /// Converts a memory address into a mutable reference to `Context`.
70    ///
71    /// # Arguments
72    ///
73    /// - `usize` - The memory address of the `Context` instance.
74    ///
75    /// # Returns
76    ///
77    /// - `&'a mut Context` - A mutable reference to the `Context` at the given address.
78    ///
79    /// # Safety
80    ///
81    /// - The address is guaranteed to be a valid `Context` instance
82    ///   that was previously converted from a reference and is managed by the runtime.
83    #[inline(always)]
84    fn from(address: usize) -> &'a mut Context {
85        unsafe { &mut *(address as *mut Context) }
86    }
87}
88
89/// Implementation of `From` trait for converting `&Context` into `usize` address.
90impl From<&Context> for usize {
91    /// Converts a reference to `Context` into its memory address.
92    ///
93    /// # Arguments
94    ///
95    /// - `&Context` - The reference to the `Context` instance.
96    ///
97    /// # Returns
98    ///
99    /// - `usize` - The memory address of the `Context` instance.
100    #[inline(always)]
101    fn from(ctx: &Context) -> Self {
102        ctx as *const Context as usize
103    }
104}
105
106/// Implementation of `From` trait for converting `&mut Context` into `usize` address.
107impl From<&mut Context> for usize {
108    /// Converts a mutable reference to `Context` into its memory address.
109    ///
110    /// # Arguments
111    ///
112    /// - `&mut Context` - The mutable reference to the `Context` instance.
113    ///
114    /// # Returns
115    ///
116    /// - `usize` - The memory address of the `Context` instance.
117    #[inline(always)]
118    fn from(ctx: &mut Context) -> Self {
119        ctx as *mut Context as usize
120    }
121}
122
123/// Implementation of `AsRef` trait for `Context`.
124impl AsRef<Context> for Context {
125    /// Converts `&Context` to `&Context` via memory address conversion.
126    ///
127    /// # Returns
128    ///
129    /// - `&Self` - A reference to the `Context` instance.
130    #[inline(always)]
131    fn as_ref(&self) -> &Self {
132        let address: usize = self.into();
133        address.into()
134    }
135}
136
137/// Implementation of `AsMut` trait for `Context`.
138impl AsMut<Context> for Context {
139    /// Converts `&mut Context` to `&mut Context` via memory address conversion.
140    ///
141    /// # Returns
142    ///
143    /// - `&mut Self` - A mutable reference to the `Context` instance.
144    #[inline(always)]
145    fn as_mut(&mut self) -> &mut Self {
146        let address: usize = self.into();
147        address.into()
148    }
149}
150
151/// Implementation of `Lifetime` trait for `Context`.
152impl Lifetime for Context {
153    /// Converts a reference to the context into a `'static` reference.
154    ///
155    /// # Returns
156    ///
157    /// - `&'static Self` - A reference to the context with a `'static` lifetime.
158    ///
159    /// # Safety
160    ///
161    /// - The address is guaranteed to be a valid `Self` instance
162    ///   that was previously converted from a reference and is managed by the runtime.
163    #[inline(always)]
164    unsafe fn leak(&self) -> &'static Self {
165        let address: usize = self.into();
166        address.into()
167    }
168
169    /// Converts a reference to the context into a `'static` mutable reference.
170    ///
171    /// # Returns
172    ///
173    /// - `&'static mut Self` - A mutable reference to the context with a `'static` lifetime.
174    ///
175    /// # Safety
176    ///
177    /// - The address is guaranteed to be a valid `Self` instance
178    ///   that was previously converted from a reference and is managed by the runtime.
179    #[inline(always)]
180    unsafe fn leak_mut(&self) -> &'static mut Self {
181        let address: usize = self.into();
182        address.into()
183    }
184}
185
186/// Implementation of methods for `Context` structure.
187impl Context {
188    /// Returns the stable map key for the original request target.
189    ///
190    /// # Returns
191    ///
192    /// - `&'static str` - The attribute key used by the public attribute API.
193    fn request_target_key() -> &'static str {
194        static KEY: OnceLock<String> = OnceLock::new();
195        KEY.get_or_init(|| Attribute::External(REQUEST_TARGET_ATTRIBUTE.to_owned()).to_string())
196    }
197
198    /// Clears request-local attributes while retaining the target's buffers.
199    ///
200    /// # Returns
201    ///
202    /// - `&mut Self` - The context ready for the next request.
203    pub(crate) fn reset_request_attributes(&mut self) -> &mut Self {
204        self.get_mut_attributes()
205            .retain(|key: &String, _: &mut ArcAnySendSync| key == Self::request_target_key());
206        self
207    }
208
209    /// Clears all route parameters while retaining the map's allocated capacity.
210    ///
211    /// Used between keep-alive requests on the same connection to avoid
212    /// reallocating the parameter map for every request.
213    ///
214    /// # Returns
215    ///
216    /// - `&mut Self` - A mutable reference to self for chaining.
217    #[inline(always)]
218    pub(crate) fn clear_route_params(&mut self) -> &mut Self {
219        self.get_mut_route_params().clear();
220        self
221    }
222
223    /// Attempts to retrieve a specific route parameter by its name.
224    ///
225    /// # Arguments
226    ///
227    /// - `T` - The name of the route parameter to retrieve.
228    ///
229    /// # Returns
230    ///
231    /// - `Option<String>` - The value of the route parameter if it exists.
232    #[inline(always)]
233    pub fn try_get_route_param<T>(&self, name: T) -> Option<String>
234    where
235        T: AsRef<str>,
236    {
237        self.get_route_params().get(name.as_ref()).cloned()
238    }
239
240    /// Retrieves a specific route parameter by its name, panicking if not found.
241    ///
242    /// # Arguments
243    ///
244    /// - `T` - The name of the route parameter to retrieve.
245    ///
246    /// # Returns
247    ///
248    /// - `String` - The value of the route parameter if it exists.
249    ///
250    /// # Panics
251    ///
252    /// - If the route parameter is not found.
253    #[inline(always)]
254    pub fn get_route_param<T>(&self, name: T) -> String
255    where
256        T: AsRef<str>,
257    {
258        self.try_get_route_param(name).unwrap()
259    }
260
261    /// Returns the original wire request target before routing or query-map conversion.
262    ///
263    /// # Returns
264    ///
265    /// - `Option<String>` - The unchanged path and query, or none for a manually constructed context.
266    pub fn get_request_target(&self) -> Option<String> {
267        self.get_attributes()
268            .get(Self::request_target_key())
269            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<String>())
270            .cloned()
271    }
272
273    /// Stores the original target for the current request before user middleware runs.
274    ///
275    /// # Arguments
276    ///
277    /// - `T` - The unmodified target supplied by the protocol transport.
278    ///
279    /// # Returns
280    ///
281    /// - `&mut Self` - The context retaining its request-local target snapshot.
282    pub(crate) fn set_request_target<T>(&mut self, target: T) -> &mut Self
283    where
284        T: AsRef<str> + Into<String>,
285    {
286        if let Some(arc) = self
287            .get_mut_attributes()
288            .get_mut(Self::request_target_key())
289        {
290            if let Some(stored) = Arc::get_mut(arc)
291                .and_then(|value: &mut (dyn Any + Send + Sync)| value.downcast_mut::<String>())
292            {
293                stored.clear();
294                stored.push_str(target.as_ref());
295                return self;
296            }
297            *arc = Arc::new(target.into());
298            return self;
299        }
300        self.get_mut_attributes().insert(
301            Self::request_target_key().to_owned(),
302            Arc::new(target.into()),
303        );
304        self
305    }
306
307    /// Attempts to retrieve a specific attribute by its key, casting it to the specified type.
308    ///
309    /// # Arguments
310    ///
311    /// - `K` - The key of the attribute to retrieve.
312    ///
313    /// # Returns
314    ///
315    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
316    #[inline(always)]
317    pub fn try_get_attribute<V, K>(&self, key: K) -> Option<V>
318    where
319        V: AnySendSyncClone,
320        K: AsRef<str>,
321    {
322        self.get_attributes()
323            .get(&Attribute::External(key.as_ref().to_owned()).to_string())
324            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<V>())
325            .cloned()
326    }
327
328    /// Retrieves a specific attribute by its key, casting it to the specified type, panicking if not found.
329    ///
330    /// # Arguments
331    ///
332    /// - `K` - The key of the attribute to retrieve.
333    ///
334    /// # Returns
335    ///
336    /// - `V` - The attribute value if it exists and can be cast to the specified type.
337    ///
338    /// # Panics
339    ///
340    /// - If the attribute is not found.
341    #[inline(always)]
342    pub fn get_attribute<V, K>(&self, key: K) -> V
343    where
344        V: AnySendSyncClone,
345        K: AsRef<str>,
346    {
347        self.try_get_attribute(key).unwrap()
348    }
349
350    /// Sets an attribute in the context.
351    ///
352    /// # Arguments
353    ///
354    /// - `K` - The key of the attribute to set.
355    /// - `V` - The value of the attribute.
356    ///
357    /// # Returns
358    ///
359    /// - `&mut Self` - A reference to the modified context.
360    #[inline(always)]
361    pub fn set_attribute<K, V>(&mut self, key: K, value: V) -> &mut Self
362    where
363        K: AsRef<str>,
364        V: AnySendSyncClone,
365    {
366        self.get_mut_attributes().insert(
367            Attribute::External(key.as_ref().to_owned()).to_string(),
368            Arc::new(value),
369        );
370        self
371    }
372
373    /// Removes an attribute from the context.
374    ///
375    /// # Arguments
376    ///
377    /// - `K` - The key of the attribute to remove.
378    ///
379    /// # Returns
380    ///
381    /// - `&mut Self` - A reference to the modified context.
382    #[inline(always)]
383    pub fn remove_attribute<K>(&mut self, key: K) -> &mut Self
384    where
385        K: AsRef<str>,
386    {
387        self.get_mut_attributes()
388            .remove(&Attribute::External(key.as_ref().to_owned()).to_string());
389        self
390    }
391
392    /// Clears all attributes from the context.
393    ///
394    /// # Returns
395    ///
396    /// - `&mut Self` - A reference to the modified context.
397    #[inline(always)]
398    pub fn clear_attribute(&mut self) -> &mut Self {
399        self.get_mut_attributes().clear();
400        self
401    }
402
403    /// Retrieves an internal framework attribute.
404    ///
405    /// # Arguments
406    ///
407    /// - `InternalAttribute` - The internal attribute key to retrieve.
408    ///
409    /// # Returns
410    ///
411    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
412    #[inline(always)]
413    fn try_get_internal_attribute<V>(&self, key: InternalAttribute) -> Option<V>
414    where
415        V: AnySendSyncClone,
416    {
417        self.get_attributes()
418            .get(&Attribute::Internal(key).to_string())
419            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<V>())
420            .cloned()
421    }
422
423    /// Retrieves an internal framework attribute.
424    ///
425    /// # Arguments
426    ///
427    /// - `InternalAttribute` - The internal attribute key to retrieve.
428    ///
429    /// # Returns
430    ///
431    /// - `V` - The attribute value if it exists and can be cast to the specified type.
432    ///
433    /// # Panics
434    ///
435    /// - If the attribute is not found.
436    #[inline(always)]
437    fn get_internal_attribute<V>(&self, key: InternalAttribute) -> V
438    where
439        V: AnySendSyncClone,
440    {
441        self.try_get_internal_attribute(key).unwrap()
442    }
443
444    /// Sets an internal framework attribute.
445    ///
446    /// # Arguments
447    ///
448    /// - `InternalAttribute` - The internal attribute key to set.
449    /// - `V` - The value of the attribute.
450    ///
451    /// # Returns
452    ///
453    /// - `&mut Self` - A reference to the modified context.
454    #[inline(always)]
455    fn set_internal_attribute<V>(&mut self, key: InternalAttribute, value: V) -> &mut Self
456    where
457        V: AnySendSyncClone,
458    {
459        self.get_mut_attributes()
460            .insert(Attribute::Internal(key).to_string(), Arc::new(value));
461        self
462    }
463
464    /// Stores panic data for the current task context.
465    ///
466    /// # Arguments
467    ///
468    /// - `PanicData` - The panic data specific to the current task.
469    ///
470    /// # Returns
471    ///
472    /// - `&mut Self` - Reference to the modified context for method chaining.
473    #[inline(always)]
474    pub fn set_task_panic(&mut self, panic_data: PanicData) -> &mut Self {
475        self.set_internal_attribute(InternalAttribute::TaskPanicData, panic_data)
476    }
477
478    /// Retrieves panic data associated with the current task.
479    ///
480    /// # Returns
481    ///
482    /// - `Option<PanicData>` - Task panic data if a panic was caught during execution.
483    #[inline(always)]
484    pub fn try_get_task_panic_data(&self) -> Option<PanicData> {
485        self.try_get_internal_attribute(InternalAttribute::TaskPanicData)
486    }
487
488    /// Retrieves panic data associated with the current task.
489    ///
490    /// # Returns
491    ///
492    /// - `PanicData` - Task panic data if available.
493    ///
494    /// # Panics
495    ///
496    /// - If no task panic data is found.
497    #[inline(always)]
498    pub fn get_task_panic_data(&self) -> PanicData {
499        self.get_internal_attribute(InternalAttribute::TaskPanicData)
500    }
501
502    /// Sets the request error information for the context.
503    ///
504    /// # Arguments
505    ///
506    /// - `RequestError` - The request error information to store.
507    ///
508    /// # Returns
509    ///
510    /// - `&mut Self` - A reference to the modified context.
511    #[inline(always)]
512    pub(crate) fn set_request_error_data(&mut self, request_error: RequestError) -> &mut Self {
513        self.set_internal_attribute(InternalAttribute::RequestErrorData, request_error)
514    }
515
516    /// Retrieves request error information if an error occurred during handling.
517    ///
518    /// # Returns
519    ///
520    /// - `Option<RequestError>` - The request error information if an error was caught.
521    #[inline(always)]
522    pub fn try_get_request_error_data(&self) -> Option<RequestError> {
523        self.try_get_internal_attribute(InternalAttribute::RequestErrorData)
524    }
525
526    /// Retrieves request error information if an error occurred during handling.
527    ///
528    /// # Returns
529    ///
530    /// - `RequestError` - The request error information if an error was caught.
531    ///
532    /// # Panics
533    ///
534    /// - If the request error information is not found.
535    #[inline(always)]
536    pub fn get_request_error_data(&self) -> RequestError {
537        self.get_internal_attribute(InternalAttribute::RequestErrorData)
538    }
539}