Skip to main content

adk_kernel/stores/
sqlite.rs

1//! The SQLite [`ProcessStore`](crate::ProcessStore) (spec 3.2 §7.1, §13 Q8, feature `sqlite`).
2
3use super::sql::{REGISTRY_TABLE, sql_process_store};
4use crate::error::{KernelError, Result};
5
6/// Migrations of [`SqliteProcessStore`], recorded in `_adk_kernel_process_migrations`.
7const MIGRATIONS: &[(i64, &str, &str)] = &[
8    (
9        1,
10        "create kernel process and spend tables",
11        "\
12CREATE TABLE IF NOT EXISTS adk_kernel_processes (\
13    pid TEXT PRIMARY KEY, \
14    parent TEXT, \
15    partition_id TEXT NOT NULL, \
16    queue TEXT NOT NULL, \
17    kind TEXT NOT NULL, \
18    wake TEXT, \
19    suspended_by TEXT, \
20    suspend_requested BOOLEAN NOT NULL DEFAULT FALSE, \
21    agenda_item TEXT, \
22    labels TEXT NOT NULL\
23);\
24CREATE INDEX IF NOT EXISTS adk_kernel_processes_partition ON adk_kernel_processes (partition_id, pid);\
25CREATE INDEX IF NOT EXISTS adk_kernel_processes_queue ON adk_kernel_processes (queue, pid);\
26CREATE INDEX IF NOT EXISTS adk_kernel_processes_parent ON adk_kernel_processes (parent, pid);\
27CREATE INDEX IF NOT EXISTS adk_kernel_processes_suspend ON adk_kernel_processes (suspend_requested, pid);\
28CREATE TABLE IF NOT EXISTS adk_kernel_spend (\
29    pid TEXT NOT NULL, \
30    partition_id TEXT NOT NULL, \
31    day BIGINT NOT NULL, \
32    micro_usd BIGINT NOT NULL, \
33    PRIMARY KEY (pid, partition_id, day)\
34);\
35CREATE INDEX IF NOT EXISTS adk_kernel_spend_partition ON adk_kernel_spend (partition_id, day);",
36    ),
37    (
38        2,
39        "create kernel usage counters table",
40        "\
41CREATE TABLE IF NOT EXISTS adk_kernel_usage (\
42    pid TEXT NOT NULL, \
43    partition_id TEXT NOT NULL, \
44    day BIGINT NOT NULL, \
45    counter TEXT NOT NULL, \
46    amount BIGINT NOT NULL, \
47    PRIMARY KEY (pid, partition_id, day, counter)\
48);\
49CREATE INDEX IF NOT EXISTS adk_kernel_usage_partition ON adk_kernel_usage (partition_id, day);",
50    ),
51];
52
53/// A [`ProcessStore`](crate::ProcessStore) in SQLite (spec 3.2 §7.1, feature `sqlite`).
54///
55/// In the CLI it lives in `harness.db` beside the harness stores, on the same pool: its
56/// tables are `adk_kernel_processes`, `adk_kernel_spend` and `adk_kernel_usage`, and
57/// [`migrate`](Self::migrate) records its steps in
58/// `_adk_kernel_process_migrations`, distinct from every other store's tables. Call
59/// `migrate` once before use.
60///
61/// Every change is a single statement, so writers sharing the pool, or another process on
62/// the same file, queue on SQLite's write lock for the pool's busy timeout instead of
63/// failing; `harness.db` is opened with a 30-second one. `pid` order is SQLite's binary
64/// collation, the byte order of the UTF-8 text.
65///
66/// # Example
67///
68/// ```rust
69/// use adk_kernel::{ProcessKind, ProcessMeta, ProcessStore, QueueClass, SqliteProcessStore};
70///
71/// # #[tokio::main(flavor = "current_thread")]
72/// # async fn main() -> adk_kernel::Result<()> {
73/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
74/// let store = SqliteProcessStore::new(pool);
75/// store.migrate().await?;
76/// store.put(ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Goal)).await?;
77/// assert_eq!(store.get("run-1").await?.unwrap().kind, ProcessKind::Goal);
78/// # Ok(())
79/// # }
80/// ```
81#[derive(Debug, Clone)]
82pub struct SqliteProcessStore {
83    pool: sqlx::SqlitePool,
84}
85
86impl SqliteProcessStore {
87    /// A store over `pool`, such as the pool of `harness.db`.
88    pub fn new(pool: sqlx::SqlitePool) -> Self {
89        Self { pool }
90    }
91
92    /// The pool the store writes to.
93    pub fn pool(&self) -> &sqlx::SqlitePool {
94        &self.pool
95    }
96
97    /// Creates or upgrades the store's table.
98    ///
99    /// Idempotent: a step already recorded in `_adk_kernel_process_migrations` is not run
100    /// again.
101    ///
102    /// # Errors
103    ///
104    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
105    /// migrated by a newer release.
106    pub async fn migrate(&self) -> Result<()> {
107        adk_session::migration::sqlite_runner::run_sql_migrations(
108            &self.pool,
109            REGISTRY_TABLE,
110            MIGRATIONS,
111            || async { Ok(false) },
112        )
113        .await
114        .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
115    }
116}
117
118sql_process_store!(SqliteProcessStore, "sqlite");