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        self.get_mut_route_params().clear();
241        self
242    }
243
244    /// Attempts to retrieve a specific route parameter by its name.
245    ///
246    /// # Arguments
247    ///
248    /// - `T` - The name of the route parameter to retrieve.
249    ///
250    /// # Returns
251    ///
252    /// - `Option<String>` - The value of the route parameter if it exists.
253    #[inline(always)]
254    pub fn try_get_route_param<T>(&self, name: T) -> Option<String>
255    where
256        T: AsRef<str>,
257    {
258        self.get_route_params().get(name.as_ref()).cloned()
259    }
260
261    /// Retrieves a specific route parameter by its name, panicking if not found.
262    ///
263    /// # Arguments
264    ///
265    /// - `T` - The name of the route parameter to retrieve.
266    ///
267    /// # Returns
268    ///
269    /// - `String` - The value of the route parameter if it exists.
270    ///
271    /// # Panics
272    ///
273    /// - If the route parameter is not found.
274    #[inline(always)]
275    pub fn get_route_param<T>(&self, name: T) -> String
276    where
277        T: AsRef<str>,
278    {
279        self.try_get_route_param(name).unwrap()
280    }
281
282    /// Returns the original wire request target before routing or query-map conversion.
283    ///
284    /// # Returns
285    ///
286    /// - `Option<String>` - The unchanged path and query, or none for a manually constructed context.
287    pub fn get_request_target(&self) -> Option<String> {
288        self.get_request_target_ref().cloned()
289    }
290
291    /// Returns the original wire request target without copying it.
292    ///
293    /// # Returns
294    ///
295    /// - `Option<&String>` - The unchanged path and query, or none for a manually constructed context.
296    pub(crate) fn get_request_target_ref(&self) -> Option<&String> {
297        self.original_target.as_ref()
298    }
299
300    /// Stores the original target for the current request before user middleware runs.
301    ///
302    /// # Arguments
303    ///
304    /// - `T` - The unmodified target supplied by the protocol transport.
305    ///
306    /// # Returns
307    ///
308    /// - `&mut Self` - The context retaining its request-local target snapshot.
309    pub(crate) fn set_request_target<T>(&mut self, target: T) -> &mut Self
310    where
311        T: AsRef<str> + Into<String>,
312    {
313        let stored: &mut Option<String> = &mut self.original_target;
314        match stored {
315            Some(existing) => {
316                existing.clear();
317                existing.push_str(target.as_ref());
318            }
319            None => {
320                *stored = Some(target.into());
321            }
322        }
323        self
324    }
325
326    /// Attempts to retrieve a specific attribute by its key, casting it to the specified type.
327    ///
328    /// The original request target is readable under its own key, because the
329    /// framework stores it in its own field rather than in the attribute map.
330    ///
331    /// # Arguments
332    ///
333    /// - `K` - The key of the attribute to retrieve.
334    ///
335    /// # Returns
336    ///
337    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
338    #[inline(always)]
339    pub fn try_get_attribute<V, K>(&self, key: K) -> Option<V>
340    where
341        V: AnySendSyncClone,
342        K: AsRef<str>,
343    {
344        let key: &str = key.as_ref();
345        if key == REQUEST_TARGET_ATTRIBUTE {
346            let target: Option<&String> = self.get_request_target_ref();
347            return match target {
348                Some(target) => {
349                    // The target is held as a plain string, so it is boxed
350                    // here to take the same downcast the map takes. This path
351                    // is not on the request path: the framework stores and
352                    // reads the target through its own field.
353                    let value: ArcAnySendSync = Arc::new(target.clone());
354                    value.downcast_ref::<V>().cloned()
355                }
356                None => None,
357            };
358        }
359        self.get_attributes()
360            .get(&Attribute::External(key.to_owned()).to_string())
361            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<V>())
362            .cloned()
363    }
364
365    /// Retrieves a specific attribute by its key, casting it to the specified type, panicking if not found.
366    ///
367    /// # Arguments
368    ///
369    /// - `K` - The key of the attribute to retrieve.
370    ///
371    /// # Returns
372    ///
373    /// - `V` - The attribute value if it exists and can be cast to the specified type.
374    ///
375    /// # Panics
376    ///
377    /// - If the attribute is not found.
378    #[inline(always)]
379    pub fn get_attribute<V, K>(&self, key: K) -> V
380    where
381        V: AnySendSyncClone,
382        K: AsRef<str>,
383    {
384        self.try_get_attribute(key).unwrap()
385    }
386
387    /// Sets an attribute in the context.
388    ///
389    /// # Arguments
390    ///
391    /// - `K` - The key of the attribute to set.
392    /// - `V` - The value of the attribute.
393    ///
394    /// # Returns
395    ///
396    /// - `&mut Self` - A reference to the modified context.
397    #[inline(always)]
398    pub fn set_attribute<K, V>(&mut self, key: K, value: V) -> &mut Self
399    where
400        K: AsRef<str>,
401        V: AnySendSyncClone,
402    {
403        self.get_mut_attributes().insert(
404            Attribute::External(key.as_ref().to_owned()).to_string(),
405            Arc::new(value),
406        );
407        self
408    }
409
410    /// Removes an attribute from the context.
411    ///
412    /// # Arguments
413    ///
414    /// - `K` - The key of the attribute to remove.
415    ///
416    /// # Returns
417    ///
418    /// - `&mut Self` - A reference to the modified context.
419    #[inline(always)]
420    pub fn remove_attribute<K>(&mut self, key: K) -> &mut Self
421    where
422        K: AsRef<str>,
423    {
424        self.get_mut_attributes()
425            .remove(&Attribute::External(key.as_ref().to_owned()).to_string());
426        self
427    }
428
429    /// Clears all attributes from the context.
430    ///
431    /// # Returns
432    ///
433    /// - `&mut Self` - A reference to the modified context.
434    #[inline(always)]
435    pub fn clear_attribute(&mut self) -> &mut Self {
436        self.get_mut_attributes().clear();
437        self
438    }
439
440    /// Retrieves an internal framework attribute.
441    ///
442    /// # Arguments
443    ///
444    /// - `InternalAttribute` - The internal attribute key to retrieve.
445    ///
446    /// # Returns
447    ///
448    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
449    #[inline(always)]
450    fn try_get_internal_attribute<V>(&self, key: InternalAttribute) -> Option<V>
451    where
452        V: AnySendSyncClone,
453    {
454        self.get_attributes()
455            .get(&Attribute::Internal(key).to_string())
456            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<V>())
457            .cloned()
458    }
459
460    /// Retrieves an internal framework attribute.
461    ///
462    /// # Arguments
463    ///
464    /// - `InternalAttribute` - The internal attribute key to retrieve.
465    ///
466    /// # Returns
467    ///
468    /// - `V` - The attribute value if it exists and can be cast to the specified type.
469    ///
470    /// # Panics
471    ///
472    /// - If the attribute is not found.
473    #[inline(always)]
474    fn get_internal_attribute<V>(&self, key: InternalAttribute) -> V
475    where
476        V: AnySendSyncClone,
477    {
478        self.try_get_internal_attribute(key).unwrap()
479    }
480
481    /// Sets an internal framework attribute.
482    ///
483    /// # Arguments
484    ///
485    /// - `InternalAttribute` - The internal attribute key to set.
486    /// - `V` - The value of the attribute.
487    ///
488    /// # Returns
489    ///
490    /// - `&mut Self` - A reference to the modified context.
491    #[inline(always)]
492    fn set_internal_attribute<V>(&mut self, key: InternalAttribute, value: V) -> &mut Self
493    where
494        V: AnySendSyncClone,
495    {
496        self.get_mut_attributes()
497            .insert(Attribute::Internal(key).to_string(), Arc::new(value));
498        self
499    }
500
501    /// Stores panic data for the current task context.
502    ///
503    /// # Arguments
504    ///
505    /// - `PanicData` - The panic data specific to the current task.
506    ///
507    /// # Returns
508    ///
509    /// - `&mut Self` - Reference to the modified context for method chaining.
510    #[inline(always)]
511    pub fn set_task_panic(&mut self, panic_data: PanicData) -> &mut Self {
512        self.set_internal_attribute(InternalAttribute::TaskPanicData, panic_data)
513    }
514
515    /// Retrieves panic data associated with the current task.
516    ///
517    /// # Returns
518    ///
519    /// - `Option<PanicData>` - Task panic data if a panic was caught during execution.
520    #[inline(always)]
521    pub fn try_get_task_panic_data(&self) -> Option<PanicData> {
522        self.try_get_internal_attribute(InternalAttribute::TaskPanicData)
523    }
524
525    /// Retrieves panic data associated with the current task.
526    ///
527    /// # Returns
528    ///
529    /// - `PanicData` - Task panic data if available.
530    ///
531    /// # Panics
532    ///
533    /// - If no task panic data is found.
534    #[inline(always)]
535    pub fn get_task_panic_data(&self) -> PanicData {
536        self.get_internal_attribute(InternalAttribute::TaskPanicData)
537    }
538
539    /// Sets the request error information for the context.
540    ///
541    /// # Arguments
542    ///
543    /// - `RequestError` - The request error information to store.
544    ///
545    /// # Returns
546    ///
547    /// - `&mut Self` - A reference to the modified context.
548    #[inline(always)]
549    pub(crate) fn set_request_error_data(&mut self, request_error: RequestError) -> &mut Self {
550        self.set_internal_attribute(InternalAttribute::RequestErrorData, request_error)
551    }
552
553    /// Retrieves request error information if an error occurred during handling.
554    ///
555    /// # Returns
556    ///
557    /// - `Option<RequestError>` - The request error information if an error was caught.
558    #[inline(always)]
559    pub fn try_get_request_error_data(&self) -> Option<RequestError> {
560        self.try_get_internal_attribute(InternalAttribute::RequestErrorData)
561    }
562
563    /// Retrieves request error information if an error occurred during handling.
564    ///
565    /// # Returns
566    ///
567    /// - `RequestError` - The request error information if an error was caught.
568    ///
569    /// # Panics
570    ///
571    /// - If the request error information is not found.
572    #[inline(always)]
573    pub fn get_request_error_data(&self) -> RequestError {
574        self.get_internal_attribute(InternalAttribute::RequestErrorData)
575    }
576}