Skip to main content

adk_kernel/stores/
driver_postgres.rs

1//! The PostgreSQL [`DriverStore`](crate::drivers::DriverStore) (spec 3.2 §7.7, §13 Q8;
2//! features `drivers`, `postgres`).
3
4use super::driver_sql::{REGISTRY_TABLE, sql_driver_store};
5use crate::error::{KernelError, Result};
6
7/// Migrations of [`PostgresDriverStore`], recorded in `_adk_kernel_driver_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    1,
13    "create kernel driver and parked-call tables",
14    "\
15CREATE TABLE IF NOT EXISTS adk_kernel_drivers (\
16    id TEXT COLLATE \"C\" PRIMARY KEY, \
17    record TEXT NOT NULL\
18);\
19CREATE TABLE IF NOT EXISTS adk_kernel_driver_parks (\
20    app_name TEXT COLLATE \"C\" NOT NULL, \
21    user_id TEXT COLLATE \"C\" NOT NULL, \
22    session_id TEXT COLLATE \"C\" NOT NULL, \
23    call_id TEXT COLLATE \"C\" NOT NULL, \
24    driver_id TEXT NOT NULL, \
25    park TEXT NOT NULL, \
26    PRIMARY KEY (app_name, user_id, session_id, call_id)\
27);\
28CREATE INDEX IF NOT EXISTS adk_kernel_driver_parks_driver ON adk_kernel_driver_parks (driver_id);",
29)];
30
31/// A [`DriverStore`](crate::drivers::DriverStore) in PostgreSQL, shared by every replica
32/// (spec 3.2 §7.7, features `drivers`, `postgres`).
33///
34/// It opens from the URL of `adk-rust serve --store`. Its tables are `adk_kernel_drivers`
35/// and `adk_kernel_driver_parks`; [`migrate`](Self::migrate) records its steps in
36/// `_adk_kernel_driver_migrations` under an advisory lock, so replicas starting together
37/// migrate one at a time.
38///
39/// # Example
40///
41/// ```rust,no_run
42/// # async fn example() -> adk_kernel::Result<()> {
43/// let store = adk_kernel::stores::PostgresDriverStore::connect("postgres://localhost/app").await?;
44/// store.migrate().await?;
45/// # Ok(())
46/// # }
47/// ```
48#[derive(Debug, Clone)]
49pub struct PostgresDriverStore {
50    pool: sqlx::PgPool,
51}
52
53impl PostgresDriverStore {
54    /// A store over `pool`, such as the one the session service and the run store use.
55    pub fn new(pool: sqlx::PgPool) -> Self {
56        Self { pool }
57    }
58
59    /// The pool the store writes to.
60    pub fn pool(&self) -> &sqlx::PgPool {
61        &self.pool
62    }
63
64    /// Connects to `database_url` with a pool of its own.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`KernelError::Store`] when the server cannot be reached.
69    pub async fn connect(database_url: &str) -> Result<Self> {
70        let pool =
71            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
72                backend: "postgres",
73                reason: format!("could not connect: {error}"),
74            })?;
75        Ok(Self::new(pool))
76    }
77
78    /// Creates or upgrades the store's tables, under a session-level advisory lock keyed
79    /// by the registry table.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
84    /// migrated by a newer release.
85    pub async fn migrate(&self) -> Result<()> {
86        migrate_locked(self.pool.clone()).await
87    }
88}
89
90/// Runs the migrations under the advisory lock. Boxed so the future is checked for `Send`
91/// here rather than inside callers' `async_trait` methods.
92fn migrate_locked(
93    pool: sqlx::PgPool,
94) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
95    use sqlx::Connection as _;
96
97    let store_error = |action: &str, error: &dyn std::fmt::Display| KernelError::Store {
98        backend: "postgres",
99        reason: format!("could not {action}: {error}"),
100    };
101    Box::pin(async move {
102        let key = REGISTRY_TABLE
103            .bytes()
104            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
105                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
106            })
107            .cast_signed();
108        let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
109            .await
110            .map_err(|error| store_error("connect for the migration lock", &error))?;
111        sqlx::query("SELECT pg_advisory_lock($1)")
112            .bind(key)
113            .execute(&mut lock)
114            .await
115            .map_err(|error| store_error("take the migration lock", &error))?;
116        let result = adk_session::migration::pg_runner::run_sql_migrations(
117            &pool,
118            REGISTRY_TABLE,
119            MIGRATIONS,
120            || async { Ok(false) },
121        )
122        .await
123        .map_err(|error| KernelError::Store { backend: "postgres", reason: error.message });
124        let _ = lock.close().await;
125        result
126    })
127}
128
129sql_driver_store!(PostgresDriverStore, "postgres");