http_cache/managers/redb.rs
1//! HTTP cache manager backed by an embedded [`redb`](https://github.com/cberner/redb)
2//! key/value database.
3//!
4//! Unlike [`CACacheManager`](crate::CACacheManager), this manager performs all
5//! of its I/O **synchronously** and depends on **no async runtime** — `redb`
6//! itself only depends on `libc`. That makes it a good fit for smol-based
7//! clients (such as `http-cache-ureq`) and for embedding runtimes like Bevy,
8//! where there is no tokio reactor available: it pulls in no `tokio`
9//! dependency and requires no reactor at runtime.
10//!
11//! The cache is stored in a single database file. Only one instance may have
12//! the file open at a time — `redb` takes an exclusive file lock — so wrap the
13//! manager in `Arc`/a `static` and share it rather than constructing a second
14//! instance for the same path.
15//!
16//! Stores are batched for durability: entries are committed without an
17//! fsync and flushed to disk every 64 writes (configurable via
18//! [`RedbManager::from_database_with_flush_interval`]) and on drop, so a
19//! crash can lose approximately the most recent 64 stores. Deletes commit
20//! durably, so an invalidated entry cannot come back after a crash. When
21//! sharing a [`Database`] via [`RedbManager::from_database`], do not drop
22//! the last manager clone while holding an open `WriteTransaction` on that
23//! database — the drop-time flush must acquire the writer lock.
24//!
25//! The cache grows without bound unless it is created with
26//! [`RedbManager::from_database_with_max_bytes`], which removes the entries
27//! written longest ago once the stored entries exceed a byte limit.
28
29use std::path::Path;
30use std::sync::Arc;
31use std::sync::atomic::{AtomicU64, Ordering};
32
33use crate::managers::limit::{Limited, Tables};
34use crate::{CacheManager, HttpResponse, Result};
35
36use http_cache_semantics::CachePolicy;
37use redb::{Database, Durability, ReadableDatabase, TableDefinition};
38use serde::{Deserialize, Serialize};
39
40pub(crate) const TABLE: TableDefinition<&str, &[u8]> =
41 TableDefinition::new("http_cache_v1");
42
43/// The entry table with the index a size limit keeps of its entries.
44pub(crate) const TABLES: Tables = Tables {
45 entries: TABLE,
46 index: TableDefinition::new("http_cache_v1_index"),
47 order: TableDefinition::new("http_cache_v1_order"),
48 bytes: TableDefinition::new("http_cache_v1_bytes"),
49};
50
51/// Implements [`CacheManager`] with [`redb`](https://github.com/cberner/redb)
52/// as the backend — a pure-Rust, embedded, persistent key/value store.
53///
54/// All operations are synchronous and require no async runtime, so this
55/// manager works under any executor (tokio, smol, Bevy, …) and adds no
56/// `tokio` dependency.
57#[cfg_attr(docsrs, doc(cfg(feature = "manager-redb")))]
58#[derive(Clone)]
59pub struct RedbManager {
60 flush: Arc<FlushState>,
61 max_bytes: Option<u64>,
62}
63
64impl std::fmt::Debug for RedbManager {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 f.debug_struct("RedbManager").finish_non_exhaustive()
67 }
68}
69
70// Store format (postcard). `manager-redb` always enables `postcard`, and this
71// is a new backend with no legacy on-disk data, so only postcard is supported.
72#[derive(Debug, Deserialize, Serialize)]
73struct Store {
74 response: HttpResponse,
75 policy: CachePolicy,
76}
77
78/// Stores are committed with `Durability::None` and made durable by an empty
79/// `Immediate` commit every `interval` writes and when the last manager
80/// clone drops.
81const DEFAULT_FLUSH_INTERVAL: u64 = 64;
82
83struct FlushState {
84 db: Arc<Database>,
85 unflushed: AtomicU64,
86 interval: u64,
87}
88
89impl FlushState {
90 fn flush(&self) -> Result<()> {
91 // An empty Immediate commit persists all prior None-durability
92 // commits.
93 let write_txn = self.db.begin_write()?;
94 write_txn.commit()?;
95 Ok(())
96 }
97
98 fn record_write(&self) {
99 if self.unflushed.fetch_add(1, Ordering::Relaxed) + 1 >= self.interval {
100 // Claim the whole batch so writers queued behind a flush in
101 // flight don't each fsync. The write's own commit already
102 // succeeded; on failure the count is restored and the drop
103 // guard retries — though redb latches I/O errors, so retries
104 // fail until the database is reopened.
105 let n = self.unflushed.swap(0, Ordering::Relaxed);
106 if n == 0 {
107 return;
108 }
109 if let Err(e) = self.flush() {
110 self.unflushed.fetch_add(n, Ordering::Relaxed);
111 log::warn!("redb interval flush failed: {e}");
112 }
113 }
114 }
115}
116
117impl Drop for FlushState {
118 fn drop(&mut self) {
119 if self.unflushed.load(Ordering::Relaxed) > 0
120 && let Err(e) = self.flush()
121 {
122 log::warn!("redb flush on drop failed: {e}");
123 }
124 }
125}
126
127/// Removes the entries written longest ago until the indexed entries fit in
128/// `max_bytes`.
129fn evict(limited: &mut Limited, max_bytes: u64) -> Result<()> {
130 while limited.pop_oldest(max_bytes)?.is_some() {}
131 Ok(())
132}
133
134impl RedbManager {
135 /// Creates a new [`RedbManager`], creating or opening the redb database
136 /// file at `path`.
137 ///
138 /// Returns an error if the database cannot be opened (for example if
139 /// another instance already holds the exclusive file lock).
140 pub fn new(path: impl AsRef<Path>) -> Result<Self> {
141 let db = Database::create(path)?;
142 Self::from_database(Arc::new(db))
143 }
144
145 /// Wraps an already-open redb [`Database`], allowing callers to configure
146 /// the database (cache size, etc.) before handing it to the manager.
147 pub fn from_database(db: Arc<Database>) -> Result<Self> {
148 Self::from_database_with_flush_interval(db, DEFAULT_FLUSH_INTERVAL)
149 }
150
151 /// Like [`from_database`](Self::from_database), but flushes stores to
152 /// disk every `flush_interval` writes instead of the default 64. An
153 /// interval of 1 flushes after every store.
154 pub fn from_database_with_flush_interval(
155 db: Arc<Database>,
156 flush_interval: u64,
157 ) -> Result<Self> {
158 Self::open(db, flush_interval, None)
159 }
160
161 /// Wraps an already-open redb [`Database`], flushing every
162 /// `flush_interval` writes and keeping the stored entries within
163 /// `max_bytes`. When a store takes the cache over the limit, the entries
164 /// written longest ago are removed in the same transaction. A response
165 /// that is larger than `max_bytes` on its own is not cached, and is
166 /// removed if it is already in the database.
167 ///
168 /// The limit counts the serialized entries, not the database file, which
169 /// is larger and does not shrink right away when entries are removed.
170 /// Entries already in the database count towards the limit. Do not open
171 /// one database with and without a limit at the same time, or let a
172 /// version of this crate without size limits write to it in between:
173 /// entries stored that way are not counted or removed until the manager
174 /// is opened again.
175 pub fn from_database_with_max_bytes(
176 db: Arc<Database>,
177 flush_interval: u64,
178 max_bytes: u64,
179 ) -> Result<Self> {
180 Self::open(db, flush_interval, Some(max_bytes))
181 }
182
183 fn open(
184 db: Arc<Database>,
185 flush_interval: u64,
186 max_bytes: Option<u64>,
187 ) -> Result<Self> {
188 // Ensure the table exists up front so reads never fail with
189 // "table does not exist".
190 let write_txn = db.begin_write()?;
191 match max_bytes {
192 Some(max_bytes) => {
193 let mut limited = Limited::open(&write_txn, &TABLES)?;
194 limited.index(|entry| entry.len() as u64)?;
195 // An entry `put` would not have stored goes first, so that
196 // evicting by age does not take the older entries with it.
197 for key in limited.oversized(max_bytes)? {
198 limited.remove(&key)?;
199 }
200 evict(&mut limited, max_bytes)?;
201 }
202 // Entries stored without a limit are not indexed, so an index
203 // left by an earlier limited manager would go stale.
204 None => {
205 write_txn.open_table(TABLE)?;
206 TABLES.delete_index(&write_txn)?;
207 }
208 }
209 write_txn.commit()?;
210 Ok(Self {
211 flush: Arc::new(FlushState {
212 db,
213 unflushed: AtomicU64::new(0),
214 interval: flush_interval.max(1),
215 }),
216 max_bytes,
217 })
218 }
219
220 /// Clears out the entire cache.
221 pub async fn clear(&self) -> Result<()> {
222 let write_txn = self.flush.db.begin_write()?;
223 write_txn.delete_table(TABLE)?;
224 TABLES.delete_index(&write_txn)?;
225 // Recreate the (now empty) table so subsequent reads still succeed.
226 {
227 let _table = write_txn.open_table(TABLE)?;
228 }
229 write_txn.commit()?;
230 Ok(())
231 }
232
233 /// Reads and decodes the stored entry for `cache_key`, if present.
234 /// Deserializes from the borrowed value while the read transaction is
235 /// alive to avoid copying the entry out of redb first.
236 fn read_entry(&self, cache_key: &str) -> Result<Option<Store>> {
237 let read_txn = self.flush.db.begin_read()?;
238 let table = read_txn.open_table(TABLE)?;
239 match table.get(cache_key)? {
240 Some(guard) => {
241 match postcard::from_bytes::<Store>(guard.value()) {
242 Ok(store) => Ok(Some(store)),
243 Err(e) => {
244 // Treat undecodable entries as a miss rather than an
245 // error, matching the other managers.
246 log::debug!(
247 "Failed to deserialize cache entry for key \
248 '{cache_key}': {e}"
249 );
250 Ok(None)
251 }
252 }
253 }
254 None => Ok(None),
255 }
256 }
257}
258
259impl CacheManager for RedbManager {
260 async fn get(
261 &self,
262 cache_key: &str,
263 ) -> Result<Option<(HttpResponse, CachePolicy)>> {
264 // A storage-level read error is treated as a cache miss (degrade to a
265 // fresh fetch) rather than a hard error, matching `CACacheManager`.
266 match self.read_entry(cache_key) {
267 Ok(Some(store)) => Ok(Some((store.response, store.policy))),
268 Ok(None) => Ok(None),
269 Err(e) => {
270 log::debug!("redb read failed for key '{cache_key}': {e}");
271 Ok(None)
272 }
273 }
274 }
275
276 async fn put(
277 &self,
278 cache_key: String,
279 response: HttpResponse,
280 policy: CachePolicy,
281 ) -> Result<HttpResponse> {
282 let data = Store { response, policy };
283 let bytes = postcard::to_allocvec(&data)?;
284 let mut write_txn = self.flush.db.begin_write()?;
285 write_txn.set_durability(Durability::None)?;
286 match self.max_bytes {
287 Some(max_bytes) => {
288 let mut limited = Limited::open(&write_txn, &TABLES)?;
289 let size = bytes.len() as u64;
290 // An entry over the limit is not stored, and must not leave
291 // an older response in its place.
292 if size > max_bytes {
293 limited.remove(&cache_key)?;
294 } else {
295 limited.insert(&cache_key, &bytes, size)?;
296 evict(&mut limited, max_bytes)?;
297 }
298 }
299 None => {
300 let mut table = write_txn.open_table(TABLE)?;
301 table.insert(cache_key.as_str(), bytes.as_slice())?;
302 }
303 }
304 write_txn.commit()?;
305 self.flush.record_write();
306 Ok(data.response)
307 }
308
309 async fn delete(&self, cache_key: &str) -> Result<()> {
310 // Deletes commit durably: an invalidation rolled back by a crash
311 // would resurrect an entry the origin already replaced.
312 let write_txn = self.flush.db.begin_write()?;
313 if self.max_bytes.is_some() {
314 Limited::open(&write_txn, &TABLES)?.remove(cache_key)?;
315 } else {
316 let mut table = write_txn.open_table(TABLE)?;
317 table.remove(cache_key)?;
318 }
319 write_txn.commit()?;
320 Ok(())
321 }
322}