hyperlane_plugin_concurrency/struct.rs
1use super::*;
2
3/// Per-route-prefix in-flight concurrency rule.
4#[derive(Clone, Data, Debug, Eq, PartialEq)]
5pub struct PrefixConcurrencyLimit {
6 /// Path prefix matched on URL segment boundaries (for example `"/api/heavy"`).
7 pub(crate) prefix: String,
8 /// Maximum concurrent in-flight requests allowed under this prefix.
9 #[get(type(copy))]
10 pub(crate) max_in_flight: usize,
11 /// Optional bounded wait timeout in milliseconds (`0` sheds immediately without queuing).
12 #[get(type(copy))]
13 pub(crate) wait_timeout_ms: u64,
14}
15
16/// Latency-driven AIMD adaptive load-shedding parameters.
17#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
18pub struct AdaptiveShedConfig {
19 /// Target request latency in milliseconds; requests exceeding this reduce the effective limit.
20 #[get(type(copy))]
21 pub(crate) target_latency_ms: u64,
22 /// Lower bound floor for the dynamically adjusted global concurrency limit.
23 #[get(type(copy))]
24 pub(crate) min_limit: usize,
25 /// Additive increment applied on fast completions (`>= 1`).
26 #[get(type(copy))]
27 pub(crate) additive_increase: usize,
28 /// Backoff numerator in percentage (`1..=99`, for example `80` shrinks limit to 80% on overload).
29 #[get(type(copy))]
30 pub(crate) decrease_percent: usize,
31}
32
33/// Top-level configuration for [`ConcurrencyLimiter`] and [`ConcurrencyPlugin`].
34#[derive(Clone, Data, Debug, Eq, PartialEq)]
35pub struct ConcurrencyConfig {
36 /// Global maximum concurrent in-flight requests (`>= 1`).
37 #[get(type(copy))]
38 pub(crate) max_in_flight: usize,
39 /// Optional global bounded wait timeout in milliseconds (`0` sheds immediately without queuing).
40 #[get(type(copy))]
41 pub(crate) wait_timeout_ms: u64,
42 /// Optional latency-driven AIMD adaptive load-shedding policy.
43 #[get(type(copy))]
44 pub(crate) adaptive: Option<AdaptiveShedConfig>,
45 /// Per-route-prefix concurrency rules (evaluated longest-prefix first).
46 pub(crate) prefix_limits: Vec<PrefixConcurrencyLimit>,
47 /// Exact paths bypassed by [`ConcurrencyRequestHook`] (for example `"/healthz"`).
48 pub(crate) exempt_paths: Vec<String>,
49 /// `Retry-After` header value in seconds attached to `503` responses.
50 #[get(type(copy))]
51 pub(crate) retry_after_secs: u64,
52 /// `Content-Type` header emitted on shed responses.
53 pub(crate) reject_content_type: String,
54 /// Body bytes emitted on shed responses.
55 pub(crate) reject_body: Vec<u8>,
56}
57
58/// Lock-free runtime state for one compiled route-prefix concurrency rule.
59pub(crate) struct CompiledPrefixLimit {
60 /// Normalized prefix string (without trailing slash except `"/"`).
61 pub(crate) prefix: String,
62 /// Maximum concurrent in-flight requests for this prefix.
63 pub(crate) max_in_flight: usize,
64 /// Bounded wait timeout in milliseconds (`0` = immediate lock-free shedding).
65 pub(crate) wait_timeout_ms: u64,
66 /// Current active in-flight request count under this prefix.
67 pub(crate) in_flight: AtomicUsize,
68 /// Optional Tokio semaphore created only when `wait_timeout_ms > 0`.
69 pub(crate) semaphore: Option<Arc<Semaphore>>,
70}
71
72/// Optional Tokio semaphore permits held by a [`ConcurrencyPermit`] when wait queuing is enabled.
73pub(crate) struct HeldSemaphorePermits {
74 /// Optional global queue permit.
75 pub(crate) global: Option<OwnedSemaphorePermit>,
76 /// Optional prefix queue permit.
77 pub(crate) prefix: Option<OwnedSemaphorePermit>,
78}
79
80/// Shared interior state of [`ConcurrencyLimiter`].
81pub(crate) struct ConcurrencyLimiterInner {
82 /// Source configuration retained for inspection.
83 pub(crate) config: ConcurrencyConfig,
84 /// Cached global maximum in-flight ceiling (`>= 1`).
85 pub(crate) max_in_flight: usize,
86 /// `true` when latency-driven AIMD adaptive load shedding is enabled.
87 pub(crate) is_adaptive: bool,
88 /// Cached adaptive configuration used when `is_adaptive` is `true`.
89 pub(crate) adaptive_cfg: AdaptiveShedConfig,
90 /// `true` when global or any prefix rule has bounded wait queuing enabled.
91 pub(crate) has_wait_queue: bool,
92 /// Monotonic time origin for compact 64-bit microsecond latency timestamps.
93 pub(crate) epoch: Instant,
94 /// Current active global in-flight requests.
95 pub(crate) global_in_flight: AtomicUsize,
96 /// Effective global concurrency ceiling (updated dynamically when adaptive shedding is active).
97 pub(crate) effective_limit: AtomicUsize,
98 /// Lock-free EWMA request latency in microseconds.
99 pub(crate) ewma_latency_us: AtomicU64,
100 /// Total admitted requests since creation.
101 pub(crate) total_admitted: AtomicU64,
102 /// Total shed requests since creation.
103 pub(crate) total_shed: AtomicU64,
104 /// Optional global Tokio semaphore created only when `wait_timeout_ms > 0`.
105 pub(crate) global_semaphore: Option<Arc<Semaphore>>,
106 /// Compiled prefix rules sorted from longest prefix to shortest prefix.
107 pub(crate) prefixes: Box<[CompiledPrefixLimit]>,
108 /// Small inline exempt path list used when `len <= EXEMPT_SET_THRESHOLD`.
109 pub(crate) exempt_small: Box<[String]>,
110 /// Exact exempt paths hash set compiled when `len > EXEMPT_SET_THRESHOLD`.
111 pub(crate) exempt_set: Option<HashSetXxHash3_64<String>>,
112 /// Pre-serialized `503 Service Unavailable` + `Retry-After` wire bytes.
113 pub(crate) prebuilt_reject_wire: Vec<u8>,
114}
115
116/// High-performance lock-free concurrency limiter backing [`ConcurrencyPlugin`].
117#[derive(Clone)]
118pub struct ConcurrencyLimiter {
119 /// Shared atomic limiter state.
120 pub(crate) inner: Arc<ConcurrencyLimiterInner>,
121}
122
123/// Interior state of an RAII [`ConcurrencyPermit`] guaranteeing single-release semantics.
124pub(crate) struct ConcurrencyPermitInner {
125 /// Owning limiter state.
126 pub(crate) limiter: Arc<ConcurrencyLimiterInner>,
127 /// Optional boxed semaphore permits (allocated only when wait queuing was used).
128 pub(crate) sem_permits: Option<Box<Mutex<Option<HeldSemaphorePermits>>>>,
129 /// Acquisition timestamp (`elapsed_us + 1`) when adaptive shedding is enabled, or `0` otherwise.
130 pub(crate) acquired_at_us_plus_one: u64,
131 /// Matched prefix rule slot index, or [`NO_PREFIX_SLOT`] when none matched.
132 pub(crate) prefix_slot: u32,
133 /// Atomic single-release guard preventing double decrements across explicit release and `Drop`.
134 pub(crate) released: AtomicBool,
135}
136
137/// Leak-proof RAII concurrency permit stored in Hyperlane [`Context`] under [`ATTR_CONCURRENCY_PERMIT`].
138///
139/// Cloning shares the same underlying permit handle; calling [`ConcurrencyPermit::release`] or
140/// dropping the final reference atomically releases the in-flight slot exactly once.
141#[derive(Clone)]
142pub struct ConcurrencyPermit {
143 /// Shared single-release permit state.
144 pub(crate) inner: Arc<ConcurrencyPermitInner>,
145}
146
147/// Point-in-time diagnostic counters exported by [`ConcurrencyLimiter::snapshot`].
148#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
149pub struct ConcurrencySnapshot {
150 /// Current global in-flight requests.
151 #[get(type(copy))]
152 pub(crate) in_flight: usize,
153 /// Current effective global concurrency limit.
154 #[get(type(copy))]
155 pub(crate) effective_limit: usize,
156 /// Exponentially weighted moving average request latency in microseconds.
157 #[get(type(copy))]
158 pub(crate) ewma_latency_us: u64,
159 /// Cumulative count of admitted requests.
160 #[get(type(copy))]
161 pub(crate) total_admitted: u64,
162 /// Cumulative count of shed requests.
163 #[get(type(copy))]
164 pub(crate) total_shed: u64,
165}
166
167/// Process-wide [`ConcurrencyPlugin`] singleton holding a compiled [`ConcurrencyLimiter`].
168#[derive(Clone)]
169pub struct ConcurrencyPlugin {
170 /// Shared concurrency limiter engine.
171 pub(crate) limiter: ConcurrencyLimiter,
172}
173
174/// Opt-in request middleware acquiring a [`ConcurrencyPermit`] or shedding with `503 Service Unavailable`.
175#[derive(Clone, Copy, Debug, Default)]
176#[hyperlane::request_middleware(-108)]
177pub struct ConcurrencyRequestHook;
178
179/// Opt-in response middleware releasing the [`ConcurrencyPermit`] stored in `Context` attributes.
180#[derive(Clone, Copy, Debug, Default)]
181#[hyperlane::response_middleware(85)]
182pub struct ConcurrencyResponseHook;