Skip to main content

laravel_rust_debugbar/
storage.rs

1use std::collections::VecDeque;
2use std::fs::{self, OpenOptions};
3use std::io::{self, BufRead, BufReader, Write};
4use std::path::PathBuf;
5use std::sync::{Mutex, PoisonError};
6
7use crate::history::{RequestRecord, RequestSummary};
8
9pub trait Storage: Send + Sync {
10    fn save(&self, record: &RequestRecord) -> io::Result<()>;
11
12    fn find(&self, id: u64) -> io::Result<Option<RequestRecord>>;
13
14    fn summaries(&self) -> io::Result<Vec<RequestSummary>>;
15
16    fn clear(&self) -> io::Result<()>;
17
18    fn prune(&self, keep: usize, oldest: u64) -> io::Result<()>;
19}
20
21static CUSTOM: std::sync::OnceLock<std::sync::Arc<dyn Storage>> = std::sync::OnceLock::new();
22
23pub fn use_storage(storage: impl Storage + 'static) -> bool {
24    CUSTOM.set(std::sync::Arc::new(storage)).is_ok()
25}
26
27pub fn custom() -> Option<std::sync::Arc<dyn Storage>> {
28    CUSTOM.get().cloned()
29}
30
31impl<T: Storage + ?Sized> Storage for Box<T> {
32    fn save(&self, record: &RequestRecord) -> io::Result<()> {
33        (**self).save(record)
34    }
35
36    fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
37        (**self).find(id)
38    }
39
40    fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
41        (**self).summaries()
42    }
43
44    fn clear(&self) -> io::Result<()> {
45        (**self).clear()
46    }
47
48    fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
49        (**self).prune(keep, oldest)
50    }
51}
52
53impl<T: Storage + ?Sized> Storage for std::sync::Arc<T> {
54    fn save(&self, record: &RequestRecord) -> io::Result<()> {
55        (**self).save(record)
56    }
57
58    fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
59        (**self).find(id)
60    }
61
62    fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
63        (**self).summaries()
64    }
65
66    fn clear(&self) -> io::Result<()> {
67        (**self).clear()
68    }
69
70    fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
71        (**self).prune(keep, oldest)
72    }
73}
74
75#[derive(Default)]
76pub struct MemoryStorage {
77    records: Mutex<VecDeque<RequestRecord>>,
78}
79
80impl Storage for MemoryStorage {
81    fn save(&self, record: &RequestRecord) -> io::Result<()> {
82        self.records().push_back(record.clone());
83        Ok(())
84    }
85
86    fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
87        Ok(self.records().iter().find(|record| record.id == id).cloned())
88    }
89
90    fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
91        Ok(self.records().iter().rev().map(RequestRecord::summary).collect())
92    }
93
94    fn clear(&self) -> io::Result<()> {
95        self.records().clear();
96        Ok(())
97    }
98
99    fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
100        let mut records = self.records();
101        while records.len() > keep || records.front().is_some_and(|record| record.id < oldest) {
102            records.pop_front();
103        }
104        Ok(())
105    }
106}
107
108impl MemoryStorage {
109    fn records(&self) -> std::sync::MutexGuard<'_, VecDeque<RequestRecord>> {
110        self.records.lock().unwrap_or_else(PoisonError::into_inner)
111    }
112}
113
114pub struct FileStorage {
115    directory: PathBuf,
116    writing: Mutex<()>,
117}
118
119impl FileStorage {
120    pub fn new(directory: impl Into<PathBuf>) -> Self {
121        Self {
122            directory: directory.into(),
123            writing: Mutex::default(),
124        }
125    }
126
127    fn index(&self) -> PathBuf {
128        self.directory.join("index.jsonl")
129    }
130
131    fn record(&self, id: u64) -> PathBuf {
132        self.directory.join(format!("{id}.json"))
133    }
134
135    fn oldest_first(&self) -> io::Result<Vec<RequestSummary>> {
136        let file = match fs::File::open(self.index()) {
137            Ok(file) => file,
138            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
139            Err(error) => return Err(error),
140        };
141
142        Ok(BufReader::new(file)
143            .lines()
144            .map_while(Result::ok)
145            .filter_map(|line| serde_json::from_str(&line).ok())
146            .collect())
147    }
148}
149
150impl Storage for FileStorage {
151    fn save(&self, record: &RequestRecord) -> io::Result<()> {
152        let _writing = self.writing.lock().unwrap_or_else(PoisonError::into_inner);
153        fs::create_dir_all(&self.directory)?;
154        fs::write(self.record(record.id), serde_json::to_vec(record)?)?;
155
156        let mut line = serde_json::to_vec(&record.summary())?;
157        line.push(b'\n');
158        OpenOptions::new()
159            .create(true)
160            .append(true)
161            .open(self.index())?
162            .write_all(&line)
163    }
164
165    fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
166        match fs::read(self.record(id)) {
167            Ok(bytes) => Ok(serde_json::from_slice(&bytes).ok()),
168            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
169            Err(error) => Err(error),
170        }
171    }
172
173    fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
174        let mut summaries = self.oldest_first()?;
175        summaries.reverse();
176        Ok(summaries)
177    }
178
179    fn clear(&self) -> io::Result<()> {
180        let _writing = self.writing.lock().unwrap_or_else(PoisonError::into_inner);
181        match fs::remove_dir_all(&self.directory) {
182            Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
183            _ => Ok(()),
184        }
185    }
186
187    fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
188        let _writing = self.writing.lock().unwrap_or_else(PoisonError::into_inner);
189        let summaries = self.oldest_first()?;
190        let expired = summaries.iter().take_while(|summary| summary.id < oldest).count();
191        if expired == 0 && summaries.len() <= keep + keep / 5 {
192            return Ok(());
193        }
194
195        let (removed, kept) = summaries.split_at(expired.max(summaries.len().saturating_sub(keep)));
196        for summary in removed {
197            let _ = fs::remove_file(self.record(summary.id));
198        }
199
200        let mut index = Vec::new();
201        for summary in kept {
202            index.extend(serde_json::to_vec(summary)?);
203            index.push(b'\n');
204        }
205        let temporary = self.directory.join("index.jsonl.tmp");
206        fs::write(&temporary, index)?;
207        fs::rename(temporary, self.index())
208    }
209}
210
211#[cfg(feature = "sqlite-storage")]
212pub struct SqliteStorage {
213    connection: Mutex<rusqlite::Connection>,
214}
215
216#[cfg(feature = "sqlite-storage")]
217impl SqliteStorage {
218    pub fn open(path: impl AsRef<std::path::Path>) -> io::Result<Self> {
219        if let Some(directory) = path.as_ref().parent() {
220            fs::create_dir_all(directory)?;
221        }
222        let connection = rusqlite::Connection::open(path).map_err(io::Error::other)?;
223        connection
224            .execute_batch(
225                "PRAGMA journal_mode = WAL;
226                 PRAGMA busy_timeout = 2000;
227                 CREATE TABLE IF NOT EXISTS debugbar_records (
228                     id INTEGER PRIMARY KEY,
229                     summary TEXT NOT NULL,
230                     record TEXT NOT NULL
231                 );",
232            )
233            .map_err(io::Error::other)?;
234
235        Ok(Self {
236            connection: Mutex::new(connection),
237        })
238    }
239
240    fn connection(&self) -> std::sync::MutexGuard<'_, rusqlite::Connection> {
241        self.connection.lock().unwrap_or_else(PoisonError::into_inner)
242    }
243}
244
245#[cfg(feature = "sqlite-storage")]
246impl Storage for SqliteStorage {
247    fn save(&self, record: &RequestRecord) -> io::Result<()> {
248        let summary = serde_json::to_string(&record.summary())?;
249        let data = serde_json::to_string(record)?;
250        self.connection()
251            .execute(
252                "INSERT OR REPLACE INTO debugbar_records (id, summary, record) VALUES (?1, ?2, ?3)",
253                rusqlite::params![record.id as i64, summary, data],
254            )
255            .map_err(io::Error::other)?;
256        Ok(())
257    }
258
259    fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
260        let connection = self.connection();
261        let mut statement = connection
262            .prepare("SELECT record FROM debugbar_records WHERE id = ?1")
263            .map_err(io::Error::other)?;
264        let mut rows = statement.query([id as i64]).map_err(io::Error::other)?;
265
266        match rows.next().map_err(io::Error::other)? {
267            Some(row) => {
268                let data: String = row.get(0).map_err(io::Error::other)?;
269                Ok(serde_json::from_str(&data).ok())
270            }
271            None => Ok(None),
272        }
273    }
274
275    fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
276        let connection = self.connection();
277        let mut statement = connection
278            .prepare("SELECT summary FROM debugbar_records ORDER BY id DESC")
279            .map_err(io::Error::other)?;
280        let summaries = statement
281            .query_map([], |row| row.get::<_, String>(0))
282            .map_err(io::Error::other)?
283            .filter_map(Result::ok)
284            .filter_map(|summary| serde_json::from_str(&summary).ok())
285            .collect();
286
287        Ok(summaries)
288    }
289
290    fn clear(&self) -> io::Result<()> {
291        self.connection()
292            .execute("DELETE FROM debugbar_records", [])
293            .map_err(io::Error::other)?;
294        Ok(())
295    }
296
297    fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
298        self.connection()
299            .execute(
300                "DELETE FROM debugbar_records WHERE id < ?2 OR id NOT IN (SELECT id FROM debugbar_records ORDER BY id DESC LIMIT ?1)",
301                [keep as i64, oldest as i64],
302            )
303            .map_err(io::Error::other)?;
304        Ok(())
305    }
306}
307
308#[cfg(feature = "redis-storage")]
309pub struct RedisStorage {
310    client: redis::Client,
311    database: Option<u32>,
312    prefix: String,
313    connection: Mutex<Option<redis::Connection>>,
314}
315
316#[cfg(feature = "redis-storage")]
317impl RedisStorage {
318    pub fn open(url: &str, database: Option<u32>, prefix: impl Into<String>) -> io::Result<Self> {
319        Ok(Self {
320            client: redis::Client::open(url).map_err(io::Error::other)?,
321            database,
322            prefix: prefix.into(),
323            connection: Mutex::default(),
324        })
325    }
326
327    fn key(&self, name: &str) -> String {
328        format!("{}{name}", self.prefix)
329    }
330
331    fn record_key(&self, id: u64) -> String {
332        self.key(&format!("record:{id}"))
333    }
334
335    fn run<T>(&self, command: impl FnOnce(&mut redis::Connection) -> redis::RedisResult<T>) -> io::Result<T> {
336        let mut slot = self.connection.lock().unwrap_or_else(PoisonError::into_inner);
337        if slot.is_none() {
338            let mut connection = self
339                .client
340                .get_connection_with_timeout(std::time::Duration::from_secs(1))
341                .map_err(io::Error::other)?;
342            connection
343                .set_read_timeout(Some(std::time::Duration::from_secs(5)))
344                .map_err(io::Error::other)?;
345            if let Some(database) = self.database {
346                redis::cmd("SELECT")
347                    .arg(database)
348                    .exec(&mut connection)
349                    .map_err(io::Error::other)?;
350            }
351            *slot = Some(connection);
352        }
353
354        let result = command(slot.as_mut().expect("connected above"));
355        if result.as_ref().is_err_and(|error| error.is_unrecoverable_error()) {
356            *slot = None;
357        }
358        result.map_err(io::Error::other)
359    }
360
361    fn forget(&self, connection: &mut redis::Connection, ids: &[u64]) -> redis::RedisResult<()> {
362        if ids.is_empty() {
363            return Ok(());
364        }
365        let records: Vec<String> = ids.iter().map(|id| self.record_key(*id)).collect();
366        redis::pipe()
367            .atomic()
368            .del(records)
369            .hdel(self.key("summaries"), ids)
370            .zrem(self.key("index"), ids)
371            .exec(connection)
372    }
373}
374
375#[cfg(feature = "redis-storage")]
376impl Storage for RedisStorage {
377    fn save(&self, record: &RequestRecord) -> io::Result<()> {
378        let data = serde_json::to_string(record)?;
379        let summary = serde_json::to_string(&record.summary())?;
380
381        self.run(|connection| {
382            redis::pipe()
383                .atomic()
384                .set(self.record_key(record.id), data)
385                .hset(self.key("summaries"), record.id, summary)
386                .zadd(self.key("index"), record.id, record.id as f64)
387                .exec(connection)
388        })
389    }
390
391    fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
392        let data: Option<String> =
393            self.run(|connection| redis::cmd("GET").arg(self.record_key(id)).query(connection))?;
394
395        Ok(data.and_then(|data| serde_json::from_str(&data).ok()))
396    }
397
398    fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
399        let summaries: Vec<Option<String>> = self.run(|connection| {
400            let ids: Vec<u64> = redis::cmd("ZREVRANGE")
401                .arg(self.key("index"))
402                .arg(0)
403                .arg(-1)
404                .query(connection)?;
405            if ids.is_empty() {
406                return Ok(Vec::new());
407            }
408            redis::cmd("HMGET")
409                .arg(self.key("summaries"))
410                .arg(ids)
411                .query(connection)
412        })?;
413
414        Ok(summaries
415            .into_iter()
416            .flatten()
417            .filter_map(|summary| serde_json::from_str(&summary).ok())
418            .collect())
419    }
420
421    fn clear(&self) -> io::Result<()> {
422        self.run(|connection| {
423            let ids: Vec<u64> = redis::cmd("ZRANGE")
424                .arg(self.key("index"))
425                .arg(0)
426                .arg(-1)
427                .query(connection)?;
428            self.forget(connection, &ids)
429        })
430    }
431
432    fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
433        self.run(|connection| {
434            let mut ids: Vec<u64> = redis::cmd("ZRANGEBYSCORE")
435                .arg(self.key("index"))
436                .arg("-inf")
437                .arg(format!("({oldest}"))
438                .query(connection)?;
439            let overflow: Vec<u64> = redis::cmd("ZRANGE")
440                .arg(self.key("index"))
441                .arg(0)
442                .arg(-(keep as i64) - 1)
443                .query(connection)?;
444            ids.extend(overflow);
445            ids.sort_unstable();
446            ids.dedup();
447            self.forget(connection, &ids)
448        })
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use std::sync::atomic::{AtomicU64, Ordering};
455
456    use super::{FileStorage, MemoryStorage, Storage};
457    use crate::history::{RecordKind, RequestRecord};
458
459    fn directory() -> std::path::PathBuf {
460        static NEXT: AtomicU64 = AtomicU64::new(0);
461        std::env::temp_dir().join(format!(
462            "debugbar-storage-{}-{}",
463            std::process::id(),
464            NEXT.fetch_add(1, Ordering::Relaxed)
465        ))
466    }
467
468    fn record(id: u64) -> RequestRecord {
469        RequestRecord::new(id, RecordKind::Request, "GET", format!("/pages/{id}"))
470    }
471
472    fn keeps_records_and_lists_the_newest_first(storage: &dyn Storage) {
473        storage.save(&record(1)).unwrap();
474        storage.save(&record(2)).unwrap();
475
476        let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
477        assert_eq!(ids, [2, 1]);
478        assert_eq!(storage.find(1).unwrap().unwrap().uri, "/pages/1");
479        assert!(storage.find(3).unwrap().is_none());
480    }
481
482    #[test]
483    fn memory_storage_keeps_records_and_lists_the_newest_first() {
484        keeps_records_and_lists_the_newest_first(&MemoryStorage::default());
485    }
486
487    #[test]
488    fn file_storage_keeps_records_and_lists_the_newest_first() {
489        let directory = directory();
490        keeps_records_and_lists_the_newest_first(&FileStorage::new(&directory));
491        assert!(FileStorage::new(&directory).find(2).unwrap().is_some());
492        FileStorage::new(&directory).clear().unwrap();
493    }
494
495    #[cfg(feature = "sqlite-storage")]
496    #[test]
497    fn sqlite_storage_keeps_prunes_and_clears_records() {
498        let path = directory().with_extension("sqlite");
499        let storage = super::SqliteStorage::open(&path).unwrap();
500        keeps_records_and_lists_the_newest_first(&storage);
501
502        for id in 3..=12 {
503            storage.save(&record(id)).unwrap();
504        }
505        storage.prune(5, 0).unwrap();
506        storage.prune(5, 10).unwrap();
507        let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
508        assert_eq!(ids, [12, 11, 10]);
509
510        storage.clear().unwrap();
511        assert!(storage.summaries().unwrap().is_empty());
512        let _ = std::fs::remove_file(path);
513    }
514
515    #[test]
516    fn file_storage_prunes_the_oldest_records_and_their_files() {
517        let storage = FileStorage::new(directory());
518        for id in 1..=13 {
519            storage.save(&record(id)).unwrap();
520            storage.prune(10, 0).unwrap();
521        }
522
523        let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
524        assert!(ids.len() <= 12 && ids.len() >= 10);
525        assert_eq!(ids[0], 13);
526        assert!(storage.find(1).unwrap().is_none());
527        storage.clear().unwrap();
528        assert!(storage.summaries().unwrap().is_empty());
529    }
530
531    #[cfg(feature = "redis-storage")]
532    #[test]
533    #[ignore = "needs a Redis server at REDIS_URL"]
534    fn redis_storage_keeps_prunes_and_clears_records() {
535        let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_owned());
536        let prefix = format!("debugbar-test-{}:", std::process::id());
537        let storage = super::RedisStorage::open(&url, Some(15), prefix).unwrap();
538        keeps_records_and_lists_the_newest_first(&storage);
539
540        for id in 3..=12 {
541            storage.save(&record(id)).unwrap();
542        }
543        storage.prune(5, 0).unwrap();
544        storage.prune(5, 10).unwrap();
545        let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
546        assert_eq!(ids, [12, 11, 10]);
547        assert!(storage.find(9).unwrap().is_none());
548
549        storage.clear().unwrap();
550        assert!(storage.summaries().unwrap().is_empty());
551    }
552
553    #[test]
554    fn records_older_than_the_cutoff_are_pruned_whatever_the_count() {
555        let directory = directory();
556        let file = FileStorage::new(&directory);
557        let memory = MemoryStorage::default();
558
559        for storage in [&file as &dyn Storage, &memory] {
560            for id in 1..=4 {
561                storage.save(&record(id)).unwrap();
562            }
563            storage.prune(50, 3).unwrap();
564
565            let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
566            assert_eq!(ids, [4, 3]);
567            assert!(storage.find(1).unwrap().is_none());
568        }
569        file.clear().unwrap();
570    }
571}