hyperlane-plugin-grpc 23.3.1

A gRPC over HTTP/2 server plugin for the Hyperlane framework with length-prefixed framing, bounded decompression, gRPC status codes, timeout parsing, service routing, and an opt-in ServerHook.
Documentation
use super::*;

/// Borrows the last value of a lowercased HTTP request header without heap allocation.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercased header key name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline(always)]
pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
    req.get_headers()
        .get(lower_key)
        .and_then(|values: &VecDeque<String>| values.back())
        .map(String::as_str)
}

/// Parses a gRPC `grpc-timeout` header value (`<1..8 digits><H|M|S|m|u|n>`) into a [`Duration`].
///
/// # Arguments
///
/// - `&str` - Raw `grpc-timeout` header value.
///
/// # Returns
///
/// - `Option<Duration>` - Parsed timeout duration, or `None` when malformed.
#[inline]
pub fn parse_grpc_timeout(raw: &str) -> Option<Duration> {
    let bytes: &[u8] = raw.trim().as_bytes();
    let len: usize = bytes.len();
    if !(2..=9).contains(&len) {
        return None;
    }
    let unit: u8 = bytes[len - 1];
    let mut value: u64 = 0;
    for &b in &bytes[..len - 1] {
        if !b.is_ascii_digit() {
            return None;
        }
        value = value * 10 + (b - ASCII_ZERO) as u64;
    }
    match unit {
        TIMEOUT_UNIT_HOURS => Some(Duration::from_secs(value.saturating_mul(3600))),
        TIMEOUT_UNIT_MINUTES => Some(Duration::from_secs(value.saturating_mul(60))),
        TIMEOUT_UNIT_SECONDS => Some(Duration::from_secs(value)),
        TIMEOUT_UNIT_MILLIS => Some(Duration::from_millis(value)),
        TIMEOUT_UNIT_MICROS => Some(Duration::from_micros(value)),
        TIMEOUT_UNIT_NANOS => Some(Duration::from_nanos(value)),
        _ => None,
    }
}

/// Finds the index of the first byte in `bytes` that requires gRPC percent-encoding using 8-byte SWAR.
///
/// # Arguments
///
/// - `&[u8]` - Raw UTF-8 message bytes.
///
/// # Returns
///
/// - `Option<usize>` - Byte offset of the first unsafe character, or `None` if all bytes are clean.
#[inline]
pub(crate) fn find_first_grpc_unsafe(bytes: &[u8]) -> Option<usize> {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for (idx, chunk) in chunks.iter().enumerate() {
        let word: u64 = u64::from_ne_bytes(*chunk);
        let non_ascii: u64 = word & SWAR_HIGH_BITS;
        let below_space: u64 = word.wrapping_sub(SWAR_SPACE_BROADCAST) & SWAR_HIGH_BITS;
        let is_del: u64 = word.wrapping_add(SWAR_ONES_BROADCAST) & SWAR_HIGH_BITS;
        let xor_pct: u64 = word ^ SWAR_PERCENT_BROADCAST;
        let is_pct: u64 = xor_pct.wrapping_sub(SWAR_ONES_BROADCAST) & !xor_pct & SWAR_HIGH_BITS;
        let mask: u64 = (non_ascii | below_space) | (is_del | is_pct);
        if mask != 0 {
            let base: usize = idx * 8;
            for (j, &b) in chunk.iter().enumerate() {
                if !((0x20..=0x7e).contains(&b) && b != ASCII_PERCENT) {
                    return Some(base + j);
                }
            }
        }
    }
    let base: usize = chunks.len() * 8;
    for (j, &b) in rem.iter().enumerate() {
        if !((0x20..=0x7e).contains(&b) && b != ASCII_PERCENT) {
            return Some(base + j);
        }
    }
    None
}

/// Percent-encodes a gRPC status message per the gRPC over HTTP/2 specification.
///
/// # Arguments
///
/// - `&str` - Raw UTF-8 status message.
///
/// # Returns
///
/// - `String` - Wire-safe percent-encoded header value.
#[inline]
pub fn percent_encode_grpc_message(raw: &str) -> String {
    let bytes: &[u8] = raw.as_bytes();
    let Some(start_escape) = find_first_grpc_unsafe(bytes) else {
        return raw.to_owned();
    };
    let mut out: String = String::with_capacity(bytes.len() + 16);
    out.push_str(&raw[..start_escape]);
    let mut safe_start: usize = start_escape;
    let mut idx: usize = start_escape;
    while idx < bytes.len() {
        let byte: u8 = bytes[idx];
        if !((0x20..=0x7e).contains(&byte) && byte != ASCII_PERCENT) {
            if safe_start < idx {
                out.push_str(&raw[safe_start..idx]);
            }
            out.push('%');
            out.push(GRPC_HEX_UPPER[(byte >> 4) as usize] as char);
            out.push(GRPC_HEX_UPPER[(byte & 0x0f) as usize] as char);
            safe_start = idx + 1;
        }
        idx += 1;
    }
    if safe_start < bytes.len() {
        out.push_str(&raw[safe_start..]);
    }
    out
}

/// Reports whether a `Content-Type` header value matches `application/grpc` (or `+proto`/`+json`).
///
/// # Arguments
///
/// - `&str` - Raw `Content-Type` header value.
///
/// # Returns
///
/// - `bool` - `true` when the media type is gRPC.
#[inline]
pub fn is_grpc_content_type(content_type: &str) -> bool {
    let mut bytes: &[u8] = content_type.as_bytes();
    while !bytes.is_empty() && bytes[0].is_ascii_whitespace() {
        bytes = &bytes[1..];
    }
    let prefix: &[u8] = GRPC_CONTENT_TYPE.as_bytes();
    let prefix_len: usize = prefix.len();
    if bytes.len() < prefix_len {
        return false;
    }
    if &bytes[..prefix_len] != prefix && !bytes[..prefix_len].eq_ignore_ascii_case(prefix) {
        return false;
    }
    if bytes.len() == prefix_len {
        return true;
    }
    let next: u8 = bytes[prefix_len];
    if next == ASCII_PLUS || next == ASCII_SEMICOLON {
        return true;
    }
    if next.is_ascii_whitespace() {
        let mut rest: &[u8] = &bytes[prefix_len + 1..];
        while !rest.is_empty() && rest[0].is_ascii_whitespace() {
            rest = &rest[1..];
        }
        return rest.is_empty() || rest[0] == ASCII_SEMICOLON;
    }
    false
}

/// Parses a `grpc-encoding` header token into a [`Compress`] algorithm.
///
/// # Arguments
///
/// - `Option<&str>` - Raw `grpc-encoding` header value.
///
/// # Returns
///
/// - `Compress` - Parsed compression algorithm (`Compress::Unknown` for identity or absent).
#[inline]
pub(crate) fn parse_grpc_encoding(raw: Option<&str>) -> Compress {
    let Some(token) = raw.map(str::trim) else {
        return Compress::Unknown;
    };
    if token.is_empty() || token.eq_ignore_ascii_case(GRPC_IDENTITY_ENCODING) {
        return Compress::Unknown;
    }
    Compress::from_str(token).unwrap_or(Compress::Unknown)
}

/// Formats a `usize` decimal length into a 20-byte stack buffer with zero heap allocations.
///
/// # Arguments
///
/// - `usize` - Non-negative integer length.
/// - `&mut [u8; GRPC_LEN_STACK_BUF]` - Caller-provided stack byte buffer.
///
/// # Returns
///
/// - `&[u8]` - Borrowed ASCII decimal byte slice inside `buf`.
#[inline]
pub(crate) fn format_usize_stack(mut value: usize, buf: &mut [u8; GRPC_LEN_STACK_BUF]) -> &[u8] {
    let mut pos: usize = GRPC_LEN_STACK_BUF;
    if value == 0 {
        pos -= 1;
        buf[pos] = ASCII_ZERO;
    } else {
        while value > 0 {
            pos -= 1;
            buf[pos] = ASCII_ZERO + (value % 10) as u8;
            value /= 10;
        }
    }
    &buf[pos..]
}

/// Encodes an uncompressed payload buffer into a 5-byte length-prefixed gRPC frame, reusing capacity in place when possible.
///
/// # Arguments
///
/// - `Vec<u8>` - Uncompressed payload bytes.
///
/// # Returns
///
/// - `Result<Vec<u8>, GrpcError>` - Framed wire bytes or [`GrpcStatus::ResourceExhausted`] on overflow.
#[inline]
pub(crate) fn encode_uncompressed_payload(mut payload: Vec<u8>) -> Result<Vec<u8>, GrpcError> {
    let payload_len: usize = payload.len();
    let len_u32: u32 = u32::try_from(payload_len)
        .map_err(|_| GrpcError::new(GrpcStatus::ResourceExhausted, ERR_GRPC_MSG_TOO_LARGE))?;
    let len_bytes: [u8; 4] = len_u32.to_be_bytes();
    let header: [u8; GRPC_FRAME_HEADER_LEN] =
        [0u8, len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]];
    let total_len: usize = GRPC_FRAME_HEADER_LEN + payload_len;
    if payload.capacity() >= total_len {
        payload.resize(total_len, 0u8);
        payload.copy_within(..payload_len, GRPC_FRAME_HEADER_LEN);
        payload[..GRPC_FRAME_HEADER_LEN].copy_from_slice(&header);
        return Ok(payload);
    }
    let mut wire: Vec<u8> = Vec::with_capacity(total_len);
    wire.extend_from_slice(&header);
    wire.extend_from_slice(&payload);
    Ok(wire)
}