Skip to main content

hyperlane_plugin_concurrency/
impl.rs

1use super::*;
2
3/// Inherent constructors and builders for [`PrefixConcurrencyLimit`].
4impl PrefixConcurrencyLimit {
5    /// Creates a per-route-prefix concurrency limit rule.
6    ///
7    /// # Arguments
8    ///
9    /// - `S` - Route path prefix (for example `"/api/export"`).
10    /// - `usize` - Maximum concurrent in-flight requests under `prefix`.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Constructed prefix concurrency rule.
15    pub fn new<S>(prefix: S, max_in_flight: usize) -> Self
16    where
17        S: Into<String>,
18    {
19        Self {
20            prefix: prefix.into(),
21            max_in_flight: max_in_flight.max(1),
22            wait_timeout_ms: 0,
23        }
24    }
25
26    /// Sets the optional bounded wait timeout in milliseconds for this prefix.
27    ///
28    /// # Arguments
29    ///
30    /// - `u64` - Wait timeout in milliseconds (`0` sheds immediately).
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - Updated prefix rule.
35    pub fn with_wait_timeout_ms(mut self, wait_timeout_ms: u64) -> Self {
36        self.set_wait_timeout_ms(wait_timeout_ms);
37        self
38    }
39}
40
41/// Default construction for [`AdaptiveShedConfig`].
42impl Default for AdaptiveShedConfig {
43    /// Constructs default AIMD adaptive load-shedding settings (100 ms target, min limit 4, 80% backoff).
44    ///
45    /// # Returns
46    ///
47    /// - `Self` - Default adaptive shedding configuration.
48    fn default() -> Self {
49        Self {
50            target_latency_ms: DEFAULT_ADAPTIVE_TARGET_LATENCY_MS,
51            min_limit: 4,
52            additive_increase: 1,
53            decrease_percent: 80,
54        }
55    }
56}
57
58/// Inherent fluent builders for [`AdaptiveShedConfig`].
59impl AdaptiveShedConfig {
60    /// Creates an [`AdaptiveShedConfig`] targeting `target_latency_ms` with a floor of `min_limit`.
61    ///
62    /// # Arguments
63    ///
64    /// - `u64` - Target request latency in milliseconds.
65    /// - `usize` - Minimum effective concurrency floor.
66    ///
67    /// # Returns
68    ///
69    /// - `Self` - Constructed adaptive configuration.
70    pub fn new(target_latency_ms: u64, min_limit: usize) -> Self {
71        Self {
72            target_latency_ms: target_latency_ms.max(1),
73            min_limit: min_limit.max(1),
74            additive_increase: 1,
75            decrease_percent: 80,
76        }
77    }
78
79    /// Sets the additive increase step applied on fast completions.
80    ///
81    /// # Arguments
82    ///
83    /// - `usize` - Additive increment (`>= 1`).
84    ///
85    /// # Returns
86    ///
87    /// - `Self` - Updated configuration.
88    pub fn with_additive_increase(mut self, step: usize) -> Self {
89        self.set_additive_increase(step.max(1));
90        self
91    }
92
93    /// Sets the multiplicative backoff percentage (`1..=99`) applied when latency exceeds target.
94    ///
95    /// # Arguments
96    ///
97    /// - `usize` - Retained limit percentage (`1..=99`).
98    ///
99    /// # Returns
100    ///
101    /// - `Self` - Updated configuration.
102    pub fn with_decrease_percent(mut self, percent: usize) -> Self {
103        self.set_decrease_percent(percent.clamp(1, 99));
104        self
105    }
106}
107
108/// Default construction for [`ConcurrencyConfig`].
109impl Default for ConcurrencyConfig {
110    /// Constructs a default [`ConcurrencyConfig`] (1 024 max in-flight, immediate shedding, `503` + `Retry-After: 1`).
111    ///
112    /// # Returns
113    ///
114    /// - `Self` - Default configuration.
115    fn default() -> Self {
116        Self {
117            max_in_flight: DEFAULT_MAX_IN_FLIGHT,
118            wait_timeout_ms: 0,
119            adaptive: None,
120            prefix_limits: Vec::new(),
121            exempt_paths: Vec::new(),
122            retry_after_secs: DEFAULT_RETRY_AFTER_SECS,
123            reject_content_type: DEFAULT_SHED_CONTENT_TYPE.to_owned(),
124            reject_body: DEFAULT_SHED_BODY.to_vec(),
125        }
126    }
127}
128
129/// Fluent configuration builders for [`ConcurrencyConfig`].
130impl ConcurrencyConfig {
131    /// Creates a [`ConcurrencyConfig`] capped at `max_in_flight` concurrent requests.
132    ///
133    /// # Arguments
134    ///
135    /// - `usize` - Global in-flight limit (`>= 1`).
136    ///
137    /// # Returns
138    ///
139    /// - `Self` - Constructed configuration.
140    pub fn new(max_in_flight: usize) -> Self {
141        Self::default().with_max_in_flight(max_in_flight)
142    }
143
144    /// Sets the global maximum concurrent in-flight requests.
145    ///
146    /// # Arguments
147    ///
148    /// - `usize` - Global in-flight limit (`>= 1`).
149    ///
150    /// # Returns
151    ///
152    /// - `Self` - Updated configuration.
153    pub fn with_max_in_flight(mut self, max_in_flight: usize) -> Self {
154        self.set_max_in_flight(max_in_flight.max(1));
155        self
156    }
157
158    /// Sets the global bounded wait timeout in milliseconds (`0` disables queuing).
159    ///
160    /// # Arguments
161    ///
162    /// - `u64` - Wait timeout in milliseconds.
163    ///
164    /// # Returns
165    ///
166    /// - `Self` - Updated configuration.
167    pub fn with_wait_timeout_ms(mut self, wait_timeout_ms: u64) -> Self {
168        self.set_wait_timeout_ms(wait_timeout_ms);
169        self
170    }
171
172    /// Enables AIMD latency-driven adaptive load shedding.
173    ///
174    /// # Arguments
175    ///
176    /// - `AdaptiveShedConfig` - Adaptive shedding parameters.
177    ///
178    /// # Returns
179    ///
180    /// - `Self` - Updated configuration.
181    pub fn with_adaptive(mut self, adaptive: AdaptiveShedConfig) -> Self {
182        self.set_adaptive(Some(adaptive));
183        self
184    }
185
186    /// Adds a per-route-prefix concurrency limit rule.
187    ///
188    /// # Arguments
189    ///
190    /// - `PrefixConcurrencyLimit` - Route-prefix limit rule.
191    ///
192    /// # Returns
193    ///
194    /// - `Self` - Updated configuration.
195    pub fn with_prefix_limit(mut self, rule: PrefixConcurrencyLimit) -> Self {
196        self.get_mut_prefix_limits().push(rule);
197        self
198    }
199
200    /// Sets exact request paths bypassed by concurrency limiting.
201    ///
202    /// # Arguments
203    ///
204    /// - `I` - Iterator of exact exempt paths.
205    ///
206    /// # Returns
207    ///
208    /// - `Self` - Updated configuration.
209    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
210    where
211        I: IntoIterator<Item = S>,
212        S: Into<String>,
213    {
214        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
215        self
216    }
217
218    /// Sets the `Retry-After` header value in seconds for shed `503` responses.
219    ///
220    /// # Arguments
221    ///
222    /// - `u64` - Retry delay in seconds (`>= 1`).
223    ///
224    /// # Returns
225    ///
226    /// - `Self` - Updated configuration.
227    pub fn with_retry_after_secs(mut self, secs: u64) -> Self {
228        self.set_retry_after_secs(secs.max(1));
229        self
230    }
231
232    /// Customizes the `Content-Type` and body emitted on `503 Service Unavailable` responses.
233    ///
234    /// # Arguments
235    ///
236    /// - `C` - `Content-Type` header value.
237    /// - `B` - Response body bytes.
238    ///
239    /// # Returns
240    ///
241    /// - `Self` - Updated configuration.
242    pub fn with_reject_body<C, B>(mut self, content_type: C, body: B) -> Self
243    where
244        C: Into<String>,
245        B: Into<Vec<u8>>,
246    {
247        self.set_reject_content_type(content_type.into())
248            .set_reject_body(body.into());
249        self
250    }
251}
252
253/// Releases the underlying concurrency slots atomically at most once.
254impl ConcurrencyPermitInner {
255    /// Atomically decrements in-flight counters, updates adaptive EWMA, and drops queued semaphore permits.
256    #[inline]
257    pub(crate) fn release_once(&self) {
258        let Self {
259            released,
260            limiter,
261            prefix_slot,
262            acquired_at_us_plus_one,
263            sem_permits,
264        } = self;
265        if released.swap(true, Ordering::Relaxed) {
266            return;
267        }
268        let slot: u32 = *prefix_slot;
269        if slot != NO_PREFIX_SLOT
270            && let Some(rule) = limiter.prefixes.get(slot as usize)
271        {
272            rule.in_flight.fetch_sub(1, Ordering::Relaxed);
273        }
274        limiter.global_in_flight.fetch_sub(1, Ordering::Relaxed);
275        let started_plus_one: u64 = *acquired_at_us_plus_one;
276        if started_plus_one != 0 {
277            let now_us: u64 = elapsed_micros_u64(limiter.epoch);
278            let elapsed_us: u64 = now_us.saturating_sub(started_plus_one - 1);
279            record_adaptive_sample(limiter, limiter.adaptive_cfg, elapsed_us);
280        }
281        if let Some(mutex) = sem_permits
282            && let Ok(mut guard) = mutex.lock()
283            && let Some(HeldSemaphorePermits { global, prefix }) = guard.take()
284        {
285            drop(prefix);
286            drop(global);
287        }
288    }
289}
290
291/// Guarantees automatic permit release when dropped on early reject, panic, or connection drop.
292impl Drop for ConcurrencyPermitInner {
293    /// Releases the permit if it has not already been explicitly released.
294    #[inline]
295    fn drop(&mut self) {
296        let Self { released, .. } = self;
297        if !*released.get_mut() {
298            self.release_once();
299        }
300    }
301}
302
303/// Inherent release and inspection helpers for [`ConcurrencyPermit`].
304impl ConcurrencyPermit {
305    /// Explicitly releases the concurrency permit immediately (idempotent).
306    #[inline(always)]
307    pub fn release(&self) {
308        let Self { inner } = self;
309        inner.release_once();
310    }
311
312    /// Reports whether this permit has already been released.
313    ///
314    /// # Returns
315    ///
316    /// - `bool` - `true` when already released.
317    #[inline(always)]
318    pub fn is_released(&self) -> bool {
319        let Self { inner } = self;
320        inner.released.load(Ordering::Acquire)
321    }
322
323    /// Retrieves the active [`ConcurrencyPermit`] stored in `ctx`, if present.
324    ///
325    /// # Arguments
326    ///
327    /// - `&Context` - Active Hyperlane context.
328    ///
329    /// # Returns
330    ///
331    /// - `Option<Self>` - Permit handle when present.
332    pub fn from_context(ctx: &Context) -> Option<Self> {
333        ctx.try_get_attribute::<Self, _>(ATTR_CONCURRENCY_PERMIT)
334    }
335}
336
337/// Inherent construction, acquisition, and metrics methods for [`ConcurrencyLimiter`].
338impl ConcurrencyLimiter {
339    /// Compiles `config` into a lock-free [`ConcurrencyLimiter`] with a prebuilt `503` response.
340    ///
341    /// # Arguments
342    ///
343    /// - `ConcurrencyConfig` - Concurrency and adaptive load-shedding configuration.
344    ///
345    /// # Returns
346    ///
347    /// - `Self` - Ready concurrency limiter.
348    pub fn new(config: ConcurrencyConfig) -> Self {
349        let max_in_flight: usize = config.get_max_in_flight().max(1);
350        let (is_adaptive, adaptive_cfg): (bool, AdaptiveShedConfig) =
351            match config.try_get_adaptive() {
352                Some(cfg) => (true, cfg),
353                None => (false, AdaptiveShedConfig::default()),
354            };
355        let global_semaphore: Option<Arc<Semaphore>> = if config.get_wait_timeout_ms() > 0 {
356            Some(Arc::new(Semaphore::new(max_in_flight)))
357        } else {
358            None
359        };
360        let mut prefixes_vec: Vec<CompiledPrefixLimit> = config
361            .get_prefix_limits()
362            .iter()
363            .filter(|r: &&PrefixConcurrencyLimit| !r.get_prefix().trim().is_empty())
364            .map(|r: &PrefixConcurrencyLimit| {
365                let limit: usize = r.get_max_in_flight().max(1);
366                let sem: Option<Arc<Semaphore>> = if r.get_wait_timeout_ms() > 0 {
367                    Some(Arc::new(Semaphore::new(limit)))
368                } else {
369                    None
370                };
371                CompiledPrefixLimit {
372                    prefix: normalize_prefix(r.get_prefix()),
373                    max_in_flight: limit,
374                    wait_timeout_ms: r.get_wait_timeout_ms(),
375                    in_flight: AtomicUsize::new(0),
376                    semaphore: sem,
377                }
378            })
379            .collect();
380        prefixes_vec.sort_by_key(|rule: &CompiledPrefixLimit| Reverse(rule.prefix.len()));
381        let has_wait_queue: bool = global_semaphore.is_some()
382            || prefixes_vec
383                .iter()
384                .any(|rule: &CompiledPrefixLimit| rule.semaphore.is_some());
385        let prefixes: Box<[CompiledPrefixLimit]> = prefixes_vec.into_boxed_slice();
386        let non_empty_exempt: Vec<String> = config
387            .get_exempt_paths()
388            .iter()
389            .filter(|p: &&String| !p.is_empty())
390            .cloned()
391            .collect();
392        let (exempt_small, exempt_set): (Box<[String]>, Option<HashSetXxHash3_64<String>>) =
393            if non_empty_exempt.len() > EXEMPT_SET_THRESHOLD {
394                let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
395                for path in non_empty_exempt {
396                    set.insert(path);
397                }
398                (Box::new([]), Some(set))
399            } else {
400                (non_empty_exempt.into_boxed_slice(), None)
401            };
402        let mut reject_resp: Response = Response::default();
403        reject_resp
404            .set_status_code(HttpStatus::ServiceUnavailable.code())
405            .set_header(RETRY_AFTER, config.get_retry_after_secs().to_string())
406            .set_header(CONTENT_TYPE, config.get_reject_content_type())
407            .set_body(config.get_reject_body().clone());
408        let prebuilt_reject_wire: Vec<u8> = reject_resp.build();
409        Self {
410            inner: Arc::new(ConcurrencyLimiterInner {
411                config,
412                max_in_flight,
413                is_adaptive,
414                adaptive_cfg,
415                has_wait_queue,
416                epoch: Instant::now(),
417                global_in_flight: AtomicUsize::new(0),
418                effective_limit: AtomicUsize::new(max_in_flight),
419                ewma_latency_us: AtomicU64::new(0),
420                total_admitted: AtomicU64::new(0),
421                total_shed: AtomicU64::new(0),
422                global_semaphore,
423                prefixes,
424                exempt_small,
425                exempt_set,
426                prebuilt_reject_wire,
427            }),
428        }
429    }
430
431    /// Returns the source [`ConcurrencyConfig`].
432    ///
433    /// # Returns
434    ///
435    /// - `&ConcurrencyConfig` - Active configuration.
436    pub fn get_config(&self) -> &ConcurrencyConfig {
437        let Self { inner } = self;
438        &inner.config
439    }
440
441    /// Returns the prebuilt `503 Service Unavailable` + `Retry-After` HTTP wire buffer.
442    ///
443    /// # Returns
444    ///
445    /// - `&Vec<u8>` - Pre-serialized wire bytes.
446    #[inline(always)]
447    pub fn get_prebuilt_reject_wire(&self) -> &Vec<u8> {
448        let Self { inner } = self;
449        &inner.prebuilt_reject_wire
450    }
451
452    /// Reports whether any global or per-prefix bounded wait queue is configured.
453    ///
454    /// # Returns
455    ///
456    /// - `bool` - `true` when semaphore waiting may be needed.
457    #[inline(always)]
458    pub(crate) fn has_wait_queue(&self) -> bool {
459        let Self { inner } = self;
460        inner.has_wait_queue
461    }
462
463    /// Reports whether `path` is exempted from concurrency enforcement.
464    ///
465    /// # Arguments
466    ///
467    /// - `&str` - Incoming request path.
468    ///
469    /// # Returns
470    ///
471    /// - `bool` - `true` when exempt.
472    #[inline(always)]
473    pub fn is_path_exempt(&self, path: &str) -> bool {
474        let Self { inner } = self;
475        if let Some(ref set) = inner.exempt_set {
476            return set.contains(path);
477        }
478        let small: &[String] = &inner.exempt_small;
479        if small.is_empty() {
480            return false;
481        }
482        let path_bytes: &[u8] = path.as_bytes();
483        let path_len: usize = path_bytes.len();
484        for item in small {
485            let item_bytes: &[u8] = item.as_bytes();
486            if item_bytes.len() == path_len && item_bytes == path_bytes {
487                return true;
488            }
489        }
490        false
491    }
492
493    /// Finds the index of the longest matching per-prefix rule for `path`.
494    ///
495    /// # Arguments
496    ///
497    /// - `&str` - Incoming request path.
498    ///
499    /// # Returns
500    ///
501    /// - `u32` - Index into compiled prefix limits, or [`NO_PREFIX_SLOT`] if unmatched.
502    #[inline(always)]
503    pub(crate) fn match_prefix_slot(&self, path: &str) -> u32 {
504        let Self { inner } = self;
505        let prefixes: &[CompiledPrefixLimit] = &inner.prefixes;
506        if prefixes.is_empty() {
507            return NO_PREFIX_SLOT;
508        }
509        let path_bytes: &[u8] = path.as_bytes();
510        for (idx, rule) in prefixes.iter().enumerate() {
511            if path_matches_prefix_bytes(path_bytes, rule.prefix.as_bytes()) {
512                return idx as u32;
513            }
514        }
515        NO_PREFIX_SLOT
516    }
517
518    /// Fast synchronous lock-free attempt to acquire a permit without waiting.
519    ///
520    /// # Arguments
521    ///
522    /// - `&str` - Incoming request path.
523    ///
524    /// # Returns
525    ///
526    /// - `Result<ConcurrencyPermit, ShedReason>` - Acquired RAII permit or shed reason.
527    #[inline]
528    pub fn try_acquire(&self, path: &str) -> Result<ConcurrencyPermit, ShedReason> {
529        let Self { inner } = self;
530        let effective: usize = if inner.is_adaptive {
531            inner.effective_limit.load(Ordering::Relaxed)
532        } else {
533            inner.max_in_flight
534        };
535        let global_sem_permit: Option<OwnedSemaphorePermit> = match &inner.global_semaphore {
536            Some(sem) => {
537                let Ok(permit) = Arc::clone(sem).try_acquire_owned() else {
538                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
539                    return Err(ShedReason::GlobalLimitExceeded);
540                };
541                if !try_increment_bounded(&inner.global_in_flight, effective) {
542                    drop(permit);
543                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
544                    return Err(ShedReason::GlobalLimitExceeded);
545                }
546                Some(permit)
547            }
548            None => {
549                if !try_increment_bounded(&inner.global_in_flight, effective) {
550                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
551                    return Err(ShedReason::GlobalLimitExceeded);
552                }
553                None
554            }
555        };
556        let prefix_slot: u32 = self.match_prefix_slot(path);
557        let prefix_sem_permit: Option<OwnedSemaphorePermit> = if prefix_slot != NO_PREFIX_SLOT {
558            let rule: &CompiledPrefixLimit = &inner.prefixes[prefix_slot as usize];
559            match &rule.semaphore {
560                Some(sem) => {
561                    let Ok(permit) = Arc::clone(sem).try_acquire_owned() else {
562                        inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
563                        drop(global_sem_permit);
564                        inner.total_shed.fetch_add(1, Ordering::Relaxed);
565                        return Err(ShedReason::PrefixLimitExceeded);
566                    };
567                    rule.in_flight.fetch_add(1, Ordering::Relaxed);
568                    Some(permit)
569                }
570                None => {
571                    if !try_increment_bounded(&rule.in_flight, rule.max_in_flight) {
572                        inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
573                        drop(global_sem_permit);
574                        inner.total_shed.fetch_add(1, Ordering::Relaxed);
575                        return Err(ShedReason::PrefixLimitExceeded);
576                    }
577                    None
578                }
579            }
580        } else {
581            None
582        };
583        inner.total_admitted.fetch_add(1, Ordering::Relaxed);
584        let sem_permits: Option<Box<Mutex<Option<HeldSemaphorePermits>>>> =
585            if global_sem_permit.is_some() || prefix_sem_permit.is_some() {
586                Some(Box::new(Mutex::new(Some(HeldSemaphorePermits {
587                    global: global_sem_permit,
588                    prefix: prefix_sem_permit,
589                }))))
590            } else {
591                None
592            };
593        let acquired_at_us_plus_one: u64 = if inner.is_adaptive {
594            elapsed_micros_u64(inner.epoch).wrapping_add(1)
595        } else {
596            0
597        };
598        Ok(ConcurrencyPermit {
599            inner: Arc::new(ConcurrencyPermitInner {
600                limiter: Arc::clone(inner),
601                sem_permits,
602                acquired_at_us_plus_one,
603                prefix_slot,
604                released: AtomicBool::new(false),
605            }),
606        })
607    }
608
609    /// Acquires a [`ConcurrencyPermit`], using the lock-free fast path first and optional bounded wait queue if saturated.
610    ///
611    /// # Arguments
612    ///
613    /// - `&str` - Incoming request path.
614    ///
615    /// # Returns
616    ///
617    /// - `Result<ConcurrencyPermit, ShedReason>` - Acquired RAII permit or shed reason.
618    #[inline]
619    pub async fn acquire(&self, path: &str) -> Result<ConcurrencyPermit, ShedReason> {
620        let Self { inner } = self;
621        if !inner.has_wait_queue {
622            return self.try_acquire(path);
623        }
624        self.acquire_with_wait_queue(path).await
625    }
626
627    /// Cold async path handling bounded Tokio semaphore queuing when wait timeouts are configured.
628    ///
629    /// # Arguments
630    ///
631    /// - `&str` - Incoming request path.
632    ///
633    /// # Returns
634    ///
635    /// - `Result<ConcurrencyPermit, ShedReason>` - Acquired RAII permit or shed reason.
636    #[cold]
637    async fn acquire_with_wait_queue(&self, path: &str) -> Result<ConcurrencyPermit, ShedReason> {
638        let Self { inner } = self;
639        let prefix_slot: u32 = self.match_prefix_slot(path);
640        let has_global_wait: bool = inner.global_semaphore.is_some();
641        let has_prefix_wait: bool = prefix_slot != NO_PREFIX_SLOT
642            && inner
643                .prefixes
644                .get(prefix_slot as usize)
645                .is_some_and(|r: &CompiledPrefixLimit| r.semaphore.is_some());
646        if !has_global_wait && !has_prefix_wait {
647            return self.try_acquire(path);
648        }
649        let global_sem_permit: Option<OwnedSemaphorePermit> = match &inner.global_semaphore {
650            Some(sem) => {
651                let fast: Option<OwnedSemaphorePermit> = Arc::clone(sem).try_acquire_owned().ok();
652                let owned: OwnedSemaphorePermit = match fast {
653                    Some(p) => p,
654                    None => {
655                        let dur: Duration =
656                            Duration::from_millis(inner.config.get_wait_timeout_ms());
657                        match timeout(dur, Arc::clone(sem).acquire_owned()).await {
658                            Ok(Ok(p)) => p,
659                            _ => {
660                                inner.total_shed.fetch_add(1, Ordering::Relaxed);
661                                return Err(ShedReason::WaitTimedOut);
662                            }
663                        }
664                    }
665                };
666                let effective: usize = if inner.is_adaptive {
667                    inner.effective_limit.load(Ordering::Relaxed)
668                } else {
669                    inner.max_in_flight
670                };
671                if !try_increment_bounded(&inner.global_in_flight, effective) {
672                    drop(owned);
673                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
674                    return Err(ShedReason::GlobalLimitExceeded);
675                }
676                Some(owned)
677            }
678            None => {
679                let effective: usize = if inner.is_adaptive {
680                    inner.effective_limit.load(Ordering::Relaxed)
681                } else {
682                    inner.max_in_flight
683                };
684                if !try_increment_bounded(&inner.global_in_flight, effective) {
685                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
686                    return Err(ShedReason::GlobalLimitExceeded);
687                }
688                None
689            }
690        };
691        let prefix_sem_permit: Option<OwnedSemaphorePermit> = if prefix_slot != NO_PREFIX_SLOT {
692            let rule: &CompiledPrefixLimit = &inner.prefixes[prefix_slot as usize];
693            match &rule.semaphore {
694                Some(sem) => {
695                    let fast: Option<OwnedSemaphorePermit> =
696                        Arc::clone(sem).try_acquire_owned().ok();
697                    let owned: OwnedSemaphorePermit = match fast {
698                        Some(p) => p,
699                        None => {
700                            let dur: Duration = Duration::from_millis(rule.wait_timeout_ms);
701                            match timeout(dur, Arc::clone(sem).acquire_owned()).await {
702                                Ok(Ok(p)) => p,
703                                _ => {
704                                    inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
705                                    drop(global_sem_permit);
706                                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
707                                    return Err(ShedReason::WaitTimedOut);
708                                }
709                            }
710                        }
711                    };
712                    rule.in_flight.fetch_add(1, Ordering::Relaxed);
713                    Some(owned)
714                }
715                None => {
716                    if !try_increment_bounded(&rule.in_flight, rule.max_in_flight) {
717                        inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
718                        drop(global_sem_permit);
719                        inner.total_shed.fetch_add(1, Ordering::Relaxed);
720                        return Err(ShedReason::PrefixLimitExceeded);
721                    }
722                    None
723                }
724            }
725        } else {
726            None
727        };
728        inner.total_admitted.fetch_add(1, Ordering::Relaxed);
729        let acquired_at_us_plus_one: u64 = if inner.is_adaptive {
730            elapsed_micros_u64(inner.epoch).wrapping_add(1)
731        } else {
732            0
733        };
734        Ok(ConcurrencyPermit {
735            inner: Arc::new(ConcurrencyPermitInner {
736                limiter: Arc::clone(inner),
737                sem_permits: Some(Box::new(Mutex::new(Some(HeldSemaphorePermits {
738                    global: global_sem_permit,
739                    prefix: prefix_sem_permit,
740                })))),
741                acquired_at_us_plus_one,
742                prefix_slot,
743                released: AtomicBool::new(false),
744            }),
745        })
746    }
747
748    /// Returns a lock-free diagnostic snapshot of live concurrency and latency metrics.
749    ///
750    /// # Returns
751    ///
752    /// - `ConcurrencySnapshot` - Current counters and adaptive state.
753    pub fn snapshot(&self) -> ConcurrencySnapshot {
754        let Self { inner } = self;
755        ConcurrencySnapshot {
756            in_flight: inner.global_in_flight.load(Ordering::Acquire),
757            effective_limit: inner.effective_limit.load(Ordering::Acquire),
758            ewma_latency_us: inner.ewma_latency_us.load(Ordering::Acquire),
759            total_admitted: inner.total_admitted.load(Ordering::Acquire),
760            total_shed: inner.total_shed.load(Ordering::Acquire),
761        }
762    }
763
764    /// Returns the live in-flight request count for the rule matching `prefix`, if configured.
765    ///
766    /// # Arguments
767    ///
768    /// - `&str` - Route prefix string.
769    ///
770    /// # Returns
771    ///
772    /// - `Option<usize>` - Current in-flight count for that prefix.
773    pub fn prefix_in_flight(&self, prefix: &str) -> Option<usize> {
774        let Self { inner } = self;
775        let normalized: String = normalize_prefix(prefix);
776        inner
777            .prefixes
778            .iter()
779            .find(|r: &&CompiledPrefixLimit| r.prefix == normalized)
780            .map(|r: &CompiledPrefixLimit| r.in_flight.load(Ordering::Acquire))
781    }
782
783    /// Manually injects a synthetic latency sample (in microseconds) to drive adaptive limit adjustment.
784    ///
785    /// # Arguments
786    ///
787    /// - `u64` - Observed latency sample in microseconds.
788    pub fn record_latency_us(&self, sample_us: u64) {
789        let Self { inner } = self;
790        if let Some(adaptive) = inner.config.try_get_adaptive() {
791            record_adaptive_sample(inner, adaptive, sample_us);
792        }
793    }
794}
795
796/// Process-wide singleton management for [`ConcurrencyPlugin`].
797impl ConcurrencyPlugin {
798    /// Initializes the global [`ConcurrencyPlugin`] once with `config`.
799    ///
800    /// # Arguments
801    ///
802    /// - `ConcurrencyConfig` - Concurrency limiter configuration.
803    ///
804    /// # Returns
805    ///
806    /// - `&'static Self` - Reference to the initialized global plugin.
807    pub fn init(config: ConcurrencyConfig) -> &'static Self {
808        CONCURRENCY_PLUGIN.get_or_init(|| Self {
809            limiter: ConcurrencyLimiter::new(config),
810        })
811    }
812
813    /// Returns the initialized global [`ConcurrencyPlugin`], if initialized.
814    ///
815    /// # Returns
816    ///
817    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
818    #[inline]
819    pub fn get() -> Option<&'static Self> {
820        CONCURRENCY_PLUGIN.get()
821    }
822
823    /// Returns the shared [`ConcurrencyLimiter`].
824    ///
825    /// # Returns
826    ///
827    /// - `&ConcurrencyLimiter` - Active concurrency limiter.
828    #[inline]
829    pub fn get_limiter(&self) -> &ConcurrencyLimiter {
830        let Self { limiter } = self;
831        limiter
832    }
833}
834
835/// Implements [`ServerHook`] for [`ConcurrencyRequestHook`].
836impl ServerHook for ConcurrencyRequestHook {
837    /// Constructs a per-request [`ConcurrencyRequestHook`].
838    ///
839    /// # Arguments
840    ///
841    /// - `&mut Stream` - Connection stream.
842    /// - `&mut Context` - Request context.
843    ///
844    /// # Returns
845    ///
846    /// - `Self` - Hook instance.
847    async fn new(_: &mut Stream, _: &mut Context) -> Self {
848        Self
849    }
850
851    /// Acquires a [`ConcurrencyPermit`] into `Context`, or sheds excess load with prebuilt `503` wire bytes.
852    ///
853    /// # Arguments
854    ///
855    /// - `Self` - Hook instance.
856    /// - `&mut Stream` - Connection stream.
857    /// - `&mut Context` - Request context.
858    ///
859    /// # Returns
860    ///
861    /// - `Status` - `Status::Continue` when admitted/unconfigured/exempt; `Status::Reject` when shed.
862    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
863        let Some(plugin) = ConcurrencyPlugin::get() else {
864            return Status::Continue;
865        };
866        let limiter: &ConcurrencyLimiter = plugin.get_limiter();
867        let path: &str = ctx.get_request().get_path();
868        if limiter.is_path_exempt(path) {
869            return Status::Continue;
870        }
871        let acquire_res: Result<ConcurrencyPermit, ShedReason> = if limiter.has_wait_queue() {
872            limiter.acquire(path).await
873        } else {
874            limiter.try_acquire(path)
875        };
876        match acquire_res {
877            Ok(permit) => {
878                ctx.set_attribute(ATTR_CONCURRENCY_PERMIT, permit);
879                Status::Continue
880            }
881            Err(_) => {
882                let _: Result<(), ResponseError> =
883                    stream.try_send(limiter.get_prebuilt_reject_wire()).await;
884                Status::Reject
885            }
886        }
887    }
888}
889
890/// Implements [`ServerHook`] for [`ConcurrencyResponseHook`].
891impl ServerHook for ConcurrencyResponseHook {
892    /// Constructs a per-response [`ConcurrencyResponseHook`].
893    ///
894    /// # Arguments
895    ///
896    /// - `&mut Stream` - Connection stream.
897    /// - `&mut Context` - Request context.
898    ///
899    /// # Returns
900    ///
901    /// - `Self` - Hook instance.
902    async fn new(_: &mut Stream, _: &mut Context) -> Self {
903        Self
904    }
905
906    /// Explicitly releases the [`ConcurrencyPermit`] stored in `Context` and removes the attribute.
907    ///
908    /// # Arguments
909    ///
910    /// - `Self` - Hook instance.
911    /// - `&mut Stream` - Connection stream.
912    /// - `&mut Context` - Request context.
913    ///
914    /// # Returns
915    ///
916    /// - `Status` - Always `Status::Continue`.
917    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
918        if let Some(permit) =
919            ctx.try_get_attribute_ref::<ConcurrencyPermit, _>(ATTR_CONCURRENCY_PERMIT)
920        {
921            permit.release();
922            ctx.remove_attribute(ATTR_CONCURRENCY_PERMIT);
923        }
924        Status::Continue
925    }
926}