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