hyperlane_plugin_idempotency/struct.rs
1use super::*;
2
3/// Cached idempotent HTTP response carrying pre-serialized zero-copy replay wire bytes.
4#[derive(Clone, Data, Debug)]
5pub struct StoredIdempotentResponse {
6 /// HTTP status code recorded from the original execution.
7 #[get(type(copy))]
8 pub(crate) status_code: usize,
9 /// Response headers preserved from the original execution.
10 pub(crate) headers: Vec<(String, String)>,
11 /// Response payload bytes.
12 pub(crate) body: Vec<u8>,
13 /// Pre-serialized HTTP wire bytes including `Idempotent-Replayed: true` for zero-copy replay.
14 pub(crate) replayed_wire: Vec<u8>,
15 /// Unix epoch timestamp in milliseconds when stored.
16 #[get(type(copy))]
17 pub(crate) stored_at_ms: u64,
18}
19
20/// Configuration controlling TTLs, memory limits, methods, and required prefixes for [`IdempotencyPlugin`].
21#[derive(Clone, Data, Debug, Eq, PartialEq)]
22pub struct IdempotencyConfig {
23 /// Incoming header name carrying the client idempotency key (default `"idempotency-key"`).
24 pub(crate) header_name: String,
25 /// Cached response TTL in milliseconds.
26 #[get(type(copy))]
27 pub(crate) ttl_ms: u64,
28 /// Maximum duration an `InFlight` guard stays locked if abandoned.
29 #[get(type(copy))]
30 pub(crate) in_flight_ttl_ms: u64,
31 /// Maximum tracked keys across all 64 shards.
32 #[get(type(copy))]
33 pub(crate) max_entries: usize,
34 /// Maximum total memory budget across all 64 shards in bytes.
35 #[get(type(copy))]
36 pub(crate) max_bytes: usize,
37 /// Maximum individual response body length cached for replay in bytes.
38 #[get(type(copy))]
39 pub(crate) max_body_bytes: usize,
40 /// Maximum accepted byte length for the `Idempotency-Key` header.
41 #[get(type(copy))]
42 pub(crate) max_key_len: usize,
43 /// HTTP methods subject to idempotency enforcement (default `POST`/`PUT`/`PATCH`/`DELETE`).
44 pub(crate) methods: Vec<Method>,
45 /// Optional path prefixes where missing `Idempotency-Key` returns `400 Bad Request`.
46 pub(crate) require_key_prefixes: Vec<String>,
47 /// Whether to cache `5xx` server error responses (default `false` so callers may safely retry).
48 #[get(type(copy))]
49 pub(crate) cache_server_errors: bool,
50}
51
52/// One record inside a shard of [`InMemoryIdempotencyStore`].
53#[derive(Clone)]
54pub(crate) struct IdempotencySlot {
55 /// `XxHash3_64` fingerprint of `(method, path, body)`.
56 pub(crate) fingerprint: u64,
57 /// Current slot state (`InFlight` or `Completed`).
58 pub(crate) state: IdempotencySlotState,
59 /// Expiration timestamp in Unix epoch milliseconds.
60 pub(crate) expires_at_ms: u64,
61 /// Approximate memory footprint in bytes.
62 pub(crate) footprint_bytes: usize,
63}
64
65/// Cache-line-padded lock-striped shard preventing false sharing between adjacent shards.
66#[repr(align(64))]
67pub(crate) struct IdempotencyShard {
68 /// Per-shard read-write locked hash table.
69 pub(crate) map: RwLock<HashMapXxHash3_64<String, IdempotencySlot>>,
70}
71
72/// Shared interior state of [`InMemoryIdempotencyStore`].
73pub(crate) struct InMemoryIdempotencyStoreInner {
74 /// Maximum tracked keys across all 64 shards.
75 pub(crate) max_entries: usize,
76 /// Maximum total byte footprint across all 64 shards.
77 pub(crate) max_bytes: usize,
78 /// Lock-free active entry count.
79 pub(crate) entry_count: AtomicUsize,
80 /// Lock-free approximate byte usage.
81 pub(crate) total_bytes: AtomicUsize,
82 /// 64-way lock-striped key tables.
83 pub(crate) shards: Box<[IdempotencyShard; IDEMPOTENCY_SHARD_COUNT]>,
84}
85
86/// High-concurrency 64-way sharded bounded in-memory [`IdempotencyStore`].
87#[derive(Clone)]
88pub struct InMemoryIdempotencyStore {
89 /// Shared sharded store interior.
90 pub(crate) inner: Arc<InMemoryIdempotencyStoreInner>,
91}
92
93/// Interior RAII guard ensuring abandoned `InFlight` locks release on panic, early reject, or drop.
94pub(crate) struct IdempotencyInFlightGuardInner {
95 /// Atomic completion flag preventing cleanup once [`IdempotencyResponseHook`] finishes.
96 pub(crate) settled: AtomicBool,
97 /// Scoped storage key (`"<method>|<path>|<client_key>"`).
98 pub(crate) storage_key: String,
99 /// Request `(method, path, body)` fingerprint.
100 pub(crate) fingerprint: u64,
101 /// Backing store notified on early abandonment.
102 pub(crate) store: Arc<dyn IdempotencyStore>,
103}
104
105/// Leak-proof RAII guard stored in Hyperlane [`Context`] under [`ATTR_IDEMPOTENCY_GUARD`].
106#[derive(Clone)]
107pub struct IdempotencyInFlightGuard {
108 /// Shared single-settlement guard state.
109 pub(crate) inner: Arc<IdempotencyInFlightGuardInner>,
110}
111
112/// Process-wide [`IdempotencyPlugin`] singleton holding policy, store, and prebuilt error wire buffers.
113#[derive(Clone)]
114pub struct IdempotencyPlugin {
115 /// Active idempotency configuration.
116 pub(crate) config: IdempotencyConfig,
117 /// Precomputed bitmask of guarded standard HTTP methods for `O(1)` dispatch.
118 pub(crate) guarded_method_mask: u16,
119 /// `true` when `config.methods` contains at least one `Method::Unknown` variant.
120 pub(crate) has_unknown_method: bool,
121 /// Normalized prefixes requiring an explicit `Idempotency-Key`.
122 pub(crate) require_prefixes: Box<[String]>,
123 /// Pluggable backing store.
124 pub(crate) store: Arc<dyn IdempotencyStore>,
125 /// Direct zero-boxing handle when initialized with the built-in [`InMemoryIdempotencyStore`].
126 pub(crate) local_store: Option<InMemoryIdempotencyStore>,
127 /// Prebuilt `400 Bad Request` wire bytes for missing/invalid keys.
128 pub(crate) prebuilt_bad_key_wire: Vec<u8>,
129 /// Prebuilt `409 Conflict` + `Retry-After: 1` wire bytes for concurrent duplicates.
130 pub(crate) prebuilt_in_flight_wire: Vec<u8>,
131 /// Prebuilt `422 Unprocessable Entity` wire bytes for payload fingerprint mismatches.
132 pub(crate) prebuilt_mismatch_wire: Vec<u8>,
133}
134
135/// Opt-in request middleware validating `Idempotency-Key`, checking fingerprints, and replaying cached responses.
136#[derive(Clone, Copy, Debug, Default)]
137#[hyperlane::request_middleware(-78)]
138pub struct IdempotencyRequestHook;
139
140/// Opt-in response middleware storing completed responses and prebuilding zero-copy replay wire bytes.
141#[derive(Clone, Copy, Debug, Default)]
142#[hyperlane::response_middleware(-60)]
143pub struct IdempotencyResponseHook;