Skip to main content

DataStore

Struct DataStore 

Source
pub struct DataStore { /* private fields */ }
Expand description

Central data store for ccboard

Thread-safe access to all Claude Code data. Uses DashMap for sessions (high contention) and RwLock for stats/settings (low contention).

Implementations§

Source§

impl DataStore

Source

pub fn new( claude_home: PathBuf, project_path: Option<PathBuf>, config: DataStoreConfig, ) -> Self

Create a new data store

Source

pub fn with_defaults( claude_home: PathBuf, project_path: Option<PathBuf>, ) -> Self

Create with default configuration

Source

pub fn event_bus(&self) -> &EventBus

Get the event bus for subscribing to updates

Source

pub fn degraded_state(&self) -> DegradedState

Get current degraded state

Source

pub async fn initial_load(&self) -> LoadReport

Initial load of all data with LoadReport for graceful degradation

Source

pub fn stats(&self) -> Option<StatsCache>

Get a clone of stats

Source

pub fn context_window_stats(&self) -> ContextWindowStats

Calculate context window saturation from current sessions

Source

pub fn settings(&self) -> MergedConfig

Get merged settings

Source

pub fn mcp_config(&self) -> Option<McpConfig>

Get MCP server configuration

Source

pub fn rules(&self) -> Rules

Get rules

Source

pub fn invocation_stats(&self) -> InvocationStats

Get invocation statistics

Source

pub fn quota_status(&self) -> Option<QuotaStatus>

Calculate current quota status from stats and budget config

Returns None if stats are not loaded or budget is not configured.

Source

pub fn live_sessions(&self) -> Vec<LiveSession>

Get live Claude Code sessions (running processes, ps-based)

Detects active Claude processes on the system and returns metadata. Returns empty vector if detection fails or no processes are running.

Source

pub fn merged_live_sessions(&self) -> Vec<MergedLiveSession>

Get merged live sessions: hook data + ps-based fallback

Hook sessions are prioritized; unmatched ps sessions appear as ProcessOnly.

Source

pub async fn reload_live_hook_sessions(&self, path: &Path)

Reload hook-based live session state from a file path

Source

pub fn claude_global_stats(&self) -> Option<ClaudeGlobalStats>

Get per-project last session stats from ~/.claude.json

Source

pub fn session_count(&self) -> usize

Get session count

Source

pub fn get_session(&self, id: &str) -> Option<Arc<SessionMetadata>>

Get session by ID Returns Arc for cheap cloning

Source

pub async fn load_session_content( &self, session_id: &str, ) -> Result<Vec<ConversationMessage>, CoreError>

Load full session content with lazy caching

Returns conversation messages parsed from session JSONL file. Uses Moka cache (LRU with 5min TTL) for repeated access.

§Performance
  • First call: Parse JSONL (~50-500ms for 1000-message session)
  • Cached calls: <1ms (memory lookup)
  • Cache eviction: LRU + 5min idle timeout
§Errors

Returns CoreError if session not found or file cannot be read.

Source

pub fn analytics(&self) -> Option<AnalyticsData>

Get analytics data for a period (cached)

Returns cached analytics if available, otherwise None. Call compute_analytics() to compute and cache.

Source

pub async fn compute_analytics(&self, period: Period)

Compute and cache analytics data for a period

This is a CPU-intensive operation (trends, forecasting, patterns). For 1000+ sessions, this may take 100-300ms, so it’s offloaded to a blocking task.

Cache is invalidated on stats reload or session updates (EventBus pattern).

Source

pub fn discover(&self) -> Option<Vec<DiscoverSuggestion>>

Get cached discover suggestions (None if not yet computed)

Source

pub async fn compute_discover( &self, max_sessions: usize, min_count: usize, top: usize, )

Extract user messages from recent sessions and run pattern discovery.

Loads JSONL content for up to max_sessions most recent sessions, extracts user message text, and stores results in discover_cache. Publishes DataEvent::AnalyticsUpdated on completion so the TUI re-renders.

Source

pub fn session_ids(&self) -> Vec<SessionId>

Get all session IDs

Source

pub fn clear_session_content_cache(&self)

Clear session content cache (for memory optimization on F5)

Source

pub fn sessions_by_project(&self) -> HashMap<String, Vec<Arc<SessionMetadata>>>

Get sessions grouped by project Returns Arc for cheap cloning

Source

pub fn all_sessions(&self) -> Vec<Arc<SessionMetadata>>

Get all sessions (unsorted) Returns Arc for cheap cloning

Source

pub fn recent_sessions(&self, limit: usize) -> Vec<Arc<SessionMetadata>>

Get recent sessions (sorted by last timestamp, newest first) Returns Arc for cheap cloning

Source

pub fn search_sessions(&self, query: &str, limit: usize) -> Vec<SearchResult>

Search sessions using FTS5 full-text search.

Returns relevance-ranked results. Returns empty vec if FTS5 not initialized.

Source

pub async fn analyze_session(&self, session_id: &str) -> Result<ActivitySummary>

Analyze a session’s tool calls and generate activity summary + alerts.

Results are stored in the in-memory DashMap and the SQLite cache. Publishes DataEvent::AnalyticsUpdated on completion so the TUI re-renders.

Source

pub fn get_session_activity(&self, session_id: &str) -> Option<ActivitySummary>

Get the cached activity summary for a session (returns None if not yet analyzed).

Source

pub fn get_all_stored_alerts( &self, min_severity: Option<&str>, ) -> Vec<StoredAlert>

Get all stored security alerts from the SQLite cache.

min_severity: optional filter — “Warning” or “Critical”

Source

pub fn mcp_call_stats(&self) -> Vec<McpCallStat>

Aggregate MCP call stats from all analyzed sessions.

Returns one entry per server that has been called, sorted by call_count descending. Servers with 0 calls are omitted.

Source

pub fn all_violations(&self) -> Vec<Alert>

Consolidated violations feed: merges in-memory DashMap results (freshest) with SQLite-persisted alerts. DashMap takes priority for sessions analyzed this run.

Returns alerts sorted Critical → Warning → Info, then by timestamp descending.

Source

pub fn top_sessions_by_tokens(&self, limit: usize) -> Vec<Arc<SessionMetadata>>

Get top sessions by total tokens (sorted descending) Returns Arc for cheap cloning

Source

pub fn top_models_by_tokens(&self) -> Vec<(String, u64)>

Get top models by total tokens (aggregated, sorted descending) Returns (model_name, total_tokens) pairs

Source

pub fn top_days_by_tokens(&self) -> Vec<(String, u64)>

Get top days by total tokens (aggregated, sorted descending) Returns (date_string, total_tokens) pairs

Source

pub fn projects_leaderboard(&self) -> Vec<ProjectLeaderboardEntry>

Get project leaderboard with aggregated metrics

Returns all projects with session count, total tokens, total cost, and average session cost. Cost is calculated using accurate model-based pricing from the pricing module.

Source

pub async fn reload_stats(&self)

Reload stats (called on file change)

Source

pub async fn reload_settings(&self)

Reload settings from files (called when settings change)

Source

pub async fn update_session(&self, path: &Path)

Add or update a session (called when session file changes)

Source

pub async fn compute_invocations(&self)

Compute invocation statistics from all sessions

This scans all session files to count agent/command/skill invocations. Should be called after initial load or when sessions are updated.

Source

pub async fn compute_billing_blocks(&self)

Compute billing blocks from all sessions

This scans all sessions with timestamps and aggregates usage into 5-hour billing blocks. Uses real model pricing based on token breakdown for accurate cost calculation.

Source

pub fn billing_blocks(&self) -> RwLockReadGuard<'_, BillingBlockManager>

Get billing blocks (read-only access)

Source

pub fn usage_estimate(&self) -> UsageEstimate

Calculate usage estimate based on billing blocks and subscription plan

Source

pub fn load_preferences(&self) -> CcboardPreferences

Load ccboard user preferences from the cache directory.

Source

pub fn save_preferences(&self, prefs: &CcboardPreferences) -> Result<()>

Save ccboard user preferences to the cache directory.

Source

pub fn is_bookmarked(&self, session_id: &str) -> bool

Returns true if the session is bookmarked

Source

pub fn bookmark_entry(&self, session_id: &str) -> Option<BookmarkEntry>

Returns the bookmark entry for a session, if any. Cloned to avoid holding the lock across an await point.

Source

pub fn toggle_bookmark(&self, session_id: &str) -> Result<bool>

Toggle bookmark (add with default tag “bookmarked”, or remove). Returns true if the session is now bookmarked.

Source

pub fn upsert_bookmark( &self, session_id: &str, tag: impl Into<String>, note: Option<String>, ) -> Result<()>

Add or update a bookmark with a custom tag and optional note.

Source

pub fn remove_bookmark(&self, session_id: &str) -> Result<bool>

Remove a bookmark explicitly.

Source

pub fn bookmark_count(&self) -> usize

Number of bookmarked sessions

Source

pub fn has_summary(&self, session_id: &str) -> bool

True if a cached LLM summary exists for this session

Source

pub fn load_summary(&self, session_id: &str) -> Option<String>

Load cached summary text, or None if not yet generated

Source

pub fn subagent_children(&self, parent_id: &str) -> Vec<Arc<SessionMetadata>>

Returns all direct subagent sessions of the given parent session ID. A session is a subagent if its parent_session_id == parent_id.

Source

pub fn compute_has_subagents(&self)

Backfills has_subagents on all sessions based on cross-references. A session has subagents if any other session has parent_session_id == this_id. Called once after initial_load() completes.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more