hyperlane-plugin-idempotency 23.0.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
use super::*;

/// Inherent constructors and replay helpers for [`StoredIdempotentResponse`].
impl StoredIdempotentResponse {
    /// Captures status, headers, and body and pre-serializes the zero-copy `Idempotent-Replayed: true` wire buffer.
    ///
    /// # Arguments
    ///
    /// - `usize` - HTTP response status code.
    /// - `Vec<(String, String)>` - Response headers.
    /// - `Vec<u8>` - Response body bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - Cached idempotent response ready for zero-copy replay.
    pub fn from_parts(status_code: usize, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
        let replayed_wire: Vec<u8> = build_replayed_wire(status_code, &headers, &body);
        Self {
            status_code,
            headers,
            body,
            replayed_wire,
            stored_at_ms: idempotency_now_ms(),
        }
    }

    /// Captures a live Hyperlane [`Response`] into a [`StoredIdempotentResponse`].
    ///
    /// # Arguments
    ///
    /// - `&Response` - Completed response from the route handler.
    ///
    /// # Returns
    ///
    /// - `Self` - Cached response carrying prebuilt replay wire bytes.
    pub fn capture(response: &Response) -> Self {
        let mut headers: Vec<(String, String)> = Vec::with_capacity(response.get_headers().len());
        for (name, values) in response.get_headers() {
            if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED)
                && let Some(last) = values.back()
            {
                headers.push((name.clone(), last.clone()));
            }
        }
        Self::from_parts(
            response.get_status_code(),
            headers,
            response.get_body().clone(),
        )
    }

    /// Applies this cached response onto a Hyperlane [`Response`] with `Idempotent-Replayed: true`.
    ///
    /// # Arguments
    ///
    /// - `&mut Response` - Target response object.
    pub fn apply_to_response(&self, response: &mut Response) {
        response.set_status_code(self.get_status_code());
        for (name, val) in self.get_headers() {
            response.set_header(name, val);
        }
        response
            .set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
            .set_body(self.get_body().clone());
    }
}

/// Default construction for [`IdempotencyConfig`].
impl Default for IdempotencyConfig {
    /// Constructs a default [`IdempotencyConfig`] covering `POST`/`PUT`/`PATCH`/`DELETE` with 24 h TTL.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            header_name: DEFAULT_IDEMPOTENCY_KEY_HEADER.to_owned(),
            ttl_ms: DEFAULT_IDEMPOTENCY_TTL_MS,
            in_flight_ttl_ms: DEFAULT_IN_FLIGHT_TTL_MS,
            max_entries: DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
            max_bytes: DEFAULT_IDEMPOTENCY_MAX_BYTES,
            max_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
            max_key_len: DEFAULT_MAX_KEY_LEN,
            methods: vec![Method::Post, Method::Put, Method::Patch, Method::Delete],
            require_key_prefixes: Vec::new(),
            cache_server_errors: false,
        }
    }
}

/// Fluent configuration builders for [`IdempotencyConfig`].
impl IdempotencyConfig {
    /// Sets the request header name carrying the client idempotency key (stored lowercased).
    ///
    /// # Arguments
    ///
    /// - `S` - Header name (for example `"idempotency-key"` or `"x-idempotency-key"`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_header_name<S>(mut self, name: S) -> Self
    where
        S: AsRef<str>,
    {
        self.set_header_name(name.as_ref().trim().to_ascii_lowercase());
        self
    }

    /// Sets the cached replay response TTL in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u64` - Replay TTL in milliseconds (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
        self.set_ttl_ms(ttl_ms.max(1));
        self
    }

    /// Sets the maximum lifetime of an `InFlight` guard in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u64` - In-flight lock TTL in milliseconds (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_in_flight_ttl_ms(mut self, in_flight_ttl_ms: u64) -> Self {
        self.set_in_flight_ttl_ms(in_flight_ttl_ms.max(1));
        self
    }

    /// Sets the maximum entry count and total byte cap across all 64 shards.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum entry count (`>= 1`).
    /// - `usize` - Maximum byte budget (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_limits(mut self, max_entries: usize, max_bytes: usize) -> Self {
        self.set_max_entries(max_entries.max(1))
            .set_max_bytes(max_bytes.max(1));
        self
    }

    /// Sets path prefixes that require an explicit `Idempotency-Key` header on mutation methods.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of path prefixes (for example `["/v1/payments"]`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_require_key_prefixes<I, S>(mut self, prefixes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_require_key_prefixes(prefixes.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the HTTP methods guarded by idempotency enforcement.
    ///
    /// # Arguments
    ///
    /// - `Vec<Method>` - Guarded HTTP methods.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_methods(mut self, methods: Vec<Method>) -> Self {
        self.set_methods(methods);
        self
    }

    /// Configures whether `5xx` server errors are cached for replay.
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` to cache `5xx` responses; `false` (default) to release the key on `5xx`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_cache_server_errors(mut self, cache_server_errors: bool) -> Self {
        self.set_cache_server_errors(cache_server_errors);
        self
    }
}

/// Default construction for [`InMemoryIdempotencyStore`].
impl Default for InMemoryIdempotencyStore {
    /// Constructs a default 64-shard [`InMemoryIdempotencyStore`].
    ///
    /// # Returns
    ///
    /// - `Self` - Default sharded store.
    fn default() -> Self {
        Self::new(
            DEFAULT_IDEMPOTENCY_MAX_ENTRIES,
            DEFAULT_IDEMPOTENCY_MAX_BYTES,
        )
    }
}

/// Inherent 64-way sharded storage operations for [`InMemoryIdempotencyStore`].
impl InMemoryIdempotencyStore {
    /// Creates a 64-way sharded bounded [`InMemoryIdempotencyStore`].
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum entry count across all shards.
    /// - `usize` - Maximum byte budget across all shards.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready sharded store.
    pub fn new(max_entries: usize, max_bytes: usize) -> Self {
        let shards: Box<[IdempotencyShard; IDEMPOTENCY_SHARD_COUNT]> =
            Box::new(from_fn(|_: usize| IdempotencyShard {
                map: RwLock::new(hash_map_xx_hash3_64()),
            }));
        Self {
            inner: Arc::new(InMemoryIdempotencyStoreInner {
                max_entries: max_entries.max(1),
                max_bytes: max_bytes.max(1),
                entry_count: AtomicUsize::new(0),
                total_bytes: AtomicUsize::new(0),
                shards,
            }),
        }
    }

    /// Returns the live tracked entry count across all 64 shards in `O(1)` time without locking.
    ///
    /// # Returns
    ///
    /// - `usize` - Current entry count.
    #[inline(always)]
    pub fn len(&self) -> usize {
        let Self { inner } = self;
        inner.entry_count.load(Ordering::Relaxed)
    }

    /// Reports whether the store contains zero entries.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when empty.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the estimated total memory usage across all shards in bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - Approximate byte footprint.
    #[inline(always)]
    pub fn total_bytes(&self) -> usize {
        let Self { inner } = self;
        inner.total_bytes.load(Ordering::Relaxed)
    }

    /// Synchronous atomic lookup or `InFlight` acquisition on a single shard.
    ///
    /// # Arguments
    ///
    /// - `&str` - Scoped storage key.
    /// - `u64` - Request fingerprint.
    /// - `u64` - In-flight lock TTL in milliseconds.
    ///
    /// # Returns
    ///
    /// - `IdempotencyLookup` - Acquisition, conflict, mismatch, or zero-copy replay result.
    #[inline]
    pub fn acquire_sync(
        &self,
        key: &str,
        fingerprint: u64,
        in_flight_ttl_ms: u64,
    ) -> IdempotencyLookup {
        let Self { inner } = self;
        let idx: usize = idempotency_shard_index(key);
        let now_ms: u64 = idempotency_now_ms();
        if inner.entry_count.load(Ordering::Relaxed) > 0
            && let Ok(read_guard) = inner.shards[idx].map.read()
            && let Some(existing) = read_guard.get(key)
            && now_ms < existing.expires_at_ms
        {
            if existing.fingerprint != fingerprint {
                return IdempotencyLookup::FingerprintMismatch;
            }
            return match &existing.state {
                IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
                IdempotencySlotState::Completed(resp) => {
                    IdempotencyLookup::Replayed(Arc::clone(resp))
                }
            };
        }
        let Ok(mut map): Result<
            RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
            _,
        > = inner.shards[idx].map.write() else {
            return IdempotencyLookup::Acquired;
        };
        if let Some(existing) = map.get_mut(key) {
            if now_ms < existing.expires_at_ms {
                if existing.fingerprint != fingerprint {
                    return IdempotencyLookup::FingerprintMismatch;
                }
                return match &existing.state {
                    IdempotencySlotState::InFlight => IdempotencyLookup::InFlight,
                    IdempotencySlotState::Completed(resp) => {
                        IdempotencyLookup::Replayed(Arc::clone(resp))
                    }
                };
            }
            let prev_footprint: usize = existing.footprint_bytes;
            let footprint: usize = key.len() + ENTRY_OVERHEAD_BYTES;
            existing.fingerprint = fingerprint;
            existing.state = IdempotencySlotState::InFlight;
            existing.expires_at_ms = now_ms.saturating_add(in_flight_ttl_ms);
            existing.footprint_bytes = footprint;
            if footprint >= prev_footprint {
                inner
                    .total_bytes
                    .fetch_add(footprint - prev_footprint, Ordering::Relaxed);
            } else {
                inner
                    .total_bytes
                    .fetch_sub(prev_footprint - footprint, Ordering::Relaxed);
            }
            return IdempotencyLookup::Acquired;
        }
        let footprint: usize = key.len() + ENTRY_OVERHEAD_BYTES;
        while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
            || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
            && !map.is_empty()
        {
            let oldest: Option<String> = map
                .iter()
                .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
                .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
            if let Some(evict_key) = oldest
                && let Some(removed) = map.remove(&evict_key)
            {
                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
                inner
                    .total_bytes
                    .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
            } else {
                break;
            }
        }
        map.insert(
            key.to_owned(),
            IdempotencySlot {
                fingerprint,
                state: IdempotencySlotState::InFlight,
                expires_at_ms: now_ms.saturating_add(in_flight_ttl_ms),
                footprint_bytes: footprint,
            },
        );
        inner.entry_count.fetch_add(1, Ordering::Relaxed);
        inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
        IdempotencyLookup::Acquired
    }

    /// Synchronous commit storing a completed [`StoredIdempotentResponse`] under `key`.
    ///
    /// # Arguments
    ///
    /// - `String` - Scoped storage key.
    /// - `u64` - Request fingerprint.
    /// - `Arc<StoredIdempotentResponse>` - Cached response and prebuilt replay wire bytes.
    /// - `u64` - Replay cache TTL in milliseconds.
    #[inline]
    pub fn complete_sync(
        &self,
        key: String,
        fingerprint: u64,
        response: Arc<StoredIdempotentResponse>,
        ttl_ms: u64,
    ) {
        let Self { inner } = self;
        let footprint: usize = estimate_response_bytes(&key, &response);
        if footprint > inner.max_bytes {
            self.release_sync(&key);
            return;
        }
        let idx: usize = idempotency_shard_index(&key);
        let now_ms: u64 = idempotency_now_ms();
        let Ok(mut map): Result<
            RwLockWriteGuard<'_, HashMapXxHash3_64<String, IdempotencySlot>>,
            _,
        > = inner.shards[idx].map.write() else {
            return;
        };
        if let Some(existing) = map.get_mut(&key) {
            let prev_footprint: usize = existing.footprint_bytes;
            let projected_bytes: usize = inner
                .total_bytes
                .load(Ordering::Relaxed)
                .saturating_sub(prev_footprint)
                .saturating_add(footprint);
            if projected_bytes <= inner.max_bytes {
                existing.fingerprint = fingerprint;
                existing.state = IdempotencySlotState::Completed(response);
                existing.expires_at_ms = now_ms.saturating_add(ttl_ms);
                existing.footprint_bytes = footprint;
                if footprint >= prev_footprint {
                    inner
                        .total_bytes
                        .fetch_add(footprint - prev_footprint, Ordering::Relaxed);
                } else {
                    inner
                        .total_bytes
                        .fetch_sub(prev_footprint - footprint, Ordering::Relaxed);
                }
                return;
            }
            if let Some(prev) = map.remove(&key) {
                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
                inner
                    .total_bytes
                    .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
            }
        }
        while (inner.entry_count.load(Ordering::Relaxed) >= inner.max_entries
            || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.max_bytes)
            && !map.is_empty()
        {
            let oldest: Option<String> = map
                .iter()
                .min_by_key(|(_, slot): &(&String, &IdempotencySlot)| slot.expires_at_ms)
                .map(|(k, _): (&String, &IdempotencySlot)| k.clone());
            if let Some(evict_key) = oldest
                && let Some(removed) = map.remove(&evict_key)
            {
                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
                inner
                    .total_bytes
                    .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
            } else {
                break;
            }
        }
        map.insert(
            key,
            IdempotencySlot {
                fingerprint,
                state: IdempotencySlotState::Completed(response),
                expires_at_ms: now_ms.saturating_add(ttl_ms),
                footprint_bytes: footprint,
            },
        );
        inner.entry_count.fetch_add(1, Ordering::Relaxed);
        inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
    }

    /// Synchronously releases an `InFlight` slot (leaving any already-completed response intact).
    ///
    /// # Arguments
    ///
    /// - `&str` - Scoped storage key.
    #[inline]
    pub fn release_sync(&self, key: &str) {
        let Self { inner } = self;
        let idx: usize = idempotency_shard_index(key);
        let Ok(mut map) = inner.shards[idx].map.write() else {
            return;
        };
        let is_inflight: bool = map
            .get(key)
            .is_some_and(|s: &IdempotencySlot| matches!(s.state, IdempotencySlotState::InFlight));
        if is_inflight && let Some(removed) = map.remove(key) {
            inner.entry_count.fetch_sub(1, Ordering::Relaxed);
            inner
                .total_bytes
                .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
        }
    }
}

/// Implements [`IdempotencyStore`] for [`InMemoryIdempotencyStore`].
impl IdempotencyStore for InMemoryIdempotencyStore {
    /// Atomically checks or acquires an `InFlight` slot asynchronously.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Store reference.
    /// - `&'a str` - Scoped storage key.
    /// - `u64` - Request fingerprint.
    /// - `u64` - In-flight TTL in milliseconds.
    ///
    /// # Returns
    ///
    /// - `IdempotencyFuture<'a, IdempotencyLookup>` - Lookup result.
    #[inline]
    fn acquire<'a>(
        &'a self,
        key: &'a str,
        fingerprint: u64,
        in_flight_ttl_ms: u64,
    ) -> IdempotencyFuture<'a, IdempotencyLookup> {
        let outcome: IdempotencyLookup = self.acquire_sync(key, fingerprint, in_flight_ttl_ms);
        Box::pin(ready(outcome))
    }

    /// Stores a completed idempotent response asynchronously.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Store reference.
    /// - `String` - Scoped storage key.
    /// - `u64` - Request fingerprint.
    /// - `Arc<StoredIdempotentResponse>` - Cached response.
    /// - `u64` - Replay TTL in milliseconds.
    ///
    /// # Returns
    ///
    /// - `IdempotencyFuture<'a, ()>` - Completion future.
    #[inline]
    fn complete<'a>(
        &'a self,
        key: String,
        fingerprint: u64,
        response: Arc<StoredIdempotentResponse>,
        ttl_ms: u64,
    ) -> IdempotencyFuture<'a, ()> {
        self.complete_sync(key, fingerprint, response, ttl_ms);
        Box::pin(ready(()))
    }

    /// Releases an `InFlight` lock asynchronously.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Store reference.
    /// - `&'a str` - Scoped storage key.
    ///
    /// # Returns
    ///
    /// - `IdempotencyFuture<'a, ()>` - Completion future.
    #[inline]
    fn release<'a>(&'a self, key: &'a str) -> IdempotencyFuture<'a, ()> {
        self.release_sync(key);
        Box::pin(ready(()))
    }

    /// Releases an abandoned `InFlight` lock synchronously during RAII `Drop`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Scoped storage key.
    fn release_on_drop(&self, key: &str) {
        self.release_sync(key);
    }

    /// Evicts expired entries across all 64 shards.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of expired entries evicted.
    fn purge_expired(&self) -> usize {
        let Self { inner } = self;
        if inner.entry_count.load(Ordering::Relaxed) == 0 {
            return 0;
        }
        let now_ms: u64 = idempotency_now_ms();
        let mut evicted: usize = 0;
        let mut freed: usize = 0;
        for shard in inner.shards.iter() {
            if let Ok(mut map) = shard.map.write() {
                if map.is_empty() {
                    continue;
                }
                map.retain(|_: &String, slot: &mut IdempotencySlot| {
                    if now_ms >= slot.expires_at_ms {
                        evicted += 1;
                        freed += slot.footprint_bytes;
                        false
                    } else {
                        true
                    }
                });
            }
        }
        if evicted > 0 {
            inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
            inner.total_bytes.fetch_sub(freed, Ordering::Relaxed);
        }
        evicted
    }
}

/// Ensures abandoned `InFlight` locks release automatically if a handler panics or rejects early.
impl Drop for IdempotencyInFlightGuardInner {
    /// Invokes [`IdempotencyStore::release_on_drop`] if the guard was not settled by [`IdempotencyResponseHook`].
    fn drop(&mut self) {
        let Self {
            settled,
            storage_key,
            store,
            ..
        } = self;
        if !*settled.get_mut() {
            store.release_on_drop(storage_key);
        }
    }
}

/// Inherent settlement helpers for [`IdempotencyInFlightGuard`].
impl IdempotencyInFlightGuard {
    /// Marks this guard settled so `Drop` will not release the slot.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if this call claimed settlement; `false` if already settled.
    pub(crate) fn claim_settlement(&self) -> bool {
        let Self { inner } = self;
        !inner.settled.swap(true, Ordering::AcqRel)
    }

    /// Returns the scoped storage key owned by this guard.
    ///
    /// # Returns
    ///
    /// - `&str` - Scoped storage key.
    pub(crate) fn storage_key(&self) -> &str {
        let Self { inner } = self;
        &inner.storage_key
    }

    /// Returns the request payload fingerprint owned by this guard.
    ///
    /// # Returns
    ///
    /// - `u64` - `XxHash3_64` fingerprint.
    pub(crate) fn fingerprint(&self) -> u64 {
        let Self { inner } = self;
        inner.fingerprint
    }
}

/// Process-wide singleton management and request evaluation helpers for [`IdempotencyPlugin`].
impl IdempotencyPlugin {
    /// Initializes the global [`IdempotencyPlugin`] once with `config` and the default 64-shard store.
    ///
    /// # Arguments
    ///
    /// - `IdempotencyConfig` - Idempotency policy and memory limits.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(config: IdempotencyConfig) -> &'static Self {
        let local: InMemoryIdempotencyStore =
            InMemoryIdempotencyStore::new(config.get_max_entries(), config.get_max_bytes());
        let store: Arc<dyn IdempotencyStore> = Arc::new(local.clone());
        IDEMPOTENCY_PLUGIN.get_or_init(|| Self::new_instance_with_local(config, store, Some(local)))
    }

    /// Initializes the global [`IdempotencyPlugin`] once with `config` and a custom [`IdempotencyStore`].
    ///
    /// # Arguments
    ///
    /// - `IdempotencyConfig` - Idempotency policy.
    /// - `Arc<dyn IdempotencyStore>` - Custom or distributed backing store.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init_with_store(
        config: IdempotencyConfig,
        store: Arc<dyn IdempotencyStore>,
    ) -> &'static Self {
        IDEMPOTENCY_PLUGIN.get_or_init(|| Self::new_instance(config, store))
    }

    /// Constructs a standalone [`IdempotencyPlugin`] instance (useful for isolated tests or custom hooks).
    ///
    /// # Arguments
    ///
    /// - `IdempotencyConfig` - Idempotency policy.
    /// - `Arc<dyn IdempotencyStore>` - Backing store.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed plugin instance with prebuilt error wire buffers.
    pub fn new_instance(config: IdempotencyConfig, store: Arc<dyn IdempotencyStore>) -> Self {
        Self::new_instance_with_local(config, store, None)
    }

    /// Constructs an [`IdempotencyPlugin`] with an optional direct [`InMemoryIdempotencyStore`] fast path.
    ///
    /// # Arguments
    ///
    /// - `IdempotencyConfig` - Idempotency policy.
    /// - `Arc<dyn IdempotencyStore>` - Pluggable backing store.
    /// - `Option<InMemoryIdempotencyStore>` - Direct built-in store handle when available.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed plugin instance.
    pub(crate) fn new_instance_with_local(
        config: IdempotencyConfig,
        store: Arc<dyn IdempotencyStore>,
        local_store: Option<InMemoryIdempotencyStore>,
    ) -> Self {
        let mut guarded_method_mask: u16 = 0;
        let mut has_unknown_method: bool = false;
        for m in config.get_methods() {
            let bit: u16 = method_bit(m);
            if bit != 0 {
                guarded_method_mask |= bit;
            } else {
                has_unknown_method = true;
            }
        }
        let require_prefixes: Box<[String]> = config
            .get_require_key_prefixes()
            .iter()
            .filter(|p: &&String| !p.trim().is_empty())
            .map(|p: &String| normalize_prefix(p))
            .collect::<Vec<String>>()
            .into_boxed_slice();
        let prebuilt_bad_key_wire: Vec<u8> =
            build_static_error_wire(HttpStatus::BadRequest, BODY_BAD_KEY, None);
        let prebuilt_in_flight_wire: Vec<u8> = build_static_error_wire(
            HttpStatus::Conflict,
            BODY_IN_FLIGHT,
            Some(IN_FLIGHT_RETRY_AFTER),
        );
        let prebuilt_mismatch_wire: Vec<u8> = build_static_error_wire(
            HttpStatus::UnprocessableEntity,
            BODY_FINGERPRINT_MISMATCH,
            None,
        );
        Self {
            config,
            guarded_method_mask,
            has_unknown_method,
            require_prefixes,
            store,
            local_store,
            prebuilt_bad_key_wire,
            prebuilt_in_flight_wire,
            prebuilt_mismatch_wire,
        }
    }

    /// Returns the initialized global [`IdempotencyPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        IDEMPOTENCY_PLUGIN.get()
    }

    /// Returns the active [`IdempotencyConfig`].
    ///
    /// # Returns
    ///
    /// - `&IdempotencyConfig` - Active configuration.
    #[inline(always)]
    pub fn get_config(&self) -> &IdempotencyConfig {
        let Self { config, .. } = self;
        config
    }

    /// Returns the active [`Arc<dyn IdempotencyStore>`].
    ///
    /// # Returns
    ///
    /// - `&Arc<dyn IdempotencyStore>` - Active backing store.
    #[inline(always)]
    pub fn get_store(&self) -> &Arc<dyn IdempotencyStore> {
        let Self { store, .. } = self;
        store
    }

    /// Returns the direct built-in [`InMemoryIdempotencyStore`] when configured via [`IdempotencyPlugin::init`].
    ///
    /// # Returns
    ///
    /// - `Option<&InMemoryIdempotencyStore>` - Direct in-memory store handle.
    #[inline(always)]
    pub(crate) fn get_local_store(&self) -> Option<&InMemoryIdempotencyStore> {
        let Self { local_store, .. } = self;
        local_store.as_ref()
    }

    /// Reports whether `method` is governed by this idempotency policy in `O(1)` time.
    ///
    /// # Arguments
    ///
    /// - `&Method` - Incoming HTTP method.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when guarded.
    #[inline(always)]
    pub(crate) fn is_guarded_method(&self, method: &Method) -> bool {
        let Self {
            config,
            guarded_method_mask,
            has_unknown_method,
            ..
        } = self;
        let bit: u16 = method_bit(method);
        if bit != 0 {
            return (guarded_method_mask & bit) != 0;
        }
        *has_unknown_method && config.get_methods().iter().any(|m: &Method| m == method)
    }

    /// Reports whether `path` requires an explicit `Idempotency-Key` header.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when key presence is mandatory.
    #[inline]
    pub(crate) fn requires_key(&self, path: &str) -> bool {
        let Self {
            require_prefixes, ..
        } = self;
        require_prefixes
            .iter()
            .any(|prefix: &String| path_matches_prefix(path, prefix))
    }
}

/// Implements [`ServerHook`] for [`IdempotencyRequestHook`].
impl ServerHook for IdempotencyRequestHook {
    /// Constructs a per-request [`IdempotencyRequestHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Validates `Idempotency-Key`, replays cached responses zero-copy, or guards concurrent duplicates.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` on replay/conflict/mismatch/bad-key; `Status::Continue` otherwise.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = IdempotencyPlugin::get() else {
            return Status::Continue;
        };
        let config: &IdempotencyConfig = plugin.get_config();
        let (lookup, acquired_key, fingerprint): (IdempotencyLookup, Option<String>, u64) = {
            let req: &Request = ctx.get_request();
            let method: &Method = req.get_method();
            if !plugin.is_guarded_method(method) {
                return Status::Continue;
            }
            let path: &str = req.get_path();
            let raw_key: Option<&str> =
                find_header_back_ref(req.get_headers(), config.get_header_name());
            let Some(key_slice) = raw_key else {
                if plugin.requires_key(path) {
                    let _: Result<(), ResponseError> =
                        stream.try_send(&plugin.prebuilt_bad_key_wire).await;
                    return Status::Reject;
                }
                return Status::Continue;
            };
            let trimmed: &str = key_slice.trim();
            if !is_valid_idempotency_key(trimmed, config.get_max_key_len()) {
                let _: Result<(), ResponseError> =
                    stream.try_send(&plugin.prebuilt_bad_key_wire).await;
                return Status::Reject;
            }
            let fingerprint: u64 = compute_request_fingerprint(method, path, req.get_body());
            let mut key_buf: [u8; STACK_STORAGE_KEY_CAP] = [0u8; STACK_STORAGE_KEY_CAP];
            if let Some(local) = plugin.get_local_store() {
                if let Some(stack_key) =
                    build_storage_key_stack(method, path, trimmed, &mut key_buf)
                {
                    let res: IdempotencyLookup =
                        local.acquire_sync(stack_key, fingerprint, config.get_in_flight_ttl_ms());
                    let owned: Option<String> = if matches!(res, IdempotencyLookup::Acquired) {
                        Some(stack_key.to_owned())
                    } else {
                        None
                    };
                    (res, owned, fingerprint)
                } else {
                    let owned_key: String = build_storage_key(method, path, trimmed);
                    let res: IdempotencyLookup =
                        local.acquire_sync(&owned_key, fingerprint, config.get_in_flight_ttl_ms());
                    let owned: Option<String> = if matches!(res, IdempotencyLookup::Acquired) {
                        Some(owned_key)
                    } else {
                        None
                    };
                    (res, owned, fingerprint)
                }
            } else {
                let owned_key: String = build_storage_key(method, path, trimmed);
                let res: IdempotencyLookup = plugin
                    .get_store()
                    .acquire(&owned_key, fingerprint, config.get_in_flight_ttl_ms())
                    .await;
                let owned: Option<String> = if matches!(res, IdempotencyLookup::Acquired) {
                    Some(owned_key)
                } else {
                    None
                };
                (res, owned, fingerprint)
            }
        };
        match lookup {
            IdempotencyLookup::Acquired => {
                if let Some(storage_key) = acquired_key {
                    let guard: IdempotencyInFlightGuard = IdempotencyInFlightGuard {
                        inner: Arc::new(IdempotencyInFlightGuardInner {
                            settled: AtomicBool::new(false),
                            storage_key,
                            fingerprint,
                            store: Arc::clone(plugin.get_store()),
                        }),
                    };
                    ctx.set_attribute(ATTR_IDEMPOTENCY_GUARD, guard);
                }
                Status::Continue
            }
            IdempotencyLookup::InFlight => {
                let _: Result<(), ResponseError> =
                    stream.try_send(&plugin.prebuilt_in_flight_wire).await;
                Status::Reject
            }
            IdempotencyLookup::FingerprintMismatch => {
                let _: Result<(), ResponseError> =
                    stream.try_send(&plugin.prebuilt_mismatch_wire).await;
                Status::Reject
            }
            IdempotencyLookup::Replayed(cached) => {
                let _: Result<(), ResponseError> =
                    stream.try_send(cached.get_replayed_wire()).await;
                Status::Reject
            }
        }
    }
}

/// Implements [`ServerHook`] for [`IdempotencyResponseHook`].
impl ServerHook for IdempotencyResponseHook {
    /// Constructs a per-response [`IdempotencyResponseHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Captures and stores the completed response for zero-copy future replay, or releases uncacheable slots.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = IdempotencyPlugin::get() else {
            return Status::Continue;
        };
        let Some(guard) =
            ctx.try_get_attribute::<IdempotencyInFlightGuard, _>(ATTR_IDEMPOTENCY_GUARD)
        else {
            return Status::Continue;
        };
        ctx.remove_attribute(ATTR_IDEMPOTENCY_GUARD);
        if !guard.claim_settlement() {
            return Status::Continue;
        }
        let config: &IdempotencyConfig = plugin.get_config();
        let status_code: usize = ctx.get_response().get_status_code();
        let body_len: usize = ctx.get_response().get_body().len();
        let status_ok: bool =
            config.get_cache_server_errors() || status_code < NON_CACHEABLE_STATUS_MIN;
        if status_ok && body_len <= config.get_max_body_bytes() {
            let stored: Arc<StoredIdempotentResponse> =
                Arc::new(StoredIdempotentResponse::capture(ctx.get_response()));
            let fp: u64 = guard.fingerprint();
            let owned_key: String = match Arc::try_unwrap(guard.inner) {
                Ok(mut inner) => take(&mut inner.storage_key),
                Err(arc_inner) => arc_inner.storage_key.clone(),
            };
            if let Some(local) = plugin.get_local_store() {
                local.complete_sync(owned_key, fp, stored, config.get_ttl_ms());
            } else {
                plugin
                    .get_store()
                    .complete(owned_key, fp, stored, config.get_ttl_ms())
                    .await;
            }
        } else if let Some(local) = plugin.get_local_store() {
            local.release_sync(guard.storage_key());
        } else {
            plugin.get_store().release(guard.storage_key()).await;
        }
        Status::Continue
    }
}