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#[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
59pub trait KeyExtractor: Clone + Send + Sync + Debug + 'static {
61 type Key: Clone + Send + Sync + Debug + Hash + Eq + 'static;
63
64 fn extract<T>(&self, req: &Request<T>) -> Result<Self::Key, CacheError>;
66}
67
68pub trait CustomBypassReason:
70 Debug + Clone + std::fmt::Display + Into<&'static str> + PartialEq + Eq + Send + Sync + 'static
71{
72}
73
74pub trait Bypasser: Clone + Send + Sync + Debug + 'static {
76 type BypassReason: CustomBypassReason;
78
79 fn bypass<T>(&self, req: &Request<T>) -> Result<Option<Self::BypassReason>, CacheError>;
81}
82
83#[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#[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 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#[derive(Clone)]
136struct Entry {
137 response: Response<Bytes>,
138 delta: f64,
141 expires: Instant,
142}
143
144impl Entry {
145 fn need_to_refresh(&self, now: Instant, beta: f64) -> bool {
149 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#[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#[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 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
248pub 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
283fn infer_ttl<T>(req: &Response<T>) -> Option<CacheControl> {
285 let hdr = req
287 .headers()
288 .get(CACHE_CONTROL)
289 .and_then(|x| x.to_str().ok())?;
290
291 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
313struct 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
327pub 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 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 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 pub const fn cache_size(mut self, v: u64) -> Self {
360 self.opts.cache_size = v;
361 self
362 }
363
364 pub const fn max_item_size(mut self, v: usize) -> Self {
366 self.opts.max_item_size = v;
367 self
368 }
369
370 pub const fn ttl(mut self, v: Duration) -> Self {
372 self.opts.ttl = v;
373 self
374 }
375
376 pub const fn max_ttl(mut self, v: Duration) -> Self {
378 self.opts.max_ttl = v;
379 self
380 }
381
382 pub const fn lock_timeout(mut self, v: Duration) -> Self {
384 self.opts.lock_timeout = v;
385 self
386 }
387
388 pub const fn body_timeout(mut self, v: Duration) -> Self {
390 self.opts.body_timeout = v;
391 self
392 }
393
394 pub const fn xfetch_beta(mut self, v: f64) -> Self {
396 self.opts.xfetch_beta = v;
397 self
398 }
399
400 pub fn methods(mut self, v: &[Method]) -> Self {
402 self.opts.methods = v.into();
403 self
404 }
405
406 pub const fn obey_cache_control(mut self, v: bool) -> Self {
408 self.opts.obey_cache_control = v;
409 self
410 }
411
412 pub fn registry(mut self, v: &Registry) -> Self {
414 self.registry = v.clone();
415 self
416 }
417
418 pub fn build(self) -> Result<Cache<K, B>, CacheError> {
420 Cache::new(self.opts, self.key_extractor, self.bypasser, &self.registry)
421 }
422}
423
424pub 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 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 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 pub fn get(&self, key: &K::Key, now: Instant, beta: f64) -> Option<(Response, i64)> {
482 let val = self.store.get(key)?;
483
484 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 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 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 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 if let Some(b) = &self.bypasser {
560 if let Ok(v) = b.bypass(&request) {
562 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 if !self.opts.methods.contains(request.method()) {
579 return Ok((
580 CacheStatus::Bypass(CacheBypassReason::MethodNotCacheable),
581 next.run(request).await,
582 ));
583 }
584
585 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 let lock = self
599 .locks
600 .get_with_by_ref(&key, || Arc::new(Mutex::new(())));
601
602 let mut guard = None;
606 select! {
607 g = lock.lock() => {
610 guard = Some(g);
611 }
612
613 _ = sleep(self.opts.lock_timeout) => {}
615 }
616
617 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 if let Some((v, ttl_left)) = self.get(&key, now, 0.0) {
626 return Ok((CacheStatus::Hit(ttl_left), v));
627 }
628
629 let now = Instant::now();
631 let result = match self.pass_request(request, next).await? {
632 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 ResponseType::Streamed(v, reason) => (CacheStatus::Bypass(reason), v),
646 };
647
648 drop(guard);
652
653 Ok(result)
654 }
655
656 async fn pass_request(
658 &self,
659 request: Request,
660 next: Next,
661 ) -> Result<ResponseType<B::BypassReason>, CacheError> {
662 let response = next.run(request).await;
664
665 if !response.status().is_success() {
667 return Ok(ResponseType::Streamed(
668 response,
669 CacheBypassReason::HTTPError,
670 ));
671 }
672
673 let body_size = response.body().size_hint().exact().map(|x| x as usize);
675
676 let Some(body_size) = body_size else {
678 return Ok(ResponseType::Streamed(
679 response,
680 CacheBypassReason::SizeUnknown,
681 ));
682 };
683
684 if body_size > self.opts.max_item_size {
686 return Ok(ResponseType::Streamed(
687 response,
688 CacheBypassReason::BodyTooBig,
689 ));
690 }
691
692 let ttl = if self.opts.obey_cache_control {
694 let ttl = infer_ttl(&response);
695
696 match ttl {
697 Some(CacheControl::NoCache) => {
699 return Ok(ResponseType::Streamed(
700 response,
701 CacheBypassReason::CacheControl,
702 ));
703 }
704
705 Some(CacheControl::MaxAge(v)) => v.min(self.opts.max_ttl),
707
708 None => self.opts.ttl,
710 }
711 } else {
712 self.opts.ttl
713 };
714
715 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#[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 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 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 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 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 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 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 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 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 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 req.headers_mut().insert(CACHE_CONTROL, hval!(""));
1001 assert_eq!(infer_ttl(&req), None);
1002
1003 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 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 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 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 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 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 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 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 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 cache.clear();
1147 let req_count = 50;
1148 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 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 cache.clear();
1161 let req_count = 500;
1162 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}