hyperlane-plugin-compression 23.3.0

A full-duplex opt-in compression middleware plugin for the Hyperlane framework providing bounded request decompression (gzip/deflate/br) and automatic Accept-Encoding response negotiation with MIME filtering and Vary merging.
Documentation
use super::*;

/// Reports whether an HTTP status code carries no message body.
///
/// # Arguments
///
/// - `usize` - HTTP status code.
///
/// # Returns
///
/// - `bool` - `true` for `1xx`, `204`, and `304`.
#[inline(always)]
pub(crate) fn status_has_no_body(status: usize) -> bool {
    (100..200).contains(&status) || status == 204 || status == 304
}

/// Checks whether a `Content-Type` value matches any excluded MIME prefix case-insensitively.
///
/// # Arguments
///
/// - `&str` - Raw `Content-Type` header value.
/// - `&[String]` - Lowercased excluded MIME prefixes.
///
/// # Returns
///
/// - `bool` - `true` when response compression should be skipped.
#[inline]
pub(crate) fn is_mime_excluded(content_type: &str, excluded_prefixes: &[String]) -> bool {
    let media: &str = match content_type.split_once(';') {
        Some((head, _)) => head.trim(),
        None => content_type.trim(),
    };
    for prefix in excluded_prefixes {
        if media.len() >= prefix.len()
            && media.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes())
        {
            return true;
        }
    }
    false
}

/// Checks whether a `Cache-Control` value contains the `no-transform` directive.
///
/// # Arguments
///
/// - `&str` - Raw `Cache-Control` header value.
///
/// # Returns
///
/// - `bool` - `true` when `no-transform` is present.
#[inline]
pub(crate) fn has_no_transform(cache_control: &str) -> bool {
    cache_control
        .split(',')
        .any(|dir: &str| dir.trim().eq_ignore_ascii_case(CACHE_CONTROL_NO_TRANSFORM))
}

/// Reports whether `haystack` contains lowercase ASCII `needle` ignoring ASCII case.
///
/// # Arguments
///
/// - `&[u8]` - Raw ASCII header slice.
/// - `&[u8]` - Lowercase ASCII token bytes.
///
/// # Returns
///
/// - `bool` - `true` when `needle` occurs inside `haystack`.
#[inline]
pub(crate) fn contains_ascii_icase(haystack: &[u8], needle: &[u8]) -> bool {
    let n_len: usize = needle.len();
    if n_len == 0 || haystack.len() < n_len {
        return false;
    }
    haystack
        .windows(n_len)
        .any(|win: &[u8]| win.eq_ignore_ascii_case(needle))
}

/// Negotiates the preferred [`Compress`] algorithm from a request's `Accept-Encoding` header.
///
/// # Arguments
///
/// - `&Request` - Incoming HTTP request.
/// - `bool` - Whether Brotli is enabled.
/// - `bool` - Whether Gzip is enabled.
/// - `bool` - Whether Deflate is enabled.
///
/// # Returns
///
/// - `Option<Compress>` - Selected content coding, or `None`.
#[inline]
pub(crate) fn negotiate_response_coding(
    request: &Request,
    enable_br: bool,
    enable_gzip: bool,
    enable_deflate: bool,
) -> Option<Compress> {
    let values: &VecDeque<String> = request.get_headers().get(ACCEPT_ENCODING)?;
    let raw: &str = values.back()?;
    let negotiated: Compress = Compress::from_accept_encoding(raw)?;
    match negotiated {
        Compress::Br if enable_br => Some(Compress::Br),
        Compress::Gzip if enable_gzip => Some(Compress::Gzip),
        Compress::Deflate if enable_deflate => Some(Compress::Deflate),
        _ => {
            let raw_bytes: &[u8] = raw.as_bytes();
            if enable_gzip && contains_ascii_icase(raw_bytes, GZIP_TOKEN_BYTES) {
                Some(Compress::Gzip)
            } else if enable_deflate && contains_ascii_icase(raw_bytes, DEFLATE_TOKEN_BYTES) {
                Some(Compress::Deflate)
            } else {
                None
            }
        }
    }
}

/// Appends `Accept-Encoding` to the `Vary` header using the pooled response header path.
///
/// # Arguments
///
/// - `&mut Response` - Mutable HTTP response.
#[inline]
pub(crate) fn ensure_vary_accept_encoding(response: &mut Response) {
    if let Some(slot) = response.get_headers().get(VARY) {
        let already: bool = slot.iter().any(|v: &String| {
            v.split(',').any(|tok: &str| {
                let t: &str = tok.trim();
                t == VARY_WILDCARD || t.eq_ignore_ascii_case(VARY_ACCEPT_ENCODING)
            })
        });
        if !already {
            response.add_header(VARY, VARY_ACCEPT_ENCODING);
        }
    } else {
        response.set_header(VARY, VARY_ACCEPT_ENCODING);
    }
}