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