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