hyperlane-plugin-rpc 22.14.0

A JSON-RPC 2.0 server plugin for the Hyperlane framework with async method routing, batch dispatch, notification handling, and configurable payload and batch DoS bounds.
Documentation
use super::*;

/// Appends one serialized [`CompactRpcResponse`] directly into `buf` using static envelope literals.
///
/// # Arguments
///
/// - `&CompactRpcResponse` - Compact response envelope to serialize.
/// - `&mut Vec<u8>` - Destination JSON byte buffer.
#[inline]
pub(crate) fn write_compact_response(response: &CompactRpcResponse, buf: &mut Vec<u8>) {
    let CompactRpcResponse { result, error, id } = response;
    buf.extend_from_slice(RPC_JSON_PREFIX);
    let _: Result<(), serde_json::Error> = to_writer(&mut *buf, id);
    if let Some(res) = result {
        buf.extend_from_slice(RPC_JSON_RESULT_KEY);
        let _: Result<(), serde_json::Error> = to_writer(&mut *buf, res);
    }
    if let Some(err) = error {
        buf.extend_from_slice(RPC_JSON_ERROR_KEY);
        let _: Result<(), serde_json::Error> = to_writer(&mut *buf, err);
    }
    buf.push(b'}');
}

/// Encodes one [`CompactRpcResponse`] into a pre-sized JSON byte buffer.
///
/// # Arguments
///
/// - `&CompactRpcResponse` - Compact response envelope to serialize.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON payload bytes.
#[inline]
pub(crate) fn encode_compact_response(response: &CompactRpcResponse) -> Vec<u8> {
    let mut buf: Vec<u8> = Vec::with_capacity(RPC_SINGLE_RESPONSE_CAP);
    write_compact_response(response, &mut buf);
    buf
}

/// Encodes all ready batch slots directly into a single JSON array buffer, returning `None` if all were notifications.
///
/// # Arguments
///
/// - `&[Option<BatchDispatchSlot>]` - Completed batch dispatch slots.
///
/// # Returns
///
/// - `Option<Vec<u8>>` - Serialized JSON array bytes, or `None` when empty.
#[inline]
pub(crate) fn encode_ready_batch_slots(slots: &[Option<BatchDispatchSlot>]) -> Option<Vec<u8>> {
    let mut buf: Vec<u8> = Vec::with_capacity(slots.len() * RPC_SINGLE_RESPONSE_CAP);
    buf.push(b'[');
    let mut written: usize = 0;
    for slot in slots.iter().flatten() {
        if let BatchDispatchSlot::Ready(resp) = slot {
            if written > 0 {
                buf.push(b',');
            }
            write_compact_response(resp, &mut buf);
            written += 1;
        }
    }
    if written == 0 {
        return None;
    }
    buf.push(b']');
    Some(buf)
}

/// Finds the first non-ASCII-whitespace byte in `raw`, if any.
///
/// # Arguments
///
/// - `&[u8]` - Raw JSON payload bytes.
///
/// # Returns
///
/// - `Option<u8>` - First non-whitespace byte, or `None` when empty/blank.
#[inline]
pub(crate) fn first_non_ws_byte(raw: &[u8]) -> Option<u8> {
    raw.iter()
        .copied()
        .find(|b: &u8| *b != b' ' && *b != b'\t' && *b != b'\r' && *b != b'\n')
}