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: HashMapXxHash3_64::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    /// - `Vec<u8>` - The serialized response bytes.
58    #[inline(always)]
59    #[must_use]
60    pub fn build_response(&mut self) -> Vec<u8> {
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 HashMapXxHash3_64<String, String> = 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    /// Reports whether an external attribute key formats identically to raw ASCII without debug escaping.
342    ///
343    /// # Arguments
344    ///
345    /// - `&str` - Candidate external attribute key.
346    ///
347    /// # Returns
348    ///
349    /// - `bool` - `true` when every byte is printable ASCII excluding `"` and `\`.
350    #[inline(always)]
351    fn is_plain_external_key(key: &str) -> bool {
352        key.len() <= EXTERNAL_ATTR_STACK_LIMIT
353            && key.bytes().all(|byte: u8| {
354                (0x20..0x7f).contains(&byte)
355                    && byte != EXTERNAL_ATTR_QUOTE
356                    && byte != EXTERNAL_ATTR_BACKSLASH
357            })
358    }
359
360    /// Formats a plain external attribute key into a caller-provided uninitialized stack buffer.
361    ///
362    /// # Arguments
363    ///
364    /// - `&str` - Plain external attribute key verified by [`Self::is_plain_external_key`].
365    /// - `&'a mut [MaybeUninit<u8>; 128]` - Uninitialized stack buffer receiving `External("<key>")`.
366    ///
367    /// # Returns
368    ///
369    /// - `&'a str` - Borrowed formatted attribute map key.
370    #[inline(always)]
371    fn format_plain_external_key<'a>(key: &str, buf: &'a mut [MaybeUninit<u8>; 128]) -> &'a str {
372        let prefix_len: usize = EXTERNAL_ATTR_PREFIX.len();
373        let key_bytes: &[u8] = key.as_bytes();
374        let key_len: usize = key_bytes.len();
375        let suffix_len: usize = EXTERNAL_ATTR_SUFFIX.len();
376        let total: usize = prefix_len + key_len + suffix_len;
377        // SAFETY: `is_plain_external_key` guarantees `total <= 128` and every byte is printable
378        // ASCII (< 0x80), so copying all three parts initializes `0..total` as valid UTF-8.
379        unsafe {
380            let dst: *mut u8 = buf.as_mut_ptr().cast::<u8>();
381            ptr::copy_nonoverlapping(EXTERNAL_ATTR_PREFIX.as_ptr(), dst, prefix_len);
382            ptr::copy_nonoverlapping(key_bytes.as_ptr(), dst.add(prefix_len), key_len);
383            ptr::copy_nonoverlapping(
384                EXTERNAL_ATTR_SUFFIX.as_ptr(),
385                dst.add(prefix_len + key_len),
386                suffix_len,
387            );
388            from_utf8_unchecked(slice::from_raw_parts(dst, total))
389        }
390    }
391
392    /// Returns the static map key for an internal framework attribute.
393    ///
394    /// # Arguments
395    ///
396    /// - `InternalAttribute` - The internal attribute variant.
397    ///
398    /// # Returns
399    ///
400    /// - `&'static str` - Formatted map key matching `Attribute::Internal(key).to_string()`.
401    #[inline(always)]
402    fn internal_attribute_key(key: InternalAttribute) -> &'static str {
403        match key {
404            InternalAttribute::TaskPanicData => INTERNAL_TASK_PANIC_KEY,
405            InternalAttribute::RequestErrorData => INTERNAL_REQUEST_ERROR_KEY,
406        }
407    }
408
409    /// Attempts to retrieve a specific attribute by its key, casting it to the specified type.
410    ///
411    /// The original request target is readable under its own key, because the
412    /// framework stores it in its own field rather than in the attribute map.
413    ///
414    /// # Arguments
415    ///
416    /// - `K` - The key of the attribute to retrieve.
417    ///
418    /// # Returns
419    ///
420    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
421    #[inline(always)]
422    pub fn try_get_attribute<V, K>(&self, key: K) -> Option<V>
423    where
424        V: AnySendSyncClone,
425        K: AsRef<str>,
426    {
427        let key: &str = key.as_ref();
428        if key == REQUEST_TARGET_ATTRIBUTE {
429            let target: Option<&String> = self.get_request_target_ref();
430            return match target {
431                Some(target) => {
432                    // The target is held as a plain string, so it is boxed
433                    // here to take the same downcast the map takes. This path
434                    // is not on the request path: the framework stores and
435                    // reads the target through its own field.
436                    let value: ArcAnySendSync = Arc::new(target.clone());
437                    value.downcast_ref::<V>().cloned()
438                }
439                None => None,
440            };
441        }
442        if Self::is_plain_external_key(key) {
443            let mut stack_buf: [MaybeUninit<u8>; 128] = [const { MaybeUninit::uninit() }; 128];
444            let formatted: &str = Self::format_plain_external_key(key, &mut stack_buf);
445            return self
446                .get_attributes()
447                .get(formatted)
448                .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<V>())
449                .cloned();
450        }
451        self.get_attributes()
452            .get(&Attribute::External(key.to_owned()).to_string())
453            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<V>())
454            .cloned()
455    }
456
457    /// Retrieves a specific attribute by its key, casting it to the specified type, panicking if not found.
458    ///
459    /// # Arguments
460    ///
461    /// - `K` - The key of the attribute to retrieve.
462    ///
463    /// # Returns
464    ///
465    /// - `V` - The attribute value if it exists and can be cast to the specified type.
466    ///
467    /// # Panics
468    ///
469    /// - If the attribute is not found.
470    #[inline(always)]
471    pub fn get_attribute<V, K>(&self, key: K) -> V
472    where
473        V: AnySendSyncClone,
474        K: AsRef<str>,
475    {
476        self.try_get_attribute(key).unwrap()
477    }
478
479    /// Sets an attribute in the context.
480    ///
481    /// # Arguments
482    ///
483    /// - `K` - The key of the attribute to set.
484    /// - `V` - The value of the attribute.
485    ///
486    /// # Returns
487    ///
488    /// - `&mut Self` - A reference to the modified context.
489    #[inline(always)]
490    pub fn set_attribute<K, V>(&mut self, key: K, value: V) -> &mut Self
491    where
492        K: AsRef<str>,
493        V: AnySendSyncClone,
494    {
495        let key_str: &str = key.as_ref();
496        let boxed: ArcAnySendSync = Arc::new(value);
497        if Self::is_plain_external_key(key_str) {
498            let mut stack_buf: [MaybeUninit<u8>; 128] = [const { MaybeUninit::uninit() }; 128];
499            let formatted: &str = Self::format_plain_external_key(key_str, &mut stack_buf);
500            let attrs: &mut ThreadSafeAttributeStore = self.get_mut_attributes();
501            if let Some(existing) = attrs.get_mut(formatted) {
502                *existing = boxed;
503            } else {
504                attrs.insert(formatted.to_owned(), boxed);
505            }
506            return self;
507        }
508        let map_key: String = Attribute::External(key_str.to_owned()).to_string();
509        self.get_mut_attributes().insert(map_key, boxed);
510        self
511    }
512
513    /// Removes an attribute from the context.
514    ///
515    /// # Arguments
516    ///
517    /// - `K` - The key of the attribute to remove.
518    ///
519    /// # Returns
520    ///
521    /// - `&mut Self` - A reference to the modified context.
522    #[inline(always)]
523    pub fn remove_attribute<K>(&mut self, key: K) -> &mut Self
524    where
525        K: AsRef<str>,
526    {
527        let key_str: &str = key.as_ref();
528        if Self::is_plain_external_key(key_str) {
529            let mut stack_buf: [MaybeUninit<u8>; 128] = [const { MaybeUninit::uninit() }; 128];
530            let formatted: &str = Self::format_plain_external_key(key_str, &mut stack_buf);
531            self.get_mut_attributes().remove(formatted);
532            return self;
533        }
534        self.get_mut_attributes()
535            .remove(&Attribute::External(key_str.to_owned()).to_string());
536        self
537    }
538
539    /// Clears all attributes from the context.
540    ///
541    /// # Returns
542    ///
543    /// - `&mut Self` - A reference to the modified context.
544    #[inline(always)]
545    pub fn clear_attribute(&mut self) -> &mut Self {
546        self.get_mut_attributes().clear();
547        self
548    }
549
550    /// Retrieves an internal framework attribute.
551    ///
552    /// # Arguments
553    ///
554    /// - `InternalAttribute` - The internal attribute key to retrieve.
555    ///
556    /// # Returns
557    ///
558    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
559    #[inline(always)]
560    fn try_get_internal_attribute<V>(&self, key: InternalAttribute) -> Option<V>
561    where
562        V: AnySendSyncClone,
563    {
564        self.get_attributes()
565            .get(Self::internal_attribute_key(key))
566            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<V>())
567            .cloned()
568    }
569
570    /// Retrieves an internal framework attribute.
571    ///
572    /// # Arguments
573    ///
574    /// - `InternalAttribute` - The internal attribute key to retrieve.
575    ///
576    /// # Returns
577    ///
578    /// - `V` - The attribute value if it exists and can be cast to the specified type.
579    ///
580    /// # Panics
581    ///
582    /// - If the attribute is not found.
583    #[inline(always)]
584    fn get_internal_attribute<V>(&self, key: InternalAttribute) -> V
585    where
586        V: AnySendSyncClone,
587    {
588        self.try_get_internal_attribute(key).unwrap()
589    }
590
591    /// Sets an internal framework attribute.
592    ///
593    /// # Arguments
594    ///
595    /// - `InternalAttribute` - The internal attribute key to set.
596    /// - `V` - The value of the attribute.
597    ///
598    /// # Returns
599    ///
600    /// - `&mut Self` - A reference to the modified context.
601    #[inline(always)]
602    fn set_internal_attribute<V>(&mut self, key: InternalAttribute, value: V) -> &mut Self
603    where
604        V: AnySendSyncClone,
605    {
606        self.get_mut_attributes().insert(
607            Self::internal_attribute_key(key).to_owned(),
608            Arc::new(value),
609        );
610        self
611    }
612
613    /// Stores panic data for the current task context.
614    ///
615    /// # Arguments
616    ///
617    /// - `PanicData` - The panic data specific to the current task.
618    ///
619    /// # Returns
620    ///
621    /// - `&mut Self` - Reference to the modified context for method chaining.
622    #[inline(always)]
623    pub fn set_task_panic(&mut self, panic_data: PanicData) -> &mut Self {
624        self.set_internal_attribute(InternalAttribute::TaskPanicData, panic_data)
625    }
626
627    /// Retrieves panic data associated with the current task.
628    ///
629    /// # Returns
630    ///
631    /// - `Option<PanicData>` - Task panic data if a panic was caught during execution.
632    #[inline(always)]
633    pub fn try_get_task_panic_data(&self) -> Option<PanicData> {
634        self.try_get_internal_attribute(InternalAttribute::TaskPanicData)
635    }
636
637    /// Retrieves panic data associated with the current task.
638    ///
639    /// # Returns
640    ///
641    /// - `PanicData` - Task panic data if available.
642    ///
643    /// # Panics
644    ///
645    /// - If no task panic data is found.
646    #[inline(always)]
647    pub fn get_task_panic_data(&self) -> PanicData {
648        self.get_internal_attribute(InternalAttribute::TaskPanicData)
649    }
650
651    /// Sets the request error information for the context.
652    ///
653    /// # Arguments
654    ///
655    /// - `RequestError` - The request error information to store.
656    ///
657    /// # Returns
658    ///
659    /// - `&mut Self` - A reference to the modified context.
660    #[inline(always)]
661    pub(crate) fn set_request_error_data(&mut self, request_error: RequestError) -> &mut Self {
662        self.set_internal_attribute(InternalAttribute::RequestErrorData, request_error)
663    }
664
665    /// Retrieves request error information if an error occurred during handling.
666    ///
667    /// # Returns
668    ///
669    /// - `Option<RequestError>` - The request error information if an error was caught.
670    #[inline(always)]
671    pub fn try_get_request_error_data(&self) -> Option<RequestError> {
672        self.try_get_internal_attribute(InternalAttribute::RequestErrorData)
673    }
674
675    /// Retrieves request error information if an error occurred during handling.
676    ///
677    /// # Returns
678    ///
679    /// - `RequestError` - The request error information if an error was caught.
680    ///
681    /// # Panics
682    ///
683    /// - If the request error information is not found.
684    #[inline(always)]
685    pub fn get_request_error_data(&self) -> RequestError {
686        self.get_internal_attribute(InternalAttribute::RequestErrorData)
687    }
688}