Skip to main content

adk_kernel/pairing/
postgres.rs

1//! The PostgreSQL [`DeviceStore`](super::DeviceStore) (spec 3.3 §10 K2; feature
2//! `postgres`).
3
4use super::sql::{REGISTRY_TABLE, sql_device_store};
5use crate::error::{KernelError, Result};
6
7/// Migrations of [`PostgresDeviceStore`], recorded in `_adk_kernel_device_migrations`.
8///
9/// The key columns take the `C` collation, so lists order by the bytes of the UTF-8 text on
10/// every server, as the other backends do.
11const MIGRATIONS: &[(i64, &str, &str)] = &[
12    (
13        1,
14        "create kernel device and pairing-code tables",
15        "\
16CREATE TABLE IF NOT EXISTS adk_kernel_devices (\
17    id TEXT COLLATE \"C\" PRIMARY KEY, \
18    created_us BIGINT NOT NULL, \
19    record TEXT NOT NULL\
20);\
21CREATE TABLE IF NOT EXISTS adk_kernel_pairing_codes (\
22    code_hash TEXT COLLATE \"C\" PRIMARY KEY, \
23    expires_us BIGINT NOT NULL, \
24    record TEXT NOT NULL\
25);\
26CREATE INDEX IF NOT EXISTS adk_kernel_pairing_codes_expiry ON adk_kernel_pairing_codes (expires_us);",
27    ),
28    (
29        2,
30        "create the shared count of pairing claims",
31        "\
32CREATE TABLE IF NOT EXISTS adk_kernel_pairing_attempts (\
33    id INTEGER PRIMARY KEY, \
34    attempts BIGINT NOT NULL\
35);",
36    ),
37    (
38        3,
39        "create device attachments",
40        "\
41CREATE TABLE IF NOT EXISTS adk_kernel_device_attachments (\
42    holder TEXT COLLATE \"C\" NOT NULL, \
43    kind TEXT COLLATE \"C\" NOT NULL, \
44    key TEXT COLLATE \"C\" NOT NULL, \
45    updated_us BIGINT NOT NULL, \
46    record TEXT NOT NULL, \
47    PRIMARY KEY (holder, kind, key)\
48);",
49    ),
50];
51
52/// A [`DeviceStore`](super::DeviceStore) in PostgreSQL, shared by every replica (spec 3.3
53/// §10 K2, feature `postgres`).
54///
55/// It opens from the URL of `adk-rust serve --store`. Its tables are `adk_kernel_devices`,
56/// `adk_kernel_pairing_codes`, `adk_kernel_pairing_attempts`, the count of claims every
57/// replica shares, and `adk_kernel_device_attachments`; [`migrate`](Self::migrate) records
58/// its steps in
59/// `_adk_kernel_device_migrations` under an advisory lock, so replicas starting together
60/// migrate one at a time.
61///
62/// # Example
63///
64/// ```rust,no_run
65/// # async fn example() -> adk_kernel::Result<()> {
66/// let store = adk_kernel::pairing::PostgresDeviceStore::connect("postgres://localhost/app").await?;
67/// store.migrate().await?;
68/// # Ok(())
69/// # }
70/// ```
71#[derive(Debug, Clone)]
72pub struct PostgresDeviceStore {
73    pool: sqlx::PgPool,
74}
75
76impl PostgresDeviceStore {
77    /// A store over `pool`, such as the one the session service and the run store use.
78    pub fn new(pool: sqlx::PgPool) -> Self {
79        Self { pool }
80    }
81
82    /// The pool the store writes to.
83    pub fn pool(&self) -> &sqlx::PgPool {
84        &self.pool
85    }
86
87    /// Connects to `database_url` with a pool of its own.
88    ///
89    /// # Errors
90    ///
91    /// Returns [`KernelError::Store`] when the server cannot be reached.
92    pub async fn connect(database_url: &str) -> Result<Self> {
93        let pool =
94            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
95                backend: "postgres",
96                reason: format!("could not connect: {error}"),
97            })?;
98        Ok(Self::new(pool))
99    }
100
101    /// Creates or upgrades the store's tables, under a session-level advisory lock keyed
102    /// by the registry table.
103    ///
104    /// # Errors
105    ///
106    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
107    /// migrated by a newer release.
108    pub async fn migrate(&self) -> Result<()> {
109        migrate_locked(self.pool.clone(), REGISTRY_TABLE, MIGRATIONS).await
110    }
111}
112
113/// Runs `migrations` recorded in `registry` under a session-level advisory lock keyed by
114/// the registry's name, so replicas starting together migrate one at a time. Boxed so the
115/// future is checked for `Send` here rather than inside callers' `async_trait` methods.
116pub(crate) fn migrate_locked(
117    pool: sqlx::PgPool,
118    registry: &'static str,
119    migrations: &'static [(i64, &'static str, &'static str)],
120) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
121    use sqlx::Connection as _;
122
123    let store_error = |action: &str, error: &dyn std::fmt::Display| KernelError::Store {
124        backend: "postgres",
125        reason: format!("could not {action}: {error}"),
126    };
127    Box::pin(async move {
128        let key = registry
129            .bytes()
130            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
131                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
132            })
133            .cast_signed();
134        let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
135            .await
136            .map_err(|error| store_error("connect for the migration lock", &error))?;
137        sqlx::query("SELECT pg_advisory_lock($1)")
138            .bind(key)
139            .execute(&mut lock)
140            .await
141            .map_err(|error| store_error("take the migration lock", &error))?;
142        let result = adk_session::migration::pg_runner::run_sql_migrations(
143            &pool,
144            registry,
145            migrations,
146            || async { Ok(false) },
147        )
148        .await
149        .map_err(|error| KernelError::Store { backend: "postgres", reason: error.message });
150        let _ = lock.close().await;
151        result
152    })
153}
154
155sql_device_store!(PostgresDeviceStore, "postgres");