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 pub fn age_secs(&self) -> u64 {
44 cache_now_ms().saturating_sub(self.get_stored_at_ms()) / 1_000
45 }
46}
47
48impl Default for CacheConfig {
50 fn default() -> Self {
52 Self {
53 default_ttl_ms: DEFAULT_CACHE_TTL_MS,
54 max_entries: DEFAULT_CACHE_MAX_ENTRIES,
55 max_bytes: DEFAULT_CACHE_MAX_BYTES,
56 max_entry_bytes: DEFAULT_CACHE_MAX_ENTRY_BYTES,
57 bypass_authenticated: true,
58 emit_diagnostic_headers: true,
59 }
60 }
61}
62
63impl CacheConfig {
65 pub fn with_default_ttl_ms(mut self, ttl_ms: u64) -> Self {
75 self.set_default_ttl_ms(ttl_ms);
76 self
77 }
78
79 pub fn with_max_entries(mut self, max_entries: usize) -> Self {
89 self.set_max_entries(max_entries.max(1));
90 self
91 }
92
93 pub fn with_max_bytes(mut self, max_bytes: usize) -> Self {
103 self.set_max_bytes(max_bytes.max(1));
104 self
105 }
106}
107
108impl Default for ShardedMemoryCache {
110 fn default() -> Self {
112 Self::new(CacheConfig::default())
113 }
114}
115
116impl ShardedMemoryCache {
118 pub fn new(config: CacheConfig) -> Self {
128 let shards: CacheShardArray =
129 Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
130 let inflight: InFlightShardArray =
131 Box::new(from_fn(|_: usize| Mutex::new(hash_map_xx_hash3_64())));
132 Self {
133 inner: Arc::new(ShardedMemoryCacheInner {
134 config,
135 entry_count: AtomicUsize::new(0),
136 total_bytes: AtomicUsize::new(0),
137 shards,
138 inflight,
139 }),
140 }
141 }
142
143 pub fn len(&self) -> usize {
149 let Self { inner } = self;
150 inner.entry_count.load(Ordering::Relaxed)
151 }
152
153 pub fn is_empty(&self) -> bool {
159 self.len() == 0
160 }
161
162 pub fn total_bytes(&self) -> usize {
168 let Self { inner } = self;
169 inner.total_bytes.load(Ordering::Relaxed)
170 }
171
172 pub fn get_sync(&self, key: &str) -> Option<CachedValue> {
182 let Self { inner } = self;
183 let idx: usize = cache_shard_index(key);
184 let now_ms: u64 = cache_now_ms();
185 let entry: Arc<CacheEntry> = {
186 let guard: RwLockReadGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>> =
187 inner.shards[idx].read().ok()?;
188 Arc::clone(guard.get(key)?)
189 };
190 if now_ms < entry.expires_at_ms {
191 return Some(entry.value.clone());
192 }
193 if let Ok(mut guard) = inner.shards[idx].write()
194 && let Some(removed) = guard.remove(key)
195 {
196 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
197 inner
198 .total_bytes
199 .fetch_sub(removed.footprint_bytes, Ordering::Relaxed);
200 }
201 None
202 }
203
204 pub fn put_sync(&self, key: String, value: CachedValue, ttl_ms: u64) {
212 if ttl_ms == 0 {
213 return;
214 }
215 let Self { inner } = self;
216 let footprint: usize = estimate_entry_bytes(&key, &value);
217 if footprint > inner.config.get_max_bytes() {
218 return;
219 }
220 let now_ms: u64 = cache_now_ms();
221 if inner.entry_count.load(Ordering::Relaxed) >= inner.config.get_max_entries()
222 || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.config.get_max_bytes()
223 {
224 let _: usize = self.purge_expired();
225 }
226 let idx: usize = cache_shard_index(&key);
227 let Ok(mut map): Result<
228 RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>,
229 _,
230 > = inner.shards[idx].write() else {
231 return;
232 };
233 if let Some(prev) = map.remove(&key) {
234 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
235 inner
236 .total_bytes
237 .fetch_sub(prev.footprint_bytes, Ordering::Relaxed);
238 }
239 while (inner.entry_count.load(Ordering::Relaxed) >= inner.config.get_max_entries()
240 || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.config.get_max_bytes())
241 && !map.is_empty()
242 {
243 let oldest_key: Option<String> = map
244 .iter()
245 .min_by_key(|(_, entry): &(&String, &Arc<CacheEntry>)| entry.expires_at_ms)
246 .map(|(k, _): (&String, &Arc<CacheEntry>)| k.clone());
247 if let Some(evict_key) = oldest_key
248 && let Some(evicted) = map.remove(&evict_key)
249 {
250 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
251 inner
252 .total_bytes
253 .fetch_sub(evicted.footprint_bytes, Ordering::Relaxed);
254 } else {
255 break;
256 }
257 }
258 if inner.entry_count.load(Ordering::Relaxed) >= inner.config.get_max_entries()
259 || inner.total_bytes.load(Ordering::Relaxed) + footprint > inner.config.get_max_bytes()
260 {
261 return;
262 }
263 let entry: Arc<CacheEntry> = Arc::new(CacheEntry {
264 value,
265 expires_at_ms: now_ms.saturating_add(ttl_ms),
266 footprint_bytes: footprint,
267 });
268 map.insert(key, entry);
269 inner.entry_count.fetch_add(1, Ordering::Relaxed);
270 inner.total_bytes.fetch_add(footprint, Ordering::Relaxed);
271 }
272
273 pub async fn get_or_load<F, Fut>(
285 &self,
286 key: &str,
287 ttl_ms: u64,
288 loader: F,
289 ) -> Option<CachedValue>
290 where
291 F: FnOnce() -> Fut,
292 Fut: Future<Output = Option<CachedValue>>,
293 {
294 if let Some(hit) = self.get_sync(key) {
295 return Some(hit);
296 }
297 let Self { inner } = self;
298 let idx: usize = cache_shard_index(key);
299 let (slot, is_leader): (Arc<InFlightSlot>, bool) = {
300 let Ok(mut guard) = inner.inflight[idx].lock() else {
301 return loader().await;
302 };
303 if let Some(existing) = guard.get(key) {
304 (Arc::clone(existing), false)
305 } else {
306 let created: Arc<InFlightSlot> = Arc::new(InFlightSlot {
307 notify: Notify::new(),
308 result: Mutex::new(None),
309 });
310 guard.insert(key.to_owned(), Arc::clone(&created));
311 (created, true)
312 }
313 };
314 if is_leader {
315 let loaded: Option<CachedValue> = loader().await;
316 if let Some(ref val) = loaded {
317 self.put_sync(key.to_owned(), val.clone(), ttl_ms);
318 }
319 if let Ok(mut res_guard) = slot.result.lock() {
320 *res_guard = Some(loaded.clone());
321 }
322 if let Ok(mut map_guard) = inner.inflight[idx].lock() {
323 map_guard.remove(key);
324 }
325 slot.notify.notify_waiters();
326 loaded
327 } else {
328 loop {
329 let notified: Notified<'_> = slot.notify.notified();
330 if let Ok(res_guard) = slot.result.lock()
331 && let Some(ref outcome) = *res_guard
332 {
333 return outcome.clone();
334 }
335 notified.await;
336 }
337 }
338 }
339}
340
341impl CacheStore for ShardedMemoryCache {
343 fn get<'a>(&'a self, key: &'a str) -> CacheFuture<'a, Option<CachedValue>> {
354 let value: Option<CachedValue> = self.get_sync(key);
355 Box::pin(async move { value })
356 }
357
358 fn put(&self, key: String, value: CachedValue, ttl_ms: u64) -> CacheFuture<'_, ()> {
370 self.put_sync(key, value, ttl_ms);
371 Box::pin(async {})
372 }
373
374 fn remove<'a>(&'a self, key: &'a str) -> CacheFuture<'a, bool> {
385 let Self { inner } = self;
386 let idx: usize = cache_shard_index(key);
387 let removed: bool = inner.shards[idx]
388 .write()
389 .ok()
390 .and_then(
391 |mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, Arc<CacheEntry>>>| {
392 map.remove(key)
393 },
394 )
395 .map(|entry: Arc<CacheEntry>| {
396 inner.entry_count.fetch_sub(1, Ordering::Relaxed);
397 inner
398 .total_bytes
399 .fetch_sub(entry.footprint_bytes, Ordering::Relaxed);
400 true
401 })
402 .unwrap_or(false);
403 Box::pin(async move { removed })
404 }
405
406 fn purge_expired(&self) -> usize {
412 let Self { inner } = self;
413 let now_ms: u64 = cache_now_ms();
414 let mut evicted: usize = 0;
415 let mut freed_bytes: usize = 0;
416 for shard in inner.shards.iter() {
417 if let Ok(mut map) = shard.write() {
418 map.retain(|_: &String, entry: &mut Arc<CacheEntry>| {
419 if now_ms >= entry.expires_at_ms {
420 evicted += 1;
421 freed_bytes += entry.footprint_bytes;
422 false
423 } else {
424 true
425 }
426 });
427 }
428 }
429 if evicted > 0 {
430 inner.entry_count.fetch_sub(evicted, Ordering::Relaxed);
431 inner.total_bytes.fetch_sub(freed_bytes, Ordering::Relaxed);
432 }
433 evicted
434 }
435}
436
437impl CachePlugin {
439 pub fn init(config: CacheConfig) -> &'static Self {
449 let store: SharedCacheStore = Arc::new(ShardedMemoryCache::new(config.clone()));
450 Self::init_with_store(config, store)
451 }
452
453 pub fn init_with_store(config: CacheConfig, store: SharedCacheStore) -> &'static Self {
464 CACHE_PLUGIN.get_or_init(|| Self { config, store })
465 }
466
467 pub fn get() -> Option<&'static Self> {
473 CACHE_PLUGIN.get()
474 }
475
476 pub fn get_config(&self) -> &CacheConfig {
482 &self.config
483 }
484
485 pub fn get_store(&self) -> &SharedCacheStore {
491 &self.store
492 }
493}
494
495impl ServerHook for CacheRequestHook {
497 async fn new(_: &mut Stream, _: &mut Context) -> Self {
508 Self
509 }
510
511 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
523 let Some(plugin) = CachePlugin::get() else {
524 return Status::Continue;
525 };
526 let is_get: bool = ctx.get_request().get_method().is_get();
527 let is_head: bool = ctx.get_request().get_method().is_head();
528 if !is_get && !is_head {
529 return Status::Continue;
530 }
531 let config: &CacheConfig = plugin.get_config();
532 let req_cc: Option<String> = ctx.get_request().try_get_header_back(CACHE_CONTROL);
533 let (req_cacheable, _): (bool, Option<u64>) = parse_cache_control(req_cc.as_deref());
534 let has_auth: bool = config.get_bypass_authenticated()
535 && (ctx
536 .get_request()
537 .try_get_header_back(AUTHORIZATION)
538 .is_some()
539 || ctx.get_request().try_get_header_back(COOKIE).is_some());
540 if !req_cacheable || has_auth {
541 if config.get_emit_diagnostic_headers() {
542 ctx.get_mut_response()
543 .set_header(HEADER_X_CACHE, X_CACHE_BYPASS);
544 }
545 return Status::Continue;
546 }
547 let key: String = build_http_cache_key(ctx);
548 if let Some(hit) = plugin.get_store().get(&key).await {
549 let age: String = hit.age_secs().to_string();
550 let resp: &mut Response = ctx.get_mut_response();
551 resp.set_status_code(hit.get_status_code());
552 for (name, val) in hit.get_headers() {
553 resp.set_header(name, val);
554 }
555 if config.get_emit_diagnostic_headers() {
556 resp.set_header(HEADER_X_CACHE, X_CACHE_HIT)
557 .set_header(AGE, age);
558 }
559 if is_head {
560 resp.set_body(Vec::new());
561 } else {
562 resp.set_body(hit.get_body().clone());
563 }
564 let wire: ResponseData = ctx.get_mut_response().build();
565 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
566 return Status::Reject;
567 }
568 ctx.set_attribute(ATTR_HTTP_CACHE_KEY, key);
569 Status::Continue
570 }
571}
572
573impl ServerHook for CacheResponseHook {
575 async fn new(_: &mut Stream, _: &mut Context) -> Self {
586 Self
587 }
588
589 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
601 let Some(plugin) = CachePlugin::get() else {
602 return Status::Continue;
603 };
604 let Some(key) = ctx.try_get_attribute::<String, _>(ATTR_HTTP_CACHE_KEY) else {
605 return Status::Continue;
606 };
607 let config: &CacheConfig = plugin.get_config();
608 let status: usize = ctx.get_response().get_status_code();
609 let body_len: usize = ctx.get_response().get_body().len();
610 let resp_cc: Option<String> = ctx.get_response().try_get_header_back(CACHE_CONTROL);
611 let (cc_ok, ttl_override): (bool, Option<u64>) = parse_cache_control(resp_cc.as_deref());
612 let vary_star: bool = ctx
613 .get_response()
614 .try_get_header_back(VARY)
615 .is_some_and(|val: String| val.trim() == "*");
616 if status == HttpStatus::Ok.code()
617 && cc_ok
618 && !vary_star
619 && body_len <= config.get_max_entry_bytes()
620 {
621 let ttl_ms: u64 = ttl_override.unwrap_or(config.get_default_ttl_ms());
622 if ttl_ms > 0 {
623 let mut headers: Vec<(String, String)> = Vec::new();
624 for (name, values) in ctx.get_response().get_headers() {
625 if !name.eq_ignore_ascii_case(HEADER_X_CACHE)
626 && !name.eq_ignore_ascii_case(AGE)
627 && let Some(last) = values.back()
628 {
629 headers.push((name.clone(), last.clone()));
630 }
631 }
632 let cached: CachedValue =
633 CachedValue::new(status, headers, ctx.get_response().get_body().clone());
634 plugin.get_store().put(key, cached, ttl_ms).await;
635 }
636 }
637 if config.get_emit_diagnostic_headers()
638 && ctx
639 .get_response()
640 .try_get_header_back(HEADER_X_CACHE)
641 .is_none()
642 {
643 ctx.get_mut_response()
644 .set_header(HEADER_X_CACHE, X_CACHE_MISS);
645 }
646 Status::Continue
647 }
648}