hyperlane-plugin-concurrency 23.2.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
use super::*;

/// Per-route-prefix in-flight concurrency rule.
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct PrefixConcurrencyLimit {
    /// Path prefix matched on URL segment boundaries (for example `"/api/heavy"`).
    pub(crate) prefix: String,
    /// Maximum concurrent in-flight requests allowed under this prefix.
    #[get(type(copy))]
    pub(crate) max_in_flight: usize,
    /// Optional bounded wait timeout in milliseconds (`0` sheds immediately without queuing).
    #[get(type(copy))]
    pub(crate) wait_timeout_ms: u64,
}

/// Latency-driven AIMD adaptive load-shedding parameters.
#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
pub struct AdaptiveShedConfig {
    /// Target request latency in milliseconds; requests exceeding this reduce the effective limit.
    #[get(type(copy))]
    pub(crate) target_latency_ms: u64,
    /// Lower bound floor for the dynamically adjusted global concurrency limit.
    #[get(type(copy))]
    pub(crate) min_limit: usize,
    /// Additive increment applied on fast completions (`>= 1`).
    #[get(type(copy))]
    pub(crate) additive_increase: usize,
    /// Backoff numerator in percentage (`1..=99`, for example `80` shrinks limit to 80% on overload).
    #[get(type(copy))]
    pub(crate) decrease_percent: usize,
}

/// Top-level configuration for [`ConcurrencyLimiter`] and [`ConcurrencyPlugin`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct ConcurrencyConfig {
    /// Global maximum concurrent in-flight requests (`>= 1`).
    #[get(type(copy))]
    pub(crate) max_in_flight: usize,
    /// Optional global bounded wait timeout in milliseconds (`0` sheds immediately without queuing).
    #[get(type(copy))]
    pub(crate) wait_timeout_ms: u64,
    /// Optional latency-driven AIMD adaptive load-shedding policy.
    #[get(type(copy))]
    pub(crate) adaptive: Option<AdaptiveShedConfig>,
    /// Per-route-prefix concurrency rules (evaluated longest-prefix first).
    pub(crate) prefix_limits: Vec<PrefixConcurrencyLimit>,
    /// Exact paths bypassed by [`ConcurrencyRequestHook`] (for example `"/healthz"`).
    pub(crate) exempt_paths: Vec<String>,
    /// `Retry-After` header value in seconds attached to `503` responses.
    #[get(type(copy))]
    pub(crate) retry_after_secs: u64,
    /// `Content-Type` header emitted on shed responses.
    pub(crate) reject_content_type: String,
    /// Body bytes emitted on shed responses.
    pub(crate) reject_body: Vec<u8>,
}

/// Lock-free runtime state for one compiled route-prefix concurrency rule.
pub(crate) struct CompiledPrefixLimit {
    /// Normalized prefix string (without trailing slash except `"/"`).
    pub(crate) prefix: String,
    /// Maximum concurrent in-flight requests for this prefix.
    pub(crate) max_in_flight: usize,
    /// Bounded wait timeout in milliseconds (`0` = immediate lock-free shedding).
    pub(crate) wait_timeout_ms: u64,
    /// Current active in-flight request count under this prefix.
    pub(crate) in_flight: AtomicUsize,
    /// Optional Tokio semaphore created only when `wait_timeout_ms > 0`.
    pub(crate) semaphore: Option<Arc<Semaphore>>,
}

/// Optional Tokio semaphore permits held by a [`ConcurrencyPermit`] when wait queuing is enabled.
pub(crate) struct HeldSemaphorePermits {
    /// Optional global queue permit.
    pub(crate) global: Option<OwnedSemaphorePermit>,
    /// Optional prefix queue permit.
    pub(crate) prefix: Option<OwnedSemaphorePermit>,
}

/// Shared interior state of [`ConcurrencyLimiter`].
pub(crate) struct ConcurrencyLimiterInner {
    /// Source configuration retained for inspection.
    pub(crate) config: ConcurrencyConfig,
    /// Cached global maximum in-flight ceiling (`>= 1`).
    pub(crate) max_in_flight: usize,
    /// `true` when latency-driven AIMD adaptive load shedding is enabled.
    pub(crate) is_adaptive: bool,
    /// Cached adaptive configuration used when `is_adaptive` is `true`.
    pub(crate) adaptive_cfg: AdaptiveShedConfig,
    /// `true` when global or any prefix rule has bounded wait queuing enabled.
    pub(crate) has_wait_queue: bool,
    /// Monotonic time origin for compact 64-bit microsecond latency timestamps.
    pub(crate) epoch: Instant,
    /// Current active global in-flight requests.
    pub(crate) global_in_flight: AtomicUsize,
    /// Effective global concurrency ceiling (updated dynamically when adaptive shedding is active).
    pub(crate) effective_limit: AtomicUsize,
    /// Lock-free EWMA request latency in microseconds.
    pub(crate) ewma_latency_us: AtomicU64,
    /// Total admitted requests since creation.
    pub(crate) total_admitted: AtomicU64,
    /// Total shed requests since creation.
    pub(crate) total_shed: AtomicU64,
    /// Optional global Tokio semaphore created only when `wait_timeout_ms > 0`.
    pub(crate) global_semaphore: Option<Arc<Semaphore>>,
    /// Compiled prefix rules sorted from longest prefix to shortest prefix.
    pub(crate) prefixes: Box<[CompiledPrefixLimit]>,
    /// Small inline exempt path list used when `len <= EXEMPT_SET_THRESHOLD`.
    pub(crate) exempt_small: Box<[String]>,
    /// Exact exempt paths hash set compiled when `len > EXEMPT_SET_THRESHOLD`.
    pub(crate) exempt_set: Option<HashSetXxHash3_64<String>>,
    /// Pre-serialized `503 Service Unavailable` + `Retry-After` wire bytes.
    pub(crate) prebuilt_reject_wire: Vec<u8>,
}

/// High-performance lock-free concurrency limiter backing [`ConcurrencyPlugin`].
#[derive(Clone)]
pub struct ConcurrencyLimiter {
    /// Shared atomic limiter state.
    pub(crate) inner: Arc<ConcurrencyLimiterInner>,
}

/// Interior state of an RAII [`ConcurrencyPermit`] guaranteeing single-release semantics.
pub(crate) struct ConcurrencyPermitInner {
    /// Owning limiter state.
    pub(crate) limiter: Arc<ConcurrencyLimiterInner>,
    /// Optional boxed semaphore permits (allocated only when wait queuing was used).
    pub(crate) sem_permits: Option<Box<Mutex<Option<HeldSemaphorePermits>>>>,
    /// Acquisition timestamp (`elapsed_us + 1`) when adaptive shedding is enabled, or `0` otherwise.
    pub(crate) acquired_at_us_plus_one: u64,
    /// Matched prefix rule slot index, or [`NO_PREFIX_SLOT`] when none matched.
    pub(crate) prefix_slot: u32,
    /// Atomic single-release guard preventing double decrements across explicit release and `Drop`.
    pub(crate) released: AtomicBool,
}

/// Leak-proof RAII concurrency permit stored in Hyperlane [`Context`] under [`ATTR_CONCURRENCY_PERMIT`].
///
/// Cloning shares the same underlying permit handle; calling [`ConcurrencyPermit::release`] or
/// dropping the final reference atomically releases the in-flight slot exactly once.
#[derive(Clone)]
pub struct ConcurrencyPermit {
    /// Shared single-release permit state.
    pub(crate) inner: Arc<ConcurrencyPermitInner>,
}

/// Point-in-time diagnostic counters exported by [`ConcurrencyLimiter::snapshot`].
#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
pub struct ConcurrencySnapshot {
    /// Current global in-flight requests.
    #[get(type(copy))]
    pub(crate) in_flight: usize,
    /// Current effective global concurrency limit.
    #[get(type(copy))]
    pub(crate) effective_limit: usize,
    /// Exponentially weighted moving average request latency in microseconds.
    #[get(type(copy))]
    pub(crate) ewma_latency_us: u64,
    /// Cumulative count of admitted requests.
    #[get(type(copy))]
    pub(crate) total_admitted: u64,
    /// Cumulative count of shed requests.
    #[get(type(copy))]
    pub(crate) total_shed: u64,
}

/// Process-wide [`ConcurrencyPlugin`] singleton holding a compiled [`ConcurrencyLimiter`].
#[derive(Clone)]
pub struct ConcurrencyPlugin {
    /// Shared concurrency limiter engine.
    pub(crate) limiter: ConcurrencyLimiter,
}

/// Opt-in request middleware acquiring a [`ConcurrencyPermit`] or shedding with `503 Service Unavailable`.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-108)]
pub struct ConcurrencyRequestHook;

/// Opt-in response middleware releasing the [`ConcurrencyPermit`] stored in `Context` attributes.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::response_middleware(85)]
pub struct ConcurrencyResponseHook;