hyperlane-plugin-timeout 23.3.1

A per-route and global request deadline budget plugin for the Hyperlane framework with X-Request-Timeout clamping, Context RequestDeadline propagation, timeout_future async helper, and 504 Gateway Timeout enforcement.
Documentation
use super::*;

/// Normalizes a path prefix by ensuring a leading `/` and trimming trailing `/`.
///
/// # Arguments
///
/// - `&str` - Raw prefix path.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(raw: &str) -> String {
    let trimmed: &str = raw.trim().trim_end_matches('/');
    if trimmed.is_empty() || trimmed == ROOT_SLASH {
        return ROOT_SLASH.to_owned();
    }
    if trimmed.starts_with('/') {
        trimmed.to_owned()
    } else {
        format!("/{trimmed}")
    }
}

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

/// Parses a client timeout header value (`"5000"`, `"500ms"`, `"5s"`) into milliseconds.
///
/// # Arguments
///
/// - `&str` - Raw header value.
///
/// # Returns
///
/// - `Option<u64>` - Parsed positive duration in milliseconds.
pub fn parse_timeout_header_ms(raw: &str) -> Option<u64> {
    let trimmed: &str = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    let ms: u64 = if let Some(s) = trimmed.strip_suffix("ms") {
        s.trim().parse::<u64>().ok()?
    } else if let Some(s) = trimmed.strip_suffix('s') {
        s.trim().parse::<u64>().ok()?.saturating_mul(1000)
    } else {
        trimmed.parse::<u64>().ok()?
    };
    if ms == 0 { None } else { Some(ms) }
}

/// Executes `future` bounded by the [`RequestDeadline`] attached to `ctx`.
///
/// If no deadline is attached to `ctx`, `future` runs without an extra timeout wrapper.
///
/// # Arguments
///
/// - `&Context` - Active Hyperlane request context.
/// - `F` - Async operation to bound.
///
/// # Returns
///
/// - `Result<T, TimeoutError>` - Future output or [`TimeoutError::DeadlineExceeded`].
pub async fn timeout_future<F, T>(ctx: &Context, future: F) -> Result<T, TimeoutError>
where
    F: Future<Output = T>,
{
    let Some(deadline) = RequestDeadline::from_context(ctx) else {
        return Ok(future.await);
    };
    let remaining: Duration = deadline.remaining();
    if remaining.is_zero() {
        return Err(TimeoutError::DeadlineExceeded);
    }
    timeout(remaining, future)
        .await
        .map_err(|_| TimeoutError::DeadlineExceeded)
}