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