hyperlane-plugin-idempotency 23.3.0

A production HTTP Idempotency-Key middleware plugin for the Hyperlane framework featuring XxHash3_64 request fingerprinting (422 mismatch), 64-way sharded bounded InMemoryIdempotencyStore + async IdempotencyStore trait, InFlight concurrent duplicate guard (409 Conflict), and zero-copy cached response replay with Idempotent-Replayed headers.
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use super::*;

/// Returns the current Unix epoch timestamp in milliseconds.
///
/// # Returns
///
/// - `u64` - Milliseconds since Unix epoch.
#[inline]
pub(crate) fn idempotency_now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_millis() as u64)
        .unwrap_or(0)
}

/// Computes the 64-way shard index for `key` using fast inline 8-byte word mixing.
///
/// # Arguments
///
/// - `&str` - Scoped idempotency key.
///
/// # Returns
///
/// - `usize` - Shard index in `0..IDEMPOTENCY_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn idempotency_shard_index(key: &str) -> usize {
    let bytes: &[u8] = key.as_bytes();
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    let mut hash: u64 = FP_SECRET0 ^ (bytes.len() as u64);
    for chunk in chunks {
        hash = (hash ^ u64::from_ne_bytes(*chunk)).wrapping_mul(IDEMP_SHARD_MUL1);
    }
    if !rem.is_empty() {
        let mut tail: u64 = 0;
        for &b in rem {
            tail = (tail << 8) | u64::from(b);
        }
        hash = (hash ^ tail).wrapping_mul(IDEMP_SHARD_MUL2);
    }
    ((hash ^ (hash >> 32)) as usize) & (IDEMPOTENCY_SHARD_COUNT - 1)
}

/// Applies one 128-bit multiply-fold avalanche step (`mum`) with zero heap allocation.
///
/// # Arguments
///
/// - `u64` - Left 64-bit word.
/// - `u64` - Right 64-bit word.
///
/// # Returns
///
/// - `u64` - High-entropy mixed 64-bit word.
#[inline(always)]
pub(crate) fn fp_mix(a: u64, b: u64) -> u64 {
    let prod: u128 = u128::from(a).wrapping_mul(u128::from(b));
    (prod as u64) ^ ((prod >> 64) as u64)
}

/// Folds a byte slice into a running 64-bit fingerprint state at 16 bytes per iteration without allocating.
///
/// # Arguments
///
/// - `u64` - Running 64-bit hash state.
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `u64` - Updated 64-bit hash state.
#[inline]
pub(crate) fn fp_hash_bytes(mut seed: u64, data: &[u8]) -> u64 {
    let len: usize = data.len();
    seed = fp_mix(seed ^ FP_SECRET0, (len as u64) ^ FP_SECRET1);
    let (blocks, rem): (&[[u8; 16]], &[u8]) = data.as_chunks::<16>();
    for chunk in blocks {
        let lo: u64 = u64::from_le_bytes([
            chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
        ]);
        let hi: u64 = u64::from_le_bytes([
            chunk[8], chunk[9], chunk[10], chunk[11], chunk[12], chunk[13], chunk[14], chunk[15],
        ]);
        seed = fp_mix(lo ^ FP_SECRET1, hi ^ seed);
    }
    let rem_len: usize = rem.len();
    if rem_len >= 8 {
        let lo: u64 = u64::from_le_bytes([
            rem[0], rem[1], rem[2], rem[3], rem[4], rem[5], rem[6], rem[7],
        ]);
        let tail: &[u8] = &rem[rem_len - 8..];
        let hi: u64 = u64::from_le_bytes([
            tail[0], tail[1], tail[2], tail[3], tail[4], tail[5], tail[6], tail[7],
        ]);
        seed = fp_mix(lo ^ FP_SECRET2, hi ^ seed);
    } else if rem_len >= 4 {
        let lo: u64 = u64::from(u32::from_le_bytes([rem[0], rem[1], rem[2], rem[3]]));
        let tail: &[u8] = &rem[rem_len - 4..];
        let hi: u64 = u64::from(u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]));
        seed = fp_mix(lo ^ FP_SECRET2, hi ^ seed);
    } else if rem_len > 0 {
        let packed: u64 = (u64::from(rem[0]) << 16)
            | (u64::from(rem[rem_len >> 1]) << 8)
            | u64::from(rem[rem_len - 1]);
        seed = fp_mix(packed ^ FP_SECRET2, seed ^ FP_SECRET3);
    }
    fp_mix(seed ^ FP_SECRET3, (len as u64) ^ FP_SECRET0)
}

/// Computes a zero-allocation 64-bit request fingerprint over `(method, path, body)`.
///
/// # Arguments
///
/// - `&Method` - HTTP request method.
/// - `&str` - Request path.
/// - `&[u8]` - Raw request body bytes.
///
/// # Returns
///
/// - `u64` - Deterministic 64-bit request payload fingerprint.
#[inline]
pub fn compute_request_fingerprint(method: &Method, path: &str, body: &[u8]) -> u64 {
    let seed: u64 = match method {
        Method::Get => 1 ^ FP_SECRET0,
        Method::Post => 2 ^ FP_SECRET0,
        Method::Put => 3 ^ FP_SECRET0,
        Method::Delete => 4 ^ FP_SECRET0,
        Method::Patch => 5 ^ FP_SECRET0,
        Method::Head => 6 ^ FP_SECRET0,
        Method::Options => 7 ^ FP_SECRET0,
        Method::Connect => 8 ^ FP_SECRET0,
        Method::Trace => 9 ^ FP_SECRET0,
        Method::Unknown(raw) => fp_hash_bytes(10 ^ FP_SECRET0, raw.as_bytes()),
    };
    let after_path: u64 = fp_hash_bytes(seed, path.as_bytes());
    fp_hash_bytes(after_path ^ FP_SECRET1, body)
}

/// Maps an HTTP [`Method`] to a borrowed string slice without allocating.
///
/// # Arguments
///
/// - `&Method` - Incoming HTTP method.
///
/// # Returns
///
/// - `&str` - Canonical uppercase method slice.
#[inline(always)]
pub(crate) fn method_as_str(method: &Method) -> &str {
    match method {
        Method::Get => GET,
        Method::Post => POST,
        Method::Put => PUT,
        Method::Delete => DELETE,
        Method::Patch => PATCH,
        Method::Head => HEAD,
        Method::Options => OPTIONS,
        Method::Connect => CONNECT,
        Method::Trace => TRACE,
        Method::Unknown(raw) => raw.as_str(),
    }
}

/// Maps standard [`Method`] variants to a unique bit position for `O(1)` bitmask dispatch.
///
/// # Arguments
///
/// - `&Method` - Incoming HTTP method.
///
/// # Returns
///
/// - `u16` - Bit mask (`0` for `Method::Unknown`).
#[inline(always)]
pub(crate) fn method_bit(method: &Method) -> u16 {
    match method {
        Method::Get => 1 << 0,
        Method::Post => 1 << 1,
        Method::Put => 1 << 2,
        Method::Delete => 1 << 3,
        Method::Patch => 1 << 4,
        Method::Head => 1 << 5,
        Method::Options => 1 << 6,
        Method::Connect => 1 << 7,
        Method::Trace => 1 << 8,
        Method::Unknown(_) => 0,
    }
}

/// Builds a scoped storage key combining HTTP method, request path, and client `Idempotency-Key`.
///
/// # Arguments
///
/// - `&Method` - HTTP request method.
/// - `&str` - Request path.
/// - `&str` - Trimmed client `Idempotency-Key`.
///
/// # Returns
///
/// - `String` - Scoped storage key isolating identical client keys across distinct endpoints.
#[inline]
pub(crate) fn build_storage_key(method: &Method, path: &str, client_key: &str) -> String {
    let method_str: &str = method_as_str(method);
    let mut out: String =
        String::with_capacity(method_str.len() + path.len() + client_key.len() + 2);
    out.push_str(method_str);
    out.push('|');
    out.push_str(path);
    out.push('|');
    out.push_str(client_key);
    out
}

/// Formats a scoped storage key into a caller-supplied stack buffer without heap allocation.
///
/// # Arguments
///
/// - `&Method` - HTTP request method.
/// - `&str` - Request path.
/// - `&str` - Trimmed client `Idempotency-Key`.
/// - `&'a mut [u8; STACK_STORAGE_KEY_CAP]` - Stack byte buffer.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed storage key when it fits inside the stack buffer.
#[inline]
pub(crate) fn build_storage_key_stack<'a>(
    method: &Method,
    path: &str,
    client_key: &str,
    buf: &'a mut [u8; STACK_STORAGE_KEY_CAP],
) -> Option<&'a str> {
    let m: &[u8] = method_as_str(method).as_bytes();
    let p: &[u8] = path.as_bytes();
    let k: &[u8] = client_key.as_bytes();
    let total: usize = m.len() + 1 + p.len() + 1 + k.len();
    if total > STACK_STORAGE_KEY_CAP {
        return None;
    }
    let mut off: usize = 0;
    buf[off..off + m.len()].copy_from_slice(m);
    off += m.len();
    buf[off] = ASCII_PIPE;
    off += 1;
    buf[off..off + p.len()].copy_from_slice(p);
    off += p.len();
    buf[off] = ASCII_PIPE;
    off += 1;
    buf[off..off + k.len()].copy_from_slice(k);
    from_utf8(&buf[..total]).ok()
}

/// Formats a `usize` decimal integer into a 20-byte stack buffer with zero heap allocations.
///
/// # Arguments
///
/// - `usize` - Non-negative integer to format.
/// - `&mut [u8; DEC_STACK_BUF_LEN]` - Stack byte buffer.
///
/// # Returns
///
/// - `&[u8]` - Borrowed ASCII decimal slice inside `buf`.
#[inline(always)]
pub(crate) fn format_usize_stack(mut value: usize, buf: &mut [u8; DEC_STACK_BUF_LEN]) -> &[u8] {
    let mut pos: usize = DEC_STACK_BUF_LEN;
    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..]
}

/// Checks whether an HTTP header name/value pair contains no CR, LF, or NUL bytes.
///
/// # Arguments
///
/// - `&str` - Header name.
/// - `&str` - Header value.
///
/// # Returns
///
/// - `bool` - `true` when safe to emit directly onto the HTTP/1.1 wire.
#[inline(always)]
pub(crate) fn is_wire_safe_header(name: &str, val: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b: u8| b > 0x20 && b < 0x7F && b != ASCII_COLON)
        && val
            .bytes()
            .all(|b: u8| b >= 0x20 && b != 0x7F || b == b'\t')
}

/// Pre-serializes a cached idempotent HTTP/1.1 response directly into one buffer without intermediate `Response` allocation.
///
/// Falls back to [`Response::build`] when special framing (`Content-Encoding`, `Transfer-Encoding`, `text/event-stream`,
/// or non-wire-safe header bytes) is present.
///
/// # Arguments
///
/// - `usize` - HTTP status code.
/// - `&[(String, String)]` - Preserved response headers.
/// - `&[u8]` - Response body bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Complete HTTP/1.1 wire buffer including `Idempotent-Replayed: true`.
pub(crate) fn build_replayed_wire(
    status_code: usize,
    headers: &[(String, String)],
    body: &[u8],
) -> Vec<u8> {
    let mut has_connection: bool = false;
    let mut has_content_type: bool = false;
    let mut extra_headers_bytes: usize = 0;
    let mut can_fast_path: bool = true;
    for (name, val) in headers {
        if name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
            continue;
        }
        if !is_wire_safe_header(name, val) {
            can_fast_path = false;
            break;
        }
        if name.eq_ignore_ascii_case(CONTENT_ENCODING)
            || name.eq_ignore_ascii_case(TRANSFER_ENCODING)
            || name.eq_ignore_ascii_case(CONTENT_LENGTH)
        {
            can_fast_path = false;
            break;
        }
        if name.eq_ignore_ascii_case(CONNECTION) {
            has_connection = true;
        } else if name.eq_ignore_ascii_case(CONTENT_TYPE) {
            has_content_type = true;
            let media: &str = val.split(';').next().unwrap_or("").trim();
            if media.eq_ignore_ascii_case(TEXT_EVENT_STREAM) {
                can_fast_path = false;
                break;
            }
        }
        extra_headers_bytes += name.len() + 1 + val.len() + WIRE_CRLF.len();
    }
    if !can_fast_path {
        let mut replay_resp: Response = Response::default();
        replay_resp.set_status_code(status_code);
        for (name, val) in headers {
            if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
                replay_resp.set_header(name, val);
            }
        }
        replay_resp
            .set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
            .set_body(body);
        return replay_resp.build();
    }
    let phrase: &str = HttpStatus::phrase_ref(status_code);
    let mut code_buf: [u8; DEC_STACK_BUF_LEN] = [0u8; DEC_STACK_BUF_LEN];
    let code_bytes: &[u8] = format_usize_stack(status_code, &mut code_buf);
    let is_bodyless: bool = (100..=199).contains(&status_code)
        || status_code == HttpStatus::NoContent.code()
        || status_code == HttpStatus::ResetContent.code()
        || status_code == HttpStatus::NotModified.code();
    let mut cl_buf: [u8; DEC_STACK_BUF_LEN] = [0u8; DEC_STACK_BUF_LEN];
    let cl_bytes: &[u8] = if is_bodyless {
        &[]
    } else {
        format_usize_stack(body.len(), &mut cl_buf)
    };
    let wire_body: &[u8] = if is_bodyless { &[] } else { body };
    let framing_len: usize = if !is_bodyless {
        WIRE_CL_PREFIX.len() + cl_bytes.len() + WIRE_CRLF.len()
    } else if status_code == HttpStatus::ResetContent.code() {
        WIRE_CL_ZERO.len()
    } else {
        0
    };
    let total_len: usize = WIRE_HTTP11_PREFIX.len()
        + code_bytes.len()
        + 1
        + phrase.len()
        + WIRE_CRLF.len()
        + extra_headers_bytes
        + WIRE_REPLAYED_LINE.len()
        + if has_connection {
            0
        } else {
            WIRE_CONN_KEEP_ALIVE.len()
        }
        + if is_bodyless || has_content_type {
            0
        } else {
            WIRE_DEFAULT_CONTENT_TYPE.len()
        }
        + framing_len
        + WIRE_CRLF.len()
        + wire_body.len();
    let mut out: Vec<u8> = Vec::with_capacity(total_len);
    out.extend_from_slice(WIRE_HTTP11_PREFIX);
    out.extend_from_slice(code_bytes);
    out.push(b' ');
    out.extend_from_slice(phrase.as_bytes());
    out.extend_from_slice(WIRE_CRLF);
    for (name, val) in headers {
        if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
            out.extend_from_slice(name.as_bytes());
            out.push(ASCII_COLON);
            out.extend_from_slice(val.as_bytes());
            out.extend_from_slice(WIRE_CRLF);
        }
    }
    out.extend_from_slice(WIRE_REPLAYED_LINE);
    if !has_connection {
        out.extend_from_slice(WIRE_CONN_KEEP_ALIVE);
    }
    if !is_bodyless && !has_content_type {
        out.extend_from_slice(WIRE_DEFAULT_CONTENT_TYPE);
    }
    if !is_bodyless {
        out.extend_from_slice(WIRE_CL_PREFIX);
        out.extend_from_slice(cl_bytes);
        out.extend_from_slice(WIRE_CRLF);
    } else if status_code == HttpStatus::ResetContent.code() {
        out.extend_from_slice(WIRE_CL_ZERO);
    }
    out.extend_from_slice(WIRE_CRLF);
    out.extend_from_slice(wire_body);
    out
}

/// Looks up a header value without cloning using an `O(1)` lowercase fast path.
///
/// # Arguments
///
/// - `&'a RequestHeaders` - Request header map.
/// - `&str` - Canonical lowercase header name.
///
/// # Returns
///
/// - `Option<&'a str>` - Last header value slice if present.
#[inline]
pub(crate) fn find_header_back_ref<'a>(
    headers: &'a RequestHeaders,
    lower_name: &str,
) -> Option<&'a str> {
    if let Some(vals) = headers.get(lower_name) {
        return vals.back().map(String::as_str);
    }
    headers
        .iter()
        .find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
        .and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}

/// Validates a client `Idempotency-Key` header value for non-emptiness, length cap, and absence of control bytes.
///
/// # Arguments
///
/// - `&str` - Trimmed header value.
/// - `usize` - Maximum allowed byte length.
///
/// # Returns
///
/// - `bool` - `true` when valid.
#[inline]
pub(crate) fn is_valid_idempotency_key(key: &str, max_len: usize) -> bool {
    !key.is_empty() && key.len() <= max_len && key.bytes().all(|b: u8| b >= 0x20 && b != 0x7F)
}

/// Normalizes a path prefix by stripping trailing slashes while preserving `"/"`.
///
/// # Arguments
///
/// - `&str` - Raw prefix string.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    let stripped: &str = trimmed.trim_end_matches('/');
    if stripped.is_empty() {
        "/".to_owned()
    } else {
        stripped.to_owned()
    }
}

/// Reports whether `path` matches normalized `prefix` on a segment boundary.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized prefix.
///
/// # Returns
///
/// - `bool` - `true` when matched.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == "/" {
        return true;
    }
    let Some(rest) = path.strip_prefix(prefix) else {
        return false;
    };
    rest.is_empty() || rest.starts_with('/')
}

/// Estimates heap byte usage of one completed [`StoredIdempotentResponse`] plus its storage key.
///
/// # Arguments
///
/// - `&str` - Scoped storage key.
/// - `&StoredIdempotentResponse` - Cached response payload and wire buffer.
///
/// # Returns
///
/// - `usize` - Estimated memory footprint in bytes.
pub(crate) fn estimate_response_bytes(key: &str, resp: &StoredIdempotentResponse) -> usize {
    let header_bytes: usize = resp
        .get_headers()
        .iter()
        .map(|(k, v): &(String, String)| k.len() + v.len())
        .sum();
    key.len()
        + header_bytes
        + resp.get_body().len()
        + resp.get_replayed_wire().len()
        + ENTRY_OVERHEAD_BYTES
}

/// Prebuilds an error HTTP wire response buffer (`400`/`409`/`422`).
///
/// # Arguments
///
/// - `HttpStatus` - HTTP error status.
/// - `&[u8]` - Static plain-text body bytes.
/// - `Option<&str>` - Optional `Retry-After` header value.
///
/// # Returns
///
/// - `Vec<u8>` - Pre-serialized HTTP wire bytes.
pub(crate) fn build_static_error_wire(
    status: HttpStatus,
    body: &[u8],
    retry_after: Option<&str>,
) -> Vec<u8> {
    let mut resp: Response = Response::default();
    resp.set_status_code(status.code())
        .set_header(CONTENT_TYPE, ERROR_CONTENT_TYPE)
        .set_body(body);
    if let Some(retry) = retry_after {
        resp.set_header(RETRY_AFTER, retry);
    }
    resp.build()
}