hyperlane_plugin_gateway/struct.rs
1use super::*;
2
3/// Token-bucket rate-limit parameters attached to a [`GatewayRoute`].
4#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
5pub struct RateLimitConfig {
6 /// Sustained refill rate in requests per second.
7 #[get(type(copy))]
8 pub(crate) requests_per_second: u64,
9 /// Maximum burst capacity in tokens.
10 #[get(type(copy))]
11 pub(crate) burst: u64,
12}
13
14/// One upstream backend endpoint participating in a [`GatewayRoute`].
15#[derive(Clone, Data, Debug, Eq, PartialEq)]
16pub struct UpstreamTarget {
17 /// Base upstream URL (for example `"http://127.0.0.1:8081"`).
18 pub(crate) url: String,
19 /// Relative load-balancing weight (`>= 1`).
20 #[get(type(copy))]
21 pub(crate) weight: u32,
22}
23
24/// Routing, load-balancing, retry, and rate-limit definition for one gateway prefix.
25#[derive(Clone, Data, Debug, Eq, PartialEq)]
26pub struct GatewayRoute {
27 /// Path prefix matched on segment boundaries (for example `"/api"` matches `"/api"` and `"/api/v1"`).
28 pub(crate) prefix: String,
29 /// Whether to strip `prefix` before forwarding the request path upstream.
30 #[get(type(copy))]
31 pub(crate) strip_prefix: bool,
32 /// Optional exact case-insensitive `Host` matcher.
33 #[get(type(clone))]
34 pub(crate) host: Option<String>,
35 /// Upstream targets eligible to serve matched traffic.
36 pub(crate) upstreams: Vec<UpstreamTarget>,
37 /// Upstream selection strategy.
38 #[get(type(copy))]
39 pub(crate) strategy: LoadBalanceStrategy,
40 /// Per-attempt upstream timeout in milliseconds.
41 #[get(type(copy))]
42 pub(crate) timeout_ms: u64,
43 /// Maximum automatic retry attempts on idempotent transient upstream errors.
44 #[get(type(copy))]
45 pub(crate) max_retries: usize,
46 /// Optional per-route token-bucket rate limiter.
47 #[get(type(copy))]
48 pub(crate) rate_limit: Option<RateLimitConfig>,
49 /// Whether to forward upstream using multiplexed HTTP/2 (`h2`/`h2c`).
50 #[get(type(copy))]
51 pub(crate) use_http2: bool,
52}
53
54/// Top-level configuration for [`GatewayRuntime`] and [`GatewayPlugin`].
55#[derive(Clone, Data, Debug, Eq, PartialEq)]
56pub struct GatewayConfig {
57 /// Configured reverse-proxy routes (matched longest-prefix first).
58 pub(crate) routes: Vec<GatewayRoute>,
59 /// Maximum forwarded request body length in bytes.
60 #[get(type(copy))]
61 pub(crate) max_body_size: usize,
62 /// Consecutive failures before opening an upstream's circuit breaker.
63 #[get(type(copy))]
64 pub(crate) circuit_failure_threshold: u32,
65 /// Cooldown duration in milliseconds before an open circuit allows a probe request.
66 #[get(type(copy))]
67 pub(crate) circuit_reset_ms: u64,
68}
69
70/// Live atomic health and concurrency state for one upstream node.
71pub(crate) struct UpstreamRuntime {
72 /// Normalized upstream base URL (without trailing slash).
73 pub(crate) base_url: String,
74 /// Load-balancing weight (`>= 1`).
75 pub(crate) weight: u32,
76 /// Current number of active in-flight requests to this node.
77 pub(crate) active_conns: AtomicUsize,
78 /// Consecutive failure count since last success.
79 pub(crate) consecutive_failures: AtomicU32,
80 /// Unix epoch millisecond until which this circuit remains open (`0` = closed).
81 pub(crate) open_until_ms: AtomicU64,
82}
83
84/// Lock-free GCRA token-bucket rate limiter using a single atomic timestamp.
85pub(crate) struct TokenBucket {
86 /// Nanoseconds required to regenerate one request token.
87 pub(crate) emission_interval_ns: u64,
88 /// Burst window in nanoseconds (`emission_interval_ns * burst`).
89 pub(crate) burst_tolerance_ns: u64,
90 /// Monotonic origin timestamp for nanosecond arithmetic.
91 pub(crate) epoch: Instant,
92 /// Theoretical Arrival Time (TAT) in nanoseconds since `epoch`.
93 pub(crate) tat_ns: AtomicU64,
94}
95
96/// Precomputed divisor state for division-free `n % divisor` remainder calculation.
97#[derive(Clone, Copy, Debug)]
98pub(crate) struct FastModU64 {
99 /// Divisor (`>= 1`).
100 pub(crate) divisor: u64,
101 /// Power-of-two bitmask (`divisor - 1`) when `is_pow2` is true.
102 pub(crate) pow2_mask: u64,
103 /// Granlund-Montgomery reciprocal multiplier (`ceil(2^(64 + shift) / divisor) - 2^64`).
104 pub(crate) mult: u64,
105 /// Post-multiply right shift (`ceil(log2(divisor)) - 1`).
106 pub(crate) shift: u32,
107 /// `true` when `divisor` is a power of two (enables single-instruction bitmask).
108 pub(crate) is_pow2: bool,
109}
110
111/// Compiled route entry carrying live upstream nodes, selector cursor, and optional limiter.
112pub(crate) struct CompiledRoute {
113 /// Original route definition.
114 pub(crate) route: GatewayRoute,
115 /// Normalized prefix (without trailing slash except `"/"`).
116 pub(crate) normalized_prefix: String,
117 /// Pre-trimmed optional `Host` matcher stored for zero-allocation matching.
118 pub(crate) normalized_host: Option<String>,
119 /// Contiguous inline live upstream runtime nodes (no per-upstream `Arc` indirection).
120 pub(crate) upstreams: Box<[UpstreamRuntime]>,
121 /// Division-free modulo helper for `upstreams.len()`.
122 pub(crate) upstreams_mod: FastModU64,
123 /// Division-free modulo helper for `(upstreams.len() - 1).max(1)` used by P2C.
124 pub(crate) upstreams_minus1_mod: FastModU64,
125 /// Precomputed `O(1)` weighted selection ring when total weight is bounded.
126 pub(crate) weighted_ring: Box<[u16]>,
127 /// Division-free modulo helper for `weighted_ring.len()`.
128 pub(crate) weighted_ring_mod: FastModU64,
129 /// Round-robin / weighted selection cursor.
130 pub(crate) cursor: AtomicUsize,
131 /// Optional compiled lock-free GCRA limiter.
132 pub(crate) limiter: Option<TokenBucket>,
133}
134
135/// Compiled thread-safe reverse-proxy engine backing [`GatewayPlugin`] and [`GatewayHook`].
136#[derive(Clone)]
137pub struct GatewayRuntime {
138 /// Top-level limits and circuit-breaker thresholds.
139 pub(crate) config: GatewayConfig,
140 /// Compiled routes sorted from longest prefix to shortest prefix.
141 pub(crate) routes: Arc<[CompiledRoute]>,
142 /// Pluggable interceptors invoked around upstream forwarding.
143 pub(crate) interceptors: Arc<[Arc<dyn GatewayInterceptor>]>,
144 /// `true` when at least one route carries a `Host` matcher.
145 pub(crate) any_host_route: bool,
146}
147
148/// Process-wide [`GatewayPlugin`] registry storing [`GatewayRuntime`].
149#[derive(Clone)]
150pub struct GatewayPlugin {
151 /// Compiled gateway runtime engine.
152 pub(crate) runtime: GatewayRuntime,
153}
154
155/// Opt-in [`ServerHook`] forwarding matched requests through [`GatewayPlugin`].
156#[derive(Clone, Copy, Debug, Default)]
157#[hyperlane::request_middleware(-50)]
158pub struct GatewayHook;