hyperlane-plugin-concurrency 23.0.0

A lock-free atomic global and per-route-prefix in-flight concurrency limiter and adaptive load-shedding plugin for the Hyperlane framework with optional bounded Tokio Semaphore queuing, leak-proof RAII Context permits, and prebuilt 503 Retry-After wire responses.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
use super::*;

/// Inherent constructors and builders for [`PrefixConcurrencyLimit`].
impl PrefixConcurrencyLimit {
    /// Creates a per-route-prefix concurrency limit rule.
    ///
    /// # Arguments
    ///
    /// - `S` - Route path prefix (for example `"/api/export"`).
    /// - `usize` - Maximum concurrent in-flight requests under `prefix`.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed prefix concurrency rule.
    pub fn new<S>(prefix: S, max_in_flight: usize) -> Self
    where
        S: Into<String>,
    {
        Self {
            prefix: prefix.into(),
            max_in_flight: max_in_flight.max(1),
            wait_timeout_ms: 0,
        }
    }

    /// Sets the optional bounded wait timeout in milliseconds for this prefix.
    ///
    /// # Arguments
    ///
    /// - `u64` - Wait timeout in milliseconds (`0` sheds immediately).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated prefix rule.
    pub fn with_wait_timeout_ms(mut self, wait_timeout_ms: u64) -> Self {
        self.set_wait_timeout_ms(wait_timeout_ms);
        self
    }
}

/// Default construction for [`AdaptiveShedConfig`].
impl Default for AdaptiveShedConfig {
    /// Constructs default AIMD adaptive load-shedding settings (100 ms target, min limit 4, 80% backoff).
    ///
    /// # Returns
    ///
    /// - `Self` - Default adaptive shedding configuration.
    fn default() -> Self {
        Self {
            target_latency_ms: DEFAULT_ADAPTIVE_TARGET_LATENCY_MS,
            min_limit: 4,
            additive_increase: 1,
            decrease_percent: 80,
        }
    }
}

/// Inherent fluent builders for [`AdaptiveShedConfig`].
impl AdaptiveShedConfig {
    /// Creates an [`AdaptiveShedConfig`] targeting `target_latency_ms` with a floor of `min_limit`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Target request latency in milliseconds.
    /// - `usize` - Minimum effective concurrency floor.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed adaptive configuration.
    pub fn new(target_latency_ms: u64, min_limit: usize) -> Self {
        Self {
            target_latency_ms: target_latency_ms.max(1),
            min_limit: min_limit.max(1),
            additive_increase: 1,
            decrease_percent: 80,
        }
    }

    /// Sets the additive increase step applied on fast completions.
    ///
    /// # Arguments
    ///
    /// - `usize` - Additive increment (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_additive_increase(mut self, step: usize) -> Self {
        self.set_additive_increase(step.max(1));
        self
    }

    /// Sets the multiplicative backoff percentage (`1..=99`) applied when latency exceeds target.
    ///
    /// # Arguments
    ///
    /// - `usize` - Retained limit percentage (`1..=99`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_decrease_percent(mut self, percent: usize) -> Self {
        self.set_decrease_percent(percent.clamp(1, 99));
        self
    }
}

/// Default construction for [`ConcurrencyConfig`].
impl Default for ConcurrencyConfig {
    /// Constructs a default [`ConcurrencyConfig`] (1 024 max in-flight, immediate shedding, `503` + `Retry-After: 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            max_in_flight: DEFAULT_MAX_IN_FLIGHT,
            wait_timeout_ms: 0,
            adaptive: None,
            prefix_limits: Vec::new(),
            exempt_paths: Vec::new(),
            retry_after_secs: DEFAULT_RETRY_AFTER_SECS,
            reject_content_type: DEFAULT_SHED_CONTENT_TYPE.to_owned(),
            reject_body: DEFAULT_SHED_BODY.to_vec(),
        }
    }
}

/// Fluent configuration builders for [`ConcurrencyConfig`].
impl ConcurrencyConfig {
    /// Creates a [`ConcurrencyConfig`] capped at `max_in_flight` concurrent requests.
    ///
    /// # Arguments
    ///
    /// - `usize` - Global in-flight limit (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed configuration.
    pub fn new(max_in_flight: usize) -> Self {
        Self::default().with_max_in_flight(max_in_flight)
    }

    /// Sets the global maximum concurrent in-flight requests.
    ///
    /// # Arguments
    ///
    /// - `usize` - Global in-flight limit (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_max_in_flight(mut self, max_in_flight: usize) -> Self {
        self.set_max_in_flight(max_in_flight.max(1));
        self
    }

    /// Sets the global bounded wait timeout in milliseconds (`0` disables queuing).
    ///
    /// # Arguments
    ///
    /// - `u64` - Wait timeout in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_wait_timeout_ms(mut self, wait_timeout_ms: u64) -> Self {
        self.set_wait_timeout_ms(wait_timeout_ms);
        self
    }

    /// Enables AIMD latency-driven adaptive load shedding.
    ///
    /// # Arguments
    ///
    /// - `AdaptiveShedConfig` - Adaptive shedding parameters.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_adaptive(mut self, adaptive: AdaptiveShedConfig) -> Self {
        self.set_adaptive(Some(adaptive));
        self
    }

    /// Adds a per-route-prefix concurrency limit rule.
    ///
    /// # Arguments
    ///
    /// - `PrefixConcurrencyLimit` - Route-prefix limit rule.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_prefix_limit(mut self, rule: PrefixConcurrencyLimit) -> Self {
        self.get_mut_prefix_limits().push(rule);
        self
    }

    /// Sets exact request paths bypassed by concurrency limiting.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of exact exempt paths.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the `Retry-After` header value in seconds for shed `503` responses.
    ///
    /// # Arguments
    ///
    /// - `u64` - Retry delay in seconds (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_retry_after_secs(mut self, secs: u64) -> Self {
        self.set_retry_after_secs(secs.max(1));
        self
    }

    /// Customizes the `Content-Type` and body emitted on `503 Service Unavailable` responses.
    ///
    /// # Arguments
    ///
    /// - `C` - `Content-Type` header value.
    /// - `B` - Response body bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_reject_body<C, B>(mut self, content_type: C, body: B) -> Self
    where
        C: Into<String>,
        B: Into<Vec<u8>>,
    {
        self.set_reject_content_type(content_type.into())
            .set_reject_body(body.into());
        self
    }
}

/// Releases the underlying concurrency slots atomically at most once.
impl ConcurrencyPermitInner {
    /// Atomically decrements in-flight counters, updates adaptive EWMA, and drops queued semaphore permits.
    #[inline]
    pub(crate) fn release_once(&self) {
        let Self {
            released,
            limiter,
            prefix_slot,
            acquired_at_us_plus_one,
            sem_permits,
        } = self;
        if released.swap(true, Ordering::Relaxed) {
            return;
        }
        let slot: u32 = *prefix_slot;
        if slot != NO_PREFIX_SLOT
            && let Some(rule) = limiter.prefixes.get(slot as usize)
        {
            rule.in_flight.fetch_sub(1, Ordering::Relaxed);
        }
        limiter.global_in_flight.fetch_sub(1, Ordering::Relaxed);
        let started_plus_one: u64 = *acquired_at_us_plus_one;
        if started_plus_one != 0 {
            let now_us: u64 = elapsed_micros_u64(limiter.epoch);
            let elapsed_us: u64 = now_us.saturating_sub(started_plus_one - 1);
            record_adaptive_sample(limiter, limiter.adaptive_cfg, elapsed_us);
        }
        if let Some(mutex) = sem_permits
            && let Ok(mut guard) = mutex.lock()
            && let Some(HeldSemaphorePermits { global, prefix }) = guard.take()
        {
            drop(prefix);
            drop(global);
        }
    }
}

/// Guarantees automatic permit release when dropped on early reject, panic, or connection drop.
impl Drop for ConcurrencyPermitInner {
    /// Releases the permit if it has not already been explicitly released.
    #[inline]
    fn drop(&mut self) {
        let Self { released, .. } = self;
        if !*released.get_mut() {
            self.release_once();
        }
    }
}

/// Inherent release and inspection helpers for [`ConcurrencyPermit`].
impl ConcurrencyPermit {
    /// Explicitly releases the concurrency permit immediately (idempotent).
    #[inline(always)]
    pub fn release(&self) {
        let Self { inner } = self;
        inner.release_once();
    }

    /// Reports whether this permit has already been released.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when already released.
    #[inline(always)]
    pub fn is_released(&self) -> bool {
        let Self { inner } = self;
        inner.released.load(Ordering::Acquire)
    }

    /// Retrieves the active [`ConcurrencyPermit`] stored in `ctx`, if present.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Active Hyperlane context.
    ///
    /// # Returns
    ///
    /// - `Option<Self>` - Permit handle when present.
    pub fn from_context(ctx: &Context) -> Option<Self> {
        ctx.try_get_attribute::<Self, _>(ATTR_CONCURRENCY_PERMIT)
    }
}

/// Inherent construction, acquisition, and metrics methods for [`ConcurrencyLimiter`].
impl ConcurrencyLimiter {
    /// Compiles `config` into a lock-free [`ConcurrencyLimiter`] with a prebuilt `503` response.
    ///
    /// # Arguments
    ///
    /// - `ConcurrencyConfig` - Concurrency and adaptive load-shedding configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready concurrency limiter.
    pub fn new(config: ConcurrencyConfig) -> Self {
        let max_in_flight: usize = config.get_max_in_flight().max(1);
        let (is_adaptive, adaptive_cfg): (bool, AdaptiveShedConfig) =
            match config.try_get_adaptive() {
                Some(cfg) => (true, cfg),
                None => (false, AdaptiveShedConfig::default()),
            };
        let global_semaphore: Option<Arc<Semaphore>> = if config.get_wait_timeout_ms() > 0 {
            Some(Arc::new(Semaphore::new(max_in_flight)))
        } else {
            None
        };
        let mut prefixes_vec: Vec<CompiledPrefixLimit> = config
            .get_prefix_limits()
            .iter()
            .filter(|r: &&PrefixConcurrencyLimit| !r.get_prefix().trim().is_empty())
            .map(|r: &PrefixConcurrencyLimit| {
                let limit: usize = r.get_max_in_flight().max(1);
                let sem: Option<Arc<Semaphore>> = if r.get_wait_timeout_ms() > 0 {
                    Some(Arc::new(Semaphore::new(limit)))
                } else {
                    None
                };
                CompiledPrefixLimit {
                    prefix: normalize_prefix(r.get_prefix()),
                    max_in_flight: limit,
                    wait_timeout_ms: r.get_wait_timeout_ms(),
                    in_flight: AtomicUsize::new(0),
                    semaphore: sem,
                }
            })
            .collect();
        prefixes_vec.sort_by_key(|rule: &CompiledPrefixLimit| Reverse(rule.prefix.len()));
        let has_wait_queue: bool = global_semaphore.is_some()
            || prefixes_vec
                .iter()
                .any(|rule: &CompiledPrefixLimit| rule.semaphore.is_some());
        let prefixes: Box<[CompiledPrefixLimit]> = prefixes_vec.into_boxed_slice();
        let non_empty_exempt: Vec<String> = config
            .get_exempt_paths()
            .iter()
            .filter(|p: &&String| !p.is_empty())
            .cloned()
            .collect();
        let (exempt_small, exempt_set): (Box<[String]>, Option<HashSetXxHash3_64<String>>) =
            if non_empty_exempt.len() > EXEMPT_SET_THRESHOLD {
                let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
                for path in non_empty_exempt {
                    set.insert(path);
                }
                (Box::new([]), Some(set))
            } else {
                (non_empty_exempt.into_boxed_slice(), None)
            };
        let mut reject_resp: Response = Response::default();
        reject_resp
            .set_status_code(HttpStatus::ServiceUnavailable.code())
            .set_header(RETRY_AFTER, config.get_retry_after_secs().to_string())
            .set_header(CONTENT_TYPE, config.get_reject_content_type())
            .set_body(config.get_reject_body().clone());
        let prebuilt_reject_wire: Vec<u8> = reject_resp.build();
        Self {
            inner: Arc::new(ConcurrencyLimiterInner {
                config,
                max_in_flight,
                is_adaptive,
                adaptive_cfg,
                has_wait_queue,
                epoch: Instant::now(),
                global_in_flight: AtomicUsize::new(0),
                effective_limit: AtomicUsize::new(max_in_flight),
                ewma_latency_us: AtomicU64::new(0),
                total_admitted: AtomicU64::new(0),
                total_shed: AtomicU64::new(0),
                global_semaphore,
                prefixes,
                exempt_small,
                exempt_set,
                prebuilt_reject_wire,
            }),
        }
    }

    /// Returns the source [`ConcurrencyConfig`].
    ///
    /// # Returns
    ///
    /// - `&ConcurrencyConfig` - Active configuration.
    pub fn get_config(&self) -> &ConcurrencyConfig {
        let Self { inner } = self;
        &inner.config
    }

    /// Returns the prebuilt `503 Service Unavailable` + `Retry-After` HTTP wire buffer.
    ///
    /// # Returns
    ///
    /// - `&Vec<u8>` - Pre-serialized wire bytes.
    #[inline(always)]
    pub fn get_prebuilt_reject_wire(&self) -> &Vec<u8> {
        let Self { inner } = self;
        &inner.prebuilt_reject_wire
    }

    /// Reports whether any global or per-prefix bounded wait queue is configured.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when semaphore waiting may be needed.
    #[inline(always)]
    pub(crate) fn has_wait_queue(&self) -> bool {
        let Self { inner } = self;
        inner.has_wait_queue
    }

    /// Reports whether `path` is exempted from concurrency enforcement.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when exempt.
    #[inline(always)]
    pub fn is_path_exempt(&self, path: &str) -> bool {
        let Self { inner } = self;
        if let Some(ref set) = inner.exempt_set {
            return set.contains(path);
        }
        let small: &[String] = &inner.exempt_small;
        if small.is_empty() {
            return false;
        }
        let path_bytes: &[u8] = path.as_bytes();
        let path_len: usize = path_bytes.len();
        for item in small {
            let item_bytes: &[u8] = item.as_bytes();
            if item_bytes.len() == path_len && item_bytes == path_bytes {
                return true;
            }
        }
        false
    }

    /// Finds the index of the longest matching per-prefix rule for `path`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `u32` - Index into compiled prefix limits, or [`NO_PREFIX_SLOT`] if unmatched.
    #[inline(always)]
    pub(crate) fn match_prefix_slot(&self, path: &str) -> u32 {
        let Self { inner } = self;
        let prefixes: &[CompiledPrefixLimit] = &inner.prefixes;
        if prefixes.is_empty() {
            return NO_PREFIX_SLOT;
        }
        let path_bytes: &[u8] = path.as_bytes();
        for (idx, rule) in prefixes.iter().enumerate() {
            if path_matches_prefix_bytes(path_bytes, rule.prefix.as_bytes()) {
                return idx as u32;
            }
        }
        NO_PREFIX_SLOT
    }

    /// Fast synchronous lock-free attempt to acquire a permit without waiting.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `Result<ConcurrencyPermit, ShedReason>` - Acquired RAII permit or shed reason.
    #[inline]
    pub fn try_acquire(&self, path: &str) -> Result<ConcurrencyPermit, ShedReason> {
        let Self { inner } = self;
        let effective: usize = if inner.is_adaptive {
            inner.effective_limit.load(Ordering::Relaxed)
        } else {
            inner.max_in_flight
        };
        let global_sem_permit: Option<OwnedSemaphorePermit> = match &inner.global_semaphore {
            Some(sem) => {
                let Ok(permit) = Arc::clone(sem).try_acquire_owned() else {
                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
                    return Err(ShedReason::GlobalLimitExceeded);
                };
                if !try_increment_bounded(&inner.global_in_flight, effective) {
                    drop(permit);
                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
                    return Err(ShedReason::GlobalLimitExceeded);
                }
                Some(permit)
            }
            None => {
                if !try_increment_bounded(&inner.global_in_flight, effective) {
                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
                    return Err(ShedReason::GlobalLimitExceeded);
                }
                None
            }
        };
        let prefix_slot: u32 = self.match_prefix_slot(path);
        let prefix_sem_permit: Option<OwnedSemaphorePermit> = if prefix_slot != NO_PREFIX_SLOT {
            let rule: &CompiledPrefixLimit = &inner.prefixes[prefix_slot as usize];
            match &rule.semaphore {
                Some(sem) => {
                    let Ok(permit) = Arc::clone(sem).try_acquire_owned() else {
                        inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
                        drop(global_sem_permit);
                        inner.total_shed.fetch_add(1, Ordering::Relaxed);
                        return Err(ShedReason::PrefixLimitExceeded);
                    };
                    rule.in_flight.fetch_add(1, Ordering::Relaxed);
                    Some(permit)
                }
                None => {
                    if !try_increment_bounded(&rule.in_flight, rule.max_in_flight) {
                        inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
                        drop(global_sem_permit);
                        inner.total_shed.fetch_add(1, Ordering::Relaxed);
                        return Err(ShedReason::PrefixLimitExceeded);
                    }
                    None
                }
            }
        } else {
            None
        };
        inner.total_admitted.fetch_add(1, Ordering::Relaxed);
        let sem_permits: Option<Box<Mutex<Option<HeldSemaphorePermits>>>> =
            if global_sem_permit.is_some() || prefix_sem_permit.is_some() {
                Some(Box::new(Mutex::new(Some(HeldSemaphorePermits {
                    global: global_sem_permit,
                    prefix: prefix_sem_permit,
                }))))
            } else {
                None
            };
        let acquired_at_us_plus_one: u64 = if inner.is_adaptive {
            elapsed_micros_u64(inner.epoch).wrapping_add(1)
        } else {
            0
        };
        Ok(ConcurrencyPermit {
            inner: Arc::new(ConcurrencyPermitInner {
                limiter: Arc::clone(inner),
                sem_permits,
                acquired_at_us_plus_one,
                prefix_slot,
                released: AtomicBool::new(false),
            }),
        })
    }

    /// Acquires a [`ConcurrencyPermit`], using the lock-free fast path first and optional bounded wait queue if saturated.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `Result<ConcurrencyPermit, ShedReason>` - Acquired RAII permit or shed reason.
    #[inline]
    pub async fn acquire(&self, path: &str) -> Result<ConcurrencyPermit, ShedReason> {
        let Self { inner } = self;
        if !inner.has_wait_queue {
            return self.try_acquire(path);
        }
        self.acquire_with_wait_queue(path).await
    }

    /// Cold async path handling bounded Tokio semaphore queuing when wait timeouts are configured.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `Result<ConcurrencyPermit, ShedReason>` - Acquired RAII permit or shed reason.
    #[cold]
    async fn acquire_with_wait_queue(&self, path: &str) -> Result<ConcurrencyPermit, ShedReason> {
        let Self { inner } = self;
        let prefix_slot: u32 = self.match_prefix_slot(path);
        let has_global_wait: bool = inner.global_semaphore.is_some();
        let has_prefix_wait: bool = prefix_slot != NO_PREFIX_SLOT
            && inner
                .prefixes
                .get(prefix_slot as usize)
                .is_some_and(|r: &CompiledPrefixLimit| r.semaphore.is_some());
        if !has_global_wait && !has_prefix_wait {
            return self.try_acquire(path);
        }
        let global_sem_permit: Option<OwnedSemaphorePermit> = match &inner.global_semaphore {
            Some(sem) => {
                let fast: Option<OwnedSemaphorePermit> = Arc::clone(sem).try_acquire_owned().ok();
                let owned: OwnedSemaphorePermit = match fast {
                    Some(p) => p,
                    None => {
                        let dur: Duration =
                            Duration::from_millis(inner.config.get_wait_timeout_ms());
                        match timeout(dur, Arc::clone(sem).acquire_owned()).await {
                            Ok(Ok(p)) => p,
                            _ => {
                                inner.total_shed.fetch_add(1, Ordering::Relaxed);
                                return Err(ShedReason::WaitTimedOut);
                            }
                        }
                    }
                };
                let effective: usize = if inner.is_adaptive {
                    inner.effective_limit.load(Ordering::Relaxed)
                } else {
                    inner.max_in_flight
                };
                if !try_increment_bounded(&inner.global_in_flight, effective) {
                    drop(owned);
                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
                    return Err(ShedReason::GlobalLimitExceeded);
                }
                Some(owned)
            }
            None => {
                let effective: usize = if inner.is_adaptive {
                    inner.effective_limit.load(Ordering::Relaxed)
                } else {
                    inner.max_in_flight
                };
                if !try_increment_bounded(&inner.global_in_flight, effective) {
                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
                    return Err(ShedReason::GlobalLimitExceeded);
                }
                None
            }
        };
        let prefix_sem_permit: Option<OwnedSemaphorePermit> = if prefix_slot != NO_PREFIX_SLOT {
            let rule: &CompiledPrefixLimit = &inner.prefixes[prefix_slot as usize];
            match &rule.semaphore {
                Some(sem) => {
                    let fast: Option<OwnedSemaphorePermit> =
                        Arc::clone(sem).try_acquire_owned().ok();
                    let owned: OwnedSemaphorePermit = match fast {
                        Some(p) => p,
                        None => {
                            let dur: Duration = Duration::from_millis(rule.wait_timeout_ms);
                            match timeout(dur, Arc::clone(sem).acquire_owned()).await {
                                Ok(Ok(p)) => p,
                                _ => {
                                    inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
                                    drop(global_sem_permit);
                                    inner.total_shed.fetch_add(1, Ordering::Relaxed);
                                    return Err(ShedReason::WaitTimedOut);
                                }
                            }
                        }
                    };
                    rule.in_flight.fetch_add(1, Ordering::Relaxed);
                    Some(owned)
                }
                None => {
                    if !try_increment_bounded(&rule.in_flight, rule.max_in_flight) {
                        inner.global_in_flight.fetch_sub(1, Ordering::Relaxed);
                        drop(global_sem_permit);
                        inner.total_shed.fetch_add(1, Ordering::Relaxed);
                        return Err(ShedReason::PrefixLimitExceeded);
                    }
                    None
                }
            }
        } else {
            None
        };
        inner.total_admitted.fetch_add(1, Ordering::Relaxed);
        let acquired_at_us_plus_one: u64 = if inner.is_adaptive {
            elapsed_micros_u64(inner.epoch).wrapping_add(1)
        } else {
            0
        };
        Ok(ConcurrencyPermit {
            inner: Arc::new(ConcurrencyPermitInner {
                limiter: Arc::clone(inner),
                sem_permits: Some(Box::new(Mutex::new(Some(HeldSemaphorePermits {
                    global: global_sem_permit,
                    prefix: prefix_sem_permit,
                })))),
                acquired_at_us_plus_one,
                prefix_slot,
                released: AtomicBool::new(false),
            }),
        })
    }

    /// Returns a lock-free diagnostic snapshot of live concurrency and latency metrics.
    ///
    /// # Returns
    ///
    /// - `ConcurrencySnapshot` - Current counters and adaptive state.
    pub fn snapshot(&self) -> ConcurrencySnapshot {
        let Self { inner } = self;
        ConcurrencySnapshot {
            in_flight: inner.global_in_flight.load(Ordering::Acquire),
            effective_limit: inner.effective_limit.load(Ordering::Acquire),
            ewma_latency_us: inner.ewma_latency_us.load(Ordering::Acquire),
            total_admitted: inner.total_admitted.load(Ordering::Acquire),
            total_shed: inner.total_shed.load(Ordering::Acquire),
        }
    }

    /// Returns the live in-flight request count for the rule matching `prefix`, if configured.
    ///
    /// # Arguments
    ///
    /// - `&str` - Route prefix string.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Current in-flight count for that prefix.
    pub fn prefix_in_flight(&self, prefix: &str) -> Option<usize> {
        let Self { inner } = self;
        let normalized: String = normalize_prefix(prefix);
        inner
            .prefixes
            .iter()
            .find(|r: &&CompiledPrefixLimit| r.prefix == normalized)
            .map(|r: &CompiledPrefixLimit| r.in_flight.load(Ordering::Acquire))
    }

    /// Manually injects a synthetic latency sample (in microseconds) to drive adaptive limit adjustment.
    ///
    /// # Arguments
    ///
    /// - `u64` - Observed latency sample in microseconds.
    pub fn record_latency_us(&self, sample_us: u64) {
        let Self { inner } = self;
        if let Some(adaptive) = inner.config.try_get_adaptive() {
            record_adaptive_sample(inner, adaptive, sample_us);
        }
    }
}

/// Process-wide singleton management for [`ConcurrencyPlugin`].
impl ConcurrencyPlugin {
    /// Initializes the global [`ConcurrencyPlugin`] once with `config`.
    ///
    /// # Arguments
    ///
    /// - `ConcurrencyConfig` - Concurrency limiter configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(config: ConcurrencyConfig) -> &'static Self {
        CONCURRENCY_PLUGIN.get_or_init(|| Self {
            limiter: ConcurrencyLimiter::new(config),
        })
    }

    /// Returns the initialized global [`ConcurrencyPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline]
    pub fn get() -> Option<&'static Self> {
        CONCURRENCY_PLUGIN.get()
    }

    /// Returns the shared [`ConcurrencyLimiter`].
    ///
    /// # Returns
    ///
    /// - `&ConcurrencyLimiter` - Active concurrency limiter.
    #[inline]
    pub fn get_limiter(&self) -> &ConcurrencyLimiter {
        let Self { limiter } = self;
        limiter
    }
}

/// Implements [`ServerHook`] for [`ConcurrencyRequestHook`].
impl ServerHook for ConcurrencyRequestHook {
    /// Constructs a per-request [`ConcurrencyRequestHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Acquires a [`ConcurrencyPermit`] into `Context`, or sheds excess load with prebuilt `503` wire bytes.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Continue` when admitted/unconfigured/exempt; `Status::Reject` when shed.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = ConcurrencyPlugin::get() else {
            return Status::Continue;
        };
        let limiter: &ConcurrencyLimiter = plugin.get_limiter();
        let path: &str = ctx.get_request().get_path();
        if limiter.is_path_exempt(path) {
            return Status::Continue;
        }
        let acquire_res: Result<ConcurrencyPermit, ShedReason> = if limiter.has_wait_queue() {
            limiter.acquire(path).await
        } else {
            limiter.try_acquire(path)
        };
        match acquire_res {
            Ok(permit) => {
                ctx.set_attribute(ATTR_CONCURRENCY_PERMIT, permit);
                Status::Continue
            }
            Err(_) => {
                let _: Result<(), ResponseError> =
                    stream.try_send(limiter.get_prebuilt_reject_wire()).await;
                Status::Reject
            }
        }
    }
}

/// Implements [`ServerHook`] for [`ConcurrencyResponseHook`].
impl ServerHook for ConcurrencyResponseHook {
    /// Constructs a per-response [`ConcurrencyResponseHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Explicitly releases the [`ConcurrencyPermit`] stored in `Context` and removes the attribute.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        if let Some(permit) = ConcurrencyPermit::from_context(ctx) {
            permit.release();
            ctx.remove_attribute(ATTR_CONCURRENCY_PERMIT);
        }
        Status::Continue
    }
}