Skip to main content

fyi_core/
storage.rs

1use std::time::Duration;
2
3use chrono::{DateTime, Utc};
4use thiserror::Error;
5
6use crate::{ApiStats, Event};
7
8/// A boxed error type for wrapping underlying storage errors.
9pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
10
11/// A simple string-based error for cases where we need to create
12/// an error from a message without an underlying error source.
13#[derive(Debug)]
14pub struct StringError(pub String);
15
16impl std::fmt::Display for StringError {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        write!(f, "{}", self.0)
19    }
20}
21
22impl std::error::Error for StringError {}
23
24#[derive(Error, Debug)]
25pub enum StorageError {
26    #[error("connection error: {0}")]
27    Connection(#[source] BoxError),
28    #[error("query error: {0}")]
29    Query(#[source] BoxError),
30    #[error("io error: {0}")]
31    Io(#[from] std::io::Error),
32}
33
34/// Sort order for query results
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Order {
37    /// Ascending order (oldest first for timestamps, lowest first for IDs)
38    Asc,
39    /// Descending order (newest first for timestamps, highest first for IDs)
40    #[default]
41    Desc,
42}
43
44/// Composable query builder for event retrieval.
45///
46/// `EventQuery` provides a fluent API for constructing event queries with
47/// filters, ordering, and pagination.
48///
49/// # Ordering Behavior
50///
51/// The query uses **implicit ordering** based on the query type:
52/// - When `after_id` is set: Results are ordered by `id` (ascending by default)
53///   to ensure consistent pagination when watching for new events.
54/// - Otherwise: Results are ordered by `timestamp` (descending by default)
55///   to show most recent events first.
56///
57/// The `direction()` method controls the sort direction (Asc/Desc) but not
58/// the column being sorted. This design ensures correct behavior for the two
59/// main use cases:
60/// - **Recent events**: Order by timestamp DESC to see newest first
61/// - **Watching new events**: Order by ID ASC to get events in insertion order
62///
63/// # Limitations
64///
65/// The ordering column (timestamp vs ID) is determined by query parameters.
66/// You cannot order by timestamp when using `after_id`, or order by ID when
67/// not using `after_id`. This is by design to optimize for the two main use
68/// cases, but reduces composability.
69///
70/// # Example
71/// ```ignore
72/// // Get 50 most recent events for a session
73/// let query = EventQuery::new()
74///     .with_session(Some("session-123".to_string()))
75///     .with_limit(50);
76///
77/// // Watch for new events after ID 100
78/// let query = EventQuery::new()
79///     .with_after_id(100)
80///     .with_limit(10);
81/// ```
82#[derive(Default, Clone)]
83pub struct EventQuery {
84    /// Filter by session ID
85    pub session_id: Option<String>,
86    /// Filter by event type (case-insensitive)
87    pub event_type: Option<String>,
88    /// Filter by permission mode
89    pub permission_mode: Option<String>,
90    /// Filter by framework (claude, cursor, gemini)
91    pub framework: Option<String>,
92    /// Filter events after this timestamp (exclusive)
93    pub after_ts: Option<DateTime<Utc>>,
94    /// Filter events before this timestamp (exclusive)
95    pub before_ts: Option<DateTime<Utc>>,
96    /// Filter events after this ID (exclusive) - triggers ID-based ordering
97    pub after_id: Option<i64>,
98    /// Maximum number of events to return
99    pub limit: Option<usize>,
100    /// Sort direction (default: Desc for timestamp queries, Asc for after_id queries)
101    pub direction: Option<Order>,
102    /// When true, only return API request events (events with token data)
103    pub api_requests_only: bool,
104    /// When true, exclude API request events
105    pub exclude_api_requests: bool,
106}
107
108impl EventQuery {
109    /// Create a new empty query
110    pub fn new() -> Self {
111        Self::default()
112    }
113
114    /// Filter events after the given timestamp (exclusive)
115    pub fn with_after_ts(mut self, ts: DateTime<Utc>) -> Self {
116        self.after_ts = Some(ts);
117        self
118    }
119
120    /// Filter events before the given timestamp (exclusive)
121    pub fn with_before_ts(mut self, ts: DateTime<Utc>) -> Self {
122        self.before_ts = Some(ts);
123        self
124    }
125
126    /// Filter events between two timestamps (exclusive on both ends).
127    ///
128    /// Note: If `start >= end`, the filter will return no results.
129    /// The caller is responsible for ensuring `start < end` for meaningful queries.
130    pub fn with_between_ts(mut self, start: DateTime<Utc>, end: DateTime<Utc>) -> Self {
131        self.after_ts = Some(start);
132        self.before_ts = Some(end);
133        self
134    }
135
136    /// Filter events after the given ID (exclusive).
137    ///
138    /// **Important**: Setting `after_id` changes the ordering behavior.
139    /// Results will be ordered by ID instead of timestamp to ensure
140    /// consistent pagination when watching for new events.
141    pub fn with_after_id(mut self, id: i64) -> Self {
142        self.after_id = Some(id);
143        self
144    }
145
146    /// Set the maximum number of events to return
147    pub fn with_limit(mut self, limit: usize) -> Self {
148        self.limit = Some(limit);
149        self
150    }
151
152    /// Set the sort direction (Asc/Desc).
153    ///
154    /// Note: This controls the direction only, not the column being sorted.
155    /// The column is determined by the query type (ID when `after_id` is set,
156    /// timestamp otherwise).
157    pub fn with_direction(mut self, direction: Order) -> Self {
158        self.direction = Some(direction);
159        self
160    }
161
162    /// Set session filter if value is Some
163    pub fn with_session(mut self, session_id: Option<String>) -> Self {
164        self.session_id = session_id;
165        self
166    }
167
168    /// Set event type filter if value is Some
169    pub fn with_event_type(mut self, event_type: Option<String>) -> Self {
170        self.event_type = event_type;
171        self
172    }
173
174    /// Set permission mode filter if value is Some
175    pub fn with_permission_mode(mut self, permission_mode: Option<String>) -> Self {
176        self.permission_mode = permission_mode;
177        self
178    }
179
180    /// Set framework filter if value is Some
181    pub fn with_framework(mut self, framework: Option<String>) -> Self {
182        self.framework = framework;
183        self
184    }
185
186    /// Only return API request events (events with token data)
187    pub fn api_requests_only(mut self) -> Self {
188        self.api_requests_only = true;
189        self.exclude_api_requests = false;
190        self
191    }
192
193    /// Exclude API request events from results
194    pub fn exclude_api_requests(mut self) -> Self {
195        self.exclude_api_requests = true;
196        self.api_requests_only = false;
197        self
198    }
199
200    /// Returns the effective sort direction for this query.
201    ///
202    /// Storage implementations should use this method to determine the sort
203    /// direction when executing queries.
204    ///
205    /// # Returns
206    /// - If `direction` is explicitly set, returns that value.
207    /// - If `after_id` is set, defaults to [`Order::Asc`] (for watching new events).
208    /// - Otherwise, defaults to [`Order::Desc`] (most recent first).
209    ///
210    /// # Example
211    /// ```
212    /// use fyi_core::{EventQuery, Order};
213    ///
214    /// // Default: Desc for recent events
215    /// let query = EventQuery::new();
216    /// assert_eq!(query.effective_direction(), Order::Desc);
217    ///
218    /// // With after_id: Asc for watching
219    /// let query = EventQuery::new().with_after_id(100);
220    /// assert_eq!(query.effective_direction(), Order::Asc);
221    ///
222    /// // Explicit direction overrides default
223    /// let query = EventQuery::new().with_direction(Order::Asc);
224    /// assert_eq!(query.effective_direction(), Order::Asc);
225    /// ```
226    pub fn effective_direction(&self) -> Order {
227        self.direction.unwrap_or_else(|| {
228            if self.after_id.is_some() {
229                Order::Asc
230            } else {
231                Order::Desc
232            }
233        })
234    }
235
236    /// Returns true if this query should order by ID instead of timestamp.
237    ///
238    /// Storage implementations should use this method to determine which column
239    /// to use for ordering results.
240    ///
241    /// When `after_id` is set, the query is typically used for "watching" new
242    /// events, so ordering by ID ensures consistent pagination.
243    ///
244    /// # Example
245    /// ```
246    /// use fyi_core::EventQuery;
247    ///
248    /// // Without after_id: order by timestamp
249    /// let query = EventQuery::new();
250    /// assert!(!query.orders_by_id());
251    ///
252    /// // With after_id: order by ID
253    /// let query = EventQuery::new().with_after_id(100);
254    /// assert!(query.orders_by_id());
255    /// ```
256    pub fn orders_by_id(&self) -> bool {
257        self.after_id.is_some()
258    }
259}
260
261/// Storage backend trait for fyi events
262///
263/// All events (including API requests) are stored in a unified events table.
264/// API requests are distinguished by having the `ApiRequest` event type and
265/// populated token fields.
266pub trait Storage {
267    /// Insert a new event, returns the event ID
268    fn insert(&self, event: &Event) -> Result<i64, StorageError>;
269
270    /// Query events using the composable EventQuery builder.
271    ///
272    /// This is the primary method for retrieving events. Use `EventQuery` to
273    /// specify filters, ordering, and pagination.
274    ///
275    /// # Ordering
276    /// - When `after_id` is set: Orders by `id` (ascending by default)
277    /// - Otherwise: Orders by `timestamp` (descending by default)
278    ///
279    /// # API Requests
280    /// Use `api_requests_only()` to filter to only API request events,
281    /// or `exclude_api_requests()` to exclude them.
282    ///
283    /// # Examples
284    /// ```ignore
285    /// // Get 50 most recent events (including API requests)
286    /// let events = storage.query(&EventQuery::new().with_limit(50))?;
287    ///
288    /// // Get events for a specific session
289    /// let events = storage.query(&EventQuery::new().with_session(Some("sess-123".to_string())).with_limit(100))?;
290    ///
291    /// // Watch for new events after a known ID
292    /// let events = storage.query(&EventQuery::new().with_after_id(last_id).with_limit(10))?;
293    ///
294    /// // Get only API request events
295    /// let api_events = storage.query(&EventQuery::new().api_requests_only().with_limit(50))?;
296    /// ```
297    fn query(&self, query: &EventQuery) -> Result<Vec<Event>, StorageError>;
298
299    /// Delete events older than the retention period, returns count deleted.
300    fn gc(&self, retention: Duration) -> Result<usize, StorageError>;
301
302    /// Count events older than the retention period (for dry-run).
303    fn count_expired(&self, retention: Duration) -> Result<usize, StorageError>;
304
305    /// Count total events
306    fn count(&self) -> Result<usize, StorageError>;
307
308    /// Get aggregated stats for API requests in a session.
309    ///
310    /// Returns token counts, costs, and timing information aggregated
311    /// across all API requests for the given session.
312    fn api_stats(&self, session_id: &str) -> Result<Option<ApiStats>, StorageError>;
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use std::error::Error;
319
320    #[test]
321    fn test_error_source_preserved() {
322        // Create an underlying IO error
323        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
324        let storage_err = StorageError::Connection(Box::new(io_err));
325
326        // Verify the error chain is preserved
327        let source = storage_err.source();
328        assert!(source.is_some(), "StorageError should have a source");
329        assert!(source.is_some_and(|s| s.to_string().contains("file not found")));
330    }
331
332    #[test]
333    fn test_string_error_works() {
334        let msg = "custom error message";
335        let storage_err = StorageError::Query(Box::new(StringError(msg.to_string())));
336
337        // Verify the error message is preserved
338        assert!(storage_err.to_string().contains(msg));
339        assert!(storage_err.source().is_some());
340    }
341}