use std::time::Duration;
use chrono::{DateTime, Utc};
use thiserror::Error;
use crate::{ApiStats, Event};
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug)]
pub struct StringError(pub String);
impl std::fmt::Display for StringError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for StringError {}
#[derive(Error, Debug)]
pub enum StorageError {
#[error("connection error: {0}")]
Connection(#[source] BoxError),
#[error("query error: {0}")]
Query(#[source] BoxError),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
Asc,
#[default]
Desc,
}
#[derive(Default, Clone)]
pub struct EventQuery {
pub session_id: Option<String>,
pub event_type: Option<String>,
pub permission_mode: Option<String>,
pub framework: Option<String>,
pub after_ts: Option<DateTime<Utc>>,
pub before_ts: Option<DateTime<Utc>>,
pub after_id: Option<i64>,
pub limit: Option<usize>,
pub direction: Option<Order>,
pub api_requests_only: bool,
pub exclude_api_requests: bool,
}
impl EventQuery {
pub fn new() -> Self {
Self::default()
}
pub fn with_after_ts(mut self, ts: DateTime<Utc>) -> Self {
self.after_ts = Some(ts);
self
}
pub fn with_before_ts(mut self, ts: DateTime<Utc>) -> Self {
self.before_ts = Some(ts);
self
}
pub fn with_between_ts(mut self, start: DateTime<Utc>, end: DateTime<Utc>) -> Self {
self.after_ts = Some(start);
self.before_ts = Some(end);
self
}
pub fn with_after_id(mut self, id: i64) -> Self {
self.after_id = Some(id);
self
}
pub fn with_limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn with_direction(mut self, direction: Order) -> Self {
self.direction = Some(direction);
self
}
pub fn with_session(mut self, session_id: Option<String>) -> Self {
self.session_id = session_id;
self
}
pub fn with_event_type(mut self, event_type: Option<String>) -> Self {
self.event_type = event_type;
self
}
pub fn with_permission_mode(mut self, permission_mode: Option<String>) -> Self {
self.permission_mode = permission_mode;
self
}
pub fn with_framework(mut self, framework: Option<String>) -> Self {
self.framework = framework;
self
}
pub fn api_requests_only(mut self) -> Self {
self.api_requests_only = true;
self.exclude_api_requests = false;
self
}
pub fn exclude_api_requests(mut self) -> Self {
self.exclude_api_requests = true;
self.api_requests_only = false;
self
}
pub fn effective_direction(&self) -> Order {
self.direction.unwrap_or_else(|| {
if self.after_id.is_some() {
Order::Asc
} else {
Order::Desc
}
})
}
pub fn orders_by_id(&self) -> bool {
self.after_id.is_some()
}
}
pub trait Storage {
fn insert(&self, event: &Event) -> Result<i64, StorageError>;
fn query(&self, query: &EventQuery) -> Result<Vec<Event>, StorageError>;
fn gc(&self, retention: Duration) -> Result<usize, StorageError>;
fn count_expired(&self, retention: Duration) -> Result<usize, StorageError>;
fn count(&self) -> Result<usize, StorageError>;
fn api_stats(&self, session_id: &str) -> Result<Option<ApiStats>, StorageError>;
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error;
#[test]
fn test_error_source_preserved() {
let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
let storage_err = StorageError::Connection(Box::new(io_err));
let source = storage_err.source();
assert!(source.is_some(), "StorageError should have a source");
assert!(source.is_some_and(|s| s.to_string().contains("file not found")));
}
#[test]
fn test_string_error_works() {
let msg = "custom error message";
let storage_err = StorageError::Query(Box::new(StringError(msg.to_string())));
assert!(storage_err.to_string().contains(msg));
assert!(storage_err.source().is_some());
}
}