Skip to main content

hyperlane_plugin_grpc/
fn.rs

1use super::*;
2
3/// Borrows the last value of a lowercased HTTP request header without heap allocation.
4///
5/// # Arguments
6///
7/// - `&'a Request` - Incoming HTTP request.
8/// - `&str` - Lowercased header key name.
9///
10/// # Returns
11///
12/// - `Option<&'a str>` - Borrowed last header value, if present.
13#[inline(always)]
14pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
15    req.get_headers()
16        .get(lower_key)
17        .and_then(|values: &VecDeque<String>| values.back())
18        .map(String::as_str)
19}
20
21/// Parses a gRPC `grpc-timeout` header value (`<1..8 digits><H|M|S|m|u|n>`) into a [`Duration`].
22///
23/// # Arguments
24///
25/// - `&str` - Raw `grpc-timeout` header value.
26///
27/// # Returns
28///
29/// - `Option<Duration>` - Parsed timeout duration, or `None` when malformed.
30#[inline]
31pub fn parse_grpc_timeout(raw: &str) -> Option<Duration> {
32    let bytes: &[u8] = raw.trim().as_bytes();
33    let len: usize = bytes.len();
34    if !(2..=9).contains(&len) {
35        return None;
36    }
37    let unit: u8 = bytes[len - 1];
38    let mut value: u64 = 0;
39    for &b in &bytes[..len - 1] {
40        if !b.is_ascii_digit() {
41            return None;
42        }
43        value = value * 10 + (b - ASCII_ZERO) as u64;
44    }
45    match unit {
46        TIMEOUT_UNIT_HOURS => Some(Duration::from_secs(value.saturating_mul(3600))),
47        TIMEOUT_UNIT_MINUTES => Some(Duration::from_secs(value.saturating_mul(60))),
48        TIMEOUT_UNIT_SECONDS => Some(Duration::from_secs(value)),
49        TIMEOUT_UNIT_MILLIS => Some(Duration::from_millis(value)),
50        TIMEOUT_UNIT_MICROS => Some(Duration::from_micros(value)),
51        TIMEOUT_UNIT_NANOS => Some(Duration::from_nanos(value)),
52        _ => None,
53    }
54}
55
56/// Finds the index of the first byte in `bytes` that requires gRPC percent-encoding using 8-byte SWAR.
57///
58/// # Arguments
59///
60/// - `&[u8]` - Raw UTF-8 message bytes.
61///
62/// # Returns
63///
64/// - `Option<usize>` - Byte offset of the first unsafe character, or `None` if all bytes are clean.
65#[inline]
66pub(crate) fn find_first_grpc_unsafe(bytes: &[u8]) -> Option<usize> {
67    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
68    for (idx, chunk) in chunks.iter().enumerate() {
69        let word: u64 = u64::from_ne_bytes(*chunk);
70        let non_ascii: u64 = word & SWAR_HIGH_BITS;
71        let below_space: u64 = word.wrapping_sub(SWAR_SPACE_BROADCAST) & SWAR_HIGH_BITS;
72        let is_del: u64 = word.wrapping_add(SWAR_ONES_BROADCAST) & SWAR_HIGH_BITS;
73        let xor_pct: u64 = word ^ SWAR_PERCENT_BROADCAST;
74        let is_pct: u64 = xor_pct.wrapping_sub(SWAR_ONES_BROADCAST) & !xor_pct & SWAR_HIGH_BITS;
75        let mask: u64 = (non_ascii | below_space) | (is_del | is_pct);
76        if mask != 0 {
77            let base: usize = idx * 8;
78            for (j, &b) in chunk.iter().enumerate() {
79                if !((0x20..=0x7e).contains(&b) && b != ASCII_PERCENT) {
80                    return Some(base + j);
81                }
82            }
83        }
84    }
85    let base: usize = chunks.len() * 8;
86    for (j, &b) in rem.iter().enumerate() {
87        if !((0x20..=0x7e).contains(&b) && b != ASCII_PERCENT) {
88            return Some(base + j);
89        }
90    }
91    None
92}
93
94/// Percent-encodes a gRPC status message per the gRPC over HTTP/2 specification.
95///
96/// # Arguments
97///
98/// - `&str` - Raw UTF-8 status message.
99///
100/// # Returns
101///
102/// - `String` - Wire-safe percent-encoded header value.
103#[inline]
104pub fn percent_encode_grpc_message(raw: &str) -> String {
105    let bytes: &[u8] = raw.as_bytes();
106    let Some(start_escape) = find_first_grpc_unsafe(bytes) else {
107        return raw.to_owned();
108    };
109    let mut out: String = String::with_capacity(bytes.len() + 16);
110    out.push_str(&raw[..start_escape]);
111    let mut safe_start: usize = start_escape;
112    let mut idx: usize = start_escape;
113    while idx < bytes.len() {
114        let byte: u8 = bytes[idx];
115        if !((0x20..=0x7e).contains(&byte) && byte != ASCII_PERCENT) {
116            if safe_start < idx {
117                out.push_str(&raw[safe_start..idx]);
118            }
119            out.push('%');
120            out.push(GRPC_HEX_UPPER[(byte >> 4) as usize] as char);
121            out.push(GRPC_HEX_UPPER[(byte & 0x0f) as usize] as char);
122            safe_start = idx + 1;
123        }
124        idx += 1;
125    }
126    if safe_start < bytes.len() {
127        out.push_str(&raw[safe_start..]);
128    }
129    out
130}
131
132/// Reports whether a `Content-Type` header value matches `application/grpc` (or `+proto`/`+json`).
133///
134/// # Arguments
135///
136/// - `&str` - Raw `Content-Type` header value.
137///
138/// # Returns
139///
140/// - `bool` - `true` when the media type is gRPC.
141#[inline]
142pub fn is_grpc_content_type(content_type: &str) -> bool {
143    let mut bytes: &[u8] = content_type.as_bytes();
144    while !bytes.is_empty() && bytes[0].is_ascii_whitespace() {
145        bytes = &bytes[1..];
146    }
147    let prefix: &[u8] = GRPC_CONTENT_TYPE.as_bytes();
148    let prefix_len: usize = prefix.len();
149    if bytes.len() < prefix_len {
150        return false;
151    }
152    if &bytes[..prefix_len] != prefix && !bytes[..prefix_len].eq_ignore_ascii_case(prefix) {
153        return false;
154    }
155    if bytes.len() == prefix_len {
156        return true;
157    }
158    let next: u8 = bytes[prefix_len];
159    if next == ASCII_PLUS || next == ASCII_SEMICOLON {
160        return true;
161    }
162    if next.is_ascii_whitespace() {
163        let mut rest: &[u8] = &bytes[prefix_len + 1..];
164        while !rest.is_empty() && rest[0].is_ascii_whitespace() {
165            rest = &rest[1..];
166        }
167        return rest.is_empty() || rest[0] == ASCII_SEMICOLON;
168    }
169    false
170}
171
172/// Parses a `grpc-encoding` header token into a [`Compress`] algorithm.
173///
174/// # Arguments
175///
176/// - `Option<&str>` - Raw `grpc-encoding` header value.
177///
178/// # Returns
179///
180/// - `Compress` - Parsed compression algorithm (`Compress::Unknown` for identity or absent).
181#[inline]
182pub(crate) fn parse_grpc_encoding(raw: Option<&str>) -> Compress {
183    let Some(token) = raw.map(str::trim) else {
184        return Compress::Unknown;
185    };
186    if token.is_empty() || token.eq_ignore_ascii_case(GRPC_IDENTITY_ENCODING) {
187        return Compress::Unknown;
188    }
189    Compress::from_str(token).unwrap_or(Compress::Unknown)
190}
191
192/// Formats a `usize` decimal length into a 20-byte stack buffer with zero heap allocations.
193///
194/// # Arguments
195///
196/// - `usize` - Non-negative integer length.
197/// - `&mut [u8; GRPC_LEN_STACK_BUF]` - Caller-provided stack byte buffer.
198///
199/// # Returns
200///
201/// - `&[u8]` - Borrowed ASCII decimal byte slice inside `buf`.
202#[inline]
203pub(crate) fn format_usize_stack(mut value: usize, buf: &mut [u8; GRPC_LEN_STACK_BUF]) -> &[u8] {
204    let mut pos: usize = GRPC_LEN_STACK_BUF;
205    if value == 0 {
206        pos -= 1;
207        buf[pos] = ASCII_ZERO;
208    } else {
209        while value > 0 {
210            pos -= 1;
211            buf[pos] = ASCII_ZERO + (value % 10) as u8;
212            value /= 10;
213        }
214    }
215    &buf[pos..]
216}
217
218/// Encodes an uncompressed payload buffer into a 5-byte length-prefixed gRPC frame, reusing capacity in place when possible.
219///
220/// # Arguments
221///
222/// - `Vec<u8>` - Uncompressed payload bytes.
223///
224/// # Returns
225///
226/// - `Result<Vec<u8>, GrpcError>` - Framed wire bytes or [`GrpcStatus::ResourceExhausted`] on overflow.
227#[inline]
228pub(crate) fn encode_uncompressed_payload(mut payload: Vec<u8>) -> Result<Vec<u8>, GrpcError> {
229    let payload_len: usize = payload.len();
230    let len_u32: u32 = u32::try_from(payload_len)
231        .map_err(|_| GrpcError::new(GrpcStatus::ResourceExhausted, ERR_GRPC_MSG_TOO_LARGE))?;
232    let len_bytes: [u8; 4] = len_u32.to_be_bytes();
233    let header: [u8; GRPC_FRAME_HEADER_LEN] =
234        [0u8, len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]];
235    let total_len: usize = GRPC_FRAME_HEADER_LEN + payload_len;
236    if payload.capacity() >= total_len {
237        payload.resize(total_len, 0u8);
238        payload.copy_within(..payload_len, GRPC_FRAME_HEADER_LEN);
239        payload[..GRPC_FRAME_HEADER_LEN].copy_from_slice(&header);
240        return Ok(payload);
241    }
242    let mut wire: Vec<u8> = Vec::with_capacity(total_len);
243    wire.extend_from_slice(&header);
244    wire.extend_from_slice(&payload);
245    Ok(wire)
246}