use std::collections::VecDeque;
use std::fs::{self, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
use std::path::PathBuf;
use std::sync::{Mutex, PoisonError};
use crate::history::{RequestRecord, RequestSummary};
pub trait Storage: Send + Sync {
fn save(&self, record: &RequestRecord) -> io::Result<()>;
fn find(&self, id: u64) -> io::Result<Option<RequestRecord>>;
fn summaries(&self) -> io::Result<Vec<RequestSummary>>;
fn clear(&self) -> io::Result<()>;
fn prune(&self, keep: usize, oldest: u64) -> io::Result<()>;
}
static CUSTOM: std::sync::OnceLock<std::sync::Arc<dyn Storage>> = std::sync::OnceLock::new();
pub fn use_storage(storage: impl Storage + 'static) -> bool {
CUSTOM.set(std::sync::Arc::new(storage)).is_ok()
}
pub fn custom() -> Option<std::sync::Arc<dyn Storage>> {
CUSTOM.get().cloned()
}
impl<T: Storage + ?Sized> Storage for Box<T> {
fn save(&self, record: &RequestRecord) -> io::Result<()> {
(**self).save(record)
}
fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
(**self).find(id)
}
fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
(**self).summaries()
}
fn clear(&self) -> io::Result<()> {
(**self).clear()
}
fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
(**self).prune(keep, oldest)
}
}
impl<T: Storage + ?Sized> Storage for std::sync::Arc<T> {
fn save(&self, record: &RequestRecord) -> io::Result<()> {
(**self).save(record)
}
fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
(**self).find(id)
}
fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
(**self).summaries()
}
fn clear(&self) -> io::Result<()> {
(**self).clear()
}
fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
(**self).prune(keep, oldest)
}
}
#[derive(Default)]
pub struct MemoryStorage {
records: Mutex<VecDeque<RequestRecord>>,
}
impl Storage for MemoryStorage {
fn save(&self, record: &RequestRecord) -> io::Result<()> {
self.records().push_back(record.clone());
Ok(())
}
fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
Ok(self.records().iter().find(|record| record.id == id).cloned())
}
fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
Ok(self.records().iter().rev().map(RequestRecord::summary).collect())
}
fn clear(&self) -> io::Result<()> {
self.records().clear();
Ok(())
}
fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
let mut records = self.records();
while records.len() > keep || records.front().is_some_and(|record| record.id < oldest) {
records.pop_front();
}
Ok(())
}
}
impl MemoryStorage {
fn records(&self) -> std::sync::MutexGuard<'_, VecDeque<RequestRecord>> {
self.records.lock().unwrap_or_else(PoisonError::into_inner)
}
}
pub struct FileStorage {
directory: PathBuf,
writing: Mutex<()>,
}
impl FileStorage {
pub fn new(directory: impl Into<PathBuf>) -> Self {
Self {
directory: directory.into(),
writing: Mutex::default(),
}
}
fn index(&self) -> PathBuf {
self.directory.join("index.jsonl")
}
fn record(&self, id: u64) -> PathBuf {
self.directory.join(format!("{id}.json"))
}
fn oldest_first(&self) -> io::Result<Vec<RequestSummary>> {
let file = match fs::File::open(self.index()) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error),
};
Ok(BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter_map(|line| serde_json::from_str(&line).ok())
.collect())
}
}
impl Storage for FileStorage {
fn save(&self, record: &RequestRecord) -> io::Result<()> {
let _writing = self.writing.lock().unwrap_or_else(PoisonError::into_inner);
fs::create_dir_all(&self.directory)?;
fs::write(self.record(record.id), serde_json::to_vec(record)?)?;
let mut line = serde_json::to_vec(&record.summary())?;
line.push(b'\n');
OpenOptions::new()
.create(true)
.append(true)
.open(self.index())?
.write_all(&line)
}
fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
match fs::read(self.record(id)) {
Ok(bytes) => Ok(serde_json::from_slice(&bytes).ok()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
let mut summaries = self.oldest_first()?;
summaries.reverse();
Ok(summaries)
}
fn clear(&self) -> io::Result<()> {
let _writing = self.writing.lock().unwrap_or_else(PoisonError::into_inner);
match fs::remove_dir_all(&self.directory) {
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
_ => Ok(()),
}
}
fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
let _writing = self.writing.lock().unwrap_or_else(PoisonError::into_inner);
let summaries = self.oldest_first()?;
let expired = summaries.iter().take_while(|summary| summary.id < oldest).count();
if expired == 0 && summaries.len() <= keep + keep / 5 {
return Ok(());
}
let (removed, kept) = summaries.split_at(expired.max(summaries.len().saturating_sub(keep)));
for summary in removed {
let _ = fs::remove_file(self.record(summary.id));
}
let mut index = Vec::new();
for summary in kept {
index.extend(serde_json::to_vec(summary)?);
index.push(b'\n');
}
let temporary = self.directory.join("index.jsonl.tmp");
fs::write(&temporary, index)?;
fs::rename(temporary, self.index())
}
}
#[cfg(feature = "sqlite-storage")]
pub struct SqliteStorage {
connection: Mutex<rusqlite::Connection>,
}
#[cfg(feature = "sqlite-storage")]
impl SqliteStorage {
pub fn open(path: impl AsRef<std::path::Path>) -> io::Result<Self> {
if let Some(directory) = path.as_ref().parent() {
fs::create_dir_all(directory)?;
}
let connection = rusqlite::Connection::open(path).map_err(io::Error::other)?;
connection
.execute_batch(
"PRAGMA journal_mode = WAL;
PRAGMA busy_timeout = 2000;
CREATE TABLE IF NOT EXISTS debugbar_records (
id INTEGER PRIMARY KEY,
summary TEXT NOT NULL,
record TEXT NOT NULL
);",
)
.map_err(io::Error::other)?;
Ok(Self {
connection: Mutex::new(connection),
})
}
fn connection(&self) -> std::sync::MutexGuard<'_, rusqlite::Connection> {
self.connection.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[cfg(feature = "sqlite-storage")]
impl Storage for SqliteStorage {
fn save(&self, record: &RequestRecord) -> io::Result<()> {
let summary = serde_json::to_string(&record.summary())?;
let data = serde_json::to_string(record)?;
self.connection()
.execute(
"INSERT OR REPLACE INTO debugbar_records (id, summary, record) VALUES (?1, ?2, ?3)",
rusqlite::params![record.id as i64, summary, data],
)
.map_err(io::Error::other)?;
Ok(())
}
fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
let connection = self.connection();
let mut statement = connection
.prepare("SELECT record FROM debugbar_records WHERE id = ?1")
.map_err(io::Error::other)?;
let mut rows = statement.query([id as i64]).map_err(io::Error::other)?;
match rows.next().map_err(io::Error::other)? {
Some(row) => {
let data: String = row.get(0).map_err(io::Error::other)?;
Ok(serde_json::from_str(&data).ok())
}
None => Ok(None),
}
}
fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
let connection = self.connection();
let mut statement = connection
.prepare("SELECT summary FROM debugbar_records ORDER BY id DESC")
.map_err(io::Error::other)?;
let summaries = statement
.query_map([], |row| row.get::<_, String>(0))
.map_err(io::Error::other)?
.filter_map(Result::ok)
.filter_map(|summary| serde_json::from_str(&summary).ok())
.collect();
Ok(summaries)
}
fn clear(&self) -> io::Result<()> {
self.connection()
.execute("DELETE FROM debugbar_records", [])
.map_err(io::Error::other)?;
Ok(())
}
fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
self.connection()
.execute(
"DELETE FROM debugbar_records WHERE id < ?2 OR id NOT IN (SELECT id FROM debugbar_records ORDER BY id DESC LIMIT ?1)",
[keep as i64, oldest as i64],
)
.map_err(io::Error::other)?;
Ok(())
}
}
#[cfg(feature = "redis-storage")]
pub struct RedisStorage {
client: redis::Client,
database: Option<u32>,
prefix: String,
connection: Mutex<Option<redis::Connection>>,
}
#[cfg(feature = "redis-storage")]
impl RedisStorage {
pub fn open(url: &str, database: Option<u32>, prefix: impl Into<String>) -> io::Result<Self> {
Ok(Self {
client: redis::Client::open(url).map_err(io::Error::other)?,
database,
prefix: prefix.into(),
connection: Mutex::default(),
})
}
fn key(&self, name: &str) -> String {
format!("{}{name}", self.prefix)
}
fn record_key(&self, id: u64) -> String {
self.key(&format!("record:{id}"))
}
fn run<T>(&self, command: impl FnOnce(&mut redis::Connection) -> redis::RedisResult<T>) -> io::Result<T> {
let mut slot = self.connection.lock().unwrap_or_else(PoisonError::into_inner);
if slot.is_none() {
let mut connection = self
.client
.get_connection_with_timeout(std::time::Duration::from_secs(1))
.map_err(io::Error::other)?;
connection
.set_read_timeout(Some(std::time::Duration::from_secs(5)))
.map_err(io::Error::other)?;
if let Some(database) = self.database {
redis::cmd("SELECT")
.arg(database)
.exec(&mut connection)
.map_err(io::Error::other)?;
}
*slot = Some(connection);
}
let result = command(slot.as_mut().expect("connected above"));
if result.as_ref().is_err_and(|error| error.is_unrecoverable_error()) {
*slot = None;
}
result.map_err(io::Error::other)
}
fn forget(&self, connection: &mut redis::Connection, ids: &[u64]) -> redis::RedisResult<()> {
if ids.is_empty() {
return Ok(());
}
let records: Vec<String> = ids.iter().map(|id| self.record_key(*id)).collect();
redis::pipe()
.atomic()
.del(records)
.hdel(self.key("summaries"), ids)
.zrem(self.key("index"), ids)
.exec(connection)
}
}
#[cfg(feature = "redis-storage")]
impl Storage for RedisStorage {
fn save(&self, record: &RequestRecord) -> io::Result<()> {
let data = serde_json::to_string(record)?;
let summary = serde_json::to_string(&record.summary())?;
self.run(|connection| {
redis::pipe()
.atomic()
.set(self.record_key(record.id), data)
.hset(self.key("summaries"), record.id, summary)
.zadd(self.key("index"), record.id, record.id as f64)
.exec(connection)
})
}
fn find(&self, id: u64) -> io::Result<Option<RequestRecord>> {
let data: Option<String> =
self.run(|connection| redis::cmd("GET").arg(self.record_key(id)).query(connection))?;
Ok(data.and_then(|data| serde_json::from_str(&data).ok()))
}
fn summaries(&self) -> io::Result<Vec<RequestSummary>> {
let summaries: Vec<Option<String>> = self.run(|connection| {
let ids: Vec<u64> = redis::cmd("ZREVRANGE")
.arg(self.key("index"))
.arg(0)
.arg(-1)
.query(connection)?;
if ids.is_empty() {
return Ok(Vec::new());
}
redis::cmd("HMGET")
.arg(self.key("summaries"))
.arg(ids)
.query(connection)
})?;
Ok(summaries
.into_iter()
.flatten()
.filter_map(|summary| serde_json::from_str(&summary).ok())
.collect())
}
fn clear(&self) -> io::Result<()> {
self.run(|connection| {
let ids: Vec<u64> = redis::cmd("ZRANGE")
.arg(self.key("index"))
.arg(0)
.arg(-1)
.query(connection)?;
self.forget(connection, &ids)
})
}
fn prune(&self, keep: usize, oldest: u64) -> io::Result<()> {
self.run(|connection| {
let mut ids: Vec<u64> = redis::cmd("ZRANGEBYSCORE")
.arg(self.key("index"))
.arg("-inf")
.arg(format!("({oldest}"))
.query(connection)?;
let overflow: Vec<u64> = redis::cmd("ZRANGE")
.arg(self.key("index"))
.arg(0)
.arg(-(keep as i64) - 1)
.query(connection)?;
ids.extend(overflow);
ids.sort_unstable();
ids.dedup();
self.forget(connection, &ids)
})
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU64, Ordering};
use super::{FileStorage, MemoryStorage, Storage};
use crate::history::{RecordKind, RequestRecord};
fn directory() -> std::path::PathBuf {
static NEXT: AtomicU64 = AtomicU64::new(0);
std::env::temp_dir().join(format!(
"debugbar-storage-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
))
}
fn record(id: u64) -> RequestRecord {
RequestRecord::new(id, RecordKind::Request, "GET", format!("/pages/{id}"))
}
fn keeps_records_and_lists_the_newest_first(storage: &dyn Storage) {
storage.save(&record(1)).unwrap();
storage.save(&record(2)).unwrap();
let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
assert_eq!(ids, [2, 1]);
assert_eq!(storage.find(1).unwrap().unwrap().uri, "/pages/1");
assert!(storage.find(3).unwrap().is_none());
}
#[test]
fn memory_storage_keeps_records_and_lists_the_newest_first() {
keeps_records_and_lists_the_newest_first(&MemoryStorage::default());
}
#[test]
fn file_storage_keeps_records_and_lists_the_newest_first() {
let directory = directory();
keeps_records_and_lists_the_newest_first(&FileStorage::new(&directory));
assert!(FileStorage::new(&directory).find(2).unwrap().is_some());
FileStorage::new(&directory).clear().unwrap();
}
#[cfg(feature = "sqlite-storage")]
#[test]
fn sqlite_storage_keeps_prunes_and_clears_records() {
let path = directory().with_extension("sqlite");
let storage = super::SqliteStorage::open(&path).unwrap();
keeps_records_and_lists_the_newest_first(&storage);
for id in 3..=12 {
storage.save(&record(id)).unwrap();
}
storage.prune(5, 0).unwrap();
storage.prune(5, 10).unwrap();
let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
assert_eq!(ids, [12, 11, 10]);
storage.clear().unwrap();
assert!(storage.summaries().unwrap().is_empty());
let _ = std::fs::remove_file(path);
}
#[test]
fn file_storage_prunes_the_oldest_records_and_their_files() {
let storage = FileStorage::new(directory());
for id in 1..=13 {
storage.save(&record(id)).unwrap();
storage.prune(10, 0).unwrap();
}
let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
assert!(ids.len() <= 12 && ids.len() >= 10);
assert_eq!(ids[0], 13);
assert!(storage.find(1).unwrap().is_none());
storage.clear().unwrap();
assert!(storage.summaries().unwrap().is_empty());
}
#[cfg(feature = "redis-storage")]
#[test]
#[ignore = "needs a Redis server at REDIS_URL"]
fn redis_storage_keeps_prunes_and_clears_records() {
let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_owned());
let prefix = format!("debugbar-test-{}:", std::process::id());
let storage = super::RedisStorage::open(&url, Some(15), prefix).unwrap();
keeps_records_and_lists_the_newest_first(&storage);
for id in 3..=12 {
storage.save(&record(id)).unwrap();
}
storage.prune(5, 0).unwrap();
storage.prune(5, 10).unwrap();
let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
assert_eq!(ids, [12, 11, 10]);
assert!(storage.find(9).unwrap().is_none());
storage.clear().unwrap();
assert!(storage.summaries().unwrap().is_empty());
}
#[test]
fn records_older_than_the_cutoff_are_pruned_whatever_the_count() {
let directory = directory();
let file = FileStorage::new(&directory);
let memory = MemoryStorage::default();
for storage in [&file as &dyn Storage, &memory] {
for id in 1..=4 {
storage.save(&record(id)).unwrap();
}
storage.prune(50, 3).unwrap();
let ids: Vec<u64> = storage.summaries().unwrap().iter().map(|summary| summary.id).collect();
assert_eq!(ids, [4, 3]);
assert!(storage.find(1).unwrap().is_none());
}
file.clear().unwrap();
}
}