Skip to main content

hyperlane_plugin_gateway/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`RateLimitConfig`].
4impl RateLimitConfig {
5    /// Creates a [`RateLimitConfig`] with sustained `requests_per_second` and `burst` capacity.
6    ///
7    /// # Arguments
8    ///
9    /// - `u64` - Sustained requests per second.
10    /// - `u64` - Maximum burst token capacity.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Constructed rate-limit parameters.
15    pub fn new(requests_per_second: u64, burst: u64) -> Self {
16        Self {
17            requests_per_second,
18            burst,
19        }
20    }
21}
22
23/// Inherent implementation of [`UpstreamTarget`].
24impl UpstreamTarget {
25    /// Creates an [`UpstreamTarget`] with default load-balancing weight `1`.
26    ///
27    /// # Arguments
28    ///
29    /// - `U` - Upstream base URL convertible into `String`.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Upstream target with weight `1`.
34    pub fn new<U>(url: U) -> Self
35    where
36        U: Into<String>,
37    {
38        Self {
39            url: url.into(),
40            weight: 1,
41        }
42    }
43
44    /// Sets a custom positive load-balancing weight (clamped to `>= 1`).
45    ///
46    /// # Arguments
47    ///
48    /// - `u32` - Desired relative weight.
49    ///
50    /// # Returns
51    ///
52    /// - `Self` - Updated upstream target.
53    pub fn with_weight(mut self, weight: u32) -> Self {
54        self.set_weight(weight.max(1));
55        self
56    }
57}
58
59/// Inherent implementation of [`GatewayRoute`].
60impl GatewayRoute {
61    /// Creates a new [`GatewayRoute`] matching `prefix` and forwarding to `upstreams`.
62    ///
63    /// # Arguments
64    ///
65    /// - `P` - Path prefix convertible into `String`.
66    /// - `Vec<UpstreamTarget>` - Upstream backend pool for this route.
67    ///
68    /// # Returns
69    ///
70    /// - `Self` - Route with default round-robin balancing and 10 s timeout.
71    pub fn new<P>(prefix: P, upstreams: Vec<UpstreamTarget>) -> Self
72    where
73        P: Into<String>,
74    {
75        Self {
76            prefix: prefix.into(),
77            strip_prefix: false,
78            host: None,
79            upstreams,
80            strategy: LoadBalanceStrategy::RoundRobin,
81            timeout_ms: DEFAULT_UPSTREAM_TIMEOUT_MS,
82            max_retries: 0,
83            rate_limit: None,
84            use_http2: false,
85        }
86    }
87
88    /// Configures whether the matched prefix is stripped before forwarding upstream.
89    ///
90    /// # Arguments
91    ///
92    /// - `bool` - `true` to strip prefix.
93    ///
94    /// # Returns
95    ///
96    /// - `Self` - Updated route.
97    pub fn with_strip_prefix(mut self, strip_prefix: bool) -> Self {
98        self.set_strip_prefix(strip_prefix);
99        self
100    }
101
102    /// Configures the upstream load-balancing strategy.
103    ///
104    /// # Arguments
105    ///
106    /// - `LoadBalanceStrategy` - Desired selection algorithm.
107    ///
108    /// # Returns
109    ///
110    /// - `Self` - Updated route.
111    pub fn with_strategy(mut self, strategy: LoadBalanceStrategy) -> Self {
112        self.set_strategy(strategy);
113        self
114    }
115
116    /// Configures an optional per-route lock-free GCRA rate limiter.
117    ///
118    /// # Arguments
119    ///
120    /// - `RateLimitConfig` - Sustained rate and burst parameters.
121    ///
122    /// # Returns
123    ///
124    /// - `Self` - Updated route.
125    pub fn with_rate_limit(mut self, rate_limit: RateLimitConfig) -> Self {
126        self.set_rate_limit(Some(rate_limit));
127        self
128    }
129}
130
131/// Default construction for [`GatewayConfig`].
132impl Default for GatewayConfig {
133    /// Constructs a default [`GatewayConfig`] value.
134    fn default() -> Self {
135        Self {
136            routes: Vec::new(),
137            max_body_size: DEFAULT_GATEWAY_MAX_BODY_SIZE,
138            circuit_failure_threshold: DEFAULT_CIRCUIT_FAILURE_THRESHOLD,
139            circuit_reset_ms: DEFAULT_CIRCUIT_RESET_MS,
140        }
141    }
142}
143
144/// Inherent implementation of [`FastModU64`].
145impl FastModU64 {
146    /// Precomputes a division-free modulo table for `divisor` (clamped to `>= 1`).
147    ///
148    /// # Arguments
149    ///
150    /// - `usize` - Positive divisor.
151    ///
152    /// # Returns
153    ///
154    /// - `Self` - Precomputed modulo helper.
155    pub(crate) fn new(divisor: usize) -> Self {
156        let d: u64 = (divisor.max(1)) as u64;
157        if d.is_power_of_two() {
158            return Self {
159                divisor: d,
160                pow2_mask: d - 1,
161                mult: 0,
162                shift: 0,
163                is_pow2: true,
164            };
165        }
166        let l: u32 = 64 - d.leading_zeros();
167        let mult: u64 = if l <= 63 {
168            let m_full: u128 = ((1u128 << (64 + l)) / u128::from(d)) + 1;
169            (m_full - (1u128 << 64)) as u64
170        } else {
171            0
172        };
173        Self {
174            divisor: d,
175            pow2_mask: 0,
176            mult,
177            shift: l.saturating_sub(1),
178            is_pow2: false,
179        }
180    }
181
182    /// Computes `n % self.divisor` without executing a hardware division instruction.
183    ///
184    /// # Arguments
185    ///
186    /// - `usize` - Dividend.
187    ///
188    /// # Returns
189    ///
190    /// - `usize` - Remainder in `0..self.divisor`.
191    #[inline(always)]
192    pub(crate) fn rem(&self, n: usize) -> usize {
193        let Self {
194            divisor,
195            pow2_mask,
196            mult,
197            shift,
198            is_pow2,
199        } = *self;
200        let x: u64 = n as u64;
201        if is_pow2 {
202            return (x & pow2_mask) as usize;
203        }
204        if mult == 0 {
205            return (x % divisor) as usize;
206        }
207        let t: u64 = ((u128::from(mult) * u128::from(x)) >> 64) as u64;
208        let q: u64 = (((x - t) >> 1) + t) >> shift;
209        (x - q * divisor) as usize
210    }
211}
212
213/// Inherent implementation of [`TokenBucket`].
214impl TokenBucket {
215    /// Builds a lock-free GCRA token-bucket rate limiter from `config`.
216    ///
217    /// # Arguments
218    ///
219    /// - `RateLimitConfig` - Refill rate and burst capacity.
220    ///
221    /// # Returns
222    ///
223    /// - `Self` - Initialized full lock-free limiter.
224    pub(crate) fn new(config: RateLimitConfig) -> Self {
225        let rps: u64 = config.get_requests_per_second().max(1);
226        let burst: u64 = config.get_burst().max(1);
227        let emission_interval_ns: u64 = (NANOS_PER_SECOND / rps).max(1);
228        let burst_tolerance_ns: u64 = emission_interval_ns.saturating_mul(burst);
229        Self {
230            emission_interval_ns,
231            burst_tolerance_ns,
232            epoch: Instant::now(),
233            tat_ns: AtomicU64::new(0),
234        }
235    }
236
237    /// Attempts to consume one request token via a lock-free atomic CAS loop.
238    ///
239    /// # Returns
240    ///
241    /// - `bool` - `true` when permitted; `false` when rate-limited.
242    #[inline]
243    pub(crate) fn try_acquire(&self) -> bool {
244        let Self {
245            emission_interval_ns,
246            burst_tolerance_ns,
247            epoch,
248            tat_ns,
249        } = self;
250        let elapsed: Duration = epoch.elapsed();
251        let elapsed_ns: u64 = elapsed
252            .as_secs()
253            .saturating_mul(NANOS_PER_SECOND)
254            .saturating_add(u64::from(elapsed.subsec_nanos()));
255        let max_tat: u64 = elapsed_ns.saturating_add(*burst_tolerance_ns);
256        let mut observed: u64 = tat_ns.load(Ordering::Relaxed);
257        loop {
258            let base: u64 = observed.max(elapsed_ns);
259            let next_tat: u64 = base.saturating_add(*emission_interval_ns);
260            if next_tat > max_tat {
261                return false;
262            }
263            match tat_ns.compare_exchange_weak(
264                observed,
265                next_tat,
266                Ordering::Relaxed,
267                Ordering::Relaxed,
268            ) {
269                Ok(_) => return true,
270                Err(actual) => observed = actual,
271            }
272        }
273    }
274}
275
276/// Inherent implementation of [`UpstreamRuntime`].
277impl UpstreamRuntime {
278    /// Reports whether this upstream's circuit breaker is closed or ready to probe, reading wall clock lazily.
279    ///
280    /// # Arguments
281    ///
282    /// - `&mut Option<u64>` - Lazy cached Unix timestamp in milliseconds, populated only if a circuit is open.
283    ///
284    /// # Returns
285    ///
286    /// - `bool` - `true` when traffic may be dispatched to this upstream.
287    #[inline(always)]
288    pub(crate) fn is_available_lazy(&self, now_cache: &mut Option<u64>) -> bool {
289        let Self { open_until_ms, .. } = self;
290        let open_until: u64 = open_until_ms.load(Ordering::Relaxed);
291        if open_until == 0 {
292            return true;
293        }
294        let now_ms: u64 = *now_cache.get_or_insert_with(gateway_now_ms);
295        now_ms >= open_until
296    }
297
298    /// Records a successful upstream exchange, resetting failure count and closing the circuit.
299    #[inline]
300    pub(crate) fn record_success(&self) {
301        let Self {
302            consecutive_failures,
303            open_until_ms,
304            ..
305        } = self;
306        if consecutive_failures.load(Ordering::Relaxed) != 0 {
307            consecutive_failures.store(0, Ordering::Relaxed);
308        }
309        if open_until_ms.load(Ordering::Relaxed) != 0 {
310            open_until_ms.store(0, Ordering::Relaxed);
311        }
312    }
313
314    /// Records an upstream failure, opening the circuit when consecutive failures hit `threshold`.
315    ///
316    /// # Arguments
317    ///
318    /// - `u32` - Failure threshold required to trip the circuit.
319    /// - `u64` - Cooldown duration in milliseconds.
320    pub(crate) fn record_failure(&self, threshold: u32, reset_ms: u64) {
321        let Self {
322            consecutive_failures,
323            open_until_ms,
324            ..
325        } = self;
326        let failures: u32 = consecutive_failures.fetch_add(1, Ordering::Relaxed) + 1;
327        if threshold > 0 && failures >= threshold {
328            let until: u64 = gateway_now_ms().saturating_add(reset_ms);
329            open_until_ms.store(until, Ordering::Relaxed);
330        }
331    }
332}
333
334/// Inherent implementation of [`CompiledRoute`].
335impl CompiledRoute {
336    /// Selects one healthy upstream node reference without heap or atomic-refcount overhead.
337    ///
338    /// # Returns
339    ///
340    /// - `Option<&UpstreamRuntime>` - Borrowed chosen upstream, or `None` when all circuits are open.
341    #[inline]
342    pub(crate) fn select_upstream_ref(&self) -> Option<&UpstreamRuntime> {
343        let Self {
344            route,
345            upstreams,
346            upstreams_mod,
347            upstreams_minus1_mod,
348            weighted_ring,
349            weighted_ring_mod,
350            cursor,
351            ..
352        } = self;
353        let len: usize = upstreams.len();
354        if len == 0 {
355            return None;
356        }
357        let mut now_cache: Option<u64> = None;
358        if len == 1 {
359            let single: &UpstreamRuntime = &upstreams[0];
360            return single.is_available_lazy(&mut now_cache).then_some(single);
361        }
362        match route.get_strategy() {
363            LoadBalanceStrategy::RoundRobin => {
364                let start: usize = upstreams_mod.rem(cursor.fetch_add(1, Ordering::Relaxed));
365                let primary: &UpstreamRuntime = &upstreams[start];
366                if primary.is_available_lazy(&mut now_cache) {
367                    return Some(primary);
368                }
369                let mut idx: usize = start;
370                for _ in 1..len {
371                    idx += 1;
372                    if idx == len {
373                        idx = 0;
374                    }
375                    let candidate: &UpstreamRuntime = &upstreams[idx];
376                    if candidate.is_available_lazy(&mut now_cache) {
377                        return Some(candidate);
378                    }
379                }
380                None
381            }
382            LoadBalanceStrategy::LeastConnections => {
383                let mut best: Option<&UpstreamRuntime> = None;
384                let mut best_conns: usize = usize::MAX;
385                for candidate in upstreams.iter() {
386                    if candidate.is_available_lazy(&mut now_cache) {
387                        let conns: usize = candidate.active_conns.load(Ordering::Relaxed);
388                        if conns < best_conns {
389                            best_conns = conns;
390                            best = Some(candidate);
391                        }
392                    }
393                }
394                best
395            }
396            LoadBalanceStrategy::WeightedRoundRobin => {
397                if !weighted_ring.is_empty() {
398                    let ring_slot: usize =
399                        weighted_ring_mod.rem(cursor.fetch_add(1, Ordering::Relaxed));
400                    let candidate: &UpstreamRuntime = &upstreams[weighted_ring[ring_slot] as usize];
401                    if candidate.is_available_lazy(&mut now_cache) {
402                        return Some(candidate);
403                    }
404                }
405                let total_weight: usize = upstreams
406                    .iter()
407                    .filter(|node: &&UpstreamRuntime| node.is_available_lazy(&mut now_cache))
408                    .map(|node: &UpstreamRuntime| node.weight.max(1) as usize)
409                    .sum();
410                if total_weight == 0 {
411                    return None;
412                }
413                let mut slot: usize = cursor.fetch_add(1, Ordering::Relaxed) % total_weight;
414                for candidate in upstreams.iter() {
415                    if !candidate.is_available_lazy(&mut now_cache) {
416                        continue;
417                    }
418                    let w: usize = candidate.weight.max(1) as usize;
419                    if slot < w {
420                        return Some(candidate);
421                    }
422                    slot -= w;
423                }
424                None
425            }
426            LoadBalanceStrategy::PowerOfTwoChoices => {
427                let tick: usize = cursor.fetch_add(1, Ordering::Relaxed);
428                let idx_a: usize = upstreams_mod.rem(tick);
429                let step: usize =
430                    upstreams_minus1_mod.rem(tick.wrapping_mul(P2C_MIX_MULTIPLIER) >> 16) + 1;
431                let sum: usize = idx_a + step;
432                let idx_b: usize = if sum >= len { sum - len } else { sum };
433                let node_a: &UpstreamRuntime = &upstreams[idx_a];
434                let node_b: &UpstreamRuntime = &upstreams[idx_b];
435                let avail_a: bool = node_a.is_available_lazy(&mut now_cache);
436                let avail_b: bool = node_b.is_available_lazy(&mut now_cache);
437                match (avail_a, avail_b) {
438                    (true, true) => {
439                        if node_a.active_conns.load(Ordering::Relaxed)
440                            <= node_b.active_conns.load(Ordering::Relaxed)
441                        {
442                            Some(node_a)
443                        } else {
444                            Some(node_b)
445                        }
446                    }
447                    (true, false) => Some(node_a),
448                    (false, true) => Some(node_b),
449                    (false, false) => upstreams
450                        .iter()
451                        .find(|node: &&UpstreamRuntime| node.is_available_lazy(&mut now_cache)),
452                }
453            }
454        }
455    }
456}
457
458/// Inherent implementation of [`GatewayRuntime`].
459impl GatewayRuntime {
460    /// Compiles a [`GatewayConfig`] into an immutable longest-prefix-sorted [`GatewayRuntime`].
461    ///
462    /// # Arguments
463    ///
464    /// - `GatewayConfig` - Gateway routing and resilience configuration.
465    ///
466    /// # Returns
467    ///
468    /// - `Self` - Ready reverse-proxy runtime.
469    pub fn new(config: GatewayConfig) -> Self {
470        let mut any_host_route: bool = false;
471        let mut compiled: Vec<CompiledRoute> = config
472            .get_routes()
473            .iter()
474            .map(|route: &GatewayRoute| {
475                let normalized_prefix: String = normalize_prefix(route.get_prefix());
476                let normalized_host: Option<String> = route
477                    .get_host()
478                    .map(|h: String| h.trim().to_owned())
479                    .filter(|h: &String| !h.is_empty());
480                if normalized_host.is_some() {
481                    any_host_route = true;
482                }
483                let upstreams: Box<[UpstreamRuntime]> = route
484                    .get_upstreams()
485                    .iter()
486                    .map(|u: &UpstreamTarget| UpstreamRuntime {
487                        base_url: u.get_url().trim_end_matches('/').to_owned(),
488                        weight: u.get_weight().max(1),
489                        active_conns: AtomicUsize::new(0),
490                        consecutive_failures: AtomicU32::new(0),
491                        open_until_ms: AtomicU64::new(0),
492                    })
493                    .collect::<Vec<UpstreamRuntime>>()
494                    .into_boxed_slice();
495                let upstreams_len: usize = upstreams.len();
496                let upstreams_mod: FastModU64 = FastModU64::new(upstreams_len);
497                let upstreams_minus1_mod: FastModU64 =
498                    FastModU64::new(upstreams_len.saturating_sub(1));
499                let mut weighted_ring_vec: Vec<u16> = Vec::new();
500                if route.get_strategy() == LoadBalanceStrategy::WeightedRoundRobin
501                    && upstreams_len <= usize::from(u16::MAX)
502                {
503                    let total_weight: usize = upstreams
504                        .iter()
505                        .map(|u: &UpstreamRuntime| u.weight as usize)
506                        .sum();
507                    if total_weight > 0 && total_weight <= WEIGHTED_RING_MAX_LEN {
508                        weighted_ring_vec.reserve(total_weight);
509                        for (idx, u) in upstreams.iter().enumerate() {
510                            for _ in 0..u.weight {
511                                weighted_ring_vec.push(idx as u16);
512                            }
513                        }
514                    }
515                }
516                let weighted_ring_mod: FastModU64 = FastModU64::new(weighted_ring_vec.len());
517                let limiter: Option<TokenBucket> = route.get_rate_limit().map(TokenBucket::new);
518                CompiledRoute {
519                    route: route.clone(),
520                    normalized_prefix,
521                    normalized_host,
522                    upstreams,
523                    upstreams_mod,
524                    upstreams_minus1_mod,
525                    weighted_ring: weighted_ring_vec.into_boxed_slice(),
526                    weighted_ring_mod,
527                    cursor: AtomicUsize::new(0),
528                    limiter,
529                }
530            })
531            .collect();
532        compiled.sort_by(|a: &CompiledRoute, b: &CompiledRoute| {
533            b.normalized_prefix
534                .len()
535                .cmp(&a.normalized_prefix.len())
536                .then_with(|| {
537                    b.normalized_host
538                        .is_some()
539                        .cmp(&a.normalized_host.is_some())
540                })
541        });
542        Self {
543            config,
544            routes: Arc::from(compiled),
545            interceptors: Arc::from(Vec::new()),
546            any_host_route,
547        }
548    }
549
550    /// Returns a [`GatewayRuntime`] with an additional pluggable [`GatewayInterceptor`].
551    ///
552    /// # Arguments
553    ///
554    /// - `I` - Interceptor implementation.
555    ///
556    /// # Returns
557    ///
558    /// - `Self` - Updated runtime carrying the interceptor.
559    pub fn with_interceptor<I>(self, interceptor: I) -> Self
560    where
561        I: GatewayInterceptor,
562    {
563        let Self {
564            config,
565            routes,
566            interceptors,
567            any_host_route,
568        } = self;
569        let mut list: Vec<Arc<dyn GatewayInterceptor>> = interceptors.to_vec();
570        list.push(Arc::new(interceptor));
571        Self {
572            config,
573            routes,
574            interceptors: Arc::from(list),
575            any_host_route,
576        }
577    }
578
579    /// Returns a reference to the active [`GatewayConfig`].
580    ///
581    /// # Returns
582    ///
583    /// - `&GatewayConfig` - Gateway configuration.
584    #[inline(always)]
585    pub fn get_config(&self) -> &GatewayConfig {
586        &self.config
587    }
588
589    /// Matches the first compiled route accepting `host` and `path`.
590    ///
591    /// # Arguments
592    ///
593    /// - `Option<&str>` - Incoming `Host` header value.
594    /// - `&str` - Incoming request path.
595    ///
596    /// # Returns
597    ///
598    /// - `Option<&CompiledRoute>` - Best matching route, or `None`.
599    #[inline]
600    pub(crate) fn match_route(&self, host: Option<&str>, path: &str) -> Option<&CompiledRoute> {
601        let Self { routes, .. } = self;
602        for compiled in routes.iter() {
603            if !path_matches_prefix(path, &compiled.normalized_prefix) {
604                continue;
605            }
606            if let Some(ref required_host) = compiled.normalized_host {
607                let matches_host: bool = host.is_some_and(|incoming: &str| {
608                    incoming.trim().eq_ignore_ascii_case(required_host.as_str())
609                });
610                if !matches_host {
611                    continue;
612                }
613            }
614            return Some(compiled);
615        }
616        None
617    }
618
619    /// Matches the first compiled route accepting `ctx` without heap allocations.
620    ///
621    /// # Arguments
622    ///
623    /// - `&Context` - Incoming request context.
624    ///
625    /// # Returns
626    ///
627    /// - `Option<&CompiledRoute>` - Matched route, or `None`.
628    #[inline]
629    pub(crate) fn match_route_for_ctx(&self, ctx: &Context) -> Option<&CompiledRoute> {
630        let Self { any_host_route, .. } = self;
631        let req: &Request = ctx.get_request();
632        let host_hdr: Option<&str> = if *any_host_route {
633            request_header_back(req, HOST)
634        } else {
635            None
636        };
637        self.match_route(host_hdr, req.get_path())
638    }
639
640    /// Selects the next healthy upstream URL for a `(host, path)` pair (useful for inspection/testing).
641    ///
642    /// # Arguments
643    ///
644    /// - `Option<&str>` - Optional incoming `Host` header value.
645    /// - `&str` - Incoming request path.
646    ///
647    /// # Returns
648    ///
649    /// - `Option<String>` - Selected upstream base URL, or `None`.
650    #[inline]
651    pub fn select_target_url(&self, host: Option<&str>, path: &str) -> Option<String> {
652        let route: &CompiledRoute = self.match_route(host, path)?;
653        route
654            .select_upstream_ref()
655            .map(|node: &UpstreamRuntime| node.base_url.clone())
656    }
657
658    /// Forwards an incoming Hyperlane [`Context`] to the matched route's healthy upstream.
659    ///
660    /// # Arguments
661    ///
662    /// - `&mut Context` - Request and response context.
663    /// - `Option<&str>` - Optional client IP address for `X-Forwarded-For`.
664    ///
665    /// # Returns
666    ///
667    /// - `bool` - `true` when a route matched and populated `ctx.response`; `false` otherwise.
668    pub async fn forward(&self, ctx: &mut Context, peer_ip: Option<&str>) -> bool {
669        let Some(compiled) = self.match_route_for_ctx(ctx) else {
670            return false;
671        };
672        self.forward_matched(compiled, ctx, peer_ip).await;
673        true
674    }
675
676    /// Forwards `ctx` using an already-matched [`CompiledRoute`], avoiding duplicate route scans.
677    ///
678    /// # Arguments
679    ///
680    /// - `&CompiledRoute` - Matched gateway route.
681    /// - `&mut Context` - Request and response context.
682    /// - `Option<&str>` - Optional client IP address for `X-Forwarded-For`.
683    pub(crate) async fn forward_matched(
684        &self,
685        compiled: &CompiledRoute,
686        ctx: &mut Context,
687        peer_ip: Option<&str>,
688    ) {
689        let Self { interceptors, .. } = self;
690        if let Some(limiter) = &compiled.limiter
691            && !limiter.try_acquire()
692        {
693            ctx.get_mut_response()
694                .set_status_code(HttpStatus::TooManyRequests.code())
695                .set_body(&[] as &[u8]);
696            return;
697        }
698        if ctx.get_request().get_body().len() > self.get_config().get_max_body_size() {
699            ctx.get_mut_response()
700                .set_status_code(HttpStatus::PayloadTooLarge.code())
701                .set_body(&[] as &[u8]);
702            return;
703        }
704        let Some(upstream) = compiled.select_upstream_ref() else {
705            ctx.get_mut_response()
706                .set_status_code(HttpStatus::ServiceUnavailable.code())
707                .set_body(&[] as &[u8]);
708            return;
709        };
710        let target_url: String = build_upstream_url_from_request(
711            &upstream.base_url,
712            ctx.get_request(),
713            &compiled.normalized_prefix,
714            compiled.route.get_strip_prefix(),
715        );
716        for interceptor in interceptors.iter() {
717            if !interceptor.before_forward(ctx, &target_url) {
718                return;
719            }
720        }
721        let req: &Request = ctx.get_request();
722        let req_body: Vec<u8> = if req.get_body().is_empty() {
723            Vec::new()
724        } else {
725            req.get_body().clone()
726        };
727        let extra_hop: HashSet<String> = extract_request_connection_tokens(req);
728        let mut forward_headers: HashMap<String, String> =
729            HashMap::with_capacity(req.get_headers().len() + 3);
730        for (name, values) in req.get_headers() {
731            if (name.len() == HOST.len() && name.eq_ignore_ascii_case(HOST))
732                || (name.len() == HEADER_CONTENT_LENGTH.len()
733                    && name.eq_ignore_ascii_case(HEADER_CONTENT_LENGTH))
734                || is_hop_by_hop_header(name, &extra_hop)
735            {
736                continue;
737            }
738            if let Some(last) = values.back() {
739                let key: String = if name.bytes().any(|b: u8| b.is_ascii_uppercase()) {
740                    name.to_ascii_lowercase()
741                } else {
742                    name.clone()
743                };
744                forward_headers.insert(key, last.clone());
745            }
746        }
747        if let Some(client_ip) = peer_ip
748            && !client_ip.is_empty()
749        {
750            if let Some(prev) = forward_headers.get_mut(HEADER_X_FORWARDED_FOR) {
751                if prev.is_empty() {
752                    prev.push_str(client_ip);
753                } else {
754                    prev.reserve(2 + client_ip.len());
755                    prev.push_str(", ");
756                    prev.push_str(client_ip);
757                }
758            } else {
759                forward_headers.insert(HEADER_X_FORWARDED_FOR.to_owned(), client_ip.to_owned());
760            }
761        }
762        if let Some(original_host) = request_header_back(req, HOST)
763            && !forward_headers.contains_key(HEADER_X_FORWARDED_HOST)
764        {
765            forward_headers.insert(HEADER_X_FORWARDED_HOST.to_owned(), original_host.to_owned());
766        }
767        if !forward_headers.contains_key(HEADER_X_FORWARDED_PROTO) {
768            forward_headers.insert(HEADER_X_FORWARDED_PROTO.to_owned(), PROTO_HTTP.to_owned());
769        }
770        let mut builder: RequestBuilder = RequestBuilder::new();
771        builder
772            .method(req.get_method().clone())
773            .url(target_url)
774            .headers(forward_headers)
775            .body(req_body)
776            .timeout(compiled.route.get_timeout_ms())
777            .retry(compiled.route.get_max_retries())
778            .keep_alive(true);
779        if compiled.route.get_use_http2() {
780            builder.http2_only();
781        }
782        let mut upstream_req: HttpRequest = builder.build();
783        upstream.active_conns.fetch_add(1, Ordering::Relaxed);
784        let send_res: Result<HttpResponse, RequestError> = upstream_req.send_async().await;
785        upstream.active_conns.fetch_sub(1, Ordering::Relaxed);
786        match send_res {
787            Ok(resp) => {
788                let status_code: usize = resp.get_status_code();
789                if (502..=504).contains(&status_code) {
790                    upstream.record_failure(
791                        self.get_config().get_circuit_failure_threshold(),
792                        self.get_config().get_circuit_reset_ms(),
793                    );
794                } else {
795                    upstream.record_success();
796                }
797                let resp_extra_hop: HashSet<String> =
798                    extract_response_connection_tokens(resp.get_headers());
799                let out_resp: &mut Response = ctx.get_mut_response();
800                out_resp.set_status_code(status_code);
801                for (name, value) in resp.get_headers() {
802                    if (name.len() == HEADER_CONTENT_LENGTH.len()
803                        && name.eq_ignore_ascii_case(HEADER_CONTENT_LENGTH))
804                        || is_hop_by_hop_header(name, &resp_extra_hop)
805                    {
806                        continue;
807                    }
808                    out_resp.set_header(name, value);
809                }
810                out_resp
811                    .set_header(HEADER_X_GATEWAY_UPSTREAM, &upstream.base_url)
812                    .set_body(resp.bytes());
813                for interceptor in interceptors.iter() {
814                    interceptor.after_forward(ctx, &upstream.base_url);
815                }
816            }
817            Err(_) => {
818                upstream.record_failure(
819                    self.get_config().get_circuit_failure_threshold(),
820                    self.get_config().get_circuit_reset_ms(),
821                );
822                ctx.get_mut_response()
823                    .set_status_code(HttpStatus::BadGateway.code())
824                    .set_body(&[] as &[u8]);
825            }
826        }
827    }
828}
829
830/// Inherent implementation of [`GatewayPlugin`].
831impl GatewayPlugin {
832    /// Initializes the global [`GatewayPlugin`] once with `config`.
833    ///
834    /// # Arguments
835    ///
836    /// - `GatewayConfig` - Reverse-proxy and resilience configuration.
837    ///
838    /// # Returns
839    ///
840    /// - `&'static Self` - Reference to the initialized global plugin.
841    pub fn init(config: GatewayConfig) -> &'static Self {
842        GATEWAY_PLUGIN.get_or_init(|| Self {
843            runtime: GatewayRuntime::new(config),
844        })
845    }
846
847    /// Initializes the global [`GatewayPlugin`] once with a prebuilt [`GatewayRuntime`].
848    ///
849    /// # Arguments
850    ///
851    /// - `GatewayRuntime` - Compiled gateway runtime (including any attached interceptors).
852    ///
853    /// # Returns
854    ///
855    /// - `&'static Self` - Reference to the initialized global plugin.
856    pub fn init_runtime(runtime: GatewayRuntime) -> &'static Self {
857        GATEWAY_PLUGIN.get_or_init(|| Self { runtime })
858    }
859
860    /// Returns the initialized global [`GatewayPlugin`], if [`GatewayPlugin::init`] was called.
861    ///
862    /// # Returns
863    ///
864    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
865    #[inline(always)]
866    pub fn get() -> Option<&'static Self> {
867        GATEWAY_PLUGIN.get()
868    }
869
870    /// Returns the compiled [`GatewayRuntime`].
871    ///
872    /// # Returns
873    ///
874    /// - `&GatewayRuntime` - Active reverse-proxy runtime.
875    #[inline(always)]
876    pub fn get_runtime(&self) -> &GatewayRuntime {
877        &self.runtime
878    }
879}
880
881/// Implements [`ServerHook`] for [`GatewayHook`].
882impl ServerHook for GatewayHook {
883    /// Constructs a per-request [`GatewayHook`].
884    ///
885    /// # Arguments
886    ///
887    /// - `&mut Stream` - Connection stream.
888    /// - `&mut Context` - Request context.
889    ///
890    /// # Returns
891    ///
892    /// - `Self` - Hook instance.
893    #[inline(always)]
894    async fn new(_: &mut Stream, _: &mut Context) -> Self {
895        Self
896    }
897
898    /// Forwards matched requests to configured upstreams via [`GatewayPlugin`].
899    ///
900    /// # Arguments
901    ///
902    /// - `Self` - Hook instance.
903    /// - `&mut Stream` - Connection stream.
904    /// - `&mut Context` - Request context.
905    ///
906    /// # Returns
907    ///
908    /// - `Status` - `Status::Continue` when unconfigured or no route matches; `Status::Reject` once forwarded.
909    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
910        let Some(plugin) = GatewayPlugin::get() else {
911            return Status::Continue;
912        };
913        let runtime: &GatewayRuntime = plugin.get_runtime();
914        let Some(compiled) = runtime.match_route_for_ctx(ctx) else {
915            return Status::Continue;
916        };
917        let peer_ip: Option<String> = stream
918            .get_peer_addr()
919            .ok()
920            .map(|addr: SocketAddr| addr.ip().to_string());
921        runtime
922            .forward_matched(compiled, ctx, peer_ip.as_deref())
923            .await;
924        let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
925        Status::Reject
926    }
927}