Skip to main content

ic_bn_lib/http/
cache.rs

1use std::{
2    fmt::Debug,
3    hash::Hash,
4    marker::PhantomData,
5    mem::size_of,
6    sync::Arc,
7    time::{Duration, Instant},
8};
9
10use ahash::RandomState;
11use async_trait::async_trait;
12use axum::{body::Body, extract::Request, middleware::Next, response::Response};
13use bytes::Bytes;
14use http::{
15    Method,
16    header::{CACHE_CONTROL, RANGE},
17};
18use http_body::Body as _;
19use moka::{
20    Expiry,
21    sync::{Cache as MokaCache, CacheBuilder as MokaCacheBuilder},
22};
23use prometheus::{
24    Counter, CounterVec, Histogram, HistogramVec, IntGauge, Registry,
25    register_counter_vec_with_registry, register_counter_with_registry,
26    register_histogram_vec_with_registry, register_histogram_with_registry,
27    register_int_gauge_with_registry,
28};
29use sha1::{Digest, Sha1};
30use strum_macros::{Display, IntoStaticStr};
31use tokio::{select, sync::Mutex, time::sleep};
32use tokio_util::sync::CancellationToken;
33
34use super::{body::buffer_body, calc_headers_size, extract_authority};
35use crate::{
36    http::{Error as HttpError, headers::X_CACHE_TTL},
37    tasks::Run,
38};
39
40/// HTTP Cache error
41#[derive(thiserror::Error, Debug)]
42pub enum CacheError {
43    #[error("unable to extract key from request: {0}")]
44    ExtractKey(String),
45    #[error("unable to execute bypasser: {0}")]
46    ExecuteBypasser(String),
47    #[error("timed out while fetching body")]
48    FetchBodyTimeout,
49    #[error("body is too big")]
50    FetchBodyTooBig,
51    #[error("unable to fetch request body: {0}")]
52    FetchBody(String),
53    #[error("unable to parse content-length header")]
54    ParseContentLength,
55    #[error("{0}")]
56    Other(String),
57}
58
59/// Trait to extract the caching key from the given HTTP request
60pub trait KeyExtractor: Clone + Send + Sync + Debug + 'static {
61    /// The type of the key.
62    type Key: Clone + Send + Sync + Debug + Hash + Eq + 'static;
63
64    /// Extraction method, will return [`Error`] response when the extraction failed
65    fn extract<T>(&self, req: &Request<T>) -> Result<Self::Key, CacheError>;
66}
67
68/// Reason for bypassing caching of the request
69pub trait CustomBypassReason:
70    Debug + Clone + std::fmt::Display + Into<&'static str> + PartialEq + Eq + Send + Sync + 'static
71{
72}
73
74/// Trait to decide if we need to bypass caching of the given request
75pub trait Bypasser: Clone + Send + Sync + Debug + 'static {
76    /// Custom bypass reason
77    type BypassReason: CustomBypassReason;
78
79    /// Checks if we should bypass the given request
80    fn bypass<T>(&self, req: &Request<T>) -> Result<Option<Self::BypassReason>, CacheError>;
81}
82
83/// Reason for bypassing the HTTP cache for the particular request
84#[derive(Debug, Clone, Display, PartialEq, Eq, IntoStaticStr)]
85#[strum(serialize_all = "snake_case")]
86pub enum CacheBypassReason<R: CustomBypassReason> {
87    MethodNotCacheable,
88    SizeUnknown,
89    BodyTooBig,
90    HTTPError,
91    UnableToExtractKey,
92    UnableToRunBypasser,
93    CacheControl,
94    Custom(R),
95}
96
97impl<R: CustomBypassReason> CacheBypassReason<R> {
98    pub fn into_str(self) -> &'static str {
99        match self {
100            Self::Custom(v) => v.into(),
101            _ => self.into(),
102        }
103    }
104}
105
106#[derive(Debug, Clone, Display, PartialEq, Eq, IntoStaticStr)]
107pub enum CustomBypassReasonDummy {}
108impl CustomBypassReason for CustomBypassReasonDummy {}
109
110/// Status of the cache lookup operation
111#[derive(Debug, Clone, Display, PartialEq, Eq, Default, IntoStaticStr)]
112#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
113pub enum CacheStatus<R: CustomBypassReason = CustomBypassReasonDummy> {
114    #[default]
115    Disabled,
116    Bypass(CacheBypassReason<R>),
117    Hit(i64),
118    Miss(i64),
119}
120
121impl<B: CustomBypassReason> CacheStatus<B> {
122    /// Injects itself into a given response to be accessible by middleware
123    pub fn with_response<T>(self, mut resp: Response<T>) -> Response<T> {
124        resp.extensions_mut().insert(self);
125        resp
126    }
127}
128
129enum ResponseType<R: CustomBypassReason> {
130    Fetched(Response<Bytes>, Duration),
131    Streamed(Response, CacheBypassReason<R>),
132}
133
134/// Cache entry
135#[derive(Clone)]
136struct Entry {
137    response: Response<Bytes>,
138    /// Time it took to generate the response for given entry.
139    /// Used for x-fetch algorithm.
140    delta: f64,
141    expires: Instant,
142}
143
144impl Entry {
145    /// Probabilistically decide if we need to refresh the given cache entry early.
146    /// This is an implementation of x-fetch algorigthm, see:
147    /// https://en.wikipedia.org/wiki/Cache_stampede#Probabilistic_early_expiration
148    fn need_to_refresh(&self, now: Instant, beta: f64) -> bool {
149        // fast path
150        if beta == 0.0 {
151            return false;
152        }
153
154        let rnd = rand::random::<f64>();
155        let xfetch = -(self.delta * beta * rnd.ln());
156        let ttl_left = (self.expires - now).as_secs_f64();
157
158        xfetch > ttl_left
159    }
160}
161
162/// No-op cache bypasser that never bypasses
163#[derive(Debug, Clone)]
164pub struct NoopBypasser;
165
166impl Bypasser for NoopBypasser {
167    type BypassReason = CustomBypassReasonDummy;
168
169    fn bypass<T>(&self, _req: &Request<T>) -> Result<Option<Self::BypassReason>, CacheError> {
170        Ok(None)
171    }
172}
173
174/// Cache metrics
175#[derive(Clone)]
176pub struct Metrics {
177    lock_await: HistogramVec,
178    requests_count: CounterVec,
179    requests_duration: HistogramVec,
180    ttl: Histogram,
181    x_fetch: Counter,
182    memory: IntGauge,
183    entries: IntGauge,
184}
185
186impl Metrics {
187    /// Create new `Metrics`
188    pub fn new(registry: &Registry) -> Self {
189        let lbls = &["cache_status", "cache_bypass_reason"];
190
191        Self {
192            lock_await: register_histogram_vec_with_registry!(
193                "cache_proxy_lock_await",
194                "Time spent waiting for the proxy cache lock",
195                &["lock_obtained"],
196                registry,
197            )
198            .unwrap(),
199
200            requests_count: register_counter_vec_with_registry!(
201                "cache_requests_count",
202                "Cache requests count",
203                lbls,
204                registry,
205            )
206            .unwrap(),
207
208            requests_duration: register_histogram_vec_with_registry!(
209                "cache_requests_duration",
210                "Time it took to execute the request",
211                lbls,
212                registry,
213            )
214            .unwrap(),
215
216            ttl: register_histogram_with_registry!(
217                "cache_ttl",
218                "TTL that was set when storing the response",
219                vec![1.0, 10.0, 100.0, 1000.0, 10000.0, 86400.0],
220                registry,
221            )
222            .unwrap(),
223
224            x_fetch: register_counter_with_registry!(
225                "cache_xfetch_count",
226                "Number of requests that x-fetch refreshed",
227                registry,
228            )
229            .unwrap(),
230
231            memory: register_int_gauge_with_registry!(
232                "cache_memory",
233                "Memory usage by the cache in bytes",
234                registry,
235            )
236            .unwrap(),
237
238            entries: register_int_gauge_with_registry!(
239                "cache_entries",
240                "Count of entries in the cache",
241                registry,
242            )
243            .unwrap(),
244        }
245    }
246}
247
248/// Cache options
249pub struct Opts {
250    pub cache_size: u64,
251    pub max_item_size: usize,
252    pub ttl: Duration,
253    pub max_ttl: Duration,
254    pub obey_cache_control: bool,
255    pub lock_timeout: Duration,
256    pub body_timeout: Duration,
257    pub xfetch_beta: f64,
258    pub methods: Vec<Method>,
259}
260
261impl Default for Opts {
262    fn default() -> Self {
263        Self {
264            cache_size: 128 * 1024 * 1024,
265            max_item_size: 16 * 1024 * 1024,
266            ttl: Duration::from_secs(10),
267            max_ttl: Duration::from_secs(86400),
268            obey_cache_control: false,
269            lock_timeout: Duration::from_secs(5),
270            body_timeout: Duration::from_secs(60),
271            xfetch_beta: 0.0,
272            methods: vec![Method::GET],
273        }
274    }
275}
276
277#[derive(Debug, PartialEq, Eq)]
278enum CacheControl {
279    NoCache,
280    MaxAge(Duration),
281}
282
283/// Tries to infer the caching TTL from the response headers
284fn infer_ttl<T>(req: &Response<T>) -> Option<CacheControl> {
285    // Extract the Cache-Control header & try to parse it as a string
286    let hdr = req
287        .headers()
288        .get(CACHE_CONTROL)
289        .and_then(|x| x.to_str().ok())?;
290
291    // Iterate over the key-value pairs (or just keys)
292    hdr.split(',').find_map(|x| {
293        let (k, v) = {
294            let mut split = x.split('=').map(|s| s.trim());
295            (split.next().unwrap(), split.next())
296        };
297
298        if ["no-cache", "no-store"].contains(&k) {
299            Some(CacheControl::NoCache)
300        } else if k == "max-age" {
301            let v = v.and_then(|x| x.parse::<u64>().ok());
302            if v == Some(0) {
303                Some(CacheControl::NoCache)
304            } else {
305                v.map(|x| CacheControl::MaxAge(Duration::from_secs(x)))
306            }
307        } else {
308            None
309        }
310    })
311}
312
313/// Extracts TTL from the Entry
314struct Expirer<K: KeyExtractor>(PhantomData<K>);
315
316impl<K: KeyExtractor> Expiry<K::Key, Arc<Entry>> for Expirer<K> {
317    fn expire_after_create(
318        &self,
319        _key: &K::Key,
320        value: &Arc<Entry>,
321        created_at: Instant,
322    ) -> Option<Duration> {
323        Some(value.expires - created_at)
324    }
325}
326
327/// Builds a cache using some overridable defaults
328pub struct CacheBuilder<K: KeyExtractor, B: Bypasser> {
329    key_extractor: K,
330    bypasser: Option<B>,
331    opts: Opts,
332    registry: Registry,
333}
334
335impl<K: KeyExtractor> CacheBuilder<K, NoopBypasser> {
336    /// Create new `CacheBuilder`
337    pub fn new(key_extractor: K) -> Self {
338        Self {
339            key_extractor,
340            bypasser: None,
341            opts: Opts::default(),
342            registry: Registry::new(),
343        }
344    }
345}
346
347impl<K: KeyExtractor, B: Bypasser> CacheBuilder<K, B> {
348    /// Create new `CacheBuilder` with a bypasser
349    pub fn new_with_bypasser(key_extractor: K, bypasser: B) -> Self {
350        Self {
351            key_extractor,
352            bypasser: Some(bypasser),
353            opts: Opts::default(),
354            registry: Registry::new(),
355        }
356    }
357
358    /// Sets the cache size. Default 128MB.
359    pub const fn cache_size(mut self, v: u64) -> Self {
360        self.opts.cache_size = v;
361        self
362    }
363
364    /// Sets the maximum entry size. Default 16MB.
365    pub const fn max_item_size(mut self, v: usize) -> Self {
366        self.opts.max_item_size = v;
367        self
368    }
369
370    /// Sets the default cache entry TTL. Default 10 sec.
371    pub const fn ttl(mut self, v: Duration) -> Self {
372        self.opts.ttl = v;
373        self
374    }
375
376    /// Sets the maximum cache entry TTL that can be overriden by `Cache-Control` header. Default 1 day.
377    pub const fn max_ttl(mut self, v: Duration) -> Self {
378        self.opts.max_ttl = v;
379        self
380    }
381
382    /// Sets the cache lock timeout. Default 5 sec.
383    pub const fn lock_timeout(mut self, v: Duration) -> Self {
384        self.opts.lock_timeout = v;
385        self
386    }
387
388    /// Sets the body reading timeout. Default 1 min.
389    pub const fn body_timeout(mut self, v: Duration) -> Self {
390        self.opts.body_timeout = v;
391        self
392    }
393
394    /// Sets the beta term of X-Fetch algorithm. Default 0.0
395    pub const fn xfetch_beta(mut self, v: f64) -> Self {
396        self.opts.xfetch_beta = v;
397        self
398    }
399
400    /// Sets cacheable methods. Defaults to only GET.
401    pub fn methods(mut self, v: &[Method]) -> Self {
402        self.opts.methods = v.into();
403        self
404    }
405
406    /// Whether to obey `Cache-Control` headers in the *response*. Defaults to false.
407    pub const fn obey_cache_control(mut self, v: bool) -> Self {
408        self.opts.obey_cache_control = v;
409        self
410    }
411
412    /// Sets the metrics registry to use.
413    pub fn registry(mut self, v: &Registry) -> Self {
414        self.registry = v.clone();
415        self
416    }
417
418    /// Try to build the cache from this builder
419    pub fn build(self) -> Result<Cache<K, B>, CacheError> {
420        Cache::new(self.opts, self.key_extractor, self.bypasser, &self.registry)
421    }
422}
423
424/// HTTP Cache
425pub struct Cache<K: KeyExtractor, B: Bypasser = NoopBypasser> {
426    store: MokaCache<K::Key, Arc<Entry>, RandomState>,
427    locks: MokaCache<K::Key, Arc<Mutex<()>>, RandomState>,
428    key_extractor: K,
429    bypasser: Option<B>,
430    metrics: Metrics,
431    opts: Opts,
432}
433
434fn weigh_entry<K: KeyExtractor>(_k: &K::Key, v: &Arc<Entry>) -> u32 {
435    let mut size = size_of::<K::Key>() + size_of::<Arc<Entry>>();
436
437    size += calc_headers_size(v.response.headers());
438    size += v.response.body().len();
439
440    size as u32
441}
442
443impl<K: KeyExtractor + 'static, B: Bypasser + 'static> Cache<K, B> {
444    /// Create new `Cache`
445    pub fn new(
446        opts: Opts,
447        key_extractor: K,
448        bypasser: Option<B>,
449        registry: &Registry,
450    ) -> Result<Self, CacheError> {
451        if opts.max_item_size as u64 >= opts.cache_size {
452            return Err(CacheError::Other(
453                "Cache item size should be less than whole cache size".into(),
454            ));
455        }
456
457        if opts.ttl > opts.max_ttl {
458            return Err(CacheError::Other("TTL should be <= max TTL".into()));
459        }
460
461        Ok(Self {
462            store: MokaCacheBuilder::new(opts.cache_size)
463                .expire_after(Expirer::<K>(PhantomData))
464                .weigher(weigh_entry::<K>)
465                .build_with_hasher(RandomState::default()),
466
467            // The params of the lock cache are somewhat arbitrary, maybe needs tuning
468            locks: MokaCacheBuilder::new(32768)
469                .time_to_idle(Duration::from_secs(60))
470                .build_with_hasher(RandomState::default()),
471
472            key_extractor,
473            bypasser,
474            metrics: Metrics::new(registry),
475
476            opts,
477        })
478    }
479
480    /// Looks up the given entry
481    pub fn get(&self, key: &K::Key, now: Instant, beta: f64) -> Option<(Response, i64)> {
482        let val = self.store.get(key)?;
483
484        // Run x-fetch if configured and simulate the cache miss if we need to refresh the entry
485        if val.need_to_refresh(now, beta) {
486            self.metrics.x_fetch.inc();
487            return None;
488        }
489
490        let (mut parts, body) = val.response.clone().into_parts();
491        let ttl_left = if now < val.expires {
492            (val.expires - now).as_secs() as i64
493        } else {
494            -((now - val.expires).as_secs() as i64)
495        };
496
497        if ttl_left >= 0 {
498            parts.headers.insert(X_CACHE_TTL, ttl_left.into());
499        }
500
501        Some((Response::from_parts(parts, Body::from(body)), ttl_left))
502    }
503
504    /// Insert a new entry into the cache
505    pub fn insert(
506        &self,
507        key: K::Key,
508        now: Instant,
509        ttl: Duration,
510        delta: Duration,
511        response: Response<Bytes>,
512    ) {
513        self.metrics.ttl.observe(ttl.as_secs_f64());
514
515        self.store.insert(
516            key,
517            Arc::new(Entry {
518                response,
519                delta: delta.as_secs_f64(),
520                expires: now + ttl,
521            }),
522        );
523    }
524
525    /// Process the HTTP request
526    pub async fn process_request(
527        &self,
528        request: Request,
529        next: Next,
530    ) -> Result<Response, CacheError> {
531        let now = Instant::now();
532        let (cache_status, response) = self.process_inner(now, request, next).await?;
533
534        // Record metrics
535        let cache_status_str: &'static str = (&cache_status).into();
536        let cache_bypass_reason_str: &'static str = match cache_status.clone() {
537            CacheStatus::Bypass(v) => v.into_str(),
538            _ => "none",
539        };
540
541        let labels = &[cache_status_str, cache_bypass_reason_str];
542
543        self.metrics.requests_count.with_label_values(labels).inc();
544        self.metrics
545            .requests_duration
546            .with_label_values(labels)
547            .observe(now.elapsed().as_secs_f64());
548
549        Ok(cache_status.with_response(response))
550    }
551
552    async fn process_inner(
553        &self,
554        now: Instant,
555        request: Request,
556        next: Next,
557    ) -> Result<(CacheStatus<B::BypassReason>, Response), CacheError> {
558        // Check if we have bypasser configured
559        if let Some(b) = &self.bypasser {
560            // Run it
561            if let Ok(v) = b.bypass(&request) {
562                // If it decided to bypass - return the custom reason
563                if let Some(r) = v {
564                    return Ok((
565                        CacheStatus::Bypass(CacheBypassReason::Custom(r)),
566                        next.run(request).await,
567                    ));
568                }
569            } else {
570                return Ok((
571                    CacheStatus::Bypass(CacheBypassReason::UnableToRunBypasser),
572                    next.run(request).await,
573                ));
574            }
575        }
576
577        // Check the method
578        if !self.opts.methods.contains(request.method()) {
579            return Ok((
580                CacheStatus::Bypass(CacheBypassReason::MethodNotCacheable),
581                next.run(request).await,
582            ));
583        }
584
585        // Use cached response if found
586        let Ok(key) = self.key_extractor.extract(&request) else {
587            return Ok((
588                CacheStatus::Bypass(CacheBypassReason::UnableToExtractKey),
589                next.run(request).await,
590            ));
591        };
592
593        if let Some((v, ttl_left)) = self.get(&key, now, self.opts.xfetch_beta) {
594            return Ok((CacheStatus::Hit(ttl_left), v));
595        }
596
597        // Get synchronization lock to handle parallel requests
598        let lock = self
599            .locks
600            .get_with_by_ref(&key, || Arc::new(Mutex::new(())));
601
602        // Holds the guard (if we got one) so that it stays locked across the
603        // backend call & cache insert below, actually serializing concurrent
604        // requests for the same key instead of releasing it immediately.
605        let mut guard = None;
606        select! {
607            // Only one parallel request should execute and populate the cache.
608            // Other requests will wait for the lock to be released and get results from the cache.
609            g = lock.lock() => {
610                guard = Some(g);
611            }
612
613            // We proceed with the request as is if takes too long to get the lock
614            _ = sleep(self.opts.lock_timeout) => {}
615        }
616
617        // Record prometheus metrics for the time spent waiting for the lock
618        self.metrics
619            .lock_await
620            .with_label_values(&[if guard.is_some() { "yes" } else { "no" }])
621            .observe(now.elapsed().as_secs_f64());
622
623        // Check again the cache in case some other request filled it
624        // while we were waiting for the lock
625        if let Some((v, ttl_left)) = self.get(&key, now, 0.0) {
626            return Ok((CacheStatus::Hit(ttl_left), v));
627        }
628
629        // Otherwise pass the request forward
630        let now = Instant::now();
631        let result = match self.pass_request(request, next).await? {
632            // If the body was fetched - cache it
633            ResponseType::Fetched(v, ttl) => {
634                let delta = now.elapsed();
635                self.insert(key, now + delta, ttl, delta, v.clone());
636
637                let ttl = ttl.as_secs();
638                let (mut parts, body) = v.into_parts();
639                parts.headers.insert(X_CACHE_TTL, ttl.into());
640                let response = Response::from_parts(parts, Body::from(body));
641                (CacheStatus::Miss(ttl as i64), response)
642            }
643
644            // Otherwise just pass it up
645            ResponseType::Streamed(v, reason) => (CacheStatus::Bypass(reason), v),
646        };
647
648        // Release the lock only now that the cache has been populated (or the
649        // request has been fully handled), so that other requests waiting on
650        // it actually observe a filled cache instead of racing to the backend.
651        drop(guard);
652
653        Ok(result)
654    }
655
656    // Passes the request down the line and conditionally fetches the response body
657    async fn pass_request(
658        &self,
659        request: Request,
660        next: Next,
661    ) -> Result<ResponseType<B::BypassReason>, CacheError> {
662        // Execute the response & get the headers
663        let response = next.run(request).await;
664
665        // Do not cache non-2xx responses
666        if !response.status().is_success() {
667            return Ok(ResponseType::Streamed(
668                response,
669                CacheBypassReason::HTTPError,
670            ));
671        }
672
673        // Extract content length from the response header if there's one
674        let body_size = response.body().size_hint().exact().map(|x| x as usize);
675
676        // Do not cache responses that have no known size (probably streaming etc)
677        let Some(body_size) = body_size else {
678            return Ok(ResponseType::Streamed(
679                response,
680                CacheBypassReason::SizeUnknown,
681            ));
682        };
683
684        // Do not cache items larger than configured
685        if body_size > self.opts.max_item_size {
686            return Ok(ResponseType::Streamed(
687                response,
688                CacheBypassReason::BodyTooBig,
689            ));
690        }
691
692        // Infer the TTL if requested to obey Cache-Control headers
693        let ttl = if self.opts.obey_cache_control {
694            let ttl = infer_ttl(&response);
695
696            match ttl {
697                // Do not cache if we're asked not to
698                Some(CacheControl::NoCache) => {
699                    return Ok(ResponseType::Streamed(
700                        response,
701                        CacheBypassReason::CacheControl,
702                    ));
703                }
704
705                // Use TTL from max-age while capping it to max_ttl
706                Some(CacheControl::MaxAge(v)) => v.min(self.opts.max_ttl),
707
708                // Otherwise use default
709                None => self.opts.ttl,
710            }
711        } else {
712            self.opts.ttl
713        };
714
715        // Read the response body into a buffer
716        let (parts, body) = response.into_parts();
717        let body = buffer_body(body, body_size, self.opts.body_timeout)
718            .await
719            .map_err(|e| match e {
720                HttpError::BodyTooBig => CacheError::FetchBodyTooBig,
721                HttpError::BodyTimedOut => CacheError::FetchBodyTimeout,
722                _ => CacheError::FetchBody(e.to_string()),
723            })?;
724
725        Ok(ResponseType::Fetched(
726            Response::from_parts(parts, body),
727            ttl,
728        ))
729    }
730}
731
732#[async_trait]
733impl<K: KeyExtractor, B: Bypasser> Run for Cache<K, B> {
734    async fn run(&self, _: CancellationToken) -> Result<(), anyhow::Error> {
735        self.store.run_pending_tasks();
736        self.metrics.memory.set(self.store.weighted_size() as i64);
737        self.metrics.entries.set(self.store.entry_count() as i64);
738        Ok(())
739    }
740}
741
742#[cfg(test)]
743impl<K: KeyExtractor + 'static, B: Bypasser + 'static> Cache<K, B> {
744    pub fn housekeep(&self) {
745        self.store.run_pending_tasks();
746        self.locks.run_pending_tasks();
747    }
748
749    pub fn size(&self) -> u64 {
750        self.store.weighted_size()
751    }
752
753    #[allow(clippy::len_without_is_empty)]
754    pub fn len(&self) -> u64 {
755        self.store.entry_count()
756    }
757
758    pub fn clear(&self) {
759        self.store.invalidate_all();
760        self.locks.invalidate_all();
761        self.housekeep();
762    }
763}
764
765/// Key extractor that is keyed by URI and a `Range` header
766#[derive(Clone, Debug)]
767pub struct KeyExtractorUriRange;
768
769impl KeyExtractor for KeyExtractorUriRange {
770    type Key = [u8; 20];
771
772    fn extract<T>(&self, request: &Request<T>) -> Result<Self::Key, CacheError> {
773        let authority = extract_authority(request)
774            .ok_or_else(|| CacheError::ExtractKey("no authority found".into()))?
775            .as_bytes();
776        let paq = request
777            .uri()
778            .path_and_query()
779            .ok_or_else(|| CacheError::ExtractKey("no path_and_query found".into()))?
780            .as_str()
781            .as_bytes();
782
783        // Compute a composite hash
784        let mut hash = Sha1::new().chain_update(authority).chain_update(paq);
785        if let Some(v) = request.headers().get(RANGE) {
786            hash = hash.chain_update(v.as_bytes());
787        }
788
789        Ok(hash.finalize().into())
790    }
791}
792
793#[cfg(test)]
794mod tests {
795    use crate::hval;
796
797    use super::*;
798
799    use axum::{
800        Router,
801        body::to_bytes,
802        extract::State,
803        middleware::from_fn_with_state,
804        response::IntoResponse,
805        routing::{get, post},
806    };
807    use http::{Request, Response, StatusCode, Uri};
808    use sha1::Digest;
809    use tower::{Service, ServiceExt};
810
811    #[derive(Clone, Debug)]
812    pub struct KeyExtractorTest;
813
814    impl KeyExtractor for KeyExtractorTest {
815        type Key = [u8; 20];
816
817        fn extract<T>(&self, request: &Request<T>) -> Result<Self::Key, CacheError> {
818            let paq = request
819                .uri()
820                .path_and_query()
821                .ok_or_else(|| CacheError::ExtractKey("no path_and_query found".into()))?
822                .as_str()
823                .as_bytes();
824
825            let hash: [u8; 20] = sha1::Sha1::new().chain_update(paq).finalize().into();
826            Ok(hash)
827        }
828    }
829
830    const MAX_ITEM_SIZE: usize = 1024;
831    const MAX_CACHE_SIZE: u64 = 32768;
832    const PROXY_LOCK_TIMEOUT: Duration = Duration::from_secs(1);
833
834    async fn dispatch_get_request(router: &mut Router, uri: String) -> Option<CacheStatus> {
835        let req = Request::get(uri).body(Body::from("")).unwrap();
836        let result = router.call(req).await.unwrap();
837        assert_eq!(result.status(), StatusCode::OK);
838        result.extensions().get::<CacheStatus>().cloned()
839    }
840
841    async fn handler(_request: Request<Body>) -> impl IntoResponse {
842        "test_body"
843    }
844
845    async fn handler_proxy_cache_lock(request: Request<Body>) -> impl IntoResponse {
846        if request.uri().path().contains("slow_response") {
847            sleep(2 * PROXY_LOCK_TIMEOUT).await;
848        } else if request.uri().path().contains("medium_response") {
849            // Slower than an instant response but well within the lock timeout,
850            // so concurrent requests actually have to wait on the lock rather
851            // than falling through via the lock-wait timeout (as "slow_response"
852            // does) or completing so fast that scheduling luck alone produces
853            // a single miss (as "fast_response" does). This is the only case
854            // that actually exercises the lock holding across the backend call.
855            sleep(PROXY_LOCK_TIMEOUT / 4).await;
856        }
857
858        "test_body"
859    }
860
861    async fn handler_too_big(_request: Request<Body>) -> impl IntoResponse {
862        "a".repeat(MAX_ITEM_SIZE + 1)
863    }
864
865    async fn handler_cache_control_max_age_1d(_request: Request<Body>) -> impl IntoResponse {
866        [(CACHE_CONTROL, "max-age=86400")]
867    }
868
869    async fn handler_cache_control_max_age_7d(_request: Request<Body>) -> impl IntoResponse {
870        [(CACHE_CONTROL, "max-age=604800")]
871    }
872
873    async fn handler_cache_control_no_cache(_request: Request<Body>) -> impl IntoResponse {
874        [(CACHE_CONTROL, "no-cache")]
875    }
876
877    async fn handler_cache_control_no_store(_request: Request<Body>) -> impl IntoResponse {
878        [(CACHE_CONTROL, "no-store")]
879    }
880
881    async fn middleware(
882        State(cache): State<Arc<Cache<KeyExtractorTest>>>,
883        request: Request<Body>,
884        next: Next,
885    ) -> impl IntoResponse {
886        cache
887            .process_request(request, next)
888            .await
889            .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
890    }
891
892    #[test]
893    fn test_bypass_reason_serialize() {
894        #[derive(Debug, Clone, Display, PartialEq, Eq, IntoStaticStr)]
895        #[strum(serialize_all = "snake_case")]
896        enum CustomReasonTest {
897            Bar,
898        }
899        impl CustomBypassReason for CustomReasonTest {}
900
901        let a: CacheBypassReason<CustomReasonTest> =
902            CacheBypassReason::Custom(CustomReasonTest::Bar);
903        let txt = a.into_str();
904        assert_eq!(txt, "bar");
905
906        let a: CacheBypassReason<CustomReasonTest> = CacheBypassReason::BodyTooBig;
907        let txt = a.into_str();
908        assert_eq!(txt, "body_too_big");
909    }
910
911    #[test]
912    fn test_key_extractor_uri_range() {
913        let x = KeyExtractorUriRange;
914
915        // Baseline
916        let mut req = Request::new("foo");
917        *req.uri_mut() = Uri::from_static("http://foo.bar.baz:80/foo/bar?abc=1");
918        let key1 = x.extract(&req).unwrap();
919
920        // Make sure that changing authority/path/query changes the key
921        let mut req = Request::new("foo");
922        *req.uri_mut() = Uri::from_static("http://foo.bar.baz:80/foo/bar?abc=2");
923        let key2 = x.extract(&req).unwrap();
924        assert_ne!(key1, key2);
925
926        let mut req = Request::new("foo");
927        *req.uri_mut() = Uri::from_static("http://foo.bar.baz:80/foo/ba?abc=1");
928        let key2 = x.extract(&req).unwrap();
929        assert_ne!(key1, key2);
930
931        let mut req = Request::new("foo");
932        *req.uri_mut() = Uri::from_static("http://foo.bar.ba:80/foo/bar?abc=1");
933        let key2 = x.extract(&req).unwrap();
934        assert_ne!(key1, key2);
935
936        // Make sure that changing schema doesn't affect the key
937        let mut req = Request::new("foo");
938        *req.uri_mut() = Uri::from_static("https://foo.bar.baz:80/foo/bar?abc=1");
939        let key2 = x.extract(&req).unwrap();
940        assert_eq!(key1, key2);
941
942        // Make sure that adding Range header changes the key
943        let mut req = Request::new("foo");
944        *req.uri_mut() = Uri::from_static("http://foo.bar.bar:80/foo/bar?abc=1");
945        (*req.headers_mut()).insert(RANGE, hval!("1000-2000"));
946        let key2 = x.extract(&req).unwrap();
947        assert_ne!(key1, key2);
948    }
949
950    #[test]
951    fn test_infer_ttl() {
952        let mut req = Response::new(());
953
954        assert_eq!(infer_ttl(&req), None);
955
956        // Don't cache
957        req.headers_mut().insert(CACHE_CONTROL, hval!("no-cache"));
958        assert_eq!(infer_ttl(&req), Some(CacheControl::NoCache));
959
960        req.headers_mut().insert(CACHE_CONTROL, hval!("no-store"));
961        assert_eq!(infer_ttl(&req), Some(CacheControl::NoCache));
962
963        req.headers_mut()
964            .insert(CACHE_CONTROL, hval!("no-store, no-cache"));
965        assert_eq!(infer_ttl(&req), Some(CacheControl::NoCache));
966
967        // Order matters
968        req.headers_mut()
969            .insert(CACHE_CONTROL, hval!("no-store, no-cache, max-age=1"));
970        assert_eq!(infer_ttl(&req), Some(CacheControl::NoCache));
971
972        req.headers_mut()
973            .insert(CACHE_CONTROL, hval!("max-age=1, no-store, no-cache"));
974        assert_eq!(
975            infer_ttl(&req),
976            Some(CacheControl::MaxAge(Duration::from_secs(1)))
977        );
978
979        // Max-age
980        req.headers_mut()
981            .insert(CACHE_CONTROL, hval!("max-age=86400"));
982        assert_eq!(
983            infer_ttl(&req),
984            Some(CacheControl::MaxAge(Duration::from_secs(86400)))
985        );
986        req.headers_mut().insert(CACHE_CONTROL, hval!("max-age=0"));
987        assert_eq!(infer_ttl(&req), Some(CacheControl::NoCache));
988
989        req.headers_mut()
990            .insert(CACHE_CONTROL, hval!("max-age=foo"));
991        assert_eq!(infer_ttl(&req), None);
992
993        req.headers_mut().insert(CACHE_CONTROL, hval!("max-age="));
994        assert_eq!(infer_ttl(&req), None);
995
996        req.headers_mut().insert(CACHE_CONTROL, hval!("max-age=-1"));
997        assert_eq!(infer_ttl(&req), None);
998
999        // Empty
1000        req.headers_mut().insert(CACHE_CONTROL, hval!(""));
1001        assert_eq!(infer_ttl(&req), None);
1002
1003        // Broken
1004        req.headers_mut()
1005            .insert(CACHE_CONTROL, hval!(", =foobar, "));
1006        assert_eq!(infer_ttl(&req), None);
1007    }
1008
1009    #[test]
1010    fn test_cache_creation_errors() {
1011        let cache = CacheBuilder::new(KeyExtractorTest)
1012            .cache_size(1)
1013            .max_item_size(2)
1014            .build();
1015        assert!(cache.is_err());
1016
1017        let cache = CacheBuilder::new(KeyExtractorTest)
1018            .ttl(Duration::from_secs(2))
1019            .max_ttl(Duration::from_secs(1))
1020            .build();
1021        assert!(cache.is_err());
1022    }
1023
1024    #[tokio::test]
1025    async fn test_cache_bypass() {
1026        let cache = Arc::new(
1027            CacheBuilder::new(KeyExtractorTest)
1028                .max_item_size(MAX_ITEM_SIZE)
1029                .build()
1030                .unwrap(),
1031        );
1032
1033        let mut app = Router::new()
1034            .route("/", post(handler))
1035            .route("/", get(handler))
1036            .route("/too_big", get(handler_too_big))
1037            .layer(from_fn_with_state(Arc::clone(&cache), middleware));
1038
1039        // Test only GET requests are cached.
1040        let req = Request::post("/").body(Body::from("")).unwrap();
1041        let result = app.call(req).await.unwrap();
1042        assert_eq!(result.status(), StatusCode::OK);
1043        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1044        assert_eq!(cache.len(), 0);
1045        assert_eq!(
1046            cache_status,
1047            CacheStatus::Bypass(CacheBypassReason::MethodNotCacheable)
1048        );
1049
1050        // Test non-2xx response are not cached
1051        let req = Request::get("/non_existing_path")
1052            .body(Body::from("foobar"))
1053            .unwrap();
1054        let result = app.call(req).await.unwrap();
1055        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1056        assert_eq!(result.status(), StatusCode::NOT_FOUND);
1057        assert_eq!(
1058            cache_status,
1059            CacheStatus::Bypass(CacheBypassReason::HTTPError)
1060        );
1061        assert_eq!(cache.len(), 0);
1062
1063        // Test body too big
1064        let req = Request::get("/too_big").body(Body::from("foobar")).unwrap();
1065        let result = app.call(req).await.unwrap();
1066        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1067        assert_eq!(
1068            cache_status,
1069            CacheStatus::Bypass(CacheBypassReason::BodyTooBig)
1070        );
1071        assert_eq!(result.status(), StatusCode::OK);
1072        assert_eq!(cache.len(), 0);
1073    }
1074
1075    #[tokio::test]
1076    async fn test_cache_hit() {
1077        let ttl = Duration::from_millis(1500);
1078
1079        let cache = Arc::new(
1080            CacheBuilder::new(KeyExtractorTest)
1081                .cache_size(MAX_CACHE_SIZE)
1082                .max_item_size(MAX_ITEM_SIZE)
1083                .ttl(ttl)
1084                .build()
1085                .unwrap(),
1086        );
1087
1088        let mut app = Router::new()
1089            .route("/{key}", get(handler))
1090            .layer(from_fn_with_state(Arc::clone(&cache), middleware));
1091
1092        // First request doesn't hit the cache, but is stored in the cache
1093        let req = Request::get("/1").body(Body::from("")).unwrap();
1094        let result = app.call(req).await.unwrap();
1095        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1096        assert_eq!(result.status(), StatusCode::OK);
1097        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1098        cache.housekeep();
1099        assert_eq!(cache.len(), 1);
1100
1101        // Next request doesn't hit the cache, but is stored in the cache
1102        let req = Request::get("/2").body(Body::from("")).unwrap();
1103        let result = app.call(req).await.unwrap();
1104        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1105        assert_eq!(result.status(), StatusCode::OK);
1106        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1107        cache.housekeep();
1108        assert_eq!(cache.len(), 2);
1109
1110        // Next request hits the cache
1111        let req = Request::get("/1").body(Body::from("")).unwrap();
1112        let result = app.call(req).await.unwrap();
1113        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1114        assert_eq!(result.status(), StatusCode::OK);
1115        assert!(matches!(cache_status, CacheStatus::Hit(_)));
1116        let (_, body) = result.into_parts();
1117        let body = to_bytes(body, usize::MAX).await.unwrap().to_vec();
1118        let body = String::from_utf8_lossy(&body);
1119        assert_eq!("test_body", body);
1120        cache.housekeep();
1121        assert_eq!(cache.len(), 2);
1122
1123        // Next request hits again
1124        let req = Request::get("/2").body(Body::from("")).unwrap();
1125        let result = app.call(req).await.unwrap();
1126        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1127        assert_eq!(result.status(), StatusCode::OK);
1128        assert!(matches!(cache_status, CacheStatus::Hit(_)));
1129        let (_, body) = result.into_parts();
1130        let body = to_bytes(body, usize::MAX).await.unwrap().to_vec();
1131        let body = String::from_utf8_lossy(&body);
1132        assert_eq!("test_body", body);
1133        cache.housekeep();
1134        assert_eq!(cache.len(), 2);
1135
1136        // After ttl, request doesn't hit the cache anymore
1137        sleep(ttl + Duration::from_millis(300)).await;
1138        cache.housekeep();
1139        let req = Request::get("/1").body(Body::from("")).unwrap();
1140        let result = app.call(req).await.unwrap();
1141        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1142        assert_eq!(result.status(), StatusCode::OK);
1143        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1144
1145        // Before cache_size limit is reached all requests should be stored in cache.
1146        cache.clear();
1147        let req_count = 50;
1148        // First dispatch round, all requests miss cache.
1149        for idx in 0..req_count {
1150            let status = dispatch_get_request(&mut app, format!("/{idx}")).await;
1151            assert!(matches!(status, Some(CacheStatus::Miss(_))));
1152        }
1153        // Second dispatch round, all requests hit the cache.
1154        for idx in 0..req_count {
1155            let status = dispatch_get_request(&mut app, format!("/{idx}")).await;
1156            assert!(matches!(status, Some(CacheStatus::Hit(_))));
1157        }
1158
1159        // Once cache_size limit is reached some requests should be evicted.
1160        cache.clear();
1161        let req_count = 500;
1162        // First dispatch round, all cache misses.
1163        for idx in 0..req_count {
1164            let status = dispatch_get_request(&mut app, format!("/{idx}")).await;
1165            assert!(matches!(status, Some(CacheStatus::Miss(_))));
1166        }
1167
1168        // Second dispatch round, some requests hit the cache, some don't
1169        let mut count_misses = 0;
1170        let mut count_hits = 0;
1171        for idx in 0..req_count {
1172            let status = dispatch_get_request(&mut app, format!("/{idx}")).await;
1173            if matches!(status, Some(CacheStatus::Miss(_))) {
1174                count_misses += 1;
1175            } else if matches!(status, Some(CacheStatus::Hit(_))) {
1176                count_hits += 1;
1177            }
1178        }
1179        assert!(count_misses > 0);
1180        assert!(count_hits > 0);
1181        cache.housekeep();
1182        let entry_size = cache.size() / cache.len();
1183
1184        // Make sure cache size limit was reached.
1185        // Check that adding one more entry to the cache would overflow its max capacity.
1186        assert!(MAX_CACHE_SIZE > cache.size());
1187        assert!(MAX_CACHE_SIZE < cache.size() + entry_size);
1188    }
1189
1190    #[tokio::test]
1191    async fn test_cache_control() {
1192        let cache = Arc::new(
1193            CacheBuilder::new(KeyExtractorTest)
1194                .obey_cache_control(true)
1195                .build()
1196                .unwrap(),
1197        );
1198
1199        let mut app = Router::new()
1200            .route("/", get(handler))
1201            .route(
1202                "/cache_control_no_store",
1203                get(handler_cache_control_no_store),
1204            )
1205            .route(
1206                "/cache_control_no_cache",
1207                get(handler_cache_control_no_cache),
1208            )
1209            .route(
1210                "/cache_control_max_age_1d",
1211                get(handler_cache_control_max_age_1d),
1212            )
1213            .route(
1214                "/cache_control_max_age_7d",
1215                get(handler_cache_control_max_age_7d),
1216            )
1217            .layer(from_fn_with_state(Arc::clone(&cache), middleware));
1218
1219        // Cache-Control no-cache
1220        let req = Request::get("/cache_control_no_cache")
1221            .body(Body::from("foobar"))
1222            .unwrap();
1223        let result = app.call(req).await.unwrap();
1224        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1225        assert_eq!(
1226            cache_status,
1227            CacheStatus::Bypass(CacheBypassReason::CacheControl)
1228        );
1229        assert_eq!(result.status(), StatusCode::OK);
1230        cache.housekeep();
1231        assert_eq!(cache.len(), 0);
1232
1233        // Cache-Control no-store
1234        let req = Request::get("/cache_control_no_store")
1235            .body(Body::from("foobar"))
1236            .unwrap();
1237        let result = app.call(req).await.unwrap();
1238        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1239        assert_eq!(
1240            cache_status,
1241            CacheStatus::Bypass(CacheBypassReason::CacheControl)
1242        );
1243        assert_eq!(result.status(), StatusCode::OK);
1244        cache.housekeep();
1245        assert_eq!(cache.len(), 0);
1246
1247        // Cache-Control max-age 1 day
1248        let req = Request::get("/cache_control_max_age_1d")
1249            .body(Body::from("foobar"))
1250            .unwrap();
1251        let result = app.call(req).await.unwrap();
1252        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1253        let ttl = result
1254            .headers()
1255            .get(X_CACHE_TTL)
1256            .unwrap()
1257            .to_str()
1258            .unwrap()
1259            .parse::<u64>()
1260            .unwrap();
1261        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1262        assert_eq!(ttl, 86400);
1263        assert_eq!(result.status(), StatusCode::OK);
1264        cache.housekeep();
1265        assert_eq!(cache.len(), 1);
1266
1267        // Cache-Control max-age 7 days should still be capped to 1 day
1268        let req = Request::get("/cache_control_max_age_7d")
1269            .body(Body::from("foobar"))
1270            .unwrap();
1271        let result = app.call(req).await.unwrap();
1272        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1273        let ttl = result
1274            .headers()
1275            .get(X_CACHE_TTL)
1276            .unwrap()
1277            .to_str()
1278            .unwrap()
1279            .parse::<u64>()
1280            .unwrap();
1281        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1282        assert_eq!(ttl, 86400);
1283        assert_eq!(result.status(), StatusCode::OK);
1284        cache.housekeep();
1285        assert_eq!(cache.len(), 2);
1286
1287        // w/o Cache-Control we should get a default 10s TTL
1288        let req = Request::get("/").body(Body::from("foobar")).unwrap();
1289        let result = app.call(req).await.unwrap();
1290        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1291        let ttl = result
1292            .headers()
1293            .get(X_CACHE_TTL)
1294            .unwrap()
1295            .to_str()
1296            .unwrap()
1297            .parse::<u64>()
1298            .unwrap();
1299        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1300        assert_eq!(ttl, 10);
1301        assert_eq!(result.status(), StatusCode::OK);
1302        cache.housekeep();
1303        assert_eq!(cache.len(), 3);
1304
1305        // Test when we do not obey
1306        let cache = Arc::new(
1307            CacheBuilder::new(KeyExtractorTest)
1308                .obey_cache_control(false)
1309                .build()
1310                .unwrap(),
1311        );
1312
1313        let mut app = Router::new()
1314            .route("/", get(handler))
1315            .route(
1316                "/cache_control_no_store",
1317                get(handler_cache_control_no_store),
1318            )
1319            .route(
1320                "/cache_control_no_cache",
1321                get(handler_cache_control_no_cache),
1322            )
1323            .route(
1324                "/cache_control_max_age_1d",
1325                get(handler_cache_control_max_age_1d),
1326            )
1327            .route(
1328                "/cache_control_max_age_7d",
1329                get(handler_cache_control_max_age_7d),
1330            )
1331            .layer(from_fn_with_state(Arc::clone(&cache), middleware));
1332
1333        // Cache-Control no-cache
1334        let req = Request::get("/cache_control_no_cache")
1335            .body(Body::from("foobar"))
1336            .unwrap();
1337        let result = app.call(req).await.unwrap();
1338        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1339        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1340        assert_eq!(result.status(), StatusCode::OK);
1341        cache.housekeep();
1342        assert_eq!(cache.len(), 1);
1343
1344        // Cache-Control no-store
1345        let req = Request::get("/cache_control_no_store")
1346            .body(Body::from("foobar"))
1347            .unwrap();
1348        let result = app.call(req).await.unwrap();
1349        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1350        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1351        assert_eq!(result.status(), StatusCode::OK);
1352        cache.housekeep();
1353        assert_eq!(cache.len(), 2);
1354
1355        // Cache-Control max-age 1 day
1356        let req = Request::get("/cache_control_max_age_1d")
1357            .body(Body::from("foobar"))
1358            .unwrap();
1359        let result = app.call(req).await.unwrap();
1360        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1361        let ttl = result
1362            .headers()
1363            .get(X_CACHE_TTL)
1364            .unwrap()
1365            .to_str()
1366            .unwrap()
1367            .parse::<u64>()
1368            .unwrap();
1369        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1370        assert_eq!(ttl, 10);
1371        assert_eq!(result.status(), StatusCode::OK);
1372        cache.housekeep();
1373        assert_eq!(cache.len(), 3);
1374
1375        // w/o Cache-Control we should get a default 10s TTL
1376        let req = Request::get("/").body(Body::from("foobar")).unwrap();
1377        let result = app.call(req).await.unwrap();
1378        let cache_status = result.extensions().get::<CacheStatus>().cloned().unwrap();
1379        let ttl = result
1380            .headers()
1381            .get(X_CACHE_TTL)
1382            .unwrap()
1383            .to_str()
1384            .unwrap()
1385            .parse::<u64>()
1386            .unwrap();
1387        assert!(matches!(cache_status, CacheStatus::Miss(_)));
1388        assert_eq!(ttl, 10);
1389        assert_eq!(result.status(), StatusCode::OK);
1390        cache.housekeep();
1391        assert_eq!(cache.len(), 4);
1392    }
1393
1394    #[tokio::test(start_paused = true)]
1395    async fn test_proxy_cache_lock() {
1396        let cache = Arc::new(
1397            CacheBuilder::new(KeyExtractorTest)
1398                .lock_timeout(PROXY_LOCK_TIMEOUT)
1399                .build()
1400                .unwrap(),
1401        );
1402
1403        let app = Router::new()
1404            .route("/{key}", get(handler_proxy_cache_lock))
1405            .layer(from_fn_with_state(Arc::clone(&cache), middleware));
1406
1407        let req_count = 50;
1408        // Expected cache misses/hits for fast/medium/slow responses, respectively.
1409        let expected_misses = [1, 1, req_count];
1410        let expected_hits = [req_count - 1, req_count - 1, 0];
1411        for (idx, uri) in ["/fast_response", "/medium_response", "/slow_response"]
1412            .iter()
1413            .enumerate()
1414        {
1415            let mut tasks = vec![];
1416            // Dispatch requests simultaneously.
1417            for _ in 0..req_count {
1418                let app = app.clone();
1419                tasks.push(tokio::spawn(async move {
1420                    let req = Request::get(*uri).body(Body::from("")).unwrap();
1421                    let result = app.oneshot(req).await.unwrap();
1422                    assert_eq!(result.status(), StatusCode::OK);
1423                    result.extensions().get::<CacheStatus>().cloned()
1424                }));
1425            }
1426            let mut count_hits = 0;
1427            let mut count_misses = 0;
1428            for task in tasks {
1429                task.await
1430                    .map(|res| match res {
1431                        Some(CacheStatus::Hit(_)) => count_hits += 1,
1432                        Some(CacheStatus::Miss(_)) => count_misses += 1,
1433                        _ => panic!("Unexpected cache status"),
1434                    })
1435                    .expect("failed to complete task");
1436            }
1437            assert_eq!(count_hits, expected_hits[idx]);
1438            assert_eq!(count_misses, expected_misses[idx]);
1439            cache.housekeep();
1440            cache.clear();
1441        }
1442    }
1443
1444    #[test]
1445    fn test_xfetch() {
1446        let now = Instant::now();
1447        let reqs = 10000;
1448
1449        let entry = Entry {
1450            response: Response::builder().body(Bytes::new()).unwrap(),
1451            delta: 0.5,
1452            expires: now + Duration::from_secs(60),
1453        };
1454
1455        // Check close to expiration
1456        let now2 = now + Duration::from_secs(58);
1457        let mut refresh = 0;
1458        for _ in 0..reqs {
1459            if entry.need_to_refresh(now2, 1.5) {
1460                refresh += 1;
1461            }
1462        }
1463
1464        assert!(refresh > 550 && refresh < 800);
1465
1466        // Check mid-expiration with small beta
1467        let now2 = now + Duration::from_secs(30);
1468        let mut refresh = 0;
1469        for _ in 0..reqs {
1470            if entry.need_to_refresh(now2, 1.0) {
1471                refresh += 1;
1472            }
1473        }
1474
1475        assert_eq!(refresh, 0);
1476
1477        // Check mid-expiration with high beta
1478        let now2 = now + Duration::from_secs(30);
1479        let mut refresh = 0;
1480        for _ in 0..reqs {
1481            if entry.need_to_refresh(now2, 10.0) {
1482                refresh += 1;
1483            }
1484        }
1485
1486        assert!(refresh > 8);
1487    }
1488}