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: CacheShardArray =
130 Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
131 let inflight: InFlightShardArray =
132 Box::new(from_fn(|_: usize| Mutex::new(hash_map_xx_hash3_64())));
133 Self {
134 inner: Arc::new(ShardedMemoryCacheInner {
135 config,
136 entry_count: AtomicUsize::new(0),
137 total_bytes: AtomicUsize::new(0),
138 shards,
139 inflight,
140 }),
141 }
142 }
143
144 #[inline(always)]
150 pub fn len(&self) -> usize {
151 let Self { inner } = self;
152 inner.entry_count.load(Ordering::Relaxed)
153 }
154
155 #[inline(always)]
161 pub fn is_empty(&self) -> bool {
162 self.len() == 0
163 }
164
165 #[inline(always)]
171 pub fn total_bytes(&self) -> usize {
172 let Self { inner } = self;
173 inner.total_bytes.load(Ordering::Relaxed)
174 }
175
176 #[inline]
187 pub(crate) fn get_entry_sync(&self, key: &str, now_ms: u64) -> Option<Arc<CacheEntry>> {
188 let Self { inner } = self;
189 if inner.entry_count.load(Ordering::Relaxed) == 0 {
190 return None;
191 }
192 let idx: usize = cache_shard_index(key);
193 let entry: Arc<CacheEntry> = {
194 let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
195 inner.shards[idx].read().ok()?;
196 Arc::clone(guard.get(key)?)
197 };
198 if now_ms < entry.expires_at_ms {
199 return Some(entry);
200 }
201 if let Ok(mut guard) = inner.shards[idx].write()
202 && guard
203 .get(key)
204 .is_some_and(|cur: &Arc<CacheEntry>| now_ms >= cur.expires_at_ms)
205 && let Some(removed) = guard.remove(key)
206 {
207 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
208 inner
209 .total_bytes
210 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
211 }
212 None
213 }
214
215 #[inline]
225 pub fn get_sync(&self, key: &str) -> Option<CachedValue> {
226 let Self { inner } = self;
227 if inner.entry_count.load(Ordering::Relaxed) == 0 {
228 return None;
229 }
230 let now_ms: u64 = cache_now_ms();
231 let idx: usize = cache_shard_index(key);
232 let expired: bool = {
233 let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
234 inner.shards[idx].read().ok()?;
235 let entry: &Arc<CacheEntry> = guard.get(key)?;
236 if now_ms < entry.expires_at_ms {
237 return Some(entry.value.clone());
238 }
239 true
240 };
241 if expired
242 && let Ok(mut guard) = inner.shards[idx].write()
243 && guard
244 .get(key)
245 .is_some_and(|cur: &Arc<CacheEntry>| now_ms >= cur.expires_at_ms)
246 && let Some(removed) = guard.remove(key)
247 {
248 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
249 inner
250 .total_bytes
251 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
252 }
253 None
254 }
255
256 pub fn put_sync(&self, key: String, value: CachedValue, ttl_ms: u64) {
264 if ttl_ms == 0 {
265 return;
266 }
267 let Self { inner } = self;
268 let max_bytes: usize = inner.config.get_max_bytes();
269 let max_entries: usize = inner.config.get_max_entries();
270 let footprint: usize = estimate_entry_bytes(&key, &value);
271 if footprint > max_bytes {
272 return;
273 }
274 let now_ms: u64 = cache_now_ms();
275 let idx: usize = cache_shard_index(&key);
276 let entry: Arc<CacheEntry> = Arc::new(CacheEntry {
277 value,
278 expires_at_ms: now_ms.saturating_add(ttl_ms),
279 footprint_bytes: footprint,
280 wire_cache: OnceLock::new(),
281 });
282 {
283 let Ok(mut map): Result<
284 RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>,
285 _,
286 > = inner.shards[idx].write() else {
287 return;
288 };
289 if let Some(existing) = map.get_mut(&key) {
290 let prev_footprint: usize = existing.footprint_bytes;
291 let total_now: usize = inner.total_bytes.load(Ordering::Relaxed);
292 let projected_bytes: usize = total_now
293 .saturating_sub(prev_footprint)
294 .saturating_add(footprint);
295 if projected_bytes <= max_bytes {
296 *existing = entry;
297 if footprint >= prev_footprint {
298 inner
299 .total_bytes
300 .fetch_add(footprint - prev_footprint, Ordering::Relaxed);
301 } else {
302 inner
303 .total_bytes
304 .fetch_sub(prev_footprint - footprint, Ordering::Relaxed);
305 }
306 return;
307 }
308 }
309 }
310 if inner.entry_count.load(Ordering::Relaxed) >= max_entries
311 || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes
312 {
313 let _: usize = self.purge_expired();
314 }
315 let Ok(mut map): Result<
316 RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>,
317 _,
318 > = inner.shards[idx].write() else {
319 return;
320 };
321 if let Some(prev) = map.remove(&key) {
322 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
323 inner
324 .total_bytes
325 .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
326 }
327 while (inner.entry_count.load(Ordering::Relaxed) >= max_entries
328 || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes)
329 && !map.is_empty()
330 {
331 let oldest_key: Option<String> = map
332 .iter()
333 .min_by_key(|(_, cur): &(&String, &Arc<CacheEntry>)| cur.expires_at_ms)
334 .map(|(k, _): (&String, &Arc<CacheEntry>)| k.clone());
335 if let Some(evict_key) = oldest_key
336 && let Some(evicted) = map.remove(&evict_key)
337 {
338 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
339 inner
340 .total_bytes
341 .fetch_sub(evicted.footprint_bytes, Ordering::Relaxed);
342 } else {
343 break;
344 }
345 }
346 if inner.entry_count.load(Ordering::Relaxed) >= max_entries
347 || inner.total_bytes.load(Ordering::Relaxed) + footprint > max_bytes
348 {
349 return;
350 }
351 map.insert(key, entry);
352 inner.entry_count.fetch_add(1, Ordering::Relaxed);
353 inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
354 }
355
356 pub async fn get_or_load<F, Fut>(
368 &self,
369 key: &str,
370 ttl_ms: u64,
371 loader: F,
372 ) -> Option<CachedValue>
373 where
374 F: FnOnce() -> Fut,
375 Fut: Future<Output = Option<CachedValue>>,
376 {
377 if let Some(hit) = self.get_sync(key) {
378 return Some(hit);
379 }
380 let Self { inner } = self;
381 let idx: usize = cache_shard_index(key);
382 let (slot, is_leader): (Arc<InFlightSlot>, bool) = {
383 let Ok(mut guard) = inner.inflight[idx].lock() else {
384 return loader().await;
385 };
386 if let Some(existing) = guard.get(key) {
387 (Arc::clone(existing), false)
388 } else {
389 let created: Arc<InFlightSlot> = Arc::new(InFlightSlot {
390 notify: Notify::new(),
391 result: Mutex::new(None),
392 });
393 guard.insert(key.to_owned(), Arc::clone(&created));
394 (created, true)
395 }
396 };
397 if is_leader {
398 let loaded: Option<CachedValue> = loader().await;
399 if let Some(ref val) = loaded {
400 self.put_sync(key.to_owned(), val.clone(), ttl_ms);
401 }
402 if let Ok(mut res_guard) = slot.result.lock() {
403 *res_guard = Some(loaded.clone());
404 }
405 if let Ok(mut map_guard) = inner.inflight[idx].lock() {
406 map_guard.remove(key);
407 }
408 slot.notify.notify_waiters();
409 loaded
410 } else {
411 loop {
412 let notified: Notified<'_> = slot.notify.notified();
413 if let Ok(res_guard) = slot.result.lock()
414 && let Some(ref outcome) = *res_guard
415 {
416 return outcome.clone();
417 }
418 notified.await;
419 }
420 }
421 }
422}
423
424impl CacheStore for ShardedMemoryCache {
426 fn get<'a>(&'a self, key: &'a str) -> CacheFuture<'a, Option<CachedValue>> {
437 Box::pin(async move { self.get_sync(key) })
438 }
439
440 fn put(&self, key: String, value: CachedValue, ttl_ms: u64) -> CacheFuture<'_, ()> {
452 self.put_sync(key, value, ttl_ms);
453 Box::pin(async {})
454 }
455
456 fn remove<'a>(&'a self, key: &'a str) -> CacheFuture<'a, bool> {
467 let Self { inner } = self;
468 let idx: usize = cache_shard_index(key);
469 let removed: bool = inner.shards[idx]
470 .write()
471 .ok()
472 .and_then(
473 |mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>| {
474 map.remove(key)
475 },
476 )
477 .map(|entry: Arc<CacheEntry>| {
478 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
479 inner
480 .total_bytes
481 .fetch_sub(entry.footprint_bytes, Ordering::Relaxed);
482 true
483 })
484 .unwrap_or(false);
485 Box::pin(async move { removed })
486 }
487
488 fn purge_expired(&self) -> usize {
494 let Self { inner } = self;
495 if inner.entry_count.load(Ordering::Relaxed) == 0 {
496 return 0;
497 }
498 let now_ms: u64 = cache_now_ms();
499 let mut evicted: usize = 0;
500 let mut freed_bytes: usize = 0;
501 for shard in inner.shards.iter() {
502 if let Ok(mut map) = shard.write() {
503 if map.is_empty() {
504 continue;
505 }
506 map.retain(|_: &String, entry: &mut Arc<CacheEntry>| {
507 if now_ms >= entry.expires_at_ms {
508 evicted += 1;
509 freed_bytes += entry.footprint_bytes;
510 false
511 } else {
512 true
513 }
514 });
515 }
516 }
517 if evicted > 0 {
518 inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
519 inner.total_bytes.fetch_sub(freed_bytes, Ordering::Relaxed);
520 }
521 evicted
522 }
523}
524
525impl CachePlugin {
527 pub fn init(config: CacheConfig) -> &'static Self {
537 let local: ShardedMemoryCache = ShardedMemoryCache::new(config.clone());
538 let store: SharedCacheStore = Arc::new(local.clone());
539 CACHE_PLUGIN.get_or_init(|| Self {
540 config,
541 store,
542 local_store: Some(local),
543 })
544 }
545
546 pub fn init_with_store(config: CacheConfig, store: SharedCacheStore) -> &'static Self {
557 CACHE_PLUGIN.get_or_init(|| Self {
558 config,
559 store,
560 local_store: None,
561 })
562 }
563
564 #[inline(always)]
570 pub fn get() -> Option<&'static Self> {
571 CACHE_PLUGIN.get()
572 }
573
574 #[inline(always)]
580 pub fn get_config(&self) -> &CacheConfig {
581 &self.config
582 }
583
584 #[inline(always)]
590 pub fn get_store(&self) -> &SharedCacheStore {
591 &self.store
592 }
593
594 #[inline(always)]
600 pub(crate) fn get_local_store(&self) -> Option<&ShardedMemoryCache> {
601 self.local_store.as_ref()
602 }
603}
604
605impl ServerHook for CacheRequestHook {
607 #[inline(always)]
618 async fn new(_: &mut Stream, _: &mut Context) -> Self {
619 Self
620 }
621
622 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
634 let Some(plugin) = CachePlugin::get() else {
635 return Status::Continue;
636 };
637 let req: &Request = ctx.get_request();
638 let is_get: bool = req.get_method().is_get();
639 let is_head: bool = !is_get && req.get_method().is_head();
640 if !is_get && !is_head {
641 return Status::Continue;
642 }
643 let config: &CacheConfig = plugin.get_config();
644 let has_auth: bool = config.get_bypass_authenticated()
645 && (req.get_headers().contains_key(AUTHORIZATION)
646 || req.get_headers().contains_key(COOKIE));
647 let req_cacheable: bool = if has_auth {
648 false
649 } else {
650 let (ok, _): (bool, Option<u64>) =
651 parse_cache_control(request_header_back(req, CACHE_CONTROL));
652 ok
653 };
654 if !req_cacheable || has_auth {
655 if config.get_emit_diagnostic_headers() {
656 ctx.get_mut_response()
657 .set_header(HEADER_X_CACHE, X_CACHE_BYPASS);
658 }
659 return Status::Continue;
660 }
661 if let Some(local) = plugin.get_local_store() {
662 let now_ms: u64 = cache_now_ms();
663 let hit_entry: Option<Arc<CacheEntry>> = {
664 let key_cow: Cow<'_, str> = build_http_cache_key_cow(ctx);
665 local.get_entry_sync(&key_cow, now_ms)
666 };
667 if let Some(entry) = hit_entry {
668 let hit: &CachedValue = &entry.value;
669 let age_secs: u64 = now_ms.saturating_sub(hit.get_stored_at_ms()) / 1_000;
670 let mut age_buf: [u8; AGE_STACK_BUF_LEN] = [0u8; AGE_STACK_BUF_LEN];
671 let age_str: &str = format_u64_stack(age_secs, &mut age_buf);
672 let can_fast_wire: bool = is_get
673 && ctx.get_request().get_version().is_http1_1()
674 && ctx.get_response().get_headers().is_empty();
675 if can_fast_wire
676 && let Some(wire_parts) = entry
677 .wire_cache
678 .get_or_init(|| build_cached_http11_wire(hit))
679 {
680 if !config.get_emit_diagnostic_headers() {
681 let _: Result<(), ResponseError> =
682 stream.try_send(&wire_parts.without_diag).await;
683 return Status::Reject;
684 }
685 let age_bytes: &[u8] = age_str.as_bytes();
686 let prefix_len: usize = wire_parts.with_diag_prefix.len();
687 let suffix_len: usize = wire_parts.with_diag_suffix.len();
688 let total_len: usize = prefix_len + age_bytes.len() + suffix_len;
689 if total_len <= CACHE_WIRE_STACK_CAP {
690 let mut stack: [u8; CACHE_WIRE_STACK_CAP] = [0u8; CACHE_WIRE_STACK_CAP];
691 stack[..prefix_len].copy_from_slice(&wire_parts.with_diag_prefix);
692 stack[prefix_len..prefix_len + age_bytes.len()].copy_from_slice(age_bytes);
693 stack[prefix_len + age_bytes.len()..total_len]
694 .copy_from_slice(&wire_parts.with_diag_suffix);
695 let _: Result<(), ResponseError> =
696 stream.try_send(&stack[..total_len]).await;
697 } else {
698 let mut wire: Vec<u8> = Vec::with_capacity(total_len);
699 wire.extend_from_slice(&wire_parts.with_diag_prefix);
700 wire.extend_from_slice(age_bytes);
701 wire.extend_from_slice(&wire_parts.with_diag_suffix);
702 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
703 }
704 return Status::Reject;
705 }
706 let resp: &mut Response = ctx.get_mut_response();
707 resp.set_status_code(hit.get_status_code());
708 for (name, val) in hit.get_headers() {
709 resp.set_header(name, val);
710 }
711 if config.get_emit_diagnostic_headers() {
712 resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
713 .set_header(AGE, age_str);
714 }
715 if is_head {
716 resp.set_body(&[] as &[u8]);
717 } else {
718 resp.set_body(hit.get_body().as_slice());
719 }
720 let wire: ResponseData = resp.build();
721 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
722 return Status::Reject;
723 }
724 let owned_key: String = build_http_cache_key_cow(ctx).into_owned();
725 ctx.set_attribute(ATTR_HTTP_CACHE_KEY, owned_key);
726 return Status::Continue;
727 }
728 let key: String = build_http_cache_key_cow(ctx).into_owned();
729 if let Some(hit) = plugin.get_store().get(&key).await {
730 let age_secs: u64 = hit.age_secs();
731 let mut age_buf: [u8; AGE_STACK_BUF_LEN] = [0u8; AGE_STACK_BUF_LEN];
732 let age_str: &str = format_u64_stack(age_secs, &mut age_buf);
733 let resp: &mut Response = ctx.get_mut_response();
734 resp.set_status_code(hit.get_status_code());
735 for (name, val) in hit.get_headers() {
736 resp.set_header(name, val);
737 }
738 if config.get_emit_diagnostic_headers() {
739 resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
740 .set_header(AGE, age_str);
741 }
742 if is_head {
743 resp.set_body(&[] as &[u8]);
744 } else {
745 resp.set_body(hit.get_body().as_slice());
746 }
747 let wire: ResponseData = resp.build();
748 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
749 return Status::Reject;
750 }
751 ctx.set_attribute(ATTR_HTTP_CACHE_KEY, key);
752 Status::Continue
753 }
754}
755
756impl ServerHook for CacheResponseHook {
758 #[inline(always)]
769 async fn new(_: &mut Stream, _: &mut Context) -> Self {
770 Self
771 }
772
773 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
785 let Some(plugin) = CachePlugin::get() else {
786 return Status::Continue;
787 };
788 let Some(key) = ctx.try_get_attribute::<String, _>(ATTR_HTTP_CACHE_KEY) else {
789 return Status::Continue;
790 };
791 let config: &CacheConfig = plugin.get_config();
792 let resp: &Response = ctx.get_response();
793 let status: usize = resp.get_status_code();
794 let body_len: usize = resp.get_body().len();
795 if status == HttpStatus::Ok.code() && body_len <= config.get_max_entry_bytes() {
796 let (cc_ok, ttl_override): (bool, Option<u64>) =
797 parse_cache_control(response_header_back(resp, CACHE_CONTROL));
798 let vary_star: bool =
799 response_header_back(resp, VARY).is_some_and(|val: &str| val.trim() == "*");
800 if cc_ok && !vary_star {
801 let ttl_ms: u64 = ttl_override.unwrap_or(config.get_default_ttl_ms());
802 if ttl_ms > 0 {
803 let mut headers: Vec<(String, String)> =
804 Vec::with_capacity(resp.get_headers().len());
805 for (name, values) in resp.get_headers() {
806 if !name.eq_ignore_ascii_case(HEADER_X_CACHE)
807 && !name.eq_ignore_ascii_case(AGE)
808 && let Some(last) = values.back()
809 {
810 headers.push((name.clone(), last.clone()));
811 }
812 }
813 let cached: CachedValue =
814 CachedValue::new(status, headers, resp.get_body().clone());
815 if let Some(local) = plugin.get_local_store() {
816 local.put_sync(key, cached, ttl_ms);
817 } else {
818 plugin.get_store().put(key, cached, ttl_ms).await;
819 }
820 }
821 }
822 }
823 if config.get_emit_diagnostic_headers() && !ctx.get_response().has_header(HEADER_X_CACHE) {
824 ctx.get_mut_response()
825 .set_header(HEADER_X_CACHE, X_CACHE_MISS);
826 }
827 Status::Continue
828 }
829}