Skip to main content

adk_kernel/pairing/
sqlite.rs

1//! The SQLite [`DeviceStore`](super::DeviceStore) (spec 3.3 §10 K2; feature `sqlite`).
2
3use super::sql::{REGISTRY_TABLE, sql_device_store};
4use crate::error::{KernelError, Result};
5
6/// Migrations of [`SqliteDeviceStore`], recorded in `_adk_kernel_device_migrations`.
7const MIGRATIONS: &[(i64, &str, &str)] = &[
8    (
9        1,
10        "create kernel device and pairing-code tables",
11        "\
12CREATE TABLE IF NOT EXISTS adk_kernel_devices (\
13    id TEXT PRIMARY KEY, \
14    created_us INTEGER NOT NULL, \
15    record TEXT NOT NULL\
16);\
17CREATE TABLE IF NOT EXISTS adk_kernel_pairing_codes (\
18    code_hash TEXT PRIMARY KEY, \
19    expires_us INTEGER NOT NULL, \
20    record TEXT NOT NULL\
21);\
22CREATE INDEX IF NOT EXISTS adk_kernel_pairing_codes_expiry ON adk_kernel_pairing_codes (expires_us);",
23    ),
24    (
25        2,
26        "create the shared count of pairing claims",
27        "\
28CREATE TABLE IF NOT EXISTS adk_kernel_pairing_attempts (\
29    id INTEGER PRIMARY KEY, \
30    attempts INTEGER NOT NULL\
31);",
32    ),
33    (
34        3,
35        "create device attachments",
36        "\
37CREATE TABLE IF NOT EXISTS adk_kernel_device_attachments (\
38    holder TEXT NOT NULL, \
39    kind TEXT NOT NULL, \
40    key TEXT NOT NULL, \
41    updated_us INTEGER NOT NULL, \
42    record TEXT NOT NULL, \
43    PRIMARY KEY (holder, kind, key)\
44);",
45    ),
46];
47
48/// A [`DeviceStore`](super::DeviceStore) in SQLite (spec 3.3 §10 K2, feature `sqlite`).
49///
50/// In the CLI it lives in `harness.db` on the same pool as the harness and process stores:
51/// its tables are `adk_kernel_devices`, `adk_kernel_pairing_codes`,
52/// `adk_kernel_pairing_attempts` and `adk_kernel_device_attachments`, and
53/// [`migrate`](Self::migrate) records its steps in `_adk_kernel_device_migrations`. Call
54/// `migrate` once before use.
55///
56/// # Example
57///
58/// ```rust
59/// use std::sync::Arc;
60/// use adk_kernel::pairing::{IssueCode, Pairing, SqliteDeviceStore};
61///
62/// # #[tokio::main(flavor = "current_thread")]
63/// # async fn main() -> adk_kernel::Result<()> {
64/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
65/// let store = SqliteDeviceStore::new(pool);
66/// store.migrate().await?;
67/// let pairing = Pairing::new(Arc::new(store));
68/// let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await?;
69/// let claimed = pairing.claim(&issued.code, None).await?;
70/// assert_eq!(pairing.authenticate(&claimed.token).await?.owner, "ana");
71/// # Ok(())
72/// # }
73/// ```
74#[derive(Debug, Clone)]
75pub struct SqliteDeviceStore {
76    pool: sqlx::SqlitePool,
77}
78
79impl SqliteDeviceStore {
80    /// A store over `pool`, such as the pool of `harness.db`.
81    pub fn new(pool: sqlx::SqlitePool) -> Self {
82        Self { pool }
83    }
84
85    /// The pool the store writes to.
86    pub fn pool(&self) -> &sqlx::SqlitePool {
87        &self.pool
88    }
89
90    /// Creates or upgrades the store's tables. Idempotent.
91    ///
92    /// # Errors
93    ///
94    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
95    /// migrated by a newer release.
96    pub async fn migrate(&self) -> Result<()> {
97        adk_session::migration::sqlite_runner::run_sql_migrations(
98            &self.pool,
99            REGISTRY_TABLE,
100            MIGRATIONS,
101            || async { Ok(false) },
102        )
103        .await
104        .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
105    }
106}
107
108sql_device_store!(SqliteDeviceStore, "sqlite");