hyperlane_plugin_rate_limit/struct.rs
1use super::*;
2
3/// Result of evaluating one request against a [`RateLimitStore`].
4#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
5pub struct RateLimitDecision {
6 /// `true` when the request is admitted; `false` when throttled (`429 Too Many Requests`).
7 #[get(type(copy))]
8 pub(crate) allowed: bool,
9 /// Effective quota limit for the window or burst.
10 #[get(type(copy))]
11 pub(crate) limit: u64,
12 /// Remaining permitted requests right after this evaluation.
13 #[get(type(copy))]
14 pub(crate) remaining: u64,
15 /// Seconds until the bucket fully resets.
16 #[get(type(copy))]
17 pub(crate) reset_after_secs: u64,
18 /// Seconds the caller should wait before retrying (`0` when allowed).
19 #[get(type(copy))]
20 pub(crate) retry_after_secs: u64,
21}
22
23/// Configuration policy governing [`ShardedRateLimiter`] and [`RateLimitPlugin`].
24#[derive(Clone, Data, Debug, Eq, PartialEq)]
25pub struct RateLimitPolicy {
26 /// Sustained requests allowed per `window_ms`.
27 #[get(type(copy))]
28 pub(crate) requests_per_window: u64,
29 /// Window length in milliseconds.
30 #[get(type(copy))]
31 pub(crate) window_ms: u64,
32 /// Maximum burst size for [`RateLimitAlgorithm::Gcra`].
33 #[get(type(copy))]
34 pub(crate) burst: u64,
35 /// Enforcement algorithm (`Gcra` or `FixedWindow`).
36 #[get(type(copy))]
37 pub(crate) algorithm: RateLimitAlgorithm,
38 /// Maximum tracked distinct keys before stale eviction triggers.
39 #[get(type(copy))]
40 pub(crate) max_keys: usize,
41 /// Whether to emit `RateLimit-*` headers on responses.
42 #[get(type(copy))]
43 pub(crate) include_headers: bool,
44 /// Exact paths bypassed by [`RateLimitHook`] (for example `"/healthz"`).
45 pub(crate) exempt_paths: Vec<String>,
46}
47
48/// Zero-allocation multiplicative 64-bit hasher for rate-limit shard tables.
49#[derive(Clone, Copy, Default)]
50pub(crate) struct FxHasher {
51 /// Running 64-bit hash accumulator.
52 pub(crate) state: u64,
53}
54
55/// Precomputed Granlund-Montgomery fast unsigned 64-bit divider avoiding runtime `udiv` instructions.
56#[derive(Clone, Copy)]
57pub(crate) struct FastDiv64 {
58 /// Original divisor (`>= 1`).
59 pub(crate) divisor: u64,
60 /// Magic high multiplier (`0` when `divisor` is a power of two).
61 pub(crate) mult: u64,
62 /// Post-shift amount (`trailing_zeros` for powers of two, `l - 1` otherwise).
63 pub(crate) shift: u32,
64 /// Whether `divisor` is a power of two (`n >> shift` fast path).
65 pub(crate) is_pow2: bool,
66}
67
68/// Cache-line-aligned rate-limiter shard preventing cross-thread false sharing.
69#[repr(align(64))]
70pub(crate) struct RateLimitShard {
71 /// Per-shard read-write lock guarding bucket entries.
72 pub(crate) map: RwLock<RateLimitShardMap>,
73}
74
75/// Lock-free atomic state for one partition key inside [`ShardedRateLimiter`].
76pub(crate) struct BucketEntry {
77 /// GCRA theoretical arrival time (ns) or fixed-window packed `(window_id, count)` / window index.
78 pub(crate) primary: AtomicU64,
79 /// Fixed-window overflow request count (used only when window or limit exceeds `u32::MAX`).
80 pub(crate) counter: AtomicU64,
81 /// Monotonic last-access timestamp in nanoseconds since limiter epoch.
82 pub(crate) last_seen_ns: AtomicU64,
83}
84
85/// Shared interior state of [`ShardedRateLimiter`].
86pub(crate) struct ShardedRateLimiterInner {
87 /// Active policy parameters.
88 pub(crate) policy: RateLimitPolicy,
89 /// Monotonic origin timestamp for nanosecond arithmetic.
90 pub(crate) epoch: Instant,
91 /// Precomputed GCRA emission interval in nanoseconds (`window_ns / requests_per_window`).
92 pub(crate) emission_interval_ns: u64,
93 /// Fast reciprocal divider for `emission_interval_ns`.
94 pub(crate) emission_div: FastDiv64,
95 /// Precomputed GCRA burst tolerance in nanoseconds (`emission_interval_ns * burst`).
96 pub(crate) burst_tolerance_ns: u64,
97 /// Precomputed window duration in nanoseconds.
98 pub(crate) window_ns: u64,
99 /// Fast reciprocal divider for `window_ns`.
100 pub(crate) window_div: FastDiv64,
101 /// Minimum nanoseconds elapsed before refreshing `BucketEntry::last_seen_ns` to avoid dirtying cache lines.
102 pub(crate) last_seen_step_ns: u64,
103 /// Lock-free count of tracked keys across all 64 shards.
104 pub(crate) key_count: AtomicUsize,
105 /// 64-way cache-aligned lock-striped key tables.
106 pub(crate) shards: Box<[RateLimitShard; RATE_LIMIT_SHARD_COUNT]>,
107}
108
109/// High-concurrency 64-way sharded lock-free in-memory [`RateLimitStore`].
110#[derive(Clone)]
111pub struct ShardedRateLimiter {
112 /// Shared limiter state.
113 pub(crate) inner: Arc<ShardedRateLimiterInner>,
114}
115
116/// Built-in [`KeyExtractor`] partitioning traffic by client IP address.
117#[derive(Clone, Copy, Data, Debug, Default, Eq, PartialEq)]
118pub struct ClientIpKeyExtractor {
119 /// When `true`, inspects `X-Forwarded-For` and `X-Real-Ip` before falling back to peer IP.
120 #[get(type(copy))]
121 pub(crate) trust_proxy_headers: bool,
122}
123
124/// Built-in [`KeyExtractor`] partitioning traffic by a specific request header value (for example `X-Api-Key`).
125#[derive(Clone, Data, Debug, Eq, PartialEq)]
126pub struct HeaderKeyExtractor {
127 /// Request header name read as the bucket key.
128 pub(crate) header_name: String,
129 /// Whether to fall back to client IP when the header is missing.
130 #[get(type(copy))]
131 pub(crate) fallback_to_ip: bool,
132}
133
134/// Built-in [`KeyExtractor`] partitioning traffic by `(request_path, client_ip)`.
135#[derive(Clone, Copy, Data, Debug, Default, Eq, PartialEq)]
136pub struct PathAndIpKeyExtractor {
137 /// Whether forwarding headers are trusted when resolving the client IP.
138 #[get(type(copy))]
139 pub(crate) trust_proxy_headers: bool,
140}
141
142/// Stack-backed `fmt::Write` cursor for zero-allocation IPv6 formatting.
143pub(crate) struct StackFmtWriter<'a> {
144 /// Destination byte buffer.
145 pub(crate) buf: &'a mut [u8],
146 /// Current number of written UTF-8 bytes.
147 pub(crate) len: usize,
148}
149
150/// Process-wide [`RateLimitPlugin`] registry storing policy, [`RateLimitStore`], and [`KeyExtractor`].
151#[derive(Clone)]
152pub struct RateLimitPlugin {
153 /// Active rate-limiting policy.
154 pub(crate) policy: RateLimitPolicy,
155 /// Backend store evaluating quota decisions.
156 pub(crate) store: Arc<dyn RateLimitStore>,
157 /// Optional direct [`ShardedRateLimiter`] handle bypassing `dyn RateLimitStore` virtual dispatch.
158 pub(crate) fast_store: Option<ShardedRateLimiter>,
159 /// Preformatted default `RateLimit-Limit` header value.
160 pub(crate) preformatted_limit: String,
161 /// Expected limit value matching `preformatted_limit`.
162 pub(crate) expected_limit: u64,
163 /// Partition key extractor.
164 pub(crate) key_extractor: Arc<dyn KeyExtractor>,
165 /// When `true`, uses the zero-allocation stack IP extraction fast path directly.
166 pub(crate) use_default_ip_fast_path: bool,
167}
168
169/// Opt-in [`ServerHook`] enforcing configured rate limits and attaching RFC `RateLimit-*` headers.
170#[derive(Clone, Copy, Debug, Default)]
171#[hyperlane::request_middleware(-95)]
172pub struct RateLimitHook;