hyperlane-plugin-concurrency 22.14.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::*;

/// Normalizes a route prefix by trimming trailing slashes while preserving `"/"`.
///
/// # Arguments
///
/// - `&str` - Raw prefix string.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    let stripped: &str = trimmed.trim_end_matches('/');
    if stripped.is_empty() {
        "/".to_owned()
    } else {
        stripped.to_owned()
    }
}

/// Reports whether `path` matches normalized `prefix` on a segment boundary.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized prefix.
///
/// # Returns
///
/// - `bool` - `true` when `path` equals `prefix` or starts with `prefix` followed by `'/'`.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == "/" {
        return true;
    }
    let Some(rest) = path.strip_prefix(prefix) else {
        return false;
    };
    rest.is_empty() || rest.starts_with('/')
}

/// Attempts a lock-free atomic increment of `counter` while keeping it strictly `<= limit`.
///
/// # Arguments
///
/// - `&AtomicUsize` - In-flight counter.
/// - `usize` - Maximum allowed count.
///
/// # Returns
///
/// - `bool` - `true` when incremented; `false` when already at or above `limit`.
#[inline]
pub(crate) fn try_increment_bounded(counter: &AtomicUsize, limit: usize) -> bool {
    let mut current: usize = counter.load(Ordering::Relaxed);
    loop {
        if current >= limit {
            return false;
        }
        match counter.compare_exchange_weak(
            current,
            current + 1,
            Ordering::AcqRel,
            Ordering::Relaxed,
        ) {
            Ok(_) => return true,
            Err(observed) => current = observed,
        }
    }
}

/// Updates the lock-free EWMA latency and AIMD effective concurrency limit on permit release.
///
/// # Arguments
///
/// - `&ConcurrencyLimiterInner` - Shared limiter interior state.
/// - `AdaptiveShedConfig` - Active adaptive shedding parameters.
/// - `u64` - Observed request latency in microseconds.
pub(crate) fn record_adaptive_sample(
    inner: &ConcurrencyLimiterInner,
    adaptive: AdaptiveShedConfig,
    sample_us: u64,
) {
    let mut prev: u64 = inner.ewma_latency_us.load(Ordering::Relaxed);
    loop {
        let next: u64 = if prev == 0 {
            sample_us.max(1)
        } else {
            let decayed: u64 = prev - (prev >> EWMA_SHIFT);
            decayed.saturating_add(sample_us >> EWMA_SHIFT).max(1)
        };
        match inner.ewma_latency_us.compare_exchange_weak(
            prev,
            next,
            Ordering::AcqRel,
            Ordering::Relaxed,
        ) {
            Ok(_) => break,
            Err(actual) => prev = actual,
        }
    }
    let target_us: u64 = adaptive
        .get_target_latency_ms()
        .max(1)
        .saturating_mul(MICROS_PER_MS);
    let max_limit: usize = inner.config.get_max_in_flight().max(1);
    let min_limit: usize = adaptive.get_min_limit().max(1).min(max_limit);
    let mut cur_limit: usize = inner.effective_limit.load(Ordering::Relaxed);
    loop {
        let next_limit: usize = if sample_us > target_us {
            let pct: usize = adaptive.get_decrease_percent().clamp(1, 99);
            let reduced: usize = cur_limit.saturating_mul(pct) / 100;
            reduced.max(min_limit)
        } else {
            cur_limit
                .saturating_add(adaptive.get_additive_increase().max(1))
                .min(max_limit)
        };
        if next_limit == cur_limit {
            break;
        }
        match inner.effective_limit.compare_exchange_weak(
            cur_limit,
            next_limit,
            Ordering::AcqRel,
            Ordering::Relaxed,
        ) {
            Ok(_) => break,
            Err(actual) => cur_limit = actual,
        }
    }
}