Skip to main content

aidaemon_work/sqlite/
mod.rs

1//! The SQLite implementation of the work stores, over a host's pool.
2//!
3//! The store traits are implemented for anything that is a [`WorkDatabase`],
4//! so a host that already owns the database implements that and gets the
5//! stores; [`SqliteWorkStore`] is the ready-made one.
6
7use std::sync::Arc;
8
9use async_trait::async_trait;
10use sqlx::{Row, SqlitePool};
11
12use crate::traits::{
13    Goal, GoalSchedule, GoalTokenBudgetStatus, ScheduledRunState, Task, TaskActivity,
14};
15
16mod goals;
17mod mandates;
18mod notifications;
19mod work;
20
21/// What the work stores need from whoever owns the database.
22pub trait WorkDatabase: Send + Sync {
23    /// The pool every statement runs on.
24    fn work_pool(&self) -> &SqlitePool;
25
26    /// Strip secrets from text before it is kept in activity logs, journals
27    /// and handoffs.
28    fn redact_secrets(&self, text: &str) -> String;
29}
30
31/// A [`WorkDatabase`] on its own pool, for hosts with no store of their own.
32pub struct SqliteWorkStore {
33    pool: SqlitePool,
34    redact: Arc<dyn Fn(&str) -> String + Send + Sync>,
35}
36
37impl SqliteWorkStore {
38    /// A store over `pool`, which already has the tables of [`crate::schema`].
39    pub fn new(pool: SqlitePool, redact: Arc<dyn Fn(&str) -> String + Send + Sync>) -> Self {
40        Self { pool, redact }
41    }
42
43    pub fn pool(&self) -> SqlitePool {
44        self.pool.clone()
45    }
46}
47
48impl WorkDatabase for SqliteWorkStore {
49    fn work_pool(&self) -> &SqlitePool {
50        &self.pool
51    }
52
53    fn redact_secrets(&self, text: &str) -> String {
54        (self.redact)(text)
55    }
56}
57
58/// A store on a fresh database file at `path`, with the event and work
59/// tables (secrets are not redacted).
60#[cfg(any(test, feature = "testing"))]
61pub async fn open_for_tests(path: &str) -> SqliteWorkStore {
62    use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
63    let options = SqliteConnectOptions::new()
64        .filename(path)
65        .create_if_missing(true)
66        .journal_mode(SqliteJournalMode::Delete)
67        .busy_timeout(std::time::Duration::from_secs(30));
68    let pool = SqlitePoolOptions::new()
69        .max_connections(10)
70        .acquire_timeout(std::time::Duration::from_secs(30))
71        .connect_with(options)
72        .await
73        .unwrap();
74    aidaemon_events::schema::migrate_events(&pool)
75        .await
76        .unwrap();
77    // goals.source_episode_id refers to long-term memory's table.
78    sqlx::query("CREATE TABLE episodes (id INTEGER PRIMARY KEY)")
79        .execute(&pool)
80        .await
81        .ok();
82    crate::schema::migrate_work_tables(&pool, |_| false)
83        .await
84        .unwrap();
85    crate::schema::migrate_work_tail(&pool).await.unwrap();
86    SqliteWorkStore::new(pool, Arc::new(|text: &str| text.to_string()))
87}