Skip to main content

hyperlane_plugin_idempotency/
impl.rs

1use super::*;
2
3/// Inherent constructors and replay helpers for [`StoredIdempotentResponse`].
4impl StoredIdempotentResponse {
5    /// Captures status, headers, and body and pre-serializes the zero-copy `Idempotent-Replayed: true` wire buffer.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - HTTP response status code.
10    /// - `Vec<(String, String)>` - Response headers.
11    /// - `Vec<u8>` - Response body bytes.
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Cached idempotent response ready for zero-copy replay.
16    pub fn from_parts(status_code: usize, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
17        let mut replay_resp: Response = Response::default();
18        replay_resp.set_status_code(status_code);
19        for (name, val) in &headers {
20            if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
21                replay_resp.set_header(name, val);
22            }
23        }
24        replay_resp
25            .set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
26            .set_body(body.clone());
27        let replayed_wire: ResponseData = replay_resp.build();
28        Self {
29            status_code,
30            headers,
31            body,
32            replayed_wire,
33            stored_at_ms: idempotency_now_ms(),
34        }
35    }
36
37    /// Captures a live Hyperlane [`Response`] into a [`StoredIdempotentResponse`].
38    ///
39    /// # Arguments
40    ///
41    /// - `&Response` - Completed response from the route handler.
42    ///
43    /// # Returns
44    ///
45    /// - `Self` - Cached response carrying prebuilt replay wire bytes.
46    pub fn capture(response: &Response) -> Self {
47        let mut headers: Vec<(String, String)> = Vec::with_capacity(response.get_headers().len());
48        for (name, values) in response.get_headers() {
49            if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED)
50                && let Some(last) = values.back()
51            {
52                headers.push((name.clone(), last.clone()));
53            }
54        }
55        Self::from_parts(
56            response.get_status_code(),
57            headers,
58            response.get_body().clone(),
59        )
60    }
61
62    /// Applies this cached response onto a Hyperlane [`Response`] with `Idempotent-Replayed: true`.
63    ///
64    /// # Arguments
65    ///
66    /// - `&mut Response` - Target response object.
67    pub fn apply_to_response(&self, response: &mut Response) {
68        response.set_status_code(self.get_status_code());
69        for (name, val) in self.get_headers() {
70            response.set_header(name, val);
71        }
72        response
73            .set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
74            .set_body(self.get_body().clone());
75    }
76}
77
78/// Default construction for [`IdempotencyConfig`].
79impl Default for IdempotencyConfig {
80    /// Constructs a default [`IdempotencyConfig`] covering `POST`/`PUT`/`PATCH`/`DELETE` with 24 h TTL.
81    ///
82    /// # Returns
83    ///
84    /// - `Self` - Default configuration.
85    fn default() -> Self {
86        Self {
87            header_name: DEFAULT_IDEMPOTENCY_KEY_HEADER.to_owned(),
88            ttl_ms: DEFAULT_IDEMPOTENCY_TTL_MS,
89            in_flight_ttl_ms: DEFAULT_IN_FLIGHT_TTL_MS,
90            max_entries: DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
91            max_bytes: DEFAULT_IDEMPOTENCY_MAX_BYTES,
92            max_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
93            max_key_len: DEFAULT_MAX_KEY_LEN,
94            methods: vec![Method::Post, Method::Put, Method::Patch, Method::Delete],
95            require_key_prefixes: Vec::new(),
96            cache_server_errors: false,
97        }
98    }
99}
100
101/// Fluent configuration builders for [`IdempotencyConfig`].
102impl IdempotencyConfig {
103    /// Sets the request header name carrying the client idempotency key (stored lowercased).
104    ///
105    /// # Arguments
106    ///
107    /// - `S` - Header name (for example `"idempotency-key"` or `"x-idempotency-key"`).
108    ///
109    /// # Returns
110    ///
111    /// - `Self` - Updated configuration.
112    pub fn with_header_name<S>(mut self, name: S) -> Self
113    where
114        S: AsRef<str>,
115    {
116        self.set_header_name(name.as_ref().trim().to_ascii_lowercase());
117        self
118    }
119
120    /// Sets the cached replay response TTL in milliseconds.
121    ///
122    /// # Arguments
123    ///
124    /// - `u64` - Replay TTL in milliseconds (`>= 1`).
125    ///
126    /// # Returns
127    ///
128    /// - `Self` - Updated configuration.
129    pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
130        self.set_ttl_ms(ttl_ms.max(1));
131        self
132    }
133
134    /// Sets the maximum lifetime of an `InFlight` guard in milliseconds.
135    ///
136    /// # Arguments
137    ///
138    /// - `u64` - In-flight lock TTL in milliseconds (`>= 1`).
139    ///
140    /// # Returns
141    ///
142    /// - `Self` - Updated configuration.
143    pub fn with_in_flight_ttl_ms(mut self, in_flight_ttl_ms: u64) -> Self {
144        self.set_in_flight_ttl_ms(in_flight_ttl_ms.max(1));
145        self
146    }
147
148    /// Sets the maximum entry count and total byte cap across all 64 shards.
149    ///
150    /// # Arguments
151    ///
152    /// - `usize` - Maximum entry count (`>= 1`).
153    /// - `usize` - Maximum byte budget (`>= 1`).
154    ///
155    /// # Returns
156    ///
157    /// - `Self` - Updated configuration.
158    pub fn with_limits(mut self, max_entries: usize, max_bytes: usize) -> Self {
159        self.set_max_entries(max_entries.max(1))
160            .set_max_bytes(max_bytes.max(1));
161        self
162    }
163
164    /// Sets path prefixes that require an explicit `Idempotency-Key` header on mutation methods.
165    ///
166    /// # Arguments
167    ///
168    /// - `I` - Iterator of path prefixes (for example `["/v1/payments"]`).
169    ///
170    /// # Returns
171    ///
172    /// - `Self` - Updated configuration.
173    pub fn with_require_key_prefixes<I, S>(mut self, prefixes: I) -> Self
174    where
175        I: IntoIterator<Item = S>,
176        S: Into<String>,
177    {
178        self.set_require_key_prefixes(prefixes.into_iter().map(Into::into).collect());
179        self
180    }
181
182    /// Sets the HTTP methods guarded by idempotency enforcement.
183    ///
184    /// # Arguments
185    ///
186    /// - `Vec<Method>` - Guarded HTTP methods.
187    ///
188    /// # Returns
189    ///
190    /// - `Self` - Updated configuration.
191    pub fn with_methods(mut self, methods: Vec<Method>) -> Self {
192        self.set_methods(methods);
193        self
194    }
195
196    /// Configures whether `5xx` server errors are cached for replay.
197    ///
198    /// # Arguments
199    ///
200    /// - `bool` - `true` to cache `5xx` responses; `false` (default) to release the key on `5xx`.
201    ///
202    /// # Returns
203    ///
204    /// - `Self` - Updated configuration.
205    pub fn with_cache_server_errors(mut self, cache_server_errors: bool) -> Self {
206        self.set_cache_server_errors(cache_server_errors);
207        self
208    }
209}
210
211/// Default construction for [`InMemoryIdempotencyStore`].
212impl Default for InMemoryIdempotencyStore {
213    /// Constructs a default 64-shard [`InMemoryIdempotencyStore`].
214    ///
215    /// # Returns
216    ///
217    /// - `Self` - Default sharded store.
218    fn default() -> Self {
219        Self::new(
220            DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
221            DEFAULT_IDEMPOTENCY_MAX_BYTES,
222        )
223    }
224}
225
226/// Inherent 64-way sharded storage operations for [`InMemoryIdempotencyStore`].
227impl InMemoryIdempotencyStore {
228    /// Creates a 64-way sharded bounded [`InMemoryIdempotencyStore`].
229    ///
230    /// # Arguments
231    ///
232    /// - `usize` - Maximum entry count across all shards.
233    /// - `usize` - Maximum byte budget across all shards.
234    ///
235    /// # Returns
236    ///
237    /// - `Self` - Ready sharded store.
238    pub fn new(max_entries: usize, max_bytes: usize) -> Self {
239        let shards: IdempotencyShardArray =
240            Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
241        Self {
242            inner: Arc::new(InMemoryIdempotencyStoreInner {
243                max_entries: max_entries.max(1),
244                max_bytes: max_bytes.max(1),
245                entry_count: AtomicUsize::new(0),
246                total_bytes: AtomicUsize::new(0),
247                shards,
248            }),
249        }
250    }
251
252    /// Returns the live tracked entry count across all 64 shards in `O(1)` time without locking.
253    ///
254    /// # Returns
255    ///
256    /// - `usize` - Current entry count.
257    #[inline]
258    pub fn len(&self) -> usize {
259        let Self { inner } = self;
260        inner.entry_count.load(Ordering::Relaxed)
261    }
262
263    /// Reports whether the store contains zero entries.
264    ///
265    /// # Returns
266    ///
267    /// - `bool` - `true` when empty.
268    #[inline]
269    pub fn is_empty(&self) -> bool {
270        self.len() == 0
271    }
272
273    /// Returns the estimated total memory usage across all shards in bytes.
274    ///
275    /// # Returns
276    ///
277    /// - `usize` - Approximate byte footprint.
278    #[inline]
279    pub fn total_bytes(&self) -> usize {
280        let Self { inner } = self;
281        inner.total_bytes.load(Ordering::Relaxed)
282    }
283
284    /// Synchronous atomic lookup or `InFlight` acquisition on a single shard.
285    ///
286    /// # Arguments
287    ///
288    /// - `&str` - Scoped storage key.
289    /// - `u64` - Request fingerprint.
290    /// - `u64` - In-flight lock TTL in milliseconds.
291    ///
292    /// # Returns
293    ///
294    /// - `IdempotencyLookup` - Acquisition, conflict, mismatch, or zero-copy replay result.
295    pub fn acquire_sync(
296        &self,
297        key: &str,
298        fingerprint: u64,
299        in_flight_ttl_ms: u64,
300    ) -> IdempotencyLookup {
301        let Self { inner } = self;
302        let idx: usize = idempotency_shard_index(key);
303        let now_ms: u64 = idempotency_now_ms();
304        if let Ok(read_guard) = inner.shards[idx].read()
305            && let Some(existing) = read_guard.get(key)
306            && now_ms < existing.expires_at_ms
307        {
308            if existing.fingerprint != fingerprint {
309                return IdempotencyLookup::FingerprintMismatch;
310            }
311            return match &existing.state {
312                IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
313                IdempotencySlotState::Completed(resp) => {
314                    IdempotencyLookup::Replayed(Arc::clone(resp))
315                }
316            };
317        }
318        let Ok(mut map): Result<
319            RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
320            _,
321        > = inner.shards[idx].write() else {
322            return IdempotencyLookup::Acquired;
323        };
324        if let Some(existing) = map.get(key) {
325            if now_ms < existing.expires_at_ms {
326                if existing.fingerprint != fingerprint {
327                    return IdempotencyLookup::FingerprintMismatch;
328                }
329                return match &existing.state {
330                    IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
331                    IdempotencySlotState::Completed(resp) => {
332                        IdempotencyLookup::Replayed(Arc::clone(resp))
333                    }
334                };
335            }
336            if let Some(expired) = map.remove(key) {
337                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
338                inner
339                    .total_bytes
340                    .fetch_sub(expired.footprint_bytes, Ordering::Relaxed);
341            }
342        }
343        let footprint: usize = key.len() + ENTRY_OVERHEAD_BYTES;
344        while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
345            || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
346            && !map.is_empty()
347        {
348            let oldest: Option<String> = map
349                .iter()
350                .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
351                .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
352            if let Some(evict_key) = oldest
353                && let Some(removed) = map.remove(&evict_key)
354            {
355                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
356                inner
357                    .total_bytes
358                    .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
359            } else {
360                break;
361            }
362        }
363        map.insert(
364            key.to_owned(),
365            IdempotencySlot {
366                fingerprint,
367                state: IdempotencySlotState::InFlight,
368                expires_at_ms: now_ms.saturating_add(in_flight_ttl_ms),
369                footprint_bytes: footprint,
370            },
371        );
372        inner.entry_count.fetch_add(1, Ordering::Relaxed);
373        inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
374        IdempotencyLookup::Acquired
375    }
376
377    /// Synchronous commit storing a completed [`StoredIdempotentResponse`] under `key`.
378    ///
379    /// # Arguments
380    ///
381    /// - `String` - Scoped storage key.
382    /// - `u64` - Request fingerprint.
383    /// - `Arc<StoredIdempotentResponse>` - Cached response and prebuilt replay wire bytes.
384    /// - `u64` - Replay cache TTL in milliseconds.
385    pub fn complete_sync(
386        &self,
387        key: String,
388        fingerprint: u64,
389        response: Arc<StoredIdempotentResponse>,
390        ttl_ms: u64,
391    ) {
392        let Self { inner } = self;
393        let footprint: usize = estimate_response_bytes(&key, &response);
394        if footprint > inner.max_bytes {
395            self.release_sync(&key);
396            return;
397        }
398        let idx: usize = idempotency_shard_index(&key);
399        let now_ms: u64 = idempotency_now_ms();
400        let Ok(mut map): Result<
401            RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
402            _,
403        > = inner.shards[idx].write() else {
404            return;
405        };
406        if let Some(prev) = map.remove(&key) {
407            inner.entry_count.fetch_sub(1, Ordering::Relaxed);
408            inner
409                .total_bytes
410                .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
411        }
412        while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
413            || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
414            && !map.is_empty()
415        {
416            let oldest: Option<String> = map
417                .iter()
418                .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
419                .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
420            if let Some(evict_key) = oldest
421                && let Some(removed) = map.remove(&evict_key)
422            {
423                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
424                inner
425                    .total_bytes
426                    .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
427            } else {
428                break;
429            }
430        }
431        map.insert(
432            key,
433            IdempotencySlot {
434                fingerprint,
435                state: IdempotencySlotState::Completed(response),
436                expires_at_ms: now_ms.saturating_add(ttl_ms),
437                footprint_bytes: footprint,
438            },
439        );
440        inner.entry_count.fetch_add(1, Ordering::Relaxed);
441        inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
442    }
443
444    /// Synchronously releases an `InFlight` slot (leaving any already-completed response intact).
445    ///
446    /// # Arguments
447    ///
448    /// - `&str` - Scoped storage key.
449    pub fn release_sync(&self, key: &str) {
450        let Self { inner } = self;
451        let idx: usize = idempotency_shard_index(key);
452        let Ok(mut map) = inner.shards[idx].write() else {
453            return;
454        };
455        let is_inflight: bool = map
456            .get(key)
457            .is_some_and(|s: &IdempotencySlot| matches!(s.state, IdempotencySlotState::InFlight));
458        if is_inflight && let Some(removed) = map.remove(key) {
459            inner.entry_count.fetch_sub(1, Ordering::Relaxed);
460            inner
461                .total_bytes
462                .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
463        }
464    }
465}
466
467/// Implements [`IdempotencyStore`] for [`InMemoryIdempotencyStore`].
468impl IdempotencyStore for InMemoryIdempotencyStore {
469    /// Atomically checks or acquires an `InFlight` slot asynchronously.
470    ///
471    /// # Arguments
472    ///
473    /// - `&'a self` - Store reference.
474    /// - `&'a str` - Scoped storage key.
475    /// - `u64` - Request fingerprint.
476    /// - `u64` - In-flight TTL in milliseconds.
477    ///
478    /// # Returns
479    ///
480    /// - `IdempotencyFuture<'a, IdempotencyLookup>` - Lookup result.
481    fn acquire<'a>(
482        &'a self,
483        key: &'a str,
484        fingerprint: u64,
485        in_flight_ttl_ms: u64,
486    ) -> IdempotencyFuture<'a, IdempotencyLookup> {
487        let outcome: IdempotencyLookup = self.acquire_sync(key, fingerprint, in_flight_ttl_ms);
488        Box::pin(async move { outcome })
489    }
490
491    /// Stores a completed idempotent response asynchronously.
492    ///
493    /// # Arguments
494    ///
495    /// - `&'a self` - Store reference.
496    /// - `String` - Scoped storage key.
497    /// - `u64` - Request fingerprint.
498    /// - `Arc<StoredIdempotentResponse>` - Cached response.
499    /// - `u64` - Replay TTL in milliseconds.
500    ///
501    /// # Returns
502    ///
503    /// - `IdempotencyFuture<'a, ()>` - Completion future.
504    fn complete<'a>(
505        &'a self,
506        key: String,
507        fingerprint: u64,
508        response: Arc<StoredIdempotentResponse>,
509        ttl_ms: u64,
510    ) -> IdempotencyFuture<'a, ()> {
511        self.complete_sync(key, fingerprint, response, ttl_ms);
512        Box::pin(async {})
513    }
514
515    /// Releases an `InFlight` lock asynchronously.
516    ///
517    /// # Arguments
518    ///
519    /// - `&'a self` - Store reference.
520    /// - `&'a str` - Scoped storage key.
521    ///
522    /// # Returns
523    ///
524    /// - `IdempotencyFuture<'a, ()>` - Completion future.
525    fn release<'a>(&'a self, key: &'a str) -> IdempotencyFuture<'a, ()> {
526        self.release_sync(key);
527        Box::pin(async {})
528    }
529
530    /// Releases an abandoned `InFlight` lock synchronously during RAII `Drop`.
531    ///
532    /// # Arguments
533    ///
534    /// - `&str` - Scoped storage key.
535    fn release_on_drop(&self, key: &str) {
536        self.release_sync(key);
537    }
538
539    /// Evicts expired entries across all 64 shards.
540    ///
541    /// # Returns
542    ///
543    /// - `usize` - Number of expired entries evicted.
544    fn purge_expired(&self) -> usize {
545        let Self { inner } = self;
546        let now_ms: u64 = idempotency_now_ms();
547        let mut evicted: usize = 0;
548        let mut freed: usize = 0;
549        for shard in inner.shards.iter() {
550            if let Ok(mut map) = shard.write() {
551                map.retain(|_: &String, slot: &mut IdempotencySlot| {
552                    if now_ms >= slot.expires_at_ms {
553                        evicted += 1;
554                        freed += slot.footprint_bytes;
555                        false
556                    } else {
557                        true
558                    }
559                });
560            }
561        }
562        if evicted > 0 {
563            inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
564            inner.total_bytes.fetch_sub(freed, Ordering::Relaxed);
565        }
566        evicted
567    }
568}
569
570/// Ensures abandoned `InFlight` locks release automatically if a handler panics or rejects early.
571impl Drop for IdempotencyInFlightGuardInner {
572    /// Invokes [`IdempotencyStore::release_on_drop`] if the guard was not settled by [`IdempotencyResponseHook`].
573    fn drop(&mut self) {
574        let Self {
575            settled,
576            storage_key,
577            store,
578            ..
579        } = self;
580        if !settled.swap(true, Ordering::AcqRel) {
581            store.release_on_drop(storage_key);
582        }
583    }
584}
585
586/// Inherent settlement helpers for [`IdempotencyInFlightGuard`].
587impl IdempotencyInFlightGuard {
588    /// Marks this guard settled so `Drop` will not release the slot.
589    ///
590    /// # Returns
591    ///
592    /// - `bool` - `true` if this call claimed settlement; `false` if already settled.
593    pub(crate) fn claim_settlement(&self) -> bool {
594        let Self { inner } = self;
595        !inner.settled.swap(true, Ordering::AcqRel)
596    }
597
598    /// Returns the scoped storage key owned by this guard.
599    ///
600    /// # Returns
601    ///
602    /// - `&str` - Scoped storage key.
603    pub(crate) fn storage_key(&self) -> &str {
604        let Self { inner } = self;
605        &inner.storage_key
606    }
607
608    /// Returns the request payload fingerprint owned by this guard.
609    ///
610    /// # Returns
611    ///
612    /// - `u64` - `XxHash3_64` fingerprint.
613    pub(crate) fn fingerprint(&self) -> u64 {
614        let Self { inner } = self;
615        inner.fingerprint
616    }
617}
618
619/// Process-wide singleton management and request evaluation helpers for [`IdempotencyPlugin`].
620impl IdempotencyPlugin {
621    /// Initializes the global [`IdempotencyPlugin`] once with `config` and the default 64-shard store.
622    ///
623    /// # Arguments
624    ///
625    /// - `IdempotencyConfig` - Idempotency policy and memory limits.
626    ///
627    /// # Returns
628    ///
629    /// - `&'static Self` - Reference to the initialized global plugin.
630    pub fn init(config: IdempotencyConfig) -> &'static Self {
631        let store: SharedIdempotencyStore = Arc::new(InMemoryIdempotencyStore::new(
632            config.get_max_entries(),
633            config.get_max_bytes(),
634        ));
635        Self::init_with_store(config, store)
636    }
637
638    /// Initializes the global [`IdempotencyPlugin`] once with `config` and a custom [`IdempotencyStore`].
639    ///
640    /// # Arguments
641    ///
642    /// - `IdempotencyConfig` - Idempotency policy.
643    /// - `SharedIdempotencyStore` - Custom or distributed backing store.
644    ///
645    /// # Returns
646    ///
647    /// - `&'static Self` - Reference to the initialized global plugin.
648    pub fn init_with_store(
649        config: IdempotencyConfig,
650        store: SharedIdempotencyStore,
651    ) -> &'static Self {
652        IDEMPOTENCY_PLUGIN.get_or_init(|| Self::new_instance(config, store))
653    }
654
655    /// Constructs a standalone [`IdempotencyPlugin`] instance (useful for isolated tests or custom hooks).
656    ///
657    /// # Arguments
658    ///
659    /// - `IdempotencyConfig` - Idempotency policy.
660    /// - `SharedIdempotencyStore` - Backing store.
661    ///
662    /// # Returns
663    ///
664    /// - `Self` - Constructed plugin instance with prebuilt error wire buffers.
665    pub fn new_instance(config: IdempotencyConfig, store: SharedIdempotencyStore) -> Self {
666        let require_prefixes: Vec<String> = config
667            .get_require_key_prefixes()
668            .iter()
669            .filter(|p: &&String| !p.trim().is_empty())
670            .map(|p: &String| normalize_prefix(p))
671            .collect();
672        let prebuilt_bad_key_wire: ResponseData =
673            build_static_error_wire(HttpStatus::BadRequest, BODY_BAD_KEY, None);
674        let prebuilt_in_flight_wire: ResponseData = build_static_error_wire(
675            HttpStatus::Conflict,
676            BODY_IN_FLIGHT,
677            Some(IN_FLIGHT_RETRY_AFTER),
678        );
679        let prebuilt_mismatch_wire: ResponseData = build_static_error_wire(
680            HttpStatus::UnprocessableEntity,
681            BODY_FINGERPRINT_MISMATCH,
682            None,
683        );
684        Self {
685            config,
686            require_prefixes,
687            store,
688            prebuilt_bad_key_wire,
689            prebuilt_in_flight_wire,
690            prebuilt_mismatch_wire,
691        }
692    }
693
694    /// Returns the initialized global [`IdempotencyPlugin`], if initialized.
695    ///
696    /// # Returns
697    ///
698    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
699    #[inline]
700    pub fn get() -> Option<&'static Self> {
701        IDEMPOTENCY_PLUGIN.get()
702    }
703
704    /// Returns the active [`IdempotencyConfig`].
705    ///
706    /// # Returns
707    ///
708    /// - `&IdempotencyConfig` - Active configuration.
709    #[inline]
710    pub fn get_config(&self) -> &IdempotencyConfig {
711        let Self { config, .. } = self;
712        config
713    }
714
715    /// Returns the active [`SharedIdempotencyStore`].
716    ///
717    /// # Returns
718    ///
719    /// - `&SharedIdempotencyStore` - Active backing store.
720    #[inline]
721    pub fn get_store(&self) -> &SharedIdempotencyStore {
722        let Self { store, .. } = self;
723        store
724    }
725
726    /// Reports whether `method` is governed by this idempotency policy.
727    ///
728    /// # Arguments
729    ///
730    /// - `&Method` - Incoming HTTP method.
731    ///
732    /// # Returns
733    ///
734    /// - `bool` - `true` when guarded.
735    #[inline]
736    pub(crate) fn is_guarded_method(&self, method: &Method) -> bool {
737        let Self { config, .. } = self;
738        config.get_methods().iter().any(|m: &Method| m == method)
739    }
740
741    /// Reports whether `path` requires an explicit `Idempotency-Key` header.
742    ///
743    /// # Arguments
744    ///
745    /// - `&str` - Incoming request path.
746    ///
747    /// # Returns
748    ///
749    /// - `bool` - `true` when key presence is mandatory.
750    #[inline]
751    pub(crate) fn requires_key(&self, path: &str) -> bool {
752        let Self {
753            require_prefixes, ..
754        } = self;
755        require_prefixes
756            .iter()
757            .any(|prefix: &String| path_matches_prefix(path, prefix))
758    }
759}
760
761/// Implements [`ServerHook`] for [`IdempotencyRequestHook`].
762impl ServerHook for IdempotencyRequestHook {
763    /// Constructs a per-request [`IdempotencyRequestHook`].
764    ///
765    /// # Arguments
766    ///
767    /// - `&mut Stream` - Connection stream.
768    /// - `&mut Context` - Request context.
769    ///
770    /// # Returns
771    ///
772    /// - `Self` - Hook instance.
773    async fn new(_: &mut Stream, _: &mut Context) -> Self {
774        Self
775    }
776
777    /// Validates `Idempotency-Key`, replays cached responses zero-copy, or guards concurrent duplicates.
778    ///
779    /// # Arguments
780    ///
781    /// - `Self` - Hook instance.
782    /// - `&mut Stream` - Connection stream.
783    /// - `&mut Context` - Request context.
784    ///
785    /// # Returns
786    ///
787    /// - `Status` - `Status::Reject` on replay/conflict/mismatch/bad-key; `Status::Continue` otherwise.
788    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
789        let Some(plugin) = IdempotencyPlugin::get() else {
790            return Status::Continue;
791        };
792        let method: Method = ctx.get_request().get_method().clone();
793        if !plugin.is_guarded_method(&method) {
794            return Status::Continue;
795        }
796        let config: &IdempotencyConfig = plugin.get_config();
797        let path: &str = ctx.get_request().get_path();
798        let raw_key: Option<&str> =
799            find_header_back_ref(ctx.get_request().get_headers(), config.get_header_name());
800        let Some(key_slice) = raw_key else {
801            if plugin.requires_key(path) {
802                let _: Result<(), ResponseError> =
803                    stream.try_send(&plugin.prebuilt_bad_key_wire).await;
804                return Status::Reject;
805            }
806            return Status::Continue;
807        };
808        let trimmed: &str = key_slice.trim();
809        if !is_valid_idempotency_key(trimmed, config.get_max_key_len()) {
810            let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_bad_key_wire).await;
811            return Status::Reject;
812        }
813        let fingerprint: u64 =
814            compute_request_fingerprint(&method, path, ctx.get_request().get_body());
815        let storage_key: String = build_storage_key(&method, path, trimmed);
816        match plugin
817            .get_store()
818            .acquire(&storage_key, fingerprint, config.get_in_flight_ttl_ms())
819            .await
820        {
821            IdempotencyLookup::Acquired => {
822                let guard: IdempotencyInFlightGuard = IdempotencyInFlightGuard {
823                    inner: Arc::new(IdempotencyInFlightGuardInner {
824                        settled: AtomicBool::new(false),
825                        storage_key,
826                        fingerprint,
827                        store: Arc::clone(plugin.get_store()),
828                    }),
829                };
830                ctx.set_attribute(ATTR_IDEMPOTENCY_GUARD, guard);
831                Status::Continue
832            }
833            IdempotencyLookup::InFlight => {
834                let _: Result<(), ResponseError> =
835                    stream.try_send(&plugin.prebuilt_in_flight_wire).await;
836                Status::Reject
837            }
838            IdempotencyLookup::FingerprintMismatch => {
839                let _: Result<(), ResponseError> =
840                    stream.try_send(&plugin.prebuilt_mismatch_wire).await;
841                Status::Reject
842            }
843            IdempotencyLookup::Replayed(cached) => {
844                let _: Result<(), ResponseError> =
845                    stream.try_send(cached.get_replayed_wire()).await;
846                Status::Reject
847            }
848        }
849    }
850}
851
852/// Implements [`ServerHook`] for [`IdempotencyResponseHook`].
853impl ServerHook for IdempotencyResponseHook {
854    /// Constructs a per-response [`IdempotencyResponseHook`].
855    ///
856    /// # Arguments
857    ///
858    /// - `&mut Stream` - Connection stream.
859    /// - `&mut Context` - Request context.
860    ///
861    /// # Returns
862    ///
863    /// - `Self` - Hook instance.
864    async fn new(_: &mut Stream, _: &mut Context) -> Self {
865        Self
866    }
867
868    /// Captures and stores the completed response for zero-copy future replay, or releases uncacheable slots.
869    ///
870    /// # Arguments
871    ///
872    /// - `Self` - Hook instance.
873    /// - `&mut Stream` - Connection stream.
874    /// - `&mut Context` - Request context.
875    ///
876    /// # Returns
877    ///
878    /// - `Status` - Always `Status::Continue`.
879    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
880        let Some(plugin) = IdempotencyPlugin::get() else {
881            return Status::Continue;
882        };
883        let Some(guard) =
884            ctx.try_get_attribute::<IdempotencyInFlightGuard, _>(ATTR_IDEMPOTENCY_GUARD)
885        else {
886            return Status::Continue;
887        };
888        ctx.remove_attribute(ATTR_IDEMPOTENCY_GUARD);
889        if !guard.claim_settlement() {
890            return Status::Continue;
891        }
892        let config: &IdempotencyConfig = plugin.get_config();
893        let status_code: usize = ctx.get_response().get_status_code();
894        let body_len: usize = ctx.get_response().get_body().len();
895        let status_ok: bool =
896            config.get_cache_server_errors() || status_code < NON_CACHEABLE_STATUS_MIN;
897        if status_ok && body_len <= config.get_max_body_bytes() {
898            let stored: Arc<StoredIdempotentResponse> =
899                Arc::new(StoredIdempotentResponse::capture(ctx.get_response()));
900            plugin
901                .get_store()
902                .complete(
903                    guard.storage_key().to_owned(),
904                    guard.fingerprint(),
905                    stored,
906                    config.get_ttl_ms(),
907                )
908                .await;
909        } else {
910            plugin.get_store().release(guard.storage_key()).await;
911        }
912        Status::Continue
913    }
914}