1use super::*;
2
3impl CachedValue {
5 pub fn new(status_code: usize, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
17 Self {
18 status_code,
19 headers,
20 body,
21 stored_at_ms: cache_now_ms(),
22 }
23 }
24
25 pub fn bytes(body: Vec<u8>) -> Self {
35 Self::new(HttpStatus::Ok.code(), Vec::new(), body)
36 }
37
38 #[inline]
44 pub fn age_secs(&self) -> u64 {
45 cache_now_ms().saturating_sub(self.get_stored_at_ms()) / 1_000
46 }
47}
48
49impl Default for CacheConfig {
51 fn default() -> Self {
53 Self {
54 default_ttl_ms: DEFAULT_CACHE_TTL_MS,
55 max_entries: DEFAULT_CACHE_MAX_ENTRIES,
56 max_bytes: DEFAULT_CACHE_MAX_BYTES,
57 max_entry_bytes: DEFAULT_CACHE_MAX_ENTRY_BYTES,
58 bypass_authenticated: true,
59 emit_diagnostic_headers: true,
60 }
61 }
62}
63
64impl CacheConfig {
66 pub fn with_default_ttl_ms(mut self, ttl_ms: u64) -> Self {
76 self.set_default_ttl_ms(ttl_ms);
77 self
78 }
79
80 pub fn with_max_entries(mut self, max_entries: usize) -> Self {
90 self.set_max_entries(max_entries.max(1));
91 self
92 }
93
94 pub fn with_max_bytes(mut self, max_bytes: usize) -> Self {
104 self.set_max_bytes(max_bytes.max(1));
105 self
106 }
107}
108
109impl Default for ShardedMemoryCache {
111 fn default() -> Self {
113 Self::new(CacheConfig::default())
114 }
115}
116
117impl ShardedMemoryCache {
119 pub fn new(config: CacheConfig) -> Self {
129 let shards: Box<[CacheShard; CACHE_SHARD_COUNT]> =
130 Box::new(from_fn(|_: usize| CacheShard {
131 map: RwLock::new(hash_map_xx_hash3_64()),
132 }));
133 let inflight: InFlightShardArray =
134 Box::new(from_fn(|_: usize| Mutex::new(hash_map_xx_hash3_64())));
135 Self {
136 inner: Arc::new(ShardedMemoryCacheInner {
137 config,
138 entry_count: AtomicUsize::new(0),
139 total_bytes: AtomicUsize::new(0),
140 min_expires_at_ms: AtomicU64::new(u64::MAX),
141 shards,
142 inflight,
143 }),
144 }
145 }
146
147 #[inline(always)]
153 pub fn len(&self) -> usize {
154 let Self { inner } = self;
155 inner.entry_count.load(Ordering::Relaxed)
156 }
157
158 #[inline(always)]
164 pub fn is_empty(&self) -> bool {
165 self.len() == 0
166 }
167
168 #[inline(always)]
174 pub fn total_bytes(&self) -> usize {
175 let Self { inner } = self;
176 inner.total_bytes.load(Ordering::Relaxed)
177 }
178
179 #[inline]
191 pub(crate) fn get_entry_sync(&self, key: &str) -> Option<(Arc<CacheEntry>, u64)> {
192 let Self { inner } = self;
193 if inner.entry_count.load(Ordering::Relaxed) == 0 {
194 return None;
195 }
196 let idx: usize = cache_shard_index(key);
197 let entry: Arc<CacheEntry> = {
198 let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
199 inner.shards[idx].map.read().ok()?;
200 Arc::clone(guard.get(key)?)
201 };
202 let now_ms: u64 = cache_now_ms();
203 if now_ms < entry.expires_at_ms {
204 return Some((entry, now_ms));
205 }
206 if let Ok(mut guard) = inner.shards[idx].map.write()
207 && guard
208 .get(key)
209 .is_some_and(|cur: &Arc<CacheEntry>| now_ms >= cur.expires_at_ms)
210 && let Some(removed) = guard.remove(key)
211 {
212 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
213 inner
214 .total_bytes
215 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
216 }
217 None
218 }
219
220 #[inline]
230 pub fn get_sync(&self, key: &str) -> Option<CachedValue> {
231 let Self { inner } = self;
232 if inner.entry_count.load(Ordering::Relaxed) == 0 {
233 return None;
234 }
235 let idx: usize = cache_shard_index(key);
236 let expired_now_ms: u64 = {
237 let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
238 inner.shards[idx].map.read().ok()?;
239 let entry: &Arc<CacheEntry> = guard.get(key)?;
240 let now_ms: u64 = cache_now_ms();
241 if now_ms < entry.expires_at_ms {
242 return Some(entry.value.clone());
243 }
244 now_ms
245 };
246 if let Ok(mut guard) = inner.shards[idx].map.write()
247 && guard
248 .get(key)
249 .is_some_and(|cur: &Arc<CacheEntry>| expired_now_ms >= cur.expires_at_ms)
250 && let Some(removed) = guard.remove(key)
251 {
252 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
253 inner
254 .total_bytes
255 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
256 }
257 None
258 }
259
260 pub fn put_sync(&self, key: String, value: CachedValue, ttl_ms: u64) {
268 if ttl_ms == 0 {
269 return;
270 }
271 let Self { inner } = self;
272 let max_bytes: usize = inner.config.get_max_bytes();
273 let max_entries: usize = inner.config.get_max_entries();
274 let footprint: usize = estimate_entry_bytes(&key, &value);
275 if footprint > max_bytes {
276 return;
277 }
278 let now_ms: u64 = cache_now_ms();
279 let expires_at_ms: u64 = now_ms.saturating_add(ttl_ms);
280 let idx: usize = cache_shard_index(&key);
281 let mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
282 match inner.shards[idx].map.write() {
283 Ok(guard) => guard,
284 Err(_) => return,
285 };
286 if let Some(existing) = map.get_mut(&key) {
287 let prev_footprint: usize = existing.footprint_bytes;
288 let total_now: usize = inner.total_bytes.load(Ordering::Relaxed);
289 let projected_bytes: usize = total_now
290 .saturating_sub(prev_footprint)
291 .saturating_add(footprint);
292 if projected_bytes <= max_bytes {
293 if let Some(entry_mut) = Arc::get_mut(existing) {
294 entry_mut.value = value;
295 entry_mut.expires_at_ms = expires_at_ms;
296 entry_mut.footprint_bytes = footprint;
297 entry_mut.wire_cache = OnceLock::new();
298 } else {
299 *existing = Arc::new(CacheEntry {
300 value,
301 expires_at_ms,
302 footprint_bytes: footprint,
303 wire_cache: OnceLock::new(),
304 });
305 }
306 if footprint >= prev_footprint {
307 inner
308 .total_bytes
309 .fetch_add(footprint - prev_footprint, Ordering::Relaxed);
310 } else {
311 inner
312 .total_bytes
313 .fetch_sub(prev_footprint - footprint, Ordering::Relaxed);
314 }
315 inner
316 .min_expires_at_ms
317 .fetch_min(expires_at_ms, Ordering::Relaxed);
318 return;
319 }
320 if let Some(prev) = map.remove(&key) {
321 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
322 inner
323 .total_bytes
324 .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
325 }
326 }
327 if (inner.entry_count.load(Ordering::Relaxed) >= max_entries
328 || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes)
329 && now_ms >= inner.min_expires_at_ms.load(Ordering::Relaxed)
330 {
331 drop(map);
332 let _: usize = self.purge_expired();
333 map = match inner.shards[idx].map.write() {
334 Ok(guard) => guard,
335 Err(_) => return,
336 };
337 if let Some(prev) = map.remove(&key) {
338 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
339 inner
340 .total_bytes
341 .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
342 }
343 }
344 while (inner.entry_count.load(Ordering::Relaxed) >= max_entries
345 || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes)
346 && !map.is_empty()
347 {
348 let mut min_exp: u64 = u64::MAX;
349 for cur in map.values() {
350 if cur.expires_at_ms < min_exp {
351 min_exp = cur.expires_at_ms;
352 }
353 }
354 let mut evicted_footprint: Option<usize> = None;
355 map.retain(|_: &String, cur: &mut Arc<CacheEntry>| {
356 if evicted_footprint.is_none() && cur.expires_at_ms == min_exp {
357 evicted_footprint = Some(cur.footprint_bytes);
358 false
359 } else {
360 true
361 }
362 });
363 if let Some(evicted_bytes) = evicted_footprint {
364 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
365 inner
366 .total_bytes
367 .fetch_sub(evicted_bytes, Ordering::Relaxed);
368 } else {
369 break;
370 }
371 }
372 if inner.entry_count.load(Ordering::Relaxed) >= max_entries
373 || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes
374 {
375 return;
376 }
377 let entry: Arc<CacheEntry> = Arc::new(CacheEntry {
378 value,
379 expires_at_ms,
380 footprint_bytes: footprint,
381 wire_cache: OnceLock::new(),
382 });
383 map.insert(key, entry);
384 inner.entry_count.fetch_add(1, Ordering::Relaxed);
385 inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
386 inner
387 .min_expires_at_ms
388 .fetch_min(expires_at_ms, Ordering::Relaxed);
389 }
390
391 pub async fn get_or_load<F, Fut>(
403 &self,
404 key: &str,
405 ttl_ms: u64,
406 loader: F,
407 ) -> Option<CachedValue>
408 where
409 F: FnOnce() -> Fut,
410 Fut: Future<Output = Option<CachedValue>>,
411 {
412 if let Some(hit) = self.get_sync(key) {
413 return Some(hit);
414 }
415 let Self { inner } = self;
416 let idx: usize = cache_shard_index(key);
417 let (slot, is_leader): (Arc<InFlightSlot>, bool) = {
418 let Ok(mut guard) = inner.inflight[idx].lock() else {
419 return loader().await;
420 };
421 if let Some(existing) = guard.get(key) {
422 (Arc::clone(existing), false)
423 } else {
424 let created: Arc<InFlightSlot> = Arc::new(InFlightSlot {
425 notify: Notify::new(),
426 result: Mutex::new(None),
427 });
428 guard.insert(key.to_owned(), Arc::clone(&created));
429 (created, true)
430 }
431 };
432 if is_leader {
433 let loaded: Option<CachedValue> = loader().await;
434 if let Some(ref val) = loaded {
435 self.put_sync(key.to_owned(), val.clone(), ttl_ms);
436 }
437 if let Ok(mut res_guard) = slot.result.lock() {
438 *res_guard = Some(loaded.clone());
439 }
440 if let Ok(mut map_guard) = inner.inflight[idx].lock() {
441 map_guard.remove(key);
442 }
443 slot.notify.notify_waiters();
444 loaded
445 } else {
446 loop {
447 let notified: Notified<'_> = slot.notify.notified();
448 if let Ok(res_guard) = slot.result.lock()
449 && let Some(ref outcome) = *res_guard
450 {
451 return outcome.clone();
452 }
453 notified.await;
454 }
455 }
456 }
457}
458
459impl CacheStore for ShardedMemoryCache {
461 fn get<'a>(&'a self, key: &'a str) -> CacheFuture<'a, Option<CachedValue>> {
472 Box::pin(async move { self.get_sync(key) })
473 }
474
475 fn put(&self, key: String, value: CachedValue, ttl_ms: u64) -> CacheFuture<'_, ()> {
487 self.put_sync(key, value, ttl_ms);
488 Box::pin(async {})
489 }
490
491 fn remove<'a>(&'a self, key: &'a str) -> CacheFuture<'a, bool> {
502 let Self { inner } = self;
503 let idx: usize = cache_shard_index(key);
504 let removed: bool = inner.shards[idx]
505 .map
506 .write()
507 .ok()
508 .and_then(
509 |mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>| {
510 map.remove(key)
511 },
512 )
513 .map(|entry: Arc<CacheEntry>| {
514 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
515 inner
516 .total_bytes
517 .fetch_sub(entry.footprint_bytes, Ordering::Relaxed);
518 true
519 })
520 .unwrap_or(false);
521 Box::pin(async move { removed })
522 }
523
524 fn purge_expired(&self) -> usize {
530 let Self { inner } = self;
531 if inner.entry_count.load(Ordering::Relaxed) == 0 {
532 return 0;
533 }
534 let now_ms: u64 = cache_now_ms();
535 let _: u64 = inner.min_expires_at_ms.swap(u64::MAX, Ordering::Relaxed);
536 let mut next_min: u64 = u64::MAX;
537 let mut evicted: usize = 0;
538 let mut freed_bytes: usize = 0;
539 for shard in inner.shards.iter() {
540 if let Ok(mut map) = shard.map.write() {
541 if map.is_empty() {
542 continue;
543 }
544 map.retain(|_: &String, entry: &mut Arc<CacheEntry>| {
545 if now_ms >= entry.expires_at_ms {
546 evicted += 1;
547 freed_bytes += entry.footprint_bytes;
548 false
549 } else {
550 if entry.expires_at_ms < next_min {
551 next_min = entry.expires_at_ms;
552 }
553 true
554 }
555 });
556 }
557 }
558 inner
559 .min_expires_at_ms
560 .fetch_min(next_min, Ordering::Relaxed);
561 if evicted > 0 {
562 inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
563 inner.total_bytes.fetch_sub(freed_bytes, Ordering::Relaxed);
564 }
565 evicted
566 }
567}
568
569impl CachePlugin {
571 pub fn init(config: CacheConfig) -> &'static Self {
581 let local: ShardedMemoryCache = ShardedMemoryCache::new(config.clone());
582 let store: Arc<dyn CacheStore> = Arc::new(local.clone());
583 CACHE_PLUGIN.get_or_init(|| Self {
584 config,
585 store,
586 local_store: Some(local),
587 })
588 }
589
590 pub fn init_with_store(config: CacheConfig, store: Arc<dyn CacheStore>) -> &'static Self {
601 CACHE_PLUGIN.get_or_init(|| Self {
602 config,
603 store,
604 local_store: None,
605 })
606 }
607
608 #[inline(always)]
614 pub fn get() -> Option<&'static Self> {
615 CACHE_PLUGIN.get()
616 }
617
618 #[inline(always)]
624 pub fn get_config(&self) -> &CacheConfig {
625 &self.config
626 }
627
628 #[inline(always)]
634 pub fn get_store(&self) -> &Arc<dyn CacheStore> {
635 &self.store
636 }
637
638 #[inline(always)]
644 pub(crate) fn get_local_store(&self) -> Option<&ShardedMemoryCache> {
645 self.local_store.as_ref()
646 }
647}
648
649impl ServerHook for CacheRequestHook {
651 #[inline(always)]
662 async fn new(_: &mut Stream, _: &mut Context) -> Self {
663 Self
664 }
665
666 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
678 let Some(plugin) = CachePlugin::get() else {
679 return Status::Continue;
680 };
681 let req: &Request = ctx.get_request();
682 let is_get: bool = req.get_method().is_get();
683 let is_head: bool = !is_get && req.get_method().is_head();
684 if !is_get && !is_head {
685 return Status::Continue;
686 }
687 let config: &CacheConfig = plugin.get_config();
688 let has_auth: bool = config.get_bypass_authenticated()
689 && (req.get_headers().contains_key(AUTHORIZATION)
690 || req.get_headers().contains_key(COOKIE));
691 let req_cacheable: bool = if has_auth {
692 false
693 } else {
694 let (ok, _): (bool, Option<u64>) =
695 parse_cache_control(request_header_back(req, CACHE_CONTROL));
696 ok
697 };
698 if !req_cacheable || has_auth {
699 if config.get_emit_diagnostic_headers() {
700 ctx.get_mut_response()
701 .set_header(HEADER_X_CACHE, X_CACHE_BYPASS);
702 }
703 return Status::Continue;
704 }
705 if let Some(local) = plugin.get_local_store() {
706 let (hit_entry, miss_key): (Option<(Arc<CacheEntry>, u64)>, Option<String>) = {
707 let key_cow: Cow<'_, str> = build_http_cache_key_cow(ctx);
708 match local.get_entry_sync(&key_cow) {
709 Some(found) => (Some(found), None),
710 None => (None, Some(key_cow.into_owned())),
711 }
712 };
713 if let Some((entry, now_ms)) = hit_entry {
714 let hit: &CachedValue = &entry.value;
715 let age_secs: u64 = now_ms.saturating_sub(hit.get_stored_at_ms()) / 1_000;
716 let mut age_buf: [u8; AGE_STACK_BUF_LEN] = [0u8; AGE_STACK_BUF_LEN];
717 let age_str: &str = format_u64_stack(age_secs, &mut age_buf);
718 let can_fast_wire: bool = is_get
719 && ctx.get_request().get_version().is_http1_1()
720 && ctx.get_response().get_headers().is_empty();
721 if can_fast_wire
722 && let Some(wire_parts) = entry
723 .wire_cache
724 .get_or_init(|| build_cached_http11_wire(hit))
725 {
726 if !config.get_emit_diagnostic_headers() {
727 let _: Result<(), ResponseError> =
728 stream.try_send(&wire_parts.without_diag).await;
729 return Status::Reject;
730 }
731 let age_bytes: &[u8] = age_str.as_bytes();
732 let prefix_len: usize = wire_parts.with_diag_prefix.len();
733 let suffix_len: usize = wire_parts.with_diag_suffix.len();
734 let total_len: usize = prefix_len + age_bytes.len() + suffix_len;
735 if total_len <= CACHE_WIRE_FAST_STACK_CAP {
736 let mut stack: [u8; CACHE_WIRE_FAST_STACK_CAP] =
737 [0u8; CACHE_WIRE_FAST_STACK_CAP];
738 stack[..prefix_len].copy_from_slice(&wire_parts.with_diag_prefix);
739 stack[prefix_len..prefix_len + age_bytes.len()].copy_from_slice(age_bytes);
740 stack[prefix_len + age_bytes.len()..total_len]
741 .copy_from_slice(&wire_parts.with_diag_suffix);
742 let _: Result<(), ResponseError> =
743 stream.try_send(&stack[..total_len]).await;
744 } else if total_len <= CACHE_WIRE_STACK_CAP {
745 let mut stack: [u8; CACHE_WIRE_STACK_CAP] = [0u8; CACHE_WIRE_STACK_CAP];
746 stack[..prefix_len].copy_from_slice(&wire_parts.with_diag_prefix);
747 stack[prefix_len..prefix_len + age_bytes.len()].copy_from_slice(age_bytes);
748 stack[prefix_len + age_bytes.len()..total_len]
749 .copy_from_slice(&wire_parts.with_diag_suffix);
750 let _: Result<(), ResponseError> =
751 stream.try_send(&stack[..total_len]).await;
752 } else {
753 let mut wire: Vec<u8> = Vec::with_capacity(total_len);
754 wire.extend_from_slice(&wire_parts.with_diag_prefix);
755 wire.extend_from_slice(age_bytes);
756 wire.extend_from_slice(&wire_parts.with_diag_suffix);
757 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
758 }
759 return Status::Reject;
760 }
761 let resp: &mut Response = ctx.get_mut_response();
762 resp.set_status_code(hit.get_status_code());
763 for (name, val) in hit.get_headers() {
764 resp.set_header(name, val);
765 }
766 if config.get_emit_diagnostic_headers() {
767 resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
768 .set_header(AGE, age_str);
769 }
770 if is_head {
771 resp.set_body(&[] as &[u8]);
772 } else {
773 resp.set_body(hit.get_body().as_slice());
774 }
775 let wire: Vec<u8> = resp.build();
776 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
777 return Status::Reject;
778 }
779 if let Some(owned_key) = miss_key {
780 ctx.set_attribute(ATTR_HTTP_CACHE_KEY, owned_key);
781 }
782 return Status::Continue;
783 }
784 let key: String = build_http_cache_key_cow(ctx).into_owned();
785 if let Some(hit) = plugin.get_store().get(&key).await {
786 let age_secs: u64 = hit.age_secs();
787 let mut age_buf: [u8; AGE_STACK_BUF_LEN] = [0u8; AGE_STACK_BUF_LEN];
788 let age_str: &str = format_u64_stack(age_secs, &mut age_buf);
789 let resp: &mut Response = ctx.get_mut_response();
790 resp.set_status_code(hit.get_status_code());
791 for (name, val) in hit.get_headers() {
792 resp.set_header(name, val);
793 }
794 if config.get_emit_diagnostic_headers() {
795 resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
796 .set_header(AGE, age_str);
797 }
798 if is_head {
799 resp.set_body(&[] as &[u8]);
800 } else {
801 resp.set_body(hit.get_body().as_slice());
802 }
803 let wire: Vec<u8> = resp.build();
804 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
805 return Status::Reject;
806 }
807 ctx.set_attribute(ATTR_HTTP_CACHE_KEY, key);
808 Status::Continue
809 }
810}
811
812impl ServerHook for CacheResponseHook {
814 #[inline(always)]
825 async fn new(_: &mut Stream, _: &mut Context) -> Self {
826 Self
827 }
828
829 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
841 let Some(plugin) = CachePlugin::get() else {
842 return Status::Continue;
843 };
844 let Some(key) = ctx.try_get_attribute::<String, _>(ATTR_HTTP_CACHE_KEY) else {
845 return Status::Continue;
846 };
847 let config: &CacheConfig = plugin.get_config();
848 let resp: &Response = ctx.get_response();
849 let status: usize = resp.get_status_code();
850 let body_len: usize = resp.get_body().len();
851 if status == HttpStatus::Ok.code() && body_len <= config.get_max_entry_bytes() {
852 let (cc_ok, ttl_override): (bool, Option<u64>) =
853 parse_cache_control(response_header_back(resp, CACHE_CONTROL));
854 let vary_star: bool =
855 response_header_back(resp, VARY).is_some_and(|val: &str| val.trim() == "*");
856 if cc_ok && !vary_star {
857 let ttl_ms: u64 = ttl_override.unwrap_or(config.get_default_ttl_ms());
858 if ttl_ms > 0 {
859 let mut headers: Vec<(String, String)> =
860 Vec::with_capacity(resp.get_headers().len());
861 for (name, values) in resp.get_headers() {
862 if !name.eq_ignore_ascii_case(HEADER_X_CACHE)
863 && !name.eq_ignore_ascii_case(AGE)
864 && let Some(last) = values.back()
865 {
866 headers.push((name.clone(), last.clone()));
867 }
868 }
869 let cached: CachedValue =
870 CachedValue::new(status, headers, resp.get_body().clone());
871 if let Some(local) = plugin.get_local_store() {
872 local.put_sync(key, cached, ttl_ms);
873 } else {
874 plugin.get_store().put(key, cached, ttl_ms).await;
875 }
876 }
877 }
878 }
879 if config.get_emit_diagnostic_headers() && !ctx.get_response().has_header(HEADER_X_CACHE) {
880 ctx.get_mut_response()
881 .set_header(HEADER_X_CACHE, X_CACHE_MISS);
882 }
883 Status::Continue
884 }
885}