hyperlane-plugin-rewrite 23.0.0

A high-performance HTTP URL rewrite and redirect plugin for the Hyperlane framework featuring canonical host/HTTPS enforcement (X-Forwarded-Proto aware), trailing-slash and duplicate-slash normalization, O(1) XxHash3_64 static tables, segment-bounded prefix rules, and compiled regex rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
use super::*;

/// Implements [`Hasher`] for [`FxHasher`] with zero allocations and 8-byte word mixing.
impl Hasher for FxHasher {
    /// Finalizes the 64-bit hash state.
    ///
    /// # Returns
    ///
    /// - `u64` - Finalized 64-bit hash.
    #[inline(always)]
    fn finish(&self) -> u64 {
        let Self { state } = *self;
        state
    }

    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input byte slice.
    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) {
        let Self { state } = self;
        let mut h: u64 = *state;
        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
        for chunk in chunks {
            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
        }
        let mut tail: &[u8] = rem;
        if tail.len() >= 4 {
            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
            tail = &tail[4..];
        }
        if tail.len() >= 2 {
            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
            tail = &tail[2..];
        }
        if let Some(&b) = tail.first() {
            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
        }
        *state = h;
    }

    /// Mixes a single `u8` delimiter byte without slice overhead.
    ///
    /// # Arguments
    ///
    /// - `u8` - Input byte.
    #[inline(always)]
    fn write_u8(&mut self, i: u8) {
        let Self { state } = self;
        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
    }
}

/// Formats [`RewriteError`] for display diagnostics.
impl Display for RewriteError {
    /// Renders a human-readable rewrite compilation error.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidRegex { pattern, message } => {
                write!(f, "{ERR_INVALID_REGEX} `{pattern}`: {message}")
            }
            Self::UnsafeLocation(raw) => write!(f, "{ERR_UNSAFE_LOCATION}: {raw:?}"),
        }
    }
}

/// Marks [`RewriteError`] as a standard error type.
impl error::Error for RewriteError {}

/// Inherent status-code mapping for [`RedirectStatus`].
impl RedirectStatus {
    /// Converts this redirect variant into its numeric HTTP status code (`301`/`302`/`307`/`308`).
    ///
    /// # Returns
    ///
    /// - `usize` - Numeric HTTP status code.
    #[inline]
    pub fn code(self) -> usize {
        match self {
            Self::MovedPermanently301 => HttpStatus::MovedPermanently.code(),
            Self::Found302 => HttpStatus::Found.code(),
            Self::Temporary307 => HttpStatus::TemporaryRedirect.code(),
            Self::Permanent308 => HttpStatus::PermanentRedirect.code(),
        }
    }
}

/// Default construction for [`RewriteConfig`].
impl Default for RewriteConfig {
    /// Constructs a no-op default [`RewriteConfig`] preserving incoming host, scheme, and path.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            force_https: false,
            canonical_host: None,
            canonical_redirect_status: RedirectStatus::Permanent308,
            trust_forwarded_proto: true,
            collapse_duplicate_slashes: false,
            trailing_slash: TrailingSlashMode::Keep,
            normalization_action: RewriteAction::InternalRewrite,
            exact_rules: Vec::new(),
            prefix_rules: Vec::new(),
            regex_rules: Vec::new(),
        }
    }
}

/// Fluent configuration builders for [`RewriteConfig`].
impl RewriteConfig {
    /// Enables or disables redirecting non-HTTPS requests to `https://`.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether HTTPS is enforced.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_force_https(mut self, force_https: bool) -> Self {
        self.set_force_https(force_https);
        self
    }

    /// Sets the canonical host (for example `"example.com"`), redirecting mismatches in a single hop.
    ///
    /// # Arguments
    ///
    /// - `S` - Canonical host value.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_canonical_host<S>(mut self, host: S) -> Self
    where
        S: Into<String>,
    {
        self.set_canonical_host(Some(host.into()));
        self
    }

    /// Sets the redirect status code used for canonical host and HTTPS redirects.
    ///
    /// # Arguments
    ///
    /// - `RedirectStatus` - Redirect HTTP status (`301`/`302`/`307`/`308`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_canonical_redirect_status(mut self, status: RedirectStatus) -> Self {
        self.set_canonical_redirect_status(status);
        self
    }

    /// Enables or disables trusting `X-Forwarded-Proto` and `Forwarded` when detecting HTTPS.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether forwarded protocol headers are trusted.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_trust_forwarded_proto(mut self, trust: bool) -> Self {
        self.set_trust_forwarded_proto(trust);
        self
    }

    /// Enables or disables collapsing consecutive duplicate slashes (`"//"` -> `"/"`).
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether duplicate slashes are collapsed.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_collapse_duplicate_slashes(mut self, collapse: bool) -> Self {
        self.set_collapse_duplicate_slashes(collapse);
        self
    }

    /// Configures trailing-slash normalization (`Keep`, `Strip`, or `Enforce`) and its [`RewriteAction`].
    ///
    /// # Arguments
    ///
    /// - `TrailingSlashMode` - Desired trailing-slash policy.
    /// - `RewriteAction` - Whether normalization rewrites internally or redirects.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_trailing_slash(mut self, mode: TrailingSlashMode, action: RewriteAction) -> Self {
        self.set_trailing_slash(mode)
            .set_normalization_action(action);
        self
    }

    /// Adds an `O(1)` exact-path internal rewrite rule (`from` -> `to`).
    ///
    /// # Arguments
    ///
    /// - `F` - Exact incoming path.
    /// - `T` - Rewritten internal path.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exact_rewrite<F, T>(mut self, from: F, to: T) -> Self
    where
        F: Into<String>,
        T: Into<String>,
    {
        self.get_mut_exact_rules().push(ExactRewriteRule {
            from: from.into(),
            to: to.into(),
            action: RewriteAction::InternalRewrite,
            preserve_query: true,
        });
        self
    }

    /// Adds an `O(1)` exact-path short-circuit HTTP redirect rule (`from` -> `to`).
    ///
    /// # Arguments
    ///
    /// - `F` - Exact incoming path.
    /// - `T` - Redirect destination path or URL.
    /// - `RedirectStatus` - Redirect HTTP status code.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exact_redirect<F, T>(mut self, from: F, to: T, status: RedirectStatus) -> Self
    where
        F: Into<String>,
        T: Into<String>,
    {
        self.get_mut_exact_rules().push(ExactRewriteRule {
            from: from.into(),
            to: to.into(),
            action: RewriteAction::Redirect(status),
            preserve_query: true,
        });
        self
    }

    /// Adds a segment-bounded prefix strip rule (for example `"/api/v1"` strips `"/api/v1"` internally).
    ///
    /// # Arguments
    ///
    /// - `F` - Incoming path prefix to strip.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_strip_prefix<F>(mut self, from: F) -> Self
    where
        F: Into<String>,
    {
        self.get_mut_prefix_rules().push(PrefixRewriteRule {
            from: from.into(),
            to: String::new(),
            action: RewriteAction::InternalRewrite,
            preserve_query: true,
        });
        self
    }

    /// Adds a segment-bounded prefix rewrite or redirect rule (`from` -> `to`).
    ///
    /// # Arguments
    ///
    /// - `F` - Incoming path prefix.
    /// - `T` - Replacement prefix.
    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_prefix_rule<F, T>(mut self, from: F, to: T, action: RewriteAction) -> Self
    where
        F: Into<String>,
        T: Into<String>,
    {
        self.get_mut_prefix_rules().push(PrefixRewriteRule {
            from: from.into(),
            to: to.into(),
            action,
            preserve_query: true,
        });
        self
    }

    /// Adds a regular-expression rewrite or redirect rule supporting capture replacements (`$1`, `$2`).
    ///
    /// # Arguments
    ///
    /// - `P` - Regular expression pattern.
    /// - `R` - Replacement template.
    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_regex_rule<P, R>(
        mut self,
        pattern: P,
        replacement: R,
        action: RewriteAction,
    ) -> Self
    where
        P: Into<String>,
        R: Into<String>,
    {
        self.get_mut_regex_rules().push(RegexRewriteRule {
            pattern: pattern.into(),
            replacement: replacement.into(),
            action,
            preserve_query: true,
        });
        self
    }
}

/// Inherent compilation and hot-path request evaluation for [`CompiledRewrite`].
impl CompiledRewrite {
    /// Compiles and validates `config` into `O(1)` zero-allocation hash tables and optimized matchers.
    ///
    /// # Arguments
    ///
    /// - `RewriteConfig` - Source rewrite configuration.
    ///
    /// # Returns
    ///
    /// - `Result<Self, RewriteError>` - Compiled rewrite engine or validation/regex error.
    pub fn compile(config: RewriteConfig) -> Result<Self, RewriteError> {
        let canonical_host_lower: Option<String> = match config.try_get_canonical_host() {
            Some(host) => {
                let trimmed: &str = host.trim();
                if has_unsafe_header_chars(trimmed) {
                    return Err(RewriteError::UnsafeLocation(trimmed.to_owned()));
                }
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_ascii_lowercase())
                }
            }
            None => None,
        };
        let (canonical_https_origin, canonical_http_origin): (Option<String>, Option<String>) =
            match canonical_host_lower.as_deref() {
                Some(host) => {
                    let mut https_origin: String = String::with_capacity(
                        SCHEME_HTTPS.len() + SCHEME_SEPARATOR.len() + host.len(),
                    );
                    https_origin.push_str(SCHEME_HTTPS);
                    https_origin.push_str(SCHEME_SEPARATOR);
                    https_origin.push_str(host);
                    let mut http_origin: String = String::with_capacity(
                        SCHEME_HTTP.len() + SCHEME_SEPARATOR.len() + host.len(),
                    );
                    http_origin.push_str(SCHEME_HTTP);
                    http_origin.push_str(SCHEME_SEPARATOR);
                    http_origin.push_str(host);
                    (Some(https_origin), Some(http_origin))
                }
                None => (None, None),
            };
        let mut exact_map: FxHashMap<String, CompiledExactTarget> =
            HashMap::with_capacity_and_hasher(
                config.get_exact_rules().len(),
                BuildHasherDefault::default(),
            );
        for rule in config.get_exact_rules() {
            let to_str: &str = rule.get_to();
            if has_unsafe_header_chars(to_str) {
                return Err(RewriteError::UnsafeLocation(to_str.to_owned()));
            }
            exact_map.insert(
                rule.get_from().clone(),
                CompiledExactTarget {
                    has_query: to_str.as_bytes().contains(&BYTE_QUESTION),
                    to: to_str.to_owned(),
                    action: rule.get_action(),
                    preserve_query: rule.get_preserve_query(),
                },
            );
        }
        let mut prefix_rules: Vec<CompiledPrefixRule> =
            Vec::with_capacity(config.get_prefix_rules().len());
        for rule in config.get_prefix_rules() {
            let raw_to: &str = rule.get_to();
            if has_unsafe_header_chars(raw_to) {
                return Err(RewriteError::UnsafeLocation(raw_to.to_owned()));
            }
            let norm_from: String = normalize_rule_prefix(rule.get_from());
            if norm_from.is_empty() {
                continue;
            }
            let norm_to: String = if raw_to.is_empty() {
                String::new()
            } else {
                normalize_rule_prefix(raw_to)
            };
            let to_has_query: bool = norm_to.as_bytes().contains(&BYTE_QUESTION);
            prefix_rules.push(CompiledPrefixRule {
                from: norm_from,
                to: norm_to,
                action: rule.get_action(),
                preserve_query: rule.get_preserve_query(),
                to_has_query,
            });
        }
        prefix_rules.sort_by_key(|rule: &CompiledPrefixRule| Reverse(rule.from.len()));
        let mut regex_rules: Vec<CompiledRegexRule> =
            Vec::with_capacity(config.get_regex_rules().len());
        let mut general_patterns: Vec<&str> = Vec::new();
        for rule in config.get_regex_rules() {
            let repl: &str = rule.get_replacement();
            if has_unsafe_header_chars(repl) {
                return Err(RewriteError::UnsafeLocation(repl.to_owned()));
            }
            let matcher: CompiledRegexMatcher =
                if let Some(fast) = try_compile_fast_regex(rule.get_pattern(), repl) {
                    fast
                } else {
                    let compiled_regex: Regex =
                        Regex::new(rule.get_pattern()).map_err(|e: Error| {
                            RewriteError::InvalidRegex {
                                pattern: rule.get_pattern().clone(),
                                message: e.to_string(),
                            }
                        })?;
                    general_patterns.push(rule.get_pattern().as_str());
                    CompiledRegexMatcher::General {
                        regex: compiled_regex,
                        replacement: repl.to_owned(),
                        has_expand: repl.as_bytes().contains(&BYTE_DOLLAR),
                    }
                };
            regex_rules.push(CompiledRegexRule {
                matcher,
                action: rule.get_action(),
                preserve_query: rule.get_preserve_query(),
            });
        }
        let general_regex_set: Option<RegexSet> = if general_patterns.len() >= 2 {
            RegexSet::new(&general_patterns).ok()
        } else {
            None
        };
        Ok(Self {
            config,
            canonical_host_lower,
            canonical_https_origin,
            canonical_http_origin,
            exact_map,
            prefix_rules,
            regex_rules,
            general_regex_set,
        })
    }

    /// Returns the source [`RewriteConfig`].
    ///
    /// # Returns
    ///
    /// - `&RewriteConfig` - Active configuration.
    #[inline]
    pub fn get_config(&self) -> &RewriteConfig {
        let Self { config, .. } = self;
        config
    }

    /// Evaluates regex rules using fast matchers and an optional combined `RegexSet` prefilter.
    ///
    /// # Arguments
    ///
    /// - `&str` - Normalized working path.
    ///
    /// # Returns
    ///
    /// - `Option<(String, RewriteAction, bool)>` - Matched replacement, action, and query preservation flag.
    #[inline]
    fn match_regex_rules(&self, working_path: &str) -> Option<(String, RewriteAction, bool)> {
        let Self {
            regex_rules,
            general_regex_set,
            ..
        } = self;
        let mut general_checked: bool = false;
        let mut general_any_match: bool = true;
        for rule in regex_rules {
            if matches!(rule.matcher, CompiledRegexMatcher::General { .. }) {
                if !general_checked {
                    general_checked = true;
                    if let Some(set) = general_regex_set {
                        general_any_match = set.is_match(working_path);
                    }
                }
                if !general_any_match {
                    continue;
                }
            }
            if let Some(replaced) = match_compiled_regex(&rule.matcher, working_path) {
                return Some((replaced, rule.action, rule.preserve_query));
            }
        }
        None
    }

    /// Evaluates canonical host/HTTPS, path normalization, exact, prefix, and regex rules against `ctx`.
    ///
    /// On an internal rewrite, updates `ctx.get_mut_request().set_path(...)` and stores the original
    /// path under [`ATTR_ORIGINAL_PATH`]. On a redirect, populates `ctx.get_mut_response()` with the
    /// redirect status code and sanitized `Location` header.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Active Hyperlane request/response context.
    ///
    /// # Returns
    ///
    /// - `RewriteOutcome` - Whether the request was unchanged, rewritten internally, or redirected.
    pub fn apply(&self, ctx: &mut Context) -> RewriteOutcome {
        let Self {
            config,
            canonical_host_lower,
            canonical_https_origin,
            canonical_http_origin,
            exact_map,
            prefix_rules,
            regex_rules,
            ..
        } = self;
        if config.get_force_https() || canonical_host_lower.is_some() {
            let headers: &RequestHeaders = ctx.get_request().get_headers();
            let req_https: bool = is_request_https(headers, config.get_trust_forwarded_proto());
            let needs_https: bool = config.get_force_https() && !req_https;
            let req_host_ref: Option<&str> = find_header_back_ref(headers, HOST);
            let needs_host_redirect: bool = match (canonical_host_lower.as_deref(), req_host_ref) {
                (Some(canonical), Some(incoming)) => !host_matches_canonical(incoming, canonical),
                (Some(_), None) => true,
                (None, _) => false,
            };
            if needs_https || needs_host_redirect {
                let use_https: bool = config.get_force_https() || req_https;
                let prebuilt_origin: Option<&str> = if use_https {
                    canonical_https_origin.as_deref()
                } else {
                    canonical_http_origin.as_deref()
                };
                let raw_path: &str = ctx.get_request().get_path();
                let mut location: Option<String> = None;
                if let Some(origin) = prebuilt_origin {
                    let mut loc: String = String::with_capacity(origin.len() + raw_path.len() + 16);
                    loc.push_str(origin);
                    loc.push_str(raw_path);
                    location = Some(loc);
                } else if let Some(host) = req_host_ref
                    && !host.is_empty()
                    && !has_unsafe_header_chars(host)
                {
                    let scheme: &str = if use_https { SCHEME_HTTPS } else { SCHEME_HTTP };
                    let mut loc: String = String::with_capacity(
                        scheme.len() + SCHEME_SEPARATOR.len() + host.len() + raw_path.len() + 16,
                    );
                    loc.push_str(scheme);
                    loc.push_str(SCHEME_SEPARATOR);
                    loc.push_str(host);
                    loc.push_str(raw_path);
                    location = Some(loc);
                }
                if let Some(mut final_loc) = location {
                    append_query_from_ctx(&mut final_loc, ctx, true, false);
                    let status_code: usize = config.get_canonical_redirect_status().code();
                    let resp: &mut Response = ctx.get_mut_response();
                    resp.set_status_code(status_code)
                        .set_header(LOCATION, &final_loc)
                        .set_body(Vec::new());
                    return RewriteOutcome::Redirected {
                        status_code,
                        location: final_loc,
                    };
                }
            }
        }
        let original_path: &str = ctx.get_request().get_path();
        let after_slash: Cow<'_, str> = if config.get_collapse_duplicate_slashes() {
            collapse_slashes(original_path)
        } else {
            Cow::Borrowed(original_path)
        };
        let slash_collapsed: bool = matches!(after_slash, Cow::Owned(_));
        let (normalized_path, trailing_changed): (Cow<'_, str>, bool) =
            normalize_trailing_slash_borrowed(after_slash, config.get_trailing_slash());
        let normalized_changed: bool = slash_collapsed || trailing_changed;
        if normalized_changed
            && let RewriteAction::Redirect(status) = config.get_normalization_action()
        {
            let mut location: String = normalized_path.into_owned();
            if !has_unsafe_header_chars(&location) {
                let has_q: bool = location.as_bytes().contains(&BYTE_QUESTION);
                append_query_from_ctx(&mut location, ctx, true, has_q);
                let status_code: usize = status.code();
                ctx.get_mut_response()
                    .set_status_code(status_code)
                    .set_header(LOCATION, &location)
                    .set_body(Vec::new());
                return RewriteOutcome::Redirected {
                    status_code,
                    location,
                };
            }
            return RewriteOutcome::Unchanged;
        }
        let working_path: &str = normalized_path.as_ref();
        if !exact_map.is_empty()
            && let Some(hit) = exact_map.get(working_path)
        {
            match hit.action {
                RewriteAction::Redirect(status) => {
                    let location: String =
                        clone_with_query_from_ctx(&hit.to, ctx, hit.preserve_query, hit.has_query);
                    let status_code: usize = status.code();
                    ctx.get_mut_response()
                        .set_status_code(status_code)
                        .set_header(LOCATION, &location)
                        .set_body(Vec::new());
                    return RewriteOutcome::Redirected {
                        status_code,
                        location,
                    };
                }
                RewriteAction::InternalRewrite => {
                    let target: String = hit.to.clone();
                    apply_internal_rewrite_copy(ctx, &target);
                    return RewriteOutcome::Rewritten(target);
                }
            }
        }
        let mut matched: Option<(String, RewriteAction, bool, bool)> = None;
        for rule in prefix_rules {
            if let Some(rest) = strip_prefix_segment(working_path, &rule.from) {
                let replaced: String = join_prefix_replacement(&rule.to, rest);
                let has_q: bool = rule.to_has_query || rest.as_bytes().contains(&BYTE_QUESTION);
                matched = Some((replaced, rule.action, rule.preserve_query, has_q));
                break;
            }
        }
        if matched.is_none()
            && !regex_rules.is_empty()
            && let Some((replaced, action, preserve_query)) = self.match_regex_rules(working_path)
        {
            let has_q: bool = replaced.as_bytes().contains(&BYTE_QUESTION);
            matched = Some((replaced, action, preserve_query, has_q));
        }
        if let Some((mut target, action, preserve_query, has_q)) = matched {
            match action {
                RewriteAction::Redirect(status) => {
                    if has_unsafe_header_chars(&target) {
                        return RewriteOutcome::Unchanged;
                    }
                    append_query_from_ctx(&mut target, ctx, preserve_query, has_q);
                    let status_code: usize = status.code();
                    ctx.get_mut_response()
                        .set_status_code(status_code)
                        .set_header(LOCATION, &target)
                        .set_body(Vec::new());
                    return RewriteOutcome::Redirected {
                        status_code,
                        location: target,
                    };
                }
                RewriteAction::InternalRewrite => {
                    apply_internal_rewrite_copy(ctx, &target);
                    return RewriteOutcome::Rewritten(target);
                }
            }
        }
        if normalized_changed {
            let new_path: String = normalized_path.into_owned();
            apply_internal_rewrite_copy(ctx, &new_path);
            return RewriteOutcome::Rewritten(new_path);
        }
        RewriteOutcome::Unchanged
    }

    /// Evaluates rewrite rules for [`RewriteHook`] without cloning discarded outcome strings and sends redirects directly on HTTP/1.1.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Active client connection stream.
    /// - `&mut Context` - Active Hyperlane request/response context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` when a redirect was sent; `Status::Continue` otherwise.
    #[inline]
    pub(crate) async fn apply_and_send_hook(
        &self,
        stream: &mut Stream,
        ctx: &mut Context,
    ) -> Status {
        let Self {
            config,
            canonical_host_lower,
            canonical_https_origin,
            canonical_http_origin,
            exact_map,
            prefix_rules,
            regex_rules,
            ..
        } = self;
        let resp: &Response = ctx.get_response();
        let can_fast_wire: bool = ctx.get_request().get_version().is_http1_1()
            && resp.get_version().is_http1_1()
            && resp.get_headers().is_empty()
            && (resp.get_reason_phrase().is_empty() || resp.get_reason_phrase().as_str() == OK);
        if config.get_force_https() || canonical_host_lower.is_some() {
            let headers: &RequestHeaders = ctx.get_request().get_headers();
            let req_https: bool = is_request_https(headers, config.get_trust_forwarded_proto());
            let needs_https: bool = config.get_force_https() && !req_https;
            let req_host_ref: Option<&str> = find_header_back_ref(headers, HOST);
            let needs_host_redirect: bool = match (canonical_host_lower.as_deref(), req_host_ref) {
                (Some(canonical), Some(incoming)) => !host_matches_canonical(incoming, canonical),
                (Some(_), None) => true,
                (None, _) => false,
            };
            if needs_https || needs_host_redirect {
                let use_https: bool = config.get_force_https() || req_https;
                let status: RedirectStatus = config.get_canonical_redirect_status();
                let prebuilt_origin: Option<&str> = if use_https {
                    canonical_https_origin.as_deref()
                } else {
                    canonical_http_origin.as_deref()
                };
                if can_fast_wire {
                    let raw_path: &str = ctx.get_request().get_path();
                    let wire_prefix: &[u8] = redirect_wire_prefix(status);
                    let mut stack: [u8; REDIRECT_WIRE_STACK_CAP] = [0u8; REDIRECT_WIRE_STACK_CAP];
                    let mut pos: usize = wire_prefix.len();
                    let host_ok: bool = if let Some(origin) = prebuilt_origin {
                        let ob: &[u8] = origin.as_bytes();
                        let pb: &[u8] = raw_path.as_bytes();
                        if pos + ob.len() + pb.len() + WIRE_HEADER_END.len()
                            <= REDIRECT_WIRE_STACK_CAP
                        {
                            stack[..pos].copy_from_slice(wire_prefix);
                            stack[pos..pos + ob.len()].copy_from_slice(ob);
                            pos += ob.len();
                            stack[pos..pos + pb.len()].copy_from_slice(pb);
                            pos += pb.len();
                            true
                        } else {
                            false
                        }
                    } else if let Some(host) = req_host_ref
                        && !host.is_empty()
                        && !has_unsafe_header_chars(host)
                    {
                        let scheme: &[u8] = if use_https {
                            SCHEME_HTTPS.as_bytes()
                        } else {
                            SCHEME_HTTP.as_bytes()
                        };
                        let sep: &[u8] = SCHEME_SEPARATOR.as_bytes();
                        let hb: &[u8] = host.as_bytes();
                        let pb: &[u8] = raw_path.as_bytes();
                        if pos
                            + scheme.len()
                            + sep.len()
                            + hb.len()
                            + pb.len()
                            + WIRE_HEADER_END.len()
                            <= REDIRECT_WIRE_STACK_CAP
                        {
                            stack[..pos].copy_from_slice(wire_prefix);
                            stack[pos..pos + scheme.len()].copy_from_slice(scheme);
                            pos += scheme.len();
                            stack[pos..pos + sep.len()].copy_from_slice(sep);
                            pos += sep.len();
                            stack[pos..pos + hb.len()].copy_from_slice(hb);
                            pos += hb.len();
                            stack[pos..pos + pb.len()].copy_from_slice(pb);
                            pos += pb.len();
                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    };
                    if host_ok
                        && let Some(end_q) = write_query_bytes_from_ctx(
                            &mut stack[..REDIRECT_WIRE_STACK_CAP - WIRE_HEADER_END.len()],
                            pos,
                            ctx,
                            true,
                            false,
                        )
                        && is_valid_wire_header_value_bytes(&stack[wire_prefix.len()..end_q])
                    {
                        let total: usize = end_q + WIRE_HEADER_END.len();
                        stack[end_q..total].copy_from_slice(WIRE_HEADER_END);
                        let _: Result<(), ResponseError> = stream.try_send(&stack[..total]).await;
                        return Status::Reject;
                    }
                }
                if matches!(self.apply(ctx), RewriteOutcome::Redirected { .. }) {
                    let wire: Vec<u8> = ctx.get_mut_response().build();
                    let _: Result<(), ResponseError> = stream.try_send(&wire).await;
                    return Status::Reject;
                }
                return Status::Continue;
            }
        }
        let original_path: &str = ctx.get_request().get_path();
        let after_slash: Cow<'_, str> = if config.get_collapse_duplicate_slashes() {
            collapse_slashes(original_path)
        } else {
            Cow::Borrowed(original_path)
        };
        let slash_collapsed: bool = matches!(after_slash, Cow::Owned(_));
        let (normalized_path, trailing_changed): (Cow<'_, str>, bool) =
            normalize_trailing_slash_borrowed(after_slash, config.get_trailing_slash());
        let normalized_changed: bool = slash_collapsed || trailing_changed;
        if normalized_changed
            && let RewriteAction::Redirect(status) = config.get_normalization_action()
        {
            let has_q: bool = normalized_path.as_bytes().contains(&BYTE_QUESTION);
            if has_unsafe_header_chars(normalized_path.as_ref()) {
                return Status::Continue;
            }
            if can_fast_wire {
                let mut stack: [u8; REDIRECT_WIRE_STACK_CAP] = [0u8; REDIRECT_WIRE_STACK_CAP];
                if let Some(total) = Self::format_redirect_wire_stack(
                    ctx,
                    status,
                    normalized_path.as_ref(),
                    true,
                    has_q,
                    &mut stack,
                ) {
                    let _: Result<(), ResponseError> = stream.try_send(&stack[..total]).await;
                    return Status::Reject;
                }
            }
            let target_owned: String = normalized_path.into_owned();
            return Self::send_redirect_fallback(stream, ctx, status, target_owned, true, has_q)
                .await;
        }
        let working_path: &str = normalized_path.as_ref();
        if !exact_map.is_empty()
            && let Some(hit) = exact_map.get(working_path)
        {
            match hit.action {
                RewriteAction::Redirect(status) => {
                    return Self::send_redirect_location(
                        stream,
                        ctx,
                        status,
                        &hit.to,
                        hit.preserve_query,
                        hit.has_query,
                        can_fast_wire,
                    )
                    .await;
                }
                RewriteAction::InternalRewrite => {
                    let target: String = hit.to.clone();
                    apply_internal_rewrite_owned(ctx, target);
                    return Status::Continue;
                }
            }
        }
        let mut matched: Option<(String, RewriteAction, bool, bool)> = None;
        for rule in prefix_rules {
            if let Some(rest) = strip_prefix_segment(working_path, &rule.from) {
                let replaced: String = join_prefix_replacement(&rule.to, rest);
                let has_q: bool = rule.to_has_query || rest.as_bytes().contains(&BYTE_QUESTION);
                matched = Some((replaced, rule.action, rule.preserve_query, has_q));
                break;
            }
        }
        if matched.is_none()
            && !regex_rules.is_empty()
            && let Some((replaced, action, preserve_query)) = self.match_regex_rules(working_path)
        {
            let has_q: bool = replaced.as_bytes().contains(&BYTE_QUESTION);
            matched = Some((replaced, action, preserve_query, has_q));
        }
        if let Some((target, action, preserve_query, has_q)) = matched {
            match action {
                RewriteAction::Redirect(status) => {
                    if has_unsafe_header_chars(&target) {
                        return Status::Continue;
                    }
                    return Self::send_redirect_location(
                        stream,
                        ctx,
                        status,
                        &target,
                        preserve_query,
                        has_q,
                        can_fast_wire,
                    )
                    .await;
                }
                RewriteAction::InternalRewrite => {
                    apply_internal_rewrite_owned(ctx, target);
                    return Status::Continue;
                }
            }
        }
        if normalized_changed {
            let new_path: String = normalized_path.into_owned();
            apply_internal_rewrite_owned(ctx, new_path);
        }
        Status::Continue
    }

    /// Formats an HTTP/1.1 redirect wire response into `stack` with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Active request context.
    /// - `RedirectStatus` - Redirect HTTP status code.
    /// - `&str` - Validated base redirect location.
    /// - `bool` - Whether to append incoming query parameters.
    /// - `bool` - Whether `base_location` already contains `'?'`.
    /// - `&mut [u8; REDIRECT_WIRE_STACK_CAP]` - Destination stack wire buffer.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Total wire bytes written when it fits in `stack`.
    #[inline]
    fn format_redirect_wire_stack(
        ctx: &Context,
        status: RedirectStatus,
        base_location: &str,
        preserve_query: bool,
        target_has_query: bool,
        stack: &mut [u8; REDIRECT_WIRE_STACK_CAP],
    ) -> Option<usize> {
        let wire_prefix: &[u8] = redirect_wire_prefix(status);
        let loc_bytes: &[u8] = base_location.as_bytes();
        let prefix_total: usize = wire_prefix.len() + loc_bytes.len();
        if prefix_total + WIRE_HEADER_END.len() > REDIRECT_WIRE_STACK_CAP {
            return None;
        }
        stack[..wire_prefix.len()].copy_from_slice(wire_prefix);
        stack[wire_prefix.len()..prefix_total].copy_from_slice(loc_bytes);
        let end_q: usize = write_query_bytes_from_ctx(
            &mut stack[..REDIRECT_WIRE_STACK_CAP - WIRE_HEADER_END.len()],
            prefix_total,
            ctx,
            preserve_query,
            target_has_query,
        )?;
        if !is_valid_wire_header_value_bytes(&stack[wire_prefix.len()..end_q]) {
            return None;
        }
        let total: usize = end_q + WIRE_HEADER_END.len();
        stack[end_q..total].copy_from_slice(WIRE_HEADER_END);
        Some(total)
    }

    /// Sends a redirect via full [`Response::build`] when stack wire fast path is ineligible.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Active client stream.
    /// - `&mut Context` - Active request/response context.
    /// - `RedirectStatus` - Redirect HTTP status code.
    /// - `String` - Owned base redirect location.
    /// - `bool` - Whether to append incoming query parameters.
    /// - `bool` - Whether `location` already contains `'?'`.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Reject`.
    #[inline]
    async fn send_redirect_fallback(
        stream: &mut Stream,
        ctx: &mut Context,
        status: RedirectStatus,
        mut location: String,
        preserve_query: bool,
        target_has_query: bool,
    ) -> Status {
        append_query_from_ctx(&mut location, ctx, preserve_query, target_has_query);
        let status_code: usize = status.code();
        ctx.get_mut_response()
            .set_status_code(status_code)
            .set_header(LOCATION, &location)
            .set_body(Vec::new());
        let wire: Vec<u8> = ctx.get_mut_response().build();
        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
        Status::Reject
    }

    /// Sends a redirect response for `base_location`, using a zero-allocation stack wire buffer on HTTP/1.1.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Active client stream.
    /// - `&mut Context` - Active request/response context.
    /// - `RedirectStatus` - Redirect HTTP status code.
    /// - `&str` - Validated base redirect location.
    /// - `bool` - Whether to append incoming query parameters.
    /// - `bool` - Whether `base_location` already contains `'?'`.
    /// - `bool` - Whether HTTP/1.1 stack wire fast path is eligible.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Reject`.
    #[inline]
    async fn send_redirect_location(
        stream: &mut Stream,
        ctx: &mut Context,
        status: RedirectStatus,
        base_location: &str,
        preserve_query: bool,
        target_has_query: bool,
        can_fast_wire: bool,
    ) -> Status {
        if can_fast_wire {
            let mut stack: [u8; REDIRECT_WIRE_STACK_CAP] = [0u8; REDIRECT_WIRE_STACK_CAP];
            if let Some(total) = Self::format_redirect_wire_stack(
                ctx,
                status,
                base_location,
                preserve_query,
                target_has_query,
                &mut stack,
            ) {
                let _: Result<(), ResponseError> = stream.try_send(&stack[..total]).await;
                return Status::Reject;
            }
        }
        Self::send_redirect_fallback(
            stream,
            ctx,
            status,
            base_location.to_owned(),
            preserve_query,
            target_has_query,
        )
        .await
    }
}

/// Process-wide singleton management for [`RewritePlugin`].
impl RewritePlugin {
    /// Compiles `config` and initializes the global [`RewritePlugin`] once.
    ///
    /// # Arguments
    ///
    /// - `RewriteConfig` - Rewrite and redirect configuration.
    ///
    /// # Returns
    ///
    /// - `Result<&'static Self, RewriteError>` - Reference to the initialized global plugin or compilation error.
    pub fn init(config: RewriteConfig) -> Result<&'static Self, RewriteError> {
        let compiled: CompiledRewrite = CompiledRewrite::compile(config)?;
        Ok(REWRITE_PLUGIN.get_or_init(|| Self { compiled }))
    }

    /// Returns the initialized global [`RewritePlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline]
    pub fn get() -> Option<&'static Self> {
        REWRITE_PLUGIN.get()
    }

    /// Returns the compiled [`CompiledRewrite`] engine.
    ///
    /// # Returns
    ///
    /// - `&CompiledRewrite` - Precompiled rewrite engine.
    #[inline]
    pub fn get_compiled(&self) -> &CompiledRewrite {
        let Self { compiled } = self;
        compiled
    }
}

/// Implements [`ServerHook`] for [`RewriteHook`].
impl ServerHook for RewriteHook {
    /// Constructs a per-request [`RewriteHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Applies rewrite/redirect rules, short-circuiting on HTTP redirects or continuing on rewrites.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` after sending redirect bytes; `Status::Continue` otherwise.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = RewritePlugin::get() else {
            return Status::Continue;
        };
        plugin.get_compiled().apply_and_send_hook(stream, ctx).await
    }
}