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: ResponseData,
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/// Shared interior state of [`InMemoryIdempotencyStore`].
66pub(crate) struct InMemoryIdempotencyStoreInner {
67 /// Maximum tracked keys across all 64 shards.
68 pub(crate) max_entries: usize,
69 /// Maximum total byte footprint across all 64 shards.
70 pub(crate) max_bytes: usize,
71 /// Lock-free active entry count.
72 pub(crate) entry_count: AtomicUsize,
73 /// Lock-free approximate byte usage.
74 pub(crate) total_bytes: AtomicUsize,
75 /// 64-way lock-striped key tables.
76 pub(crate) shards: IdempotencyShardArray,
77}
78
79/// High-concurrency 64-way sharded bounded in-memory [`IdempotencyStore`].
80#[derive(Clone)]
81pub struct InMemoryIdempotencyStore {
82 /// Shared sharded store interior.
83 pub(crate) inner: Arc<InMemoryIdempotencyStoreInner>,
84}
85
86/// Interior RAII guard ensuring abandoned `InFlight` locks release on panic, early reject, or drop.
87pub(crate) struct IdempotencyInFlightGuardInner {
88 /// Atomic completion flag preventing cleanup once [`IdempotencyResponseHook`] finishes.
89 pub(crate) settled: AtomicBool,
90 /// Scoped storage key (`"<method>|<path>|<client_key>"`).
91 pub(crate) storage_key: String,
92 /// Request `(method, path, body)` fingerprint.
93 pub(crate) fingerprint: u64,
94 /// Backing store notified on early abandonment.
95 pub(crate) store: SharedIdempotencyStore,
96}
97
98/// Leak-proof RAII guard stored in Hyperlane [`Context`] under [`ATTR_IDEMPOTENCY_GUARD`].
99#[derive(Clone)]
100pub struct IdempotencyInFlightGuard {
101 /// Shared single-settlement guard state.
102 pub(crate) inner: Arc<IdempotencyInFlightGuardInner>,
103}
104
105/// Process-wide [`IdempotencyPlugin`] singleton holding policy, store, and prebuilt error wire buffers.
106#[derive(Clone)]
107pub struct IdempotencyPlugin {
108 /// Active idempotency configuration.
109 pub(crate) config: IdempotencyConfig,
110 /// Normalized prefixes requiring an explicit `Idempotency-Key`.
111 pub(crate) require_prefixes: Vec<String>,
112 /// Pluggable backing store.
113 pub(crate) store: SharedIdempotencyStore,
114 /// Prebuilt `400 Bad Request` wire bytes for missing/invalid keys.
115 pub(crate) prebuilt_bad_key_wire: ResponseData,
116 /// Prebuilt `409 Conflict` + `Retry-After: 1` wire bytes for concurrent duplicates.
117 pub(crate) prebuilt_in_flight_wire: ResponseData,
118 /// Prebuilt `422 Unprocessable Entity` wire bytes for payload fingerprint mismatches.
119 pub(crate) prebuilt_mismatch_wire: ResponseData,
120}
121
122/// Opt-in request middleware validating `Idempotency-Key`, checking fingerprints, and replaying cached responses.
123#[derive(Clone, Copy, Debug, Default)]
124#[hyperlane::request_middleware(-78)]
125pub struct IdempotencyRequestHook;
126
127/// Opt-in response middleware storing completed responses and prebuilding zero-copy replay wire bytes.
128#[derive(Clone, Copy, Debug, Default)]
129#[hyperlane::response_middleware(-60)]
130pub struct IdempotencyResponseHook;