hyperlane_plugin_cache/struct.rs
1use super::*;
2
3/// Cached HTTP response or arbitrary byte payload with headers and timestamp metadata.
4#[derive(Clone, Data, Debug, Eq, PartialEq)]
5pub struct CachedValue {
6 /// Cached HTTP status code (for example `200`).
7 #[get(type(copy))]
8 pub(crate) status_code: usize,
9 /// Cached response headers `(name, value)`.
10 pub(crate) headers: Vec<(String, String)>,
11 /// Cached payload bytes.
12 pub(crate) body: Vec<u8>,
13 /// Unix epoch millisecond when this entry was stored.
14 #[get(type(copy))]
15 pub(crate) stored_at_ms: u64,
16}
17
18/// Prebuilt HTTP/1.1 wire fragments for zero-allocation cache-hit transmission.
19pub(crate) struct CachedHttp11Wire {
20 /// Complete HTTP/1.1 response bytes without diagnostic `X-Cache`/`Age` headers.
21 pub(crate) without_diag: Vec<u8>,
22 /// HTTP/1.1 response bytes up to and including `x-cache: HIT\r\nage: `.
23 pub(crate) with_diag_prefix: Vec<u8>,
24 /// Remaining HTTP/1.1 bytes starting with `\r\n\r\n` followed by the body.
25 pub(crate) with_diag_suffix: Vec<u8>,
26}
27
28/// Internal cache record pairing a [`CachedValue`] with expiration, footprint, and lazy wire cache.
29pub(crate) struct CacheEntry {
30 /// Cached payload.
31 pub(crate) value: CachedValue,
32 /// Unix epoch millisecond at which this entry expires.
33 pub(crate) expires_at_ms: u64,
34 /// Approximate memory footprint in bytes for budget enforcement.
35 pub(crate) footprint_bytes: usize,
36 /// Lazily initialized HTTP/1.1 wire bytes shared across concurrent cache hits.
37 pub(crate) wire_cache: OnceLock<Option<Box<CachedHttp11Wire>>>,
38}
39
40/// Single-flight coordination slot coalescing concurrent cache misses for one key.
41pub(crate) struct InFlightSlot {
42 /// Notifier woken once the leader finishes loading.
43 pub(crate) notify: Notify,
44 /// Completed result shared with all waiting followers.
45 pub(crate) result: Mutex<Option<Option<CachedValue>>>,
46}
47
48/// Configuration for [`ShardedMemoryCache`] and [`CachePlugin`].
49#[derive(Clone, Data, Debug, Eq, PartialEq)]
50pub struct CacheConfig {
51 /// Default entry TTL in milliseconds when no `Cache-Control: max-age` override is present.
52 #[get(type(copy))]
53 pub(crate) default_ttl_ms: u64,
54 /// Maximum cached entries across all 64 shards.
55 #[get(type(copy))]
56 pub(crate) max_entries: usize,
57 /// Maximum aggregate memory footprint across all 64 shards in bytes.
58 #[get(type(copy))]
59 pub(crate) max_bytes: usize,
60 /// Maximum single response body length eligible for automatic HTTP response caching.
61 #[get(type(copy))]
62 pub(crate) max_entry_bytes: usize,
63 /// Bypasses HTTP response caching when `Authorization` or `Cookie` is present when `true`.
64 #[get(type(copy))]
65 pub(crate) bypass_authenticated: bool,
66 /// Emits diagnostic `X-Cache` and `Age` headers when `true`.
67 #[get(type(copy))]
68 pub(crate) emit_diagnostic_headers: bool,
69}
70
71/// Cache-line padded shard container preventing false sharing between adjacent shard locks.
72#[repr(align(64))]
73pub(crate) struct CacheShard {
74 /// Read-write guarded per-shard map of cached entries.
75 pub(crate) map: RwLock<HashMapXxHash3_64<String, Arc<CacheEntry>>>,
76}
77
78/// Shared interior state of [`ShardedMemoryCache`].
79pub(crate) struct ShardedMemoryCacheInner {
80 /// Cache capacity and TTL configuration.
81 pub(crate) config: CacheConfig,
82 /// Lock-free count of live entries across all shards.
83 pub(crate) entry_count: AtomicUsize,
84 /// Lock-free estimated total byte usage across all shards.
85 pub(crate) total_bytes: AtomicUsize,
86 /// Lower bound on the earliest `expires_at_ms` across all live entries (`u64::MAX` when empty).
87 pub(crate) min_expires_at_ms: AtomicU64,
88 /// 64-way sharded entry tables.
89 pub(crate) shards: Box<[CacheShard; CACHE_SHARD_COUNT]>,
90 /// 64-way sharded single-flight stampede-coalescing map.
91 pub(crate) inflight: InFlightShardArray,
92}
93
94/// High-concurrency 64-way sharded bounded in-memory [`CacheStore`] with single-flight coalescing.
95#[derive(Clone)]
96pub struct ShardedMemoryCache {
97 /// Shared sharded cache state.
98 pub(crate) inner: Arc<ShardedMemoryCacheInner>,
99}
100
101/// Process-wide [`CachePlugin`] singleton storing [`CacheConfig`] and a pluggable [`CacheStore`].
102#[derive(Clone)]
103pub struct CachePlugin {
104 /// Active HTTP caching policy.
105 pub(crate) config: CacheConfig,
106 /// Backing cache store (default [`ShardedMemoryCache`] or custom distributed store).
107 pub(crate) store: Arc<dyn CacheStore>,
108 /// Direct zero-boxing handle when initialized with the built-in [`ShardedMemoryCache`].
109 pub(crate) local_store: Option<ShardedMemoryCache>,
110}
111
112/// Opt-in request middleware serving cached `GET`/`HEAD` responses with `X-Cache: HIT` and `Age`.
113#[derive(Clone, Copy, Debug, Default)]
114#[hyperlane::request_middleware(-80)]
115pub struct CacheRequestHook;
116
117/// Opt-in response middleware storing eligible `200 OK` responses according to `Cache-Control` and `Vary`.
118#[derive(Clone, Copy, Debug, Default)]
119#[hyperlane::response_middleware(-65)]
120pub struct CacheResponseHook;