hyperlane-plugin-rpc 23.3.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use super::*;

/// Formats an unsigned 64-bit integer into `digits`, returning the start offset.
///
/// # Arguments
///
/// - `u64` - Unsigned integer value.
/// - `&mut [u8; 20]` - Destination digit array.
///
/// # Returns
///
/// - `usize` - Start index inside `digits`.
#[inline(always)]
pub(crate) fn format_u64_digits(mut value: u64, digits: &mut [u8; 20]) -> usize {
    if value < 10 {
        digits[19] = BYTE_ZERO + value as u8;
        return 19;
    }
    let mut idx: usize = 20;
    while value >= 100 {
        let pair: usize = ((value % 100) as usize) * 2;
        value /= 100;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    if value >= 10 {
        let pair: usize = (value as usize) * 2;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    } else {
        idx -= 1;
        digits[idx] = BYTE_ZERO + value as u8;
    }
    idx
}

/// Appends decimal ASCII digits for `value` directly into `buf`.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut Vec<u8>` - Destination byte buffer.
#[inline(always)]
pub(crate) fn write_u64_decimal(value: u64, buf: &mut Vec<u8>) {
    let mut digits: [u8; 20] = [0u8; 20];
    let idx: usize = format_u64_digits(value, &mut digits);
    buf.extend_from_slice(&digits[idx..]);
}

/// Appends signed decimal ASCII digits for `value` directly into `buf`.
///
/// # Arguments
///
/// - `i64` - Signed integer to format.
/// - `&mut Vec<u8>` - Destination byte buffer.
#[inline(always)]
pub(crate) fn write_i64_decimal(value: i64, buf: &mut Vec<u8>) {
    if value < 0 {
        buf.push(BYTE_DASH);
        write_u64_decimal(value.unsigned_abs(), buf);
    } else {
        write_u64_decimal(value as u64, buf);
    }
}

/// Writes unsigned decimal ASCII digits into fixed slice `buf` at `pos`.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8]` - Destination slice.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `Option<usize>` - Updated write offset, or `None` on overflow.
#[inline(always)]
pub(crate) fn write_u64_decimal_slice(value: u64, buf: &mut [u8], pos: usize) -> Option<usize> {
    let mut digits: [u8; 20] = [0u8; 20];
    let idx: usize = format_u64_digits(value, &mut digits);
    let slice: &[u8] = &digits[idx..];
    let next: usize = pos + slice.len();
    if next > buf.len() {
        return None;
    }
    buf[pos..next].copy_from_slice(slice);
    Some(next)
}

/// Writes signed decimal ASCII digits into fixed slice `buf` at `pos`.
///
/// # Arguments
///
/// - `i64` - Signed integer to format.
/// - `&mut [u8]` - Destination slice.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `Option<usize>` - Updated write offset, or `None` on overflow.
#[inline(always)]
pub(crate) fn write_i64_decimal_slice(value: i64, buf: &mut [u8], pos: usize) -> Option<usize> {
    if value < 0 {
        if pos >= buf.len() {
            return None;
        }
        buf[pos] = BYTE_DASH;
        return write_u64_decimal_slice(value.unsigned_abs(), buf, pos + 1);
    }
    write_u64_decimal_slice(value as u64, buf, pos)
}

/// Reports whether `bytes` contains characters requiring JSON string escaping (`< 0x20`, `"`, `\`).
///
/// # Arguments
///
/// - `&[u8]` - UTF-8 string bytes.
///
/// # Returns
///
/// - `bool` - `true` when JSON escaping is required.
#[inline(always)]
pub(crate) fn needs_json_escape(bytes: &[u8]) -> bool {
    bytes
        .iter()
        .any(|b: &u8| *b < 0x20 || *b == BYTE_QUOTE || *b == BYTE_BACKSLASH)
}

/// Serializes a JSON string directly when escape-free, falling back to `serde_json::to_writer`.
///
/// # Arguments
///
/// - `&str` - String value to serialize.
/// - `&mut Vec<u8>` - Destination JSON byte buffer.
#[inline]
pub(crate) fn write_json_str_fast(s: &str, buf: &mut Vec<u8>) {
    let bytes: &[u8] = s.as_bytes();
    if !needs_json_escape(bytes) {
        buf.push(BYTE_QUOTE);
        buf.extend_from_slice(bytes);
        buf.push(BYTE_QUOTE);
    } else {
        let _: Result<(), serde_json::Error> = to_writer(&mut *buf, s);
    }
}

/// Serializes [`RpcId`] directly into `buf` without `serde_json::Serializer` setup for common variants.
///
/// # Arguments
///
/// - `&RpcId` - Correlation identifier.
/// - `&mut Vec<u8>` - Destination JSON byte buffer.
#[inline]
pub(crate) fn write_rpc_id(id: &RpcId, buf: &mut Vec<u8>) {
    match id {
        RpcId::Number(n) => write_i64_decimal(*n, buf),
        RpcId::Null => buf.extend_from_slice(JSON_NULL),
        RpcId::Text(s) => write_json_str_fast(s, buf),
    }
}

/// Serializes [`Value`] directly for primitive variants, falling back to `serde_json::to_writer` for composites.
///
/// # Arguments
///
/// - `&Value` - JSON value to serialize.
/// - `&mut Vec<u8>` - Destination JSON byte buffer.
#[inline]
pub(crate) fn write_json_value_fast(value: &Value, buf: &mut Vec<u8>) {
    match value {
        Value::Null => buf.extend_from_slice(JSON_NULL),
        Value::Bool(true) => buf.extend_from_slice(JSON_TRUE),
        Value::Bool(false) => buf.extend_from_slice(JSON_FALSE),
        Value::Number(num) => {
            if let Some(i) = num.as_i64() {
                write_i64_decimal(i, buf);
            } else if let Some(u) = num.as_u64() {
                write_u64_decimal(u, buf);
            } else {
                let _: Result<(), serde_json::Error> = to_writer(&mut *buf, num);
            }
        }
        Value::String(s) => write_json_str_fast(s, buf),
        Value::Array(_) | Value::Object(_) => {
            let _: Result<(), serde_json::Error> = to_writer(&mut *buf, value);
        }
    }
}

/// 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 { body, id } = response;
    buf.extend_from_slice(RPC_JSON_PREFIX);
    write_rpc_id(id, buf);
    match body {
        CompactRpcBody::Result(res) => {
            buf.extend_from_slice(RPC_JSON_RESULT_KEY);
            write_json_value_fast(res, buf);
        }
        CompactRpcBody::Error(err) => {
            buf.extend_from_slice(RPC_JSON_ERROR_KEY);
            let _: Result<(), serde_json::Error> = to_writer(&mut *buf, err);
        }
        CompactRpcBody::StaticError(raw_err) => {
            buf.extend_from_slice(RPC_JSON_ERROR_KEY);
            buf.extend_from_slice(raw_err);
        }
    }
    buf.push(BYTE_RBRACE);
}

/// Serializes a compact response directly into a stack slice when primitive and within `RPC_PAYLOAD_STACK_CAP`.
///
/// # Arguments
///
/// - `&CompactRpcResponse` - Compact response envelope.
/// - `&mut [u8; RPC_PAYLOAD_STACK_CAP]` - Destination stack byte buffer.
///
/// # Returns
///
/// - `Option<usize>` - Written JSON byte length if serialized without heap allocation.
#[inline]
pub(crate) fn write_compact_response_stack(
    response: &CompactRpcResponse,
    buf: &mut [u8; RPC_PAYLOAD_STACK_CAP],
) -> Option<usize> {
    let CompactRpcResponse { body, id } = response;
    let pfx: &[u8] = RPC_JSON_PREFIX;
    if pfx.len() >= RPC_PAYLOAD_STACK_CAP {
        return None;
    }
    buf[..pfx.len()].copy_from_slice(pfx);
    let mut pos: usize = pfx.len();
    match id {
        RpcId::Number(n) => pos = write_i64_decimal_slice(*n, buf, pos)?,
        RpcId::Null => {
            let next: usize = pos + JSON_NULL.len();
            if next > RPC_PAYLOAD_STACK_CAP {
                return None;
            }
            buf[pos..next].copy_from_slice(JSON_NULL);
            pos = next;
        }
        RpcId::Text(s) => {
            let sb: &[u8] = s.as_bytes();
            if needs_json_escape(sb) || pos + sb.len() + 2 > RPC_PAYLOAD_STACK_CAP {
                return None;
            }
            buf[pos] = BYTE_QUOTE;
            pos += 1;
            buf[pos..pos + sb.len()].copy_from_slice(sb);
            pos += sb.len();
            buf[pos] = BYTE_QUOTE;
            pos += 1;
        }
    }
    match body {
        CompactRpcBody::Result(res) => {
            let key: &[u8] = RPC_JSON_RESULT_KEY;
            if pos + key.len() >= RPC_PAYLOAD_STACK_CAP {
                return None;
            }
            buf[pos..pos + key.len()].copy_from_slice(key);
            pos += key.len();
            match res {
                Value::Null => {
                    let next: usize = pos + JSON_NULL.len();
                    if next >= RPC_PAYLOAD_STACK_CAP {
                        return None;
                    }
                    buf[pos..next].copy_from_slice(JSON_NULL);
                    pos = next;
                }
                Value::Bool(flag) => {
                    let lit: &[u8] = if *flag { JSON_TRUE } else { JSON_FALSE };
                    let next: usize = pos + lit.len();
                    if next >= RPC_PAYLOAD_STACK_CAP {
                        return None;
                    }
                    buf[pos..next].copy_from_slice(lit);
                    pos = next;
                }
                Value::Number(num) => {
                    if let Some(i) = num.as_i64() {
                        pos = write_i64_decimal_slice(i, buf, pos)?;
                    } else {
                        let u: u64 = num.as_u64()?;
                        pos = write_u64_decimal_slice(u, buf, pos)?;
                    }
                }
                Value::String(s) => {
                    let sb: &[u8] = s.as_bytes();
                    if needs_json_escape(sb) || pos + sb.len() + 3 > RPC_PAYLOAD_STACK_CAP {
                        return None;
                    }
                    buf[pos] = BYTE_QUOTE;
                    pos += 1;
                    buf[pos..pos + sb.len()].copy_from_slice(sb);
                    pos += sb.len();
                    buf[pos] = BYTE_QUOTE;
                    pos += 1;
                }
                Value::Array(_) | Value::Object(_) => return None,
            }
        }
        CompactRpcBody::StaticError(raw_err) => {
            let key: &[u8] = RPC_JSON_ERROR_KEY;
            let next: usize = pos + key.len() + raw_err.len();
            if next >= RPC_PAYLOAD_STACK_CAP {
                return None;
            }
            buf[pos..pos + key.len()].copy_from_slice(key);
            pos += key.len();
            buf[pos..pos + raw_err.len()].copy_from_slice(raw_err);
            pos += raw_err.len();
        }
        CompactRpcBody::Error(_) => return None,
    }
    if pos >= RPC_PAYLOAD_STACK_CAP {
        return None;
    }
    buf[pos] = BYTE_RBRACE;
    Some(pos + 1)
}

/// Formats an HTTP/1.1 `200 OK` JSON wire response into `stack` with zero heap allocations.
///
/// # Arguments
///
/// - `&[u8]` - Serialized JSON-RPC response payload.
/// - `&mut [u8; RPC_WIRE_STACK_CAP]` - Destination wire stack buffer.
///
/// # Returns
///
/// - `Option<usize>` - Total wire byte count when it fits in `stack`.
#[inline]
pub(crate) fn format_http11_json_wire_stack(
    payload: &[u8],
    stack: &mut [u8; RPC_WIRE_STACK_CAP],
) -> Option<usize> {
    let pfx: &[u8] = WIRE_HTTP11_200_JSON_PREFIX;
    if pfx.len() + 20 + WIRE_HEADER_END.len() + payload.len() > RPC_WIRE_STACK_CAP {
        return None;
    }
    stack[..pfx.len()].copy_from_slice(pfx);
    let end_len: usize = write_u64_decimal_slice(payload.len() as u64, stack, pfx.len())?;
    let body_start: usize = end_len + WIRE_HEADER_END.len();
    let total: usize = body_start + payload.len();
    if total > RPC_WIRE_STACK_CAP {
        return None;
    }
    stack[end_len..body_start].copy_from_slice(WIRE_HEADER_END);
    stack[body_start..total].copy_from_slice(payload);
    Some(total)
}

/// Formats an HTTP/1.1 `200 OK` JSON wire response into a single exact-sized `Vec<u8>`.
///
/// # Arguments
///
/// - `&[u8]` - Serialized JSON-RPC response payload.
///
/// # Returns
///
/// - `Vec<u8>` - Complete HTTP/1.1 wire bytes.
#[inline]
pub(crate) fn build_http11_json_wire_vec(payload: &[u8]) -> Vec<u8> {
    let pfx: &[u8] = WIRE_HTTP11_200_JSON_PREFIX;
    let mut digits: [u8; 20] = [0u8; 20];
    let idx: usize = format_u64_digits(payload.len() as u64, &mut digits);
    let len_bytes: &[u8] = &digits[idx..];
    let mut out: Vec<u8> =
        Vec::with_capacity(pfx.len() + len_bytes.len() + WIRE_HEADER_END.len() + payload.len());
    out.extend_from_slice(pfx);
    out.extend_from_slice(len_bytes);
    out.extend_from_slice(WIRE_HEADER_END);
    out.extend_from_slice(payload);
    out
}

/// Returns lazily prebuilt HTTP/1.1 empty-body wire bytes for `status`.
///
/// # Arguments
///
/// - `&'static OnceLock<Vec<u8>>` - Static cache slot.
/// - `HttpStatus` - Target HTTP status code.
///
/// # Returns
///
/// - `&'static [u8]` - Pre-serialized HTTP/1.1 wire bytes.
#[inline]
pub(crate) fn get_prebuilt_empty_wire(
    cache: &'static OnceLock<Vec<u8>>,
    status: HttpStatus,
) -> &'static [u8] {
    cache
        .get_or_init(|| {
            let mut resp: Response = Response::default();
            resp.set_status_code(status.code()).set_body(Vec::new());
            resp.build()
        })
        .as_slice()
}

/// 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(BYTE_LBRACKET);
    let mut written: usize = 0;
    for slot in slots.iter().flatten() {
        if let BatchDispatchSlot::Ready(resp) = slot {
            if written > 0 {
                buf.push(BYTE_COMMA);
            }
            write_compact_response(resp, &mut buf);
            written += 1;
        }
    }
    if written == 0 {
        return None;
    }
    buf.push(BYTE_RBRACKET);
    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(always)]
pub(crate) fn first_non_ws_byte(raw: &[u8]) -> Option<u8> {
    raw.iter()
        .copied()
        .find(|b: &u8| *b != BYTE_SPACE && *b != BYTE_TAB && *b != BYTE_CR && *b != BYTE_LF)
}