fyi-core 0.1.0

Core types and traits for fyi
Documentation
use std::time::Duration;

use chrono::{DateTime, Utc};
use thiserror::Error;

use crate::{ApiStats, Event};

/// A boxed error type for wrapping underlying storage errors.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// A simple string-based error for cases where we need to create
/// an error from a message without an underlying error source.
#[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),
}

/// Sort order for query results
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
    /// Ascending order (oldest first for timestamps, lowest first for IDs)
    Asc,
    /// Descending order (newest first for timestamps, highest first for IDs)
    #[default]
    Desc,
}

/// Composable query builder for event retrieval.
///
/// `EventQuery` provides a fluent API for constructing event queries with
/// filters, ordering, and pagination.
///
/// # Ordering Behavior
///
/// The query uses **implicit ordering** based on the query type:
/// - When `after_id` is set: Results are ordered by `id` (ascending by default)
///   to ensure consistent pagination when watching for new events.
/// - Otherwise: Results are ordered by `timestamp` (descending by default)
///   to show most recent events first.
///
/// The `direction()` method controls the sort direction (Asc/Desc) but not
/// the column being sorted. This design ensures correct behavior for the two
/// main use cases:
/// - **Recent events**: Order by timestamp DESC to see newest first
/// - **Watching new events**: Order by ID ASC to get events in insertion order
///
/// # Limitations
///
/// The ordering column (timestamp vs ID) is determined by query parameters.
/// You cannot order by timestamp when using `after_id`, or order by ID when
/// not using `after_id`. This is by design to optimize for the two main use
/// cases, but reduces composability.
///
/// # Example
/// ```ignore
/// // Get 50 most recent events for a session
/// let query = EventQuery::new()
///     .with_session(Some("session-123".to_string()))
///     .with_limit(50);
///
/// // Watch for new events after ID 100
/// let query = EventQuery::new()
///     .with_after_id(100)
///     .with_limit(10);
/// ```
#[derive(Default, Clone)]
pub struct EventQuery {
    /// Filter by session ID
    pub session_id: Option<String>,
    /// Filter by event type (case-insensitive)
    pub event_type: Option<String>,
    /// Filter by permission mode
    pub permission_mode: Option<String>,
    /// Filter by framework (claude, cursor, gemini)
    pub framework: Option<String>,
    /// Filter events after this timestamp (exclusive)
    pub after_ts: Option<DateTime<Utc>>,
    /// Filter events before this timestamp (exclusive)
    pub before_ts: Option<DateTime<Utc>>,
    /// Filter events after this ID (exclusive) - triggers ID-based ordering
    pub after_id: Option<i64>,
    /// Maximum number of events to return
    pub limit: Option<usize>,
    /// Sort direction (default: Desc for timestamp queries, Asc for after_id queries)
    pub direction: Option<Order>,
    /// When true, only return API request events (events with token data)
    pub api_requests_only: bool,
    /// When true, exclude API request events
    pub exclude_api_requests: bool,
}

impl EventQuery {
    /// Create a new empty query
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter events after the given timestamp (exclusive)
    pub fn with_after_ts(mut self, ts: DateTime<Utc>) -> Self {
        self.after_ts = Some(ts);
        self
    }

    /// Filter events before the given timestamp (exclusive)
    pub fn with_before_ts(mut self, ts: DateTime<Utc>) -> Self {
        self.before_ts = Some(ts);
        self
    }

    /// Filter events between two timestamps (exclusive on both ends).
    ///
    /// Note: If `start >= end`, the filter will return no results.
    /// The caller is responsible for ensuring `start < end` for meaningful queries.
    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
    }

    /// Filter events after the given ID (exclusive).
    ///
    /// **Important**: Setting `after_id` changes the ordering behavior.
    /// Results will be ordered by ID instead of timestamp to ensure
    /// consistent pagination when watching for new events.
    pub fn with_after_id(mut self, id: i64) -> Self {
        self.after_id = Some(id);
        self
    }

    /// Set the maximum number of events to return
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set the sort direction (Asc/Desc).
    ///
    /// Note: This controls the direction only, not the column being sorted.
    /// The column is determined by the query type (ID when `after_id` is set,
    /// timestamp otherwise).
    pub fn with_direction(mut self, direction: Order) -> Self {
        self.direction = Some(direction);
        self
    }

    /// Set session filter if value is Some
    pub fn with_session(mut self, session_id: Option<String>) -> Self {
        self.session_id = session_id;
        self
    }

    /// Set event type filter if value is Some
    pub fn with_event_type(mut self, event_type: Option<String>) -> Self {
        self.event_type = event_type;
        self
    }

    /// Set permission mode filter if value is Some
    pub fn with_permission_mode(mut self, permission_mode: Option<String>) -> Self {
        self.permission_mode = permission_mode;
        self
    }

    /// Set framework filter if value is Some
    pub fn with_framework(mut self, framework: Option<String>) -> Self {
        self.framework = framework;
        self
    }

    /// Only return API request events (events with token data)
    pub fn api_requests_only(mut self) -> Self {
        self.api_requests_only = true;
        self.exclude_api_requests = false;
        self
    }

    /// Exclude API request events from results
    pub fn exclude_api_requests(mut self) -> Self {
        self.exclude_api_requests = true;
        self.api_requests_only = false;
        self
    }

    /// Returns the effective sort direction for this query.
    ///
    /// Storage implementations should use this method to determine the sort
    /// direction when executing queries.
    ///
    /// # Returns
    /// - If `direction` is explicitly set, returns that value.
    /// - If `after_id` is set, defaults to [`Order::Asc`] (for watching new events).
    /// - Otherwise, defaults to [`Order::Desc`] (most recent first).
    ///
    /// # Example
    /// ```
    /// use fyi_core::{EventQuery, Order};
    ///
    /// // Default: Desc for recent events
    /// let query = EventQuery::new();
    /// assert_eq!(query.effective_direction(), Order::Desc);
    ///
    /// // With after_id: Asc for watching
    /// let query = EventQuery::new().with_after_id(100);
    /// assert_eq!(query.effective_direction(), Order::Asc);
    ///
    /// // Explicit direction overrides default
    /// let query = EventQuery::new().with_direction(Order::Asc);
    /// assert_eq!(query.effective_direction(), Order::Asc);
    /// ```
    pub fn effective_direction(&self) -> Order {
        self.direction.unwrap_or_else(|| {
            if self.after_id.is_some() {
                Order::Asc
            } else {
                Order::Desc
            }
        })
    }

    /// Returns true if this query should order by ID instead of timestamp.
    ///
    /// Storage implementations should use this method to determine which column
    /// to use for ordering results.
    ///
    /// When `after_id` is set, the query is typically used for "watching" new
    /// events, so ordering by ID ensures consistent pagination.
    ///
    /// # Example
    /// ```
    /// use fyi_core::EventQuery;
    ///
    /// // Without after_id: order by timestamp
    /// let query = EventQuery::new();
    /// assert!(!query.orders_by_id());
    ///
    /// // With after_id: order by ID
    /// let query = EventQuery::new().with_after_id(100);
    /// assert!(query.orders_by_id());
    /// ```
    pub fn orders_by_id(&self) -> bool {
        self.after_id.is_some()
    }
}

/// Storage backend trait for fyi events
///
/// All events (including API requests) are stored in a unified events table.
/// API requests are distinguished by having the `ApiRequest` event type and
/// populated token fields.
pub trait Storage {
    /// Insert a new event, returns the event ID
    fn insert(&self, event: &Event) -> Result<i64, StorageError>;

    /// Query events using the composable EventQuery builder.
    ///
    /// This is the primary method for retrieving events. Use `EventQuery` to
    /// specify filters, ordering, and pagination.
    ///
    /// # Ordering
    /// - When `after_id` is set: Orders by `id` (ascending by default)
    /// - Otherwise: Orders by `timestamp` (descending by default)
    ///
    /// # API Requests
    /// Use `api_requests_only()` to filter to only API request events,
    /// or `exclude_api_requests()` to exclude them.
    ///
    /// # Examples
    /// ```ignore
    /// // Get 50 most recent events (including API requests)
    /// let events = storage.query(&EventQuery::new().with_limit(50))?;
    ///
    /// // Get events for a specific session
    /// let events = storage.query(&EventQuery::new().with_session(Some("sess-123".to_string())).with_limit(100))?;
    ///
    /// // Watch for new events after a known ID
    /// let events = storage.query(&EventQuery::new().with_after_id(last_id).with_limit(10))?;
    ///
    /// // Get only API request events
    /// let api_events = storage.query(&EventQuery::new().api_requests_only().with_limit(50))?;
    /// ```
    fn query(&self, query: &EventQuery) -> Result<Vec<Event>, StorageError>;

    /// Delete events older than the retention period, returns count deleted.
    fn gc(&self, retention: Duration) -> Result<usize, StorageError>;

    /// Count events older than the retention period (for dry-run).
    fn count_expired(&self, retention: Duration) -> Result<usize, StorageError>;

    /// Count total events
    fn count(&self) -> Result<usize, StorageError>;

    /// Get aggregated stats for API requests in a session.
    ///
    /// Returns token counts, costs, and timing information aggregated
    /// across all API requests for the given session.
    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() {
        // Create an underlying IO error
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let storage_err = StorageError::Connection(Box::new(io_err));

        // Verify the error chain is preserved
        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())));

        // Verify the error message is preserved
        assert!(storage_err.to_string().contains(msg));
        assert!(storage_err.source().is_some());
    }
}