hyperlane-plugin-cache 23.1.0

A 64-way sharded bounded in-memory and HTTP response cache plugin for the Hyperlane framework with TTL, byte-budget eviction, single-flight stampede coalescing, pluggable CacheStore traits, and RFC Cache-Control/Vary/Age/X-Cache handling.
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
use super::*;

/// Inherent constructors for [`CachedValue`].
impl CachedValue {
    /// Creates a [`CachedValue`] with status code, headers, and body stamped with current epoch time.
    ///
    /// # Arguments
    ///
    /// - `usize` - HTTP status code.
    /// - `Vec<(String, String)>` - Response headers.
    /// - `Vec<u8>` - Payload bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed cached value.
    pub fn new(status_code: usize, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
        Self {
            status_code,
            headers,
            body,
            stored_at_ms: cache_now_ms(),
        }
    }

    /// Creates a raw byte payload cache value with status `200` and no headers.
    ///
    /// # Arguments
    ///
    /// - `Vec<u8>` - Raw bytes to cache.
    ///
    /// # Returns
    ///
    /// - `Self` - Cached byte payload.
    pub fn bytes(body: Vec<u8>) -> Self {
        Self::new(HttpStatus::Ok.code(), Vec::new(), body)
    }

    /// Computes elapsed age in whole seconds since this entry was stored.
    ///
    /// # Returns
    ///
    /// - `u64` - Elapsed age in seconds.
    #[inline]
    pub fn age_secs(&self) -> u64 {
        cache_now_ms().saturating_sub(self.get_stored_at_ms()) / 1_000
    }
}

/// Default construction for [`CacheConfig`].
impl Default for CacheConfig {
    /// Constructs a default [`CacheConfig`] (60 s TTL, 16 384 entries, 64 MiB total cap).
    fn default() -> Self {
        Self {
            default_ttl_ms: DEFAULT_CACHE_TTL_MS,
            max_entries: DEFAULT_CACHE_MAX_ENTRIES,
            max_bytes: DEFAULT_CACHE_MAX_BYTES,
            max_entry_bytes: DEFAULT_CACHE_MAX_ENTRY_BYTES,
            bypass_authenticated: true,
            emit_diagnostic_headers: true,
        }
    }
}

/// Inherent fluent builders for [`CacheConfig`].
impl CacheConfig {
    /// Sets the default entry TTL in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u64` - Default TTL in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_default_ttl_ms(mut self, ttl_ms: u64) -> Self {
        self.set_default_ttl_ms(ttl_ms);
        self
    }

    /// Sets the maximum tracked entry count across all shards.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum entry count.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_max_entries(mut self, max_entries: usize) -> Self {
        self.set_max_entries(max_entries.max(1));
        self
    }

    /// Sets the maximum total byte budget across all shards.
    ///
    /// # Arguments
    ///
    /// - `usize` - Byte budget cap.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_max_bytes(mut self, max_bytes: usize) -> Self {
        self.set_max_bytes(max_bytes.max(1));
        self
    }
}

/// Default construction for [`ShardedMemoryCache`].
impl Default for ShardedMemoryCache {
    /// Constructs a default 64-shard [`ShardedMemoryCache`].
    fn default() -> Self {
        Self::new(CacheConfig::default())
    }
}

/// Inherent implementation of [`ShardedMemoryCache`].
impl ShardedMemoryCache {
    /// Creates a 64-way sharded bounded [`ShardedMemoryCache`] governed by `config`.
    ///
    /// # Arguments
    ///
    /// - `CacheConfig` - TTL and memory cap configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready sharded cache.
    pub fn new(config: CacheConfig) -> Self {
        let shards: Box<[CacheShard; CACHE_SHARD_COUNT]> =
            Box::new(from_fn(|_: usize| CacheShard {
                map: RwLock::new(hash_map_xx_hash3_64()),
            }));
        let inflight: InFlightShardArray =
            Box::new(from_fn(|_: usize| Mutex::new(hash_map_xx_hash3_64())));
        Self {
            inner: Arc::new(ShardedMemoryCacheInner {
                config,
                entry_count: AtomicUsize::new(0),
                total_bytes: AtomicUsize::new(0),
                min_expires_at_ms: AtomicU64::new(u64::MAX),
                shards,
                inflight,
            }),
        }
    }

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

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

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

    /// Looks up a shared unexpired [`CacheEntry`] without cloning the cached headers or payload.
    ///
    /// Defers the wall-clock read until after a shard hit so misses incur zero timestamp overhead.
    ///
    /// # Arguments
    ///
    /// - `&str` - Cache key.
    ///
    /// # Returns
    ///
    /// - `Option<(Arc<CacheEntry>, u64)>` - Shared cache entry paired with the observed timestamp when hit.
    #[inline]
    pub(crate) fn get_entry_sync(&self, key: &str) -> Option<(Arc<CacheEntry>, u64)> {
        let Self { inner } = self;
        if inner.entry_count.load(Ordering::Relaxed) == 0 {
            return None;
        }
        let idx: usize = cache_shard_index(key);
        let entry: Arc<CacheEntry> = {
            let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
                inner.shards[idx].map.read().ok()?;
            Arc::clone(guard.get(key)?)
        };
        let now_ms: u64 = cache_now_ms();
        if now_ms < entry.expires_at_ms {
            return Some((entry, now_ms));
        }
        if let Ok(mut guard) = inner.shards[idx].map.write()
            && guard
                .get(key)
                .is_some_and(|cur: &Arc<CacheEntry>| now_ms >= cur.expires_at_ms)
            && let Some(removed) = guard.remove(key)
        {
            inner.entry_count.fetch_sub(1, Ordering::Relaxed);
            inner
                .total_bytes
                .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
        }
        None
    }

    /// Synchronous read-fast lookup returning an unexpired [`CachedValue`].
    ///
    /// # Arguments
    ///
    /// - `&str` - Cache key.
    ///
    /// # Returns
    ///
    /// - `Option<CachedValue>` - Cached value when present and unexpired.
    #[inline]
    pub fn get_sync(&self, key: &str) -> Option<CachedValue> {
        let Self { inner } = self;
        if inner.entry_count.load(Ordering::Relaxed) == 0 {
            return None;
        }
        let idx: usize = cache_shard_index(key);
        let expired_now_ms: u64 = {
            let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
                inner.shards[idx].map.read().ok()?;
            let entry: &Arc<CacheEntry> = guard.get(key)?;
            let now_ms: u64 = cache_now_ms();
            if now_ms < entry.expires_at_ms {
                return Some(entry.value.clone());
            }
            now_ms
        };
        if let Ok(mut guard) = inner.shards[idx].map.write()
            && guard
                .get(key)
                .is_some_and(|cur: &Arc<CacheEntry>| expired_now_ms >= cur.expires_at_ms)
            && let Some(removed) = guard.remove(key)
        {
            inner.entry_count.fetch_sub(1, Ordering::Relaxed);
            inner
                .total_bytes
                .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
        }
        None
    }

    /// Synchronous insert enforcing entry-count and byte-budget caps via expired & oldest eviction.
    ///
    /// # Arguments
    ///
    /// - `String` - Cache key.
    /// - `CachedValue` - Value to store.
    /// - `u64` - TTL in milliseconds.
    pub fn put_sync(&self, key: String, value: CachedValue, ttl_ms: u64) {
        if ttl_ms == 0 {
            return;
        }
        let Self { inner } = self;
        let max_bytes: usize = inner.config.get_max_bytes();
        let max_entries: usize = inner.config.get_max_entries();
        let footprint: usize = estimate_entry_bytes(&key, &value);
        if footprint > max_bytes {
            return;
        }
        let now_ms: u64 = cache_now_ms();
        let expires_at_ms: u64 = now_ms.saturating_add(ttl_ms);
        let idx: usize = cache_shard_index(&key);
        let mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
            match inner.shards[idx].map.write() {
                Ok(guard) => guard,
                Err(_) => return,
            };
        if let Some(existing) = map.get_mut(&key) {
            let prev_footprint: usize = existing.footprint_bytes;
            let total_now: usize = inner.total_bytes.load(Ordering::Relaxed);
            let projected_bytes: usize = total_now
                .saturating_sub(prev_footprint)
                .saturating_add(footprint);
            if projected_bytes <= max_bytes {
                if let Some(entry_mut) = Arc::get_mut(existing) {
                    entry_mut.value = value;
                    entry_mut.expires_at_ms = expires_at_ms;
                    entry_mut.footprint_bytes = footprint;
                    entry_mut.wire_cache = OnceLock::new();
                } else {
                    *existing = Arc::new(CacheEntry {
                        value,
                        expires_at_ms,
                        footprint_bytes: footprint,
                        wire_cache: OnceLock::new(),
                    });
                }
                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);
                }
                inner
                    .min_expires_at_ms
                    .fetch_min(expires_at_ms, 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);
            }
        }
        if (inner.entry_count.load(Ordering::Relaxed) >= max_entries
            || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes)
            && now_ms >= inner.min_expires_at_ms.load(Ordering::Relaxed)
        {
            drop(map);
            let _: usize = self.purge_expired();
            map = match inner.shards[idx].map.write() {
                Ok(guard) => guard,
                Err(_) => 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) >= max_entries
            || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes)
            && !map.is_empty()
        {
            let mut min_exp: u64 = u64::MAX;
            for cur in map.values() {
                if cur.expires_at_ms < min_exp {
                    min_exp = cur.expires_at_ms;
                }
            }
            let mut evicted_footprint: Option<usize> = None;
            map.retain(|_: &String, cur: &mut Arc<CacheEntry>| {
                if evicted_footprint.is_none() && cur.expires_at_ms == min_exp {
                    evicted_footprint = Some(cur.footprint_bytes);
                    false
                } else {
                    true
                }
            });
            if let Some(evicted_bytes) = evicted_footprint {
                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
                inner
                    .total_bytes
                    .fetch_sub(evicted_bytes, Ordering::Relaxed);
            } else {
                break;
            }
        }
        if inner.entry_count.load(Ordering::Relaxed) >= max_entries
            || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes
        {
            return;
        }
        let entry: Arc<CacheEntry> = Arc::new(CacheEntry {
            value,
            expires_at_ms,
            footprint_bytes: footprint,
            wire_cache: OnceLock::new(),
        });
        map.insert(key, entry);
        inner.entry_count.fetch_add(1, Ordering::Relaxed);
        inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
        inner
            .min_expires_at_ms
            .fetch_min(expires_at_ms, Ordering::Relaxed);
    }

    /// Single-flight cache loader coalescing concurrent cache misses on `key` into one origin call.
    ///
    /// # Arguments
    ///
    /// - `&str` - Cache key.
    /// - `u64` - Entry TTL in milliseconds when loaded.
    /// - `F` - Async origin loader invoked at most once across concurrent misses.
    ///
    /// # Returns
    ///
    /// - `Option<CachedValue>` - Cached or freshly loaded value.
    pub async fn get_or_load<F, Fut>(
        &self,
        key: &str,
        ttl_ms: u64,
        loader: F,
    ) -> Option<CachedValue>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Option<CachedValue>>,
    {
        if let Some(hit) = self.get_sync(key) {
            return Some(hit);
        }
        let Self { inner } = self;
        let idx: usize = cache_shard_index(key);
        let (slot, is_leader): (Arc<InFlightSlot>, bool) = {
            let Ok(mut guard) = inner.inflight[idx].lock() else {
                return loader().await;
            };
            if let Some(existing) = guard.get(key) {
                (Arc::clone(existing), false)
            } else {
                let created: Arc<InFlightSlot> = Arc::new(InFlightSlot {
                    notify: Notify::new(),
                    result: Mutex::new(None),
                });
                guard.insert(key.to_owned(), Arc::clone(&created));
                (created, true)
            }
        };
        if is_leader {
            let loaded: Option<CachedValue> = loader().await;
            if let Some(ref val) = loaded {
                self.put_sync(key.to_owned(), val.clone(), ttl_ms);
            }
            if let Ok(mut res_guard) = slot.result.lock() {
                *res_guard = Some(loaded.clone());
            }
            if let Ok(mut map_guard) = inner.inflight[idx].lock() {
                map_guard.remove(key);
            }
            slot.notify.notify_waiters();
            loaded
        } else {
            loop {
                let notified: Notified<'_> = slot.notify.notified();
                if let Ok(res_guard) = slot.result.lock()
                    && let Some(ref outcome) = *res_guard
                {
                    return outcome.clone();
                }
                notified.await;
            }
        }
    }
}

/// Implements [`CacheStore`] for [`ShardedMemoryCache`].
impl CacheStore for ShardedMemoryCache {
    /// Looks up an unexpired [`CachedValue`] asynchronously.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to self.
    /// - `&'a str` - Cache key.
    ///
    /// # Returns
    ///
    /// - `CacheFuture<'a, Option<CachedValue>>` - Cached value if present and unexpired.
    fn get<'a>(&'a self, key: &'a str) -> CacheFuture<'a, Option<CachedValue>> {
        Box::pin(async move { self.get_sync(key) })
    }

    /// Inserts or replaces a [`CachedValue`] asynchronously.
    ///
    /// # Arguments
    ///
    /// - `String` - Cache key.
    /// - `CachedValue` - Value to cache.
    /// - `u64` - Entry TTL in milliseconds.
    ///
    /// # Returns
    ///
    /// - `CacheFuture<'_, ()>` - Completion future.
    fn put(&self, key: String, value: CachedValue, ttl_ms: u64) -> CacheFuture<'_, ()> {
        self.put_sync(key, value, ttl_ms);
        Box::pin(async {})
    }

    /// Removes a cached key asynchronously.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to self.
    /// - `&'a str` - Cache key to remove.
    ///
    /// # Returns
    ///
    /// - `CacheFuture<'a, bool>` - `true` if removed.
    fn remove<'a>(&'a self, key: &'a str) -> CacheFuture<'a, bool> {
        let Self { inner } = self;
        let idx: usize = cache_shard_index(key);
        let removed: bool = inner.shards[idx]
            .map
            .write()
            .ok()
            .and_then(
                |mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>| {
                    map.remove(key)
                },
            )
            .map(|entry: Arc<CacheEntry>| {
                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
                inner
                    .total_bytes
                    .fetch_sub(entry.footprint_bytes, Ordering::Relaxed);
                true
            })
            .unwrap_or(false);
        Box::pin(async move { removed })
    }

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

/// Inherent implementation of [`CachePlugin`].
impl CachePlugin {
    /// Initializes the global [`CachePlugin`] once with `config` and the default [`ShardedMemoryCache`].
    ///
    /// # Arguments
    ///
    /// - `CacheConfig` - HTTP cache policy and memory limits.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(config: CacheConfig) -> &'static Self {
        let local: ShardedMemoryCache = ShardedMemoryCache::new(config.clone());
        let store: Arc<dyn CacheStore> = Arc::new(local.clone());
        CACHE_PLUGIN.get_or_init(|| Self {
            config,
            store,
            local_store: Some(local),
        })
    }

    /// Initializes the global [`CachePlugin`] once with `config` and a custom [`CacheStore`].
    ///
    /// # Arguments
    ///
    /// - `CacheConfig` - HTTP cache policy.
    /// - `Arc<dyn CacheStore>` - Pluggable cache backend.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init_with_store(config: CacheConfig, store: Arc<dyn CacheStore>) -> &'static Self {
        CACHE_PLUGIN.get_or_init(|| Self {
            config,
            store,
            local_store: None,
        })
    }

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

    /// Returns the active [`CacheConfig`].
    ///
    /// # Returns
    ///
    /// - `&CacheConfig` - Active configuration.
    #[inline(always)]
    pub fn get_config(&self) -> &CacheConfig {
        &self.config
    }

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

    /// Returns the direct built-in [`ShardedMemoryCache`] when configured via [`CachePlugin::init`].
    ///
    /// # Returns
    ///
    /// - `Option<&ShardedMemoryCache>` - Direct in-memory cache handle, if available.
    #[inline(always)]
    pub(crate) fn get_local_store(&self) -> Option<&ShardedMemoryCache> {
        self.local_store.as_ref()
    }
}

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

    /// Serves cached `GET`/`HEAD` responses directly on cache hit, or records cache key for [`CacheResponseHook`].
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` on cache hit; `Status::Continue` on miss or bypass.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = CachePlugin::get() else {
            return Status::Continue;
        };
        let req: &Request = ctx.get_request();
        let is_get: bool = req.get_method().is_get();
        let is_head: bool = !is_get && req.get_method().is_head();
        if !is_get && !is_head {
            return Status::Continue;
        }
        let config: &CacheConfig = plugin.get_config();
        let has_auth: bool = config.get_bypass_authenticated()
            && (req.get_headers().contains_key(AUTHORIZATION)
                || req.get_headers().contains_key(COOKIE));
        let req_cacheable: bool = if has_auth {
            false
        } else {
            let (ok, _): (bool, Option<u64>) =
                parse_cache_control(request_header_back(req, CACHE_CONTROL));
            ok
        };
        if !req_cacheable || has_auth {
            if config.get_emit_diagnostic_headers() {
                ctx.get_mut_response()
                    .set_header(HEADER_X_CACHE, X_CACHE_BYPASS);
            }
            return Status::Continue;
        }
        if let Some(local) = plugin.get_local_store() {
            let (hit_entry, miss_key): (Option<(Arc<CacheEntry>, u64)>, Option<String>) = {
                let key_cow: Cow<'_, str> = build_http_cache_key_cow(ctx);
                match local.get_entry_sync(&key_cow) {
                    Some(found) => (Some(found), None),
                    None => (None, Some(key_cow.into_owned())),
                }
            };
            if let Some((entry, now_ms)) = hit_entry {
                let hit: &CachedValue = &entry.value;
                let age_secs: u64 = now_ms.saturating_sub(hit.get_stored_at_ms()) / 1_000;
                let mut age_buf: [u8; AGE_STACK_BUF_LEN] = [0u8; AGE_STACK_BUF_LEN];
                let age_str: &str = format_u64_stack(age_secs, &mut age_buf);
                let can_fast_wire: bool = is_get
                    && ctx.get_request().get_version().is_http1_1()
                    && ctx.get_response().get_headers().is_empty();
                if can_fast_wire
                    && let Some(wire_parts) = entry
                        .wire_cache
                        .get_or_init(|| build_cached_http11_wire(hit))
                {
                    if !config.get_emit_diagnostic_headers() {
                        let _: Result<(), ResponseError> =
                            stream.try_send(&wire_parts.without_diag).await;
                        return Status::Reject;
                    }
                    let age_bytes: &[u8] = age_str.as_bytes();
                    let prefix_len: usize = wire_parts.with_diag_prefix.len();
                    let suffix_len: usize = wire_parts.with_diag_suffix.len();
                    let total_len: usize = prefix_len + age_bytes.len() + suffix_len;
                    if total_len <= CACHE_WIRE_FAST_STACK_CAP {
                        let mut stack: [u8; CACHE_WIRE_FAST_STACK_CAP] =
                            [0u8; CACHE_WIRE_FAST_STACK_CAP];
                        stack[..prefix_len].copy_from_slice(&wire_parts.with_diag_prefix);
                        stack[prefix_len..prefix_len + age_bytes.len()].copy_from_slice(age_bytes);
                        stack[prefix_len + age_bytes.len()..total_len]
                            .copy_from_slice(&wire_parts.with_diag_suffix);
                        let _: Result<(), ResponseError> =
                            stream.try_send(&stack[..total_len]).await;
                    } else if total_len <= CACHE_WIRE_STACK_CAP {
                        let mut stack: [u8; CACHE_WIRE_STACK_CAP] = [0u8; CACHE_WIRE_STACK_CAP];
                        stack[..prefix_len].copy_from_slice(&wire_parts.with_diag_prefix);
                        stack[prefix_len..prefix_len + age_bytes.len()].copy_from_slice(age_bytes);
                        stack[prefix_len + age_bytes.len()..total_len]
                            .copy_from_slice(&wire_parts.with_diag_suffix);
                        let _: Result<(), ResponseError> =
                            stream.try_send(&stack[..total_len]).await;
                    } else {
                        let mut wire: Vec<u8> = Vec::with_capacity(total_len);
                        wire.extend_from_slice(&wire_parts.with_diag_prefix);
                        wire.extend_from_slice(age_bytes);
                        wire.extend_from_slice(&wire_parts.with_diag_suffix);
                        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
                    }
                    return Status::Reject;
                }
                let resp: &mut Response = ctx.get_mut_response();
                resp.set_status_code(hit.get_status_code());
                for (name, val) in hit.get_headers() {
                    resp.set_header(name, val);
                }
                if config.get_emit_diagnostic_headers() {
                    resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
                        .set_header(AGE, age_str);
                }
                if is_head {
                    resp.set_body(&[] as &[u8]);
                } else {
                    resp.set_body(hit.get_body().as_slice());
                }
                let wire: Vec<u8> = resp.build();
                let _: Result<(), ResponseError> = stream.try_send(&wire).await;
                return Status::Reject;
            }
            if let Some(owned_key) = miss_key {
                ctx.set_attribute(ATTR_HTTP_CACHE_KEY, owned_key);
            }
            return Status::Continue;
        }
        let key: String = build_http_cache_key_cow(ctx).into_owned();
        if let Some(hit) = plugin.get_store().get(&key).await {
            let age_secs: u64 = hit.age_secs();
            let mut age_buf: [u8; AGE_STACK_BUF_LEN] = [0u8; AGE_STACK_BUF_LEN];
            let age_str: &str = format_u64_stack(age_secs, &mut age_buf);
            let resp: &mut Response = ctx.get_mut_response();
            resp.set_status_code(hit.get_status_code());
            for (name, val) in hit.get_headers() {
                resp.set_header(name, val);
            }
            if config.get_emit_diagnostic_headers() {
                resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
                    .set_header(AGE, age_str);
            }
            if is_head {
                resp.set_body(&[] as &[u8]);
            } else {
                resp.set_body(hit.get_body().as_slice());
            }
            let wire: Vec<u8> = resp.build();
            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
            return Status::Reject;
        }
        ctx.set_attribute(ATTR_HTTP_CACHE_KEY, key);
        Status::Continue
    }
}

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

    /// Stores eligible `200 OK` responses into [`CachePlugin`]'s backing store and emits `X-Cache: MISS`.
    ///
    /// # 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) = CachePlugin::get() else {
            return Status::Continue;
        };
        let Some(key) = ctx.try_get_attribute::<String, _>(ATTR_HTTP_CACHE_KEY) else {
            return Status::Continue;
        };
        let config: &CacheConfig = plugin.get_config();
        let resp: &Response = ctx.get_response();
        let status: usize = resp.get_status_code();
        let body_len: usize = resp.get_body().len();
        if status == HttpStatus::Ok.code() && body_len <= config.get_max_entry_bytes() {
            let (cc_ok, ttl_override): (bool, Option<u64>) =
                parse_cache_control(response_header_back(resp, CACHE_CONTROL));
            let vary_star: bool =
                response_header_back(resp, VARY).is_some_and(|val: &str| val.trim() == "*");
            if cc_ok && !vary_star {
                let ttl_ms: u64 = ttl_override.unwrap_or(config.get_default_ttl_ms());
                if ttl_ms > 0 {
                    let mut headers: Vec<(String, String)> =
                        Vec::with_capacity(resp.get_headers().len());
                    for (name, values) in resp.get_headers() {
                        if !name.eq_ignore_ascii_case(HEADER_X_CACHE)
                            && !name.eq_ignore_ascii_case(AGE)
                            && let Some(last) = values.back()
                        {
                            headers.push((name.clone(), last.clone()));
                        }
                    }
                    let cached: CachedValue =
                        CachedValue::new(status, headers, resp.get_body().clone());
                    if let Some(local) = plugin.get_local_store() {
                        local.put_sync(key, cached, ttl_ms);
                    } else {
                        plugin.get_store().put(key, cached, ttl_ms).await;
                    }
                }
            }
        }
        if config.get_emit_diagnostic_headers() && !ctx.get_response().has_header(HEADER_X_CACHE) {
            ctx.get_mut_response()
                .set_header(HEADER_X_CACHE, X_CACHE_MISS);
        }
        Status::Continue
    }
}