hyperlane-plugin-grpc 22.14.0

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: &RequestHeadersValue| 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 - b'0') as u64;
    }
    match unit {
        b'H' => Some(Duration::from_secs(value.saturating_mul(3600))),
        b'M' => Some(Duration::from_secs(value.saturating_mul(60))),
        b'S' => Some(Duration::from_secs(value)),
        b'm' => Some(Duration::from_millis(value)),
        b'u' => Some(Duration::from_micros(value)),
        b'n' => Some(Duration::from_nanos(value)),
        _ => 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 first_unsafe: Option<usize> = bytes
        .iter()
        .position(|&b: &u8| !((0x20..=0x7e).contains(&b) && b != b'%'));
    let Some(start_escape) = first_unsafe else {
        return raw.to_owned();
    };
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len() + 16);
    out.extend_from_slice(&bytes[..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 != b'%') {
            if safe_start < idx {
                out.extend_from_slice(&bytes[safe_start..idx]);
            }
            out.extend_from_slice(&[
                b'%',
                GRPC_HEX_UPPER[(byte >> 4) as usize],
                GRPC_HEX_UPPER[(byte & 0x0f) as usize],
            ]);
            safe_start = idx + 1;
        }
        idx += 1;
    }
    if safe_start < bytes.len() {
        out.extend_from_slice(&bytes[safe_start..]);
    }
    String::from_utf8(out).unwrap_or_default()
}

/// 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 bytes: &[u8] = content_type.as_bytes();
    let mut end: usize = bytes.len();
    for (i, &b) in bytes.iter().enumerate() {
        if b == b';' {
            end = i;
            break;
        }
    }
    let mut start: usize = 0;
    while start < end && bytes[start].is_ascii_whitespace() {
        start += 1;
    }
    while end > start && bytes[end - 1].is_ascii_whitespace() {
        end -= 1;
    }
    let base: &[u8] = &bytes[start..end];
    let prefix_len: usize = GRPC_CONTENT_TYPE.len();
    if base.len() < prefix_len {
        return false;
    }
    base[..prefix_len].eq_ignore_ascii_case(GRPC_CONTENT_TYPE.as_bytes())
        && (base.len() == prefix_len || base[prefix_len] == b'+')
}

/// 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] = b'0';
    } else {
        while value > 0 {
            pos -= 1;
            buf[pos] = b'0' + (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)
}