Skip to main content

hyperlane_plugin_cache/
impl.rs

1use super::*;
2
3/// Inherent constructors for [`CachedValue`].
4impl CachedValue {
5    /// Creates a [`CachedValue`] with status code, headers, and body stamped with current epoch time.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - HTTP status code.
10    /// - `Vec<(String, String)>` - Response headers.
11    /// - `Vec<u8>` - Payload bytes.
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Constructed cached value.
16    pub fn new(status_code: usize, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
17        Self {
18            status_code,
19            headers,
20            body,
21            stored_at_ms: cache_now_ms(),
22        }
23    }
24
25    /// Creates a raw byte payload cache value with status `200` and no headers.
26    ///
27    /// # Arguments
28    ///
29    /// - `Vec<u8>` - Raw bytes to cache.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Cached byte payload.
34    pub fn bytes(body: Vec<u8>) -> Self {
35        Self::new(HttpStatus::Ok.code(), Vec::new(), body)
36    }
37
38    /// Computes elapsed age in whole seconds since this entry was stored.
39    ///
40    /// # Returns
41    ///
42    /// - `u64` - Elapsed age in seconds.
43    pub fn age_secs(&self) -> u64 {
44        cache_now_ms().saturating_sub(self.get_stored_at_ms()) / 1_000
45    }
46}
47
48/// Default construction for [`CacheConfig`].
49impl Default for CacheConfig {
50    /// Constructs a default [`CacheConfig`] (60 s TTL, 16 384 entries, 64 MiB total cap).
51    fn default() -> Self {
52        Self {
53            default_ttl_ms: DEFAULT_CACHE_TTL_MS,
54            max_entries: DEFAULT_CACHE_MAX_ENTRIES,
55            max_bytes: DEFAULT_CACHE_MAX_BYTES,
56            max_entry_bytes: DEFAULT_CACHE_MAX_ENTRY_BYTES,
57            bypass_authenticated: true,
58            emit_diagnostic_headers: true,
59        }
60    }
61}
62
63/// Inherent fluent builders for [`CacheConfig`].
64impl CacheConfig {
65    /// Sets the default entry TTL in milliseconds.
66    ///
67    /// # Arguments
68    ///
69    /// - `u64` - Default TTL in milliseconds.
70    ///
71    /// # Returns
72    ///
73    /// - `Self` - Updated configuration.
74    pub fn with_default_ttl_ms(mut self, ttl_ms: u64) -> Self {
75        self.set_default_ttl_ms(ttl_ms);
76        self
77    }
78
79    /// Sets the maximum tracked entry count across all shards.
80    ///
81    /// # Arguments
82    ///
83    /// - `usize` - Maximum entry count.
84    ///
85    /// # Returns
86    ///
87    /// - `Self` - Updated configuration.
88    pub fn with_max_entries(mut self, max_entries: usize) -> Self {
89        self.set_max_entries(max_entries.max(1));
90        self
91    }
92
93    /// Sets the maximum total byte budget across all shards.
94    ///
95    /// # Arguments
96    ///
97    /// - `usize` - Byte budget cap.
98    ///
99    /// # Returns
100    ///
101    /// - `Self` - Updated configuration.
102    pub fn with_max_bytes(mut self, max_bytes: usize) -> Self {
103        self.set_max_bytes(max_bytes.max(1));
104        self
105    }
106}
107
108/// Default construction for [`ShardedMemoryCache`].
109impl Default for ShardedMemoryCache {
110    /// Constructs a default 64-shard [`ShardedMemoryCache`].
111    fn default() -> Self {
112        Self::new(CacheConfig::default())
113    }
114}
115
116/// Inherent implementation of [`ShardedMemoryCache`].
117impl ShardedMemoryCache {
118    /// Creates a 64-way sharded bounded [`ShardedMemoryCache`] governed by `config`.
119    ///
120    /// # Arguments
121    ///
122    /// - `CacheConfig` - TTL and memory cap configuration.
123    ///
124    /// # Returns
125    ///
126    /// - `Self` - Ready sharded cache.
127    pub fn new(config: CacheConfig) -> Self {
128        let shards: CacheShardArray =
129            Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
130        let inflight: InFlightShardArray =
131            Box::new(from_fn(|_: usize| Mutex::new(hash_map_xx_hash3_64())));
132        Self {
133            inner: Arc::new(ShardedMemoryCacheInner {
134                config,
135                entry_count: AtomicUsize::new(0),
136                total_bytes: AtomicUsize::new(0),
137                shards,
138                inflight,
139            }),
140        }
141    }
142
143    /// Returns the number of cached entries across all shards in `O(1)` time without locking.
144    ///
145    /// # Returns
146    ///
147    /// - `usize` - Entry count.
148    pub fn len(&self) -> usize {
149        let Self { inner } = self;
150        inner.entry_count.load(Ordering::Relaxed)
151    }
152
153    /// Reports whether the cache contains zero entries.
154    ///
155    /// # Returns
156    ///
157    /// - `bool` - `true` when empty.
158    pub fn is_empty(&self) -> bool {
159        self.len() == 0
160    }
161
162    /// Returns the estimated total byte usage across all shards in `O(1)` time.
163    ///
164    /// # Returns
165    ///
166    /// - `usize` - Approximate cached byte footprint.
167    pub fn total_bytes(&self) -> usize {
168        let Self { inner } = self;
169        inner.total_bytes.load(Ordering::Relaxed)
170    }
171
172    /// Synchronous read-fast lookup returning an unexpired [`CachedValue`].
173    ///
174    /// # Arguments
175    ///
176    /// - `&str` - Cache key.
177    ///
178    /// # Returns
179    ///
180    /// - `Option<CachedValue>` - Cached value when present and unexpired.
181    pub fn get_sync(&self, key: &str) -> Option<CachedValue> {
182        let Self { inner } = self;
183        let idx: usize = cache_shard_index(key);
184        let now_ms: u64 = cache_now_ms();
185        let entry: Arc<CacheEntry> = {
186            let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
187                inner.shards[idx].read().ok()?;
188            Arc::clone(guard.get(key)?)
189        };
190        if now_ms < entry.expires_at_ms {
191            return Some(entry.value.clone());
192        }
193        if let Ok(mut guard) = inner.shards[idx].write()
194            && let Some(removed) = guard.remove(key)
195        {
196            inner.entry_count.fetch_sub(1, Ordering::Relaxed);
197            inner
198                .total_bytes
199                .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
200        }
201        None
202    }
203
204    /// Synchronous insert enforcing entry-count and byte-budget caps via expired & oldest eviction.
205    ///
206    /// # Arguments
207    ///
208    /// - `String` - Cache key.
209    /// - `CachedValue` - Value to store.
210    /// - `u64` - TTL in milliseconds.
211    pub fn put_sync(&self, key: String, value: CachedValue, ttl_ms: u64) {
212        if ttl_ms == 0 {
213            return;
214        }
215        let Self { inner } = self;
216        let footprint: usize = estimate_entry_bytes(&key, &value);
217        if footprint > inner.config.get_max_bytes() {
218            return;
219        }
220        let now_ms: u64 = cache_now_ms();
221        if inner.entry_count.load(Ordering::Relaxed) >= inner.config.get_max_entries()
222            || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.config.get_max_bytes()
223        {
224            let _: usize = self.purge_expired();
225        }
226        let idx: usize = cache_shard_index(&key);
227        let Ok(mut map): Result<
228            RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>,
229            _,
230        > = inner.shards[idx].write() else {
231            return;
232        };
233        if let Some(prev) = map.remove(&key) {
234            inner.entry_count.fetch_sub(1, Ordering::Relaxed);
235            inner
236                .total_bytes
237                .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
238        }
239        while (inner.entry_count.load(Ordering::Relaxed) >= inner.config.get_max_entries()
240            || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.config.get_max_bytes())
241            && !map.is_empty()
242        {
243            let oldest_key: Option<String> = map
244                .iter()
245                .min_by_key(|(_, entry): &(&String, &Arc<CacheEntry>)| entry.expires_at_ms)
246                .map(|(k, _): (&String, &Arc<CacheEntry>)| k.clone());
247            if let Some(evict_key) = oldest_key
248                && let Some(evicted) = map.remove(&evict_key)
249            {
250                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
251                inner
252                    .total_bytes
253                    .fetch_sub(evicted.footprint_bytes, Ordering::Relaxed);
254            } else {
255                break;
256            }
257        }
258        if inner.entry_count.load(Ordering::Relaxed) >= inner.config.get_max_entries()
259            || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.config.get_max_bytes()
260        {
261            return;
262        }
263        let entry: Arc<CacheEntry> = Arc::new(CacheEntry {
264            value,
265            expires_at_ms: now_ms.saturating_add(ttl_ms),
266            footprint_bytes: footprint,
267        });
268        map.insert(key, entry);
269        inner.entry_count.fetch_add(1, Ordering::Relaxed);
270        inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
271    }
272
273    /// Single-flight cache loader coalescing concurrent cache misses on `key` into one origin call.
274    ///
275    /// # Arguments
276    ///
277    /// - `&str` - Cache key.
278    /// - `u64` - Entry TTL in milliseconds when loaded.
279    /// - `F` - Async origin loader invoked at most once across concurrent misses.
280    ///
281    /// # Returns
282    ///
283    /// - `Option<CachedValue>` - Cached or freshly loaded value.
284    pub async fn get_or_load<F, Fut>(
285        &self,
286        key: &str,
287        ttl_ms: u64,
288        loader: F,
289    ) -> Option<CachedValue>
290    where
291        F: FnOnce() -> Fut,
292        Fut: Future<Output = Option<CachedValue>>,
293    {
294        if let Some(hit) = self.get_sync(key) {
295            return Some(hit);
296        }
297        let Self { inner } = self;
298        let idx: usize = cache_shard_index(key);
299        let (slot, is_leader): (Arc<InFlightSlot>, bool) = {
300            let Ok(mut guard) = inner.inflight[idx].lock() else {
301                return loader().await;
302            };
303            if let Some(existing) = guard.get(key) {
304                (Arc::clone(existing), false)
305            } else {
306                let created: Arc<InFlightSlot> = Arc::new(InFlightSlot {
307                    notify: Notify::new(),
308                    result: Mutex::new(None),
309                });
310                guard.insert(key.to_owned(), Arc::clone(&created));
311                (created, true)
312            }
313        };
314        if is_leader {
315            let loaded: Option<CachedValue> = loader().await;
316            if let Some(ref val) = loaded {
317                self.put_sync(key.to_owned(), val.clone(), ttl_ms);
318            }
319            if let Ok(mut res_guard) = slot.result.lock() {
320                *res_guard = Some(loaded.clone());
321            }
322            if let Ok(mut map_guard) = inner.inflight[idx].lock() {
323                map_guard.remove(key);
324            }
325            slot.notify.notify_waiters();
326            loaded
327        } else {
328            loop {
329                let notified: Notified<'_> = slot.notify.notified();
330                if let Ok(res_guard) = slot.result.lock()
331                    && let Some(ref outcome) = *res_guard
332                {
333                    return outcome.clone();
334                }
335                notified.await;
336            }
337        }
338    }
339}
340
341/// Implements [`CacheStore`] for [`ShardedMemoryCache`].
342impl CacheStore for ShardedMemoryCache {
343    /// Looks up an unexpired [`CachedValue`] asynchronously.
344    ///
345    /// # Arguments
346    ///
347    /// - `&'a self` - Shared reference to self.
348    /// - `&'a str` - Cache key.
349    ///
350    /// # Returns
351    ///
352    /// - `CacheFuture<'a, Option<CachedValue>>` - Cached value if present and unexpired.
353    fn get<'a>(&'a self, key: &'a str) -> CacheFuture<'a, Option<CachedValue>> {
354        let value: Option<CachedValue> = self.get_sync(key);
355        Box::pin(async move { value })
356    }
357
358    /// Inserts or replaces a [`CachedValue`] asynchronously.
359    ///
360    /// # Arguments
361    ///
362    /// - `String` - Cache key.
363    /// - `CachedValue` - Value to cache.
364    /// - `u64` - Entry TTL in milliseconds.
365    ///
366    /// # Returns
367    ///
368    /// - `CacheFuture<'_, ()>` - Completion future.
369    fn put(&self, key: String, value: CachedValue, ttl_ms: u64) -> CacheFuture<'_, ()> {
370        self.put_sync(key, value, ttl_ms);
371        Box::pin(async {})
372    }
373
374    /// Removes a cached key asynchronously.
375    ///
376    /// # Arguments
377    ///
378    /// - `&'a self` - Shared reference to self.
379    /// - `&'a str` - Cache key to remove.
380    ///
381    /// # Returns
382    ///
383    /// - `CacheFuture<'a, bool>` - `true` if removed.
384    fn remove<'a>(&'a self, key: &'a str) -> CacheFuture<'a, bool> {
385        let Self { inner } = self;
386        let idx: usize = cache_shard_index(key);
387        let removed: bool = inner.shards[idx]
388            .write()
389            .ok()
390            .and_then(
391                |mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>| {
392                    map.remove(key)
393                },
394            )
395            .map(|entry: Arc<CacheEntry>| {
396                inner.entry_count.fetch_sub(1, Ordering::Relaxed);
397                inner
398                    .total_bytes
399                    .fetch_sub(entry.footprint_bytes, Ordering::Relaxed);
400                true
401            })
402            .unwrap_or(false);
403        Box::pin(async move { removed })
404    }
405
406    /// Evicts expired entries across all 64 shards.
407    ///
408    /// # Returns
409    ///
410    /// - `usize` - Number of expired entries removed.
411    fn purge_expired(&self) -> usize {
412        let Self { inner } = self;
413        let now_ms: u64 = cache_now_ms();
414        let mut evicted: usize = 0;
415        let mut freed_bytes: usize = 0;
416        for shard in inner.shards.iter() {
417            if let Ok(mut map) = shard.write() {
418                map.retain(|_: &String, entry: &mut Arc<CacheEntry>| {
419                    if now_ms >= entry.expires_at_ms {
420                        evicted += 1;
421                        freed_bytes += entry.footprint_bytes;
422                        false
423                    } else {
424                        true
425                    }
426                });
427            }
428        }
429        if evicted > 0 {
430            inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
431            inner.total_bytes.fetch_sub(freed_bytes, Ordering::Relaxed);
432        }
433        evicted
434    }
435}
436
437/// Inherent implementation of [`CachePlugin`].
438impl CachePlugin {
439    /// Initializes the global [`CachePlugin`] once with `config` and the default [`ShardedMemoryCache`].
440    ///
441    /// # Arguments
442    ///
443    /// - `CacheConfig` - HTTP cache policy and memory limits.
444    ///
445    /// # Returns
446    ///
447    /// - `&'static Self` - Reference to the initialized global plugin.
448    pub fn init(config: CacheConfig) -> &'static Self {
449        let store: SharedCacheStore = Arc::new(ShardedMemoryCache::new(config.clone()));
450        Self::init_with_store(config, store)
451    }
452
453    /// Initializes the global [`CachePlugin`] once with `config` and a custom [`CacheStore`].
454    ///
455    /// # Arguments
456    ///
457    /// - `CacheConfig` - HTTP cache policy.
458    /// - `SharedCacheStore` - Pluggable cache backend.
459    ///
460    /// # Returns
461    ///
462    /// - `&'static Self` - Reference to the initialized global plugin.
463    pub fn init_with_store(config: CacheConfig, store: SharedCacheStore) -> &'static Self {
464        CACHE_PLUGIN.get_or_init(|| Self { config, store })
465    }
466
467    /// Returns the initialized global [`CachePlugin`], if initialized.
468    ///
469    /// # Returns
470    ///
471    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
472    pub fn get() -> Option<&'static Self> {
473        CACHE_PLUGIN.get()
474    }
475
476    /// Returns the active [`CacheConfig`].
477    ///
478    /// # Returns
479    ///
480    /// - `&CacheConfig` - Active configuration.
481    pub fn get_config(&self) -> &CacheConfig {
482        &self.config
483    }
484
485    /// Returns the active [`SharedCacheStore`].
486    ///
487    /// # Returns
488    ///
489    /// - `&SharedCacheStore` - Active backing store.
490    pub fn get_store(&self) -> &SharedCacheStore {
491        &self.store
492    }
493}
494
495/// Implements [`ServerHook`] for [`CacheRequestHook`].
496impl ServerHook for CacheRequestHook {
497    /// Constructs a per-request [`CacheRequestHook`].
498    ///
499    /// # Arguments
500    ///
501    /// - `&mut Stream` - Connection stream.
502    /// - `&mut Context` - Request context.
503    ///
504    /// # Returns
505    ///
506    /// - `Self` - Hook instance.
507    async fn new(_: &mut Stream, _: &mut Context) -> Self {
508        Self
509    }
510
511    /// Serves cached `GET`/`HEAD` responses directly on cache hit, or records cache key for [`CacheResponseHook`].
512    ///
513    /// # Arguments
514    ///
515    /// - `Self` - Hook instance.
516    /// - `&mut Stream` - Connection stream.
517    /// - `&mut Context` - Request context.
518    ///
519    /// # Returns
520    ///
521    /// - `Status` - `Status::Reject` on cache hit; `Status::Continue` on miss or bypass.
522    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
523        let Some(plugin) = CachePlugin::get() else {
524            return Status::Continue;
525        };
526        let is_get: bool = ctx.get_request().get_method().is_get();
527        let is_head: bool = ctx.get_request().get_method().is_head();
528        if !is_get && !is_head {
529            return Status::Continue;
530        }
531        let config: &CacheConfig = plugin.get_config();
532        let req_cc: Option<String> = ctx.get_request().try_get_header_back(CACHE_CONTROL);
533        let (req_cacheable, _): (bool, Option<u64>) = parse_cache_control(req_cc.as_deref());
534        let has_auth: bool = config.get_bypass_authenticated()
535            && (ctx
536                .get_request()
537                .try_get_header_back(AUTHORIZATION)
538                .is_some()
539                || ctx.get_request().try_get_header_back(COOKIE).is_some());
540        if !req_cacheable || has_auth {
541            if config.get_emit_diagnostic_headers() {
542                ctx.get_mut_response()
543                    .set_header(HEADER_X_CACHE, X_CACHE_BYPASS);
544            }
545            return Status::Continue;
546        }
547        let key: String = build_http_cache_key(ctx);
548        if let Some(hit) = plugin.get_store().get(&key).await {
549            let age: String = hit.age_secs().to_string();
550            let resp: &mut Response = ctx.get_mut_response();
551            resp.set_status_code(hit.get_status_code());
552            for (name, val) in hit.get_headers() {
553                resp.set_header(name, val);
554            }
555            if config.get_emit_diagnostic_headers() {
556                resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
557                    .set_header(AGE, age);
558            }
559            if is_head {
560                resp.set_body(Vec::new());
561            } else {
562                resp.set_body(hit.get_body().clone());
563            }
564            let wire: ResponseData = ctx.get_mut_response().build();
565            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
566            return Status::Reject;
567        }
568        ctx.set_attribute(ATTR_HTTP_CACHE_KEY, key);
569        Status::Continue
570    }
571}
572
573/// Implements [`ServerHook`] for [`CacheResponseHook`].
574impl ServerHook for CacheResponseHook {
575    /// Constructs a per-response [`CacheResponseHook`].
576    ///
577    /// # Arguments
578    ///
579    /// - `&mut Stream` - Connection stream.
580    /// - `&mut Context` - Request context.
581    ///
582    /// # Returns
583    ///
584    /// - `Self` - Hook instance.
585    async fn new(_: &mut Stream, _: &mut Context) -> Self {
586        Self
587    }
588
589    /// Stores eligible `200 OK` responses into [`CachePlugin`]'s backing store and emits `X-Cache: MISS`.
590    ///
591    /// # Arguments
592    ///
593    /// - `Self` - Hook instance.
594    /// - `&mut Stream` - Connection stream.
595    /// - `&mut Context` - Request context.
596    ///
597    /// # Returns
598    ///
599    /// - `Status` - Always `Status::Continue`.
600    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
601        let Some(plugin) = CachePlugin::get() else {
602            return Status::Continue;
603        };
604        let Some(key) = ctx.try_get_attribute::<String, _>(ATTR_HTTP_CACHE_KEY) else {
605            return Status::Continue;
606        };
607        let config: &CacheConfig = plugin.get_config();
608        let status: usize = ctx.get_response().get_status_code();
609        let body_len: usize = ctx.get_response().get_body().len();
610        let resp_cc: Option<String> = ctx.get_response().try_get_header_back(CACHE_CONTROL);
611        let (cc_ok, ttl_override): (bool, Option<u64>) = parse_cache_control(resp_cc.as_deref());
612        let vary_star: bool = ctx
613            .get_response()
614            .try_get_header_back(VARY)
615            .is_some_and(|val: String| val.trim() == "*");
616        if status == HttpStatus::Ok.code()
617            && cc_ok
618            && !vary_star
619            && body_len <= config.get_max_entry_bytes()
620        {
621            let ttl_ms: u64 = ttl_override.unwrap_or(config.get_default_ttl_ms());
622            if ttl_ms > 0 {
623                let mut headers: Vec<(String, String)> = Vec::new();
624                for (name, values) in ctx.get_response().get_headers() {
625                    if !name.eq_ignore_ascii_case(HEADER_X_CACHE)
626                        && !name.eq_ignore_ascii_case(AGE)
627                        && let Some(last) = values.back()
628                    {
629                        headers.push((name.clone(), last.clone()));
630                    }
631                }
632                let cached: CachedValue =
633                    CachedValue::new(status, headers, ctx.get_response().get_body().clone());
634                plugin.get_store().put(key, cached, ttl_ms).await;
635            }
636        }
637        if config.get_emit_diagnostic_headers()
638            && ctx
639                .get_response()
640                .try_get_header_back(HEADER_X_CACHE)
641                .is_none()
642        {
643            ctx.get_mut_response()
644                .set_header(HEADER_X_CACHE, X_CACHE_MISS);
645        }
646        Status::Continue
647    }
648}