hyperlane-plugin-maintenance 23.3.0

A lock-free atomic maintenance and read-only mode plugin for the Hyperlane framework with live zero-restart switching, path and constant-time bypass-token exemptions, Retry-After headers, and prebuilt 503 wire responses.
Documentation
use super::*;

/// Normalizes a path prefix by ensuring a leading `/` and stripping trailing `/`.
///
/// # Arguments
///
/// - `&str` - Raw prefix string.
///
/// # 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
    }
}

/// Performs constant-time equality comparison for bypass tokens.
///
/// # Arguments
///
/// - `&[u8]` - First byte slice.
/// - `&[u8]` - Second byte slice.
///
/// # Returns
///
/// - `bool` - `true` iff slices match identically.
#[inline(never)]
pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for (&x, &y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    black_box(diff) == 0
}

/// Reports whether `method` is a safe read-only HTTP method.
///
/// # Arguments
///
/// - `&Method` - Request HTTP method.
///
/// # Returns
///
/// - `bool` - `true` for `GET`, `HEAD`, and `OPTIONS`.
#[inline(always)]
pub(crate) fn is_read_only_method(method: &Method) -> bool {
    method.is_get() || method.is_head() || method.is_options()
}

/// Encodes a [`MaintenanceMode`] into a compact `u8` for atomic storage.
///
/// # Arguments
///
/// - `MaintenanceMode` - Operating mode.
///
/// # Returns
///
/// - `u8` - Encoded tag.
#[inline(always)]
pub(crate) fn mode_to_u8(mode: MaintenanceMode) -> u8 {
    match mode {
        MaintenanceMode::Active => MODE_TAG_ACTIVE,
        MaintenanceMode::ReadOnly => MODE_TAG_READ_ONLY,
        MaintenanceMode::Maintenance => MODE_TAG_MAINTENANCE,
    }
}

/// Decodes a `u8` tag back into a [`MaintenanceMode`].
///
/// # Arguments
///
/// - `u8` - Atomic tag value.
///
/// # Returns
///
/// - `MaintenanceMode` - Decoded operating mode.
#[inline(always)]
pub(crate) fn mode_from_u8(tag: u8) -> MaintenanceMode {
    match tag {
        MODE_TAG_READ_ONLY => MaintenanceMode::ReadOnly,
        MODE_TAG_MAINTENANCE => MaintenanceMode::Maintenance,
        _ => MaintenanceMode::Active,
    }
}

/// Pre-serializes a `503 Service Unavailable` wire response with optional `Retry-After`.
///
/// # Arguments
///
/// - `HttpStatus` - Rejection status code.
/// - `&str` - Content-Type header value.
/// - `Option<u64>` - Optional `Retry-After` seconds.
/// - `&[u8]` - Response payload bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Complete HTTP/1.1 wire bytes.
pub(crate) fn build_reject_wire(
    status: HttpStatus,
    content_type: &str,
    retry_after_secs: Option<u64>,
    body: &[u8],
) -> Vec<u8> {
    let mut resp: Response = Response::default();
    resp.set_status_code(status.code())
        .set_header(CONTENT_TYPE, content_type)
        .set_body(body);
    if let Some(secs) = retry_after_secs {
        resp.set_header(RETRY_AFTER, secs.to_string());
    }
    resp.build()
}