Skip to main content

hyperlane_core/route/
impl.rs

1use super::*;
2
3// Associate a plugin registry with the specified type.
4collect!(HookType);
5
6/// Provides a default implementation for RouteMatcher.
7impl Default for RouteMatcher {
8    /// Creates a new, empty RouteMatcher.
9    ///
10    /// # Returns
11    ///
12    /// - `RouteMatcher` - A new RouteMatcher with empty storage for static, dynamic, and regex route.
13    #[inline(always)]
14    fn default() -> Self {
15        Self {
16            static_route: hash_map_xx_hash3_64(),
17            dynamic_route: hash_map_xx_hash3_64(),
18            regex_route: hash_map_xx_hash3_64(),
19        }
20    }
21}
22
23/// Implements the `PartialEq` trait for `RoutePattern`.
24///
25/// This allows for comparing two `RoutePattern` instances for equality.
26impl PartialEq for RoutePattern {
27    /// Checks if two `RoutePattern` instances are equal.
28    ///
29    /// # Arguments
30    ///
31    /// - `&Self` - The other `RoutePattern` instance to compare against.
32    ///
33    /// # Returns
34    ///
35    /// - `bool` - `true` if the instances are equal, `false` otherwise.
36    #[inline(always)]
37    fn eq(&self, other: &Self) -> bool {
38        self.get_0() == other.get_0()
39    }
40}
41
42/// Implements the `Eq` trait for `RoutePattern`.
43///
44/// This indicates that `RoutePattern` has a total equality relation.
45impl Eq for RoutePattern {}
46
47/// Implements the `Hash` trait for `RoutePattern`.
48///
49/// This allows `RoutePattern` to be used as a key in hash-based collections.
50impl Hash for RoutePattern {
51    /// Hashes the `RoutePattern` instance.
52    ///
53    /// # Arguments
54    ///
55    /// - `&mut H` - The hasher to use.
56    #[inline(always)]
57    fn hash<H: Hasher>(&self, state: &mut H) {
58        self.get_0().hash(state);
59    }
60}
61
62/// Implements the `PartialOrd` trait for `RoutePattern`.
63///
64/// This allows for partial ordering of `RoutePattern` instances.
65impl PartialOrd for RoutePattern {
66    /// Partially compares two `RoutePattern` instances.
67    ///
68    /// # Arguments
69    ///
70    /// - `&Self` - The other `RoutePattern` instance to compare against.
71    ///
72    /// # Returns
73    ///
74    /// - `Option<Ordering>` - The ordering of the two instances.
75    #[inline(always)]
76    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
77        Some(self.cmp(other))
78    }
79}
80
81/// Implements the `Ord` trait for `RoutePattern`.
82///
83/// This allows for total ordering of `RoutePattern` instances.
84impl Ord for RoutePattern {
85    /// Compares two `RoutePattern` instances.
86    ///
87    /// # Arguments
88    ///
89    /// - `&Self` - The other `RoutePattern` instance to compare against.
90    ///
91    /// # Returns
92    ///
93    /// - `Ordering` - The ordering of the two instances.
94    #[inline(always)]
95    fn cmp(&self, other: &Self) -> Ordering {
96        self.get_0().cmp(other.get_0())
97    }
98}
99
100/// Implements the `PartialEq` trait for `RouteMatcher`.
101///
102/// This allows for comparing two `RouteMatcher` instances for equality.
103impl PartialEq for RouteMatcher {
104    /// Checks if two `RouteMatcher` instances are equal.
105    ///
106    /// # Arguments
107    ///
108    /// - `&Self` - The other `RouteMatcher` instance to compare against.
109    ///
110    /// # Returns
111    ///
112    /// - `bool` - `true` if the instances are equal, `false` otherwise.
113    fn eq(&self, other: &Self) -> bool {
114        if self.get_static_route().len() != other.get_static_route().len() {
115            return false;
116        }
117        for key in self.get_static_route().keys() {
118            if !other.get_static_route().contains_key(key) {
119                return false;
120            }
121        }
122        if self.get_dynamic_route().len() != other.get_dynamic_route().len() {
123            return false;
124        }
125        for (segment_count, routes) in self.get_dynamic_route() {
126            match other.get_dynamic_route().get(segment_count) {
127                Some(other_routes) if routes.len() == other_routes.len() => {
128                    for (pattern, _) in routes {
129                        if !other_routes
130                            .iter()
131                            .any(|entry: &(RoutePattern, ServerHookHandler)| &entry.0 == pattern)
132                        {
133                            return false;
134                        }
135                    }
136                }
137                _ => return false,
138            }
139        }
140        if self.get_regex_route().len() != other.get_regex_route().len() {
141            return false;
142        }
143        for (segment_count, routes) in self.get_regex_route() {
144            match other.get_regex_route().get(segment_count) {
145                Some(other_routes) if routes.len() == other_routes.len() => {
146                    for (pattern, _) in routes {
147                        if !other_routes
148                            .iter()
149                            .any(|entry: &(RoutePattern, ServerHookHandler)| &entry.0 == pattern)
150                        {
151                            return false;
152                        }
153                    }
154                }
155                _ => return false,
156            }
157        }
158        true
159    }
160}
161
162/// Implements the `Eq` trait for `RouteMatcher`.
163///
164/// This indicates that `RouteMatcher` has a total equality relation.
165impl Eq for RouteMatcher {}
166
167/// Implements the `Eq` trait for `RouteSegment`.
168///
169/// This indicates that `RouteSegment` has a total equality relation.
170impl Eq for RouteSegment {}
171
172/// Implements the `PartialOrd` trait for `RouteSegment`.
173///
174/// This allows for partial ordering of `RouteSegment` instances.
175impl PartialOrd for RouteSegment {
176    /// Partially compares two `RouteSegment` instances.
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - The other `RouteSegment` instance to compare against.
181    ///
182    /// # Returns
183    ///
184    /// - `Option<Ordering>` - The ordering of the two instances.
185    #[inline(always)]
186    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
187        Some(self.cmp(other))
188    }
189}
190
191/// Implements the `Ord` trait for `RouteSegment`.
192///
193/// This allows for total ordering of `RouteSegment` instances.
194impl Ord for RouteSegment {
195    /// Compares two `RouteSegment` instances.
196    ///
197    /// # Arguments
198    ///
199    /// - `&Self` - The other `RouteSegment` instance to compare against.
200    ///
201    /// # Returns
202    ///
203    /// - `Ordering` - The ordering of the two instances.
204    #[inline(always)]
205    fn cmp(&self, other: &Self) -> Ordering {
206        match (self, other) {
207            (Self::Static(left_static), Self::Static(right_static)) => {
208                left_static.cmp(right_static)
209            }
210            (Self::Dynamic(left_dynamic), Self::Dynamic(right_dynamic)) => {
211                left_dynamic.cmp(right_dynamic)
212            }
213            (Self::Regex(left_name, left_regex), Self::Regex(right_name, right_regex)) => left_name
214                .cmp(right_name)
215                .then_with(|| left_regex.as_str().cmp(right_regex.as_str())),
216            (Self::Static(_), _) => Ordering::Less,
217            (_, Self::Static(_)) => Ordering::Greater,
218            (Self::Dynamic(_), _) => Ordering::Less,
219            (_, Self::Dynamic(_)) => Ordering::Greater,
220        }
221    }
222}
223
224/// Implements the `PartialEq` trait for `RouteSegment`.
225///
226/// This allows for comparing two `RouteSegment` instances for equality.
227impl PartialEq for RouteSegment {
228    /// Checks if two `RouteSegment` instances are equal.
229    ///
230    /// # Arguments
231    ///
232    /// - `&Self` - The other `RouteSegment` instance to compare against.
233    ///
234    /// # Returns
235    ///
236    /// - `bool` - `true` if the instances are equal, `false` otherwise.
237    #[inline(always)]
238    fn eq(&self, other: &Self) -> bool {
239        match (self, other) {
240            (Self::Static(left_value), Self::Static(right_value)) => left_value == right_value,
241            (Self::Dynamic(left_value), Self::Dynamic(right_value)) => left_value == right_value,
242            (Self::Regex(left_name, left_regex), Self::Regex(right_name, right_regex)) => {
243                left_name == right_name && left_regex.as_str() == right_regex.as_str()
244            }
245            _ => false,
246        }
247    }
248}
249
250/// Implements the `Hash` trait for `RouteSegment`.
251///
252/// This allows `RouteSegment` to be used in hash-based collections.
253impl Hash for RouteSegment {
254    /// Hashes the `RouteSegment` instance.
255    ///
256    /// # Arguments
257    ///
258    /// - `&mut H` - The hasher to use.
259    #[inline(always)]
260    fn hash<H: Hasher>(&self, state: &mut H) {
261        match self {
262            Self::Static(static_value) => {
263                0u8.hash(state);
264                static_value.hash(state);
265            }
266            Self::Dynamic(dynamic_value) => {
267                1u8.hash(state);
268                dynamic_value.hash(state);
269            }
270            Self::Regex(name, regex) => {
271                2u8.hash(state);
272                name.hash(state);
273                regex.as_str().hash(state);
274            }
275        }
276    }
277}
278
279/// Manages route patterns, including parsing and matching.
280///
281/// This struct is responsible for defining and validating route structures,
282/// supporting static, dynamic, and regex-based path matching.
283impl RoutePattern {
284    /// Creates a new RoutePattern by parsing a route string.
285    ///
286    /// # Arguments
287    ///
288    /// - `&str` - The raw route string to parse.
289    ///
290    /// # Returns
291    ///
292    /// - `Result<RoutePattern, RouteError>` - The parsed RoutePattern on success, or RouteError on failure.
293    pub(crate) fn new(route: &str) -> Result<RoutePattern, RouteError> {
294        Ok(Self(Self::parse_route(route)?))
295    }
296
297    /// Parses a raw route string into RouteSegments.
298    ///
299    /// This is the core logic for interpreting the route syntax.
300    ///
301    /// # Arguments
302    ///
303    /// - `&str` - The raw route string.
304    ///
305    /// # Returns
306    ///
307    /// - `Result<Vec<RouteSegment>, RouteError>` - Vector of RouteSegments on success, or RouteError on failure.
308    fn parse_route(route: &str) -> Result<Vec<RouteSegment>, RouteError> {
309        if route.is_empty() {
310            return Err(RouteError::EmptyPattern);
311        }
312        let route: &str = route.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(route);
313        if route.is_empty() {
314            return Ok(Vec::new());
315        }
316        let estimated_segments: usize = route.matches(DEFAULT_HTTP_PATH).count() + 1;
317        let mut segments: Vec<RouteSegment> = Vec::with_capacity(estimated_segments);
318        for segment in route.split(DEFAULT_HTTP_PATH) {
319            if segment.starts_with(LEFT_BRACKET) && segment.ends_with(RIGHT_BRACKET) {
320                let content: &str = &segment[1..segment.len() - 1];
321                if let Some((name, pattern)) = content.split_once(COLON) {
322                    let anchored: String = format!("\\A(?:{pattern})\\z");
323                    match Regex::new(&anchored) {
324                        Ok(regex) => {
325                            segments.push(RouteSegment::Regex(name.to_owned(), regex));
326                        }
327                        Err(error) => {
328                            return Err(RouteError::InvalidRegexPattern(format!(
329                                "Invalid regex pattern '{}{}{}",
330                                pattern, COLON, error
331                            )));
332                        }
333                    }
334                } else {
335                    segments.push(RouteSegment::Dynamic(content.to_owned()));
336                }
337            } else {
338                segments.push(RouteSegment::Static(segment.to_owned()));
339            }
340        }
341        Ok(segments)
342    }
343
344    /// Matches this route pattern against a request path and populates `params`
345    /// in place without allocating an intermediate segment vector.
346    ///
347    /// # Arguments
348    ///
349    /// - `&str` - The request path to match against.
350    /// - `&mut HashMapXxHash3_64<String, String>` - The recycled parameter map to populate on match.
351    ///
352    /// # Returns
353    ///
354    /// - `bool` - `true` if the pattern matched and `params` was populated.
355    pub(crate) fn try_match_path_into(
356        &self,
357        path: &str,
358        params: &mut HashMapXxHash3_64<String, String>,
359    ) -> bool {
360        let trimmed: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
361        let route_segments: &[RouteSegment] = self.get_0().as_slice();
362        let route_segments_len: usize = route_segments.len();
363        if trimmed.is_empty() {
364            return route_segments_len == 0;
365        }
366        let is_tail_regex: bool = matches!(route_segments.last(), Some(RouteSegment::Regex(_, _)));
367        if !is_tail_regex {
368            let mut captured: [MaybeUninit<(&str, &str)>; 16] =
369                [const { MaybeUninit::uninit() }; 16];
370            let mut captured_len: usize = 0;
371            let mut overflow: Option<Vec<(&str, &str)>> = None;
372            let mut seg_idx: usize = 0;
373            for part in trimmed.split(DEFAULT_HTTP_PATH) {
374                if part.is_empty() {
375                    return false;
376                }
377                let Some(expected) = route_segments.get(seg_idx) else {
378                    return false;
379                };
380                match expected {
381                    RouteSegment::Static(literal) => {
382                        if part != literal.as_str() {
383                            return false;
384                        }
385                    }
386                    RouteSegment::Dynamic(param_name) => {
387                        if captured_len < captured.len() {
388                            captured[captured_len].write((param_name.as_str(), part));
389                            captured_len += 1;
390                        } else {
391                            overflow
392                                .get_or_insert_with(Vec::new)
393                                .push((param_name.as_str(), part));
394                        }
395                    }
396                    RouteSegment::Regex(param_name, regex) => {
397                        if !regex.is_match(part) {
398                            return false;
399                        }
400                        if captured_len < captured.len() {
401                            captured[captured_len].write((param_name.as_str(), part));
402                            captured_len += 1;
403                        } else {
404                            overflow
405                                .get_or_insert_with(Vec::new)
406                                .push((param_name.as_str(), part));
407                        }
408                    }
409                }
410                seg_idx += 1;
411            }
412            if seg_idx != route_segments_len {
413                return false;
414            }
415            if !params.is_empty() {
416                for pair in params.drain() {
417                    return_route_param_entry(pair);
418                }
419            }
420            for slot in &captured[..captured_len] {
421                // SAFETY: Every slot in `0..captured_len` was initialized via `MaybeUninit::write`.
422                let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
423                let (mut key, mut val): (String, String) = take_route_param_entry();
424                key.push_str(param_name);
425                val.push_str(part);
426                params.insert(key, val);
427            }
428            if let Some(extra) = overflow {
429                for (param_name, part) in extra {
430                    let (mut key, mut val): (String, String) = take_route_param_entry();
431                    key.push_str(param_name);
432                    val.push_str(part);
433                    params.insert(key, val);
434                }
435            }
436            return true;
437        }
438        let prefix_len: usize = route_segments_len - 1;
439        let mut captured: [MaybeUninit<(&str, &str)>; 16] = [const { MaybeUninit::uninit() }; 16];
440        let mut captured_len: usize = 0;
441        let mut overflow: Option<Vec<(&str, &str)>> = None;
442        let sep_byte: u8 = DEFAULT_HTTP_PATH_BYTES[0];
443        let trimmed_bytes: &[u8] = trimmed.as_bytes();
444        let mut offset: usize = 0;
445        for expected in &route_segments[..prefix_len] {
446            if offset >= trimmed_bytes.len() {
447                return false;
448            }
449            let rel_end: usize = trimmed_bytes[offset..]
450                .iter()
451                .position(|byte: &u8| *byte == sep_byte)
452                .unwrap_or(trimmed_bytes.len() - offset);
453            let seg_end: usize = offset + rel_end;
454            let part: &str = &trimmed[offset..seg_end];
455            if part.is_empty() {
456                return false;
457            }
458            match expected {
459                RouteSegment::Static(literal) => {
460                    if part != literal.as_str() {
461                        return false;
462                    }
463                }
464                RouteSegment::Dynamic(param_name) => {
465                    if captured_len < captured.len() {
466                        captured[captured_len].write((param_name.as_str(), part));
467                        captured_len += 1;
468                    } else {
469                        overflow
470                            .get_or_insert_with(Vec::new)
471                            .push((param_name.as_str(), part));
472                    }
473                }
474                RouteSegment::Regex(param_name, regex) => {
475                    if !regex.is_match(part) {
476                        return false;
477                    }
478                    if captured_len < captured.len() {
479                        captured[captured_len].write((param_name.as_str(), part));
480                        captured_len += 1;
481                    } else {
482                        overflow
483                            .get_or_insert_with(Vec::new)
484                            .push((param_name.as_str(), part));
485                    }
486                }
487            }
488            offset = if seg_end < trimmed_bytes.len() {
489                seg_end + 1
490            } else {
491                trimmed_bytes.len()
492            };
493        }
494        let tail_slice: &str = if offset <= trimmed.len() {
495            &trimmed[offset..]
496        } else {
497            EMPTY_STR
498        };
499        let Some(RouteSegment::Regex(tail_name, tail_regex)) = route_segments.last() else {
500            return false;
501        };
502        if !tail_regex.is_match(tail_slice) {
503            return false;
504        }
505        if !params.is_empty() {
506            for pair in params.drain() {
507                return_route_param_entry(pair);
508            }
509        }
510        for slot in &captured[..captured_len] {
511            // SAFETY: Every slot in `0..captured_len` was initialized via `MaybeUninit::write`.
512            let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
513            let (mut key, mut val): (String, String) = take_route_param_entry();
514            key.push_str(param_name);
515            val.push_str(part);
516            params.insert(key, val);
517        }
518        if let Some(extra) = overflow {
519            for (param_name, part) in extra {
520                let (mut key, mut val): (String, String) = take_route_param_entry();
521                key.push_str(param_name);
522                val.push_str(part);
523                params.insert(key, val);
524            }
525        }
526        let (mut tail_key, mut tail_val): (String, String) = take_route_param_entry();
527        tail_key.push_str(tail_name.as_str());
528        tail_val.push_str(tail_slice);
529        params.insert(tail_key, tail_val);
530        true
531    }
532
533    /// Checks if the route pattern is static.
534    ///
535    /// # Returns
536    ///
537    /// - `bool` - true if the pattern is static, false otherwise.
538    #[inline(always)]
539    pub(crate) fn is_static(&self) -> bool {
540        self.get_0()
541            .iter()
542            .all(|segment: &RouteSegment| matches!(segment, RouteSegment::Static(_)))
543    }
544
545    /// Checks if the route pattern is dynamic.
546    ///
547    /// # Returns
548    ///
549    /// - `bool` - true if the pattern is dynamic, false otherwise.
550    #[inline(always)]
551    pub(crate) fn is_dynamic(&self) -> bool {
552        self.get_0()
553            .iter()
554            .any(|segment: &RouteSegment| matches!(segment, RouteSegment::Dynamic(_)))
555            && self
556                .get_0()
557                .iter()
558                .all(|segment: &RouteSegment| !matches!(segment, RouteSegment::Regex(_, _)))
559    }
560
561    /// Gets the number of segments in this route pattern.
562    ///
563    /// # Returns
564    ///
565    /// - `usize` - The number of segments.
566    #[inline(always)]
567    pub(crate) fn segment_count(&self) -> usize {
568        self.get_0().len()
569    }
570
571    /// Checks if the last segment is a regex pattern.
572    ///
573    /// # Returns
574    ///
575    /// - `bool` - true if the last segment is a regex, false otherwise.
576    #[inline(always)]
577    pub(crate) fn has_tail_regex(&self) -> bool {
578        matches!(self.get_0().last(), Some(RouteSegment::Regex(_, _)))
579    }
580}
581
582/// Manages a collection of route, enabling efficient lookup and dispatch.
583///
584/// This struct stores route categorized by type (static, dynamic, regex)
585/// to quickly find the appropriate hook for incoming requests.
586impl RouteMatcher {
587    /// Creates a new, empty RouteMatcher.
588    ///
589    /// # Returns
590    ///
591    /// - `RouteMatcher` - A new RouteMatcher instance with empty route stores.
592    #[inline(always)]
593    pub(crate) fn new() -> Self {
594        Self::default()
595    }
596
597    /// Counts the number of segments in a path.
598    ///
599    /// # Arguments
600    ///
601    /// - `&str` - The path to count segments in.
602    ///
603    /// # Returns
604    ///
605    /// - `usize` - The number of segments.
606    #[inline(always)]
607    fn count_path_segments(path: &str) -> usize {
608        let path: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
609        if path.is_empty() {
610            return 0;
611        }
612        let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0];
613        let mut count: usize = 1;
614        for &byte in path.as_bytes() {
615            if byte == sep {
616                count += 1;
617            }
618        }
619        count
620    }
621
622    /// Adds a new route and its hook to the matcher.
623    ///
624    /// Adds a route hook to the matcher.
625    ///
626    /// This method categorizes the route as static, dynamic, or regex based on its pattern
627    /// and stores it in the appropriate collection.
628    ///
629    /// # Arguments
630    ///
631    /// - `&str` - The route pattern string.
632    /// - `ServerHookHandler` - The boxed route hook.
633    ///
634    /// # Returns
635    ///
636    /// - `Result<(), RouteError>` - Ok on success, or RouteError if pattern is duplicate.
637    pub(crate) fn add(&mut self, pattern: &str, hook: ServerHookHandler) -> Result<(), RouteError> {
638        let route_pattern: RoutePattern = RoutePattern::new(pattern)?;
639        if route_pattern.is_static() {
640            if self.get_static_route().contains_key(pattern) {
641                return Err(RouteError::DuplicatePattern(pattern.to_owned()));
642            }
643            self.get_mut_static_route()
644                .insert(pattern.to_string(), hook);
645            return Ok(());
646        }
647        let target_map: &mut ServerHookPatternRoute = if route_pattern.is_dynamic() {
648            self.get_mut_dynamic_route()
649        } else {
650            self.get_mut_regex_route()
651        };
652        let segment_count: usize = route_pattern.segment_count();
653        let routes_for_count: &mut Vec<(RoutePattern, ServerHookHandler)> =
654            target_map.entry(segment_count).or_default();
655        match routes_for_count.binary_search_by(|entry: &(RoutePattern, ServerHookHandler)| {
656            entry.0.cmp(&route_pattern)
657        }) {
658            Ok(_) => return Err(RouteError::DuplicatePattern(pattern.to_owned())),
659            Err(pos) => routes_for_count.insert(pos, (route_pattern, hook)),
660        }
661        Ok(())
662    }
663
664    /// Resolves a route hook by reference (no Arc::clone) for hot-path use.
665    ///
666    /// Returns a reference to the matched `ServerHookHandler` if any. The
667    /// caller must clone if it needs to retain the hook beyond the await point.
668    /// Returns `None` if no route matched.
669    ///
670    /// # Arguments
671    ///
672    /// - `&'a self` - The route table to search.
673    /// - `&mut Context` - The request context (for storing route params).
674    /// - `&str` - The request path to resolve.
675    ///
676    /// # Returns
677    ///
678    /// - `Option<&'a ServerHookHandler>`: The matched handler, or `None` when no
679    ///   route matched.
680    pub fn try_resolve_route<'a>(
681        &'a self,
682        ctx: &mut Context,
683        path: &str,
684    ) -> Option<&'a ServerHookHandler> {
685        if let Some(hook) = self.get_static_route().get(path) {
686            return Some(hook);
687        }
688        let path_segment_count: usize = Self::count_path_segments(path);
689        if let Some(routes) = self.get_dynamic_route().get(&path_segment_count) {
690            for (pattern, hook) in routes {
691                if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
692                    return Some(hook);
693                }
694            }
695        }
696        if let Some(routes) = self.get_regex_route().get(&path_segment_count) {
697            for (pattern, hook) in routes {
698                if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
699                    return Some(hook);
700                }
701            }
702        }
703        for (&segment_count, routes) in self.get_regex_route() {
704            if segment_count == path_segment_count || segment_count > path_segment_count + 1 {
705                continue;
706            }
707            for (pattern, hook) in routes {
708                if pattern.has_tail_regex()
709                    && pattern.try_match_path_into(path, ctx.get_mut_route_params())
710                {
711                    return Some(hook);
712                }
713            }
714        }
715        None
716    }
717}