Skip to main content

adk_kernel/stores/
postgres.rs

1//! The PostgreSQL [`ProcessStore`](crate::ProcessStore) (spec 3.2 §7.1, §13 Q8, feature
2//! `postgres`).
3
4use super::sql::{REGISTRY_TABLE, sql_process_store};
5use crate::error::{KernelError, Result};
6
7/// Migrations of [`PostgresProcessStore`], recorded in `_adk_kernel_process_migrations`.
8///
9/// `pid` takes the `C` collation, so `list` orders by the bytes of the UTF-8 text on every
10/// server, as the other backends do, whatever the database's locale.
11const MIGRATIONS: &[(i64, &str, &str)] = &[
12    (
13        1,
14        "create kernel process and spend tables",
15        "\
16CREATE TABLE IF NOT EXISTS adk_kernel_processes (\
17    pid TEXT COLLATE \"C\" PRIMARY KEY, \
18    parent TEXT, \
19    partition_id TEXT NOT NULL, \
20    queue TEXT NOT NULL, \
21    kind TEXT NOT NULL, \
22    wake TEXT, \
23    suspended_by TEXT, \
24    suspend_requested BOOLEAN NOT NULL DEFAULT FALSE, \
25    agenda_item TEXT, \
26    labels TEXT NOT NULL\
27);\
28CREATE INDEX IF NOT EXISTS adk_kernel_processes_partition ON adk_kernel_processes (partition_id, pid);\
29CREATE INDEX IF NOT EXISTS adk_kernel_processes_queue ON adk_kernel_processes (queue, pid);\
30CREATE INDEX IF NOT EXISTS adk_kernel_processes_parent ON adk_kernel_processes (parent, pid);\
31CREATE INDEX IF NOT EXISTS adk_kernel_processes_suspend ON adk_kernel_processes (suspend_requested, pid);\
32CREATE TABLE IF NOT EXISTS adk_kernel_spend (\
33    pid TEXT NOT NULL, \
34    partition_id TEXT NOT NULL, \
35    day BIGINT NOT NULL, \
36    micro_usd BIGINT NOT NULL, \
37    PRIMARY KEY (pid, partition_id, day)\
38);\
39CREATE INDEX IF NOT EXISTS adk_kernel_spend_partition ON adk_kernel_spend (partition_id, day);",
40    ),
41    (
42        2,
43        "create kernel usage counters table",
44        "\
45CREATE TABLE IF NOT EXISTS adk_kernel_usage (\
46    pid TEXT NOT NULL, \
47    partition_id TEXT NOT NULL, \
48    day BIGINT NOT NULL, \
49    counter TEXT NOT NULL, \
50    amount BIGINT NOT NULL, \
51    PRIMARY KEY (pid, partition_id, day, counter)\
52);\
53CREATE INDEX IF NOT EXISTS adk_kernel_usage_partition ON adk_kernel_usage (partition_id, day);",
54    ),
55];
56
57/// A [`ProcessStore`](crate::ProcessStore) in PostgreSQL, shared by every replica (spec 3.2
58/// §7.1, feature `postgres`).
59///
60/// It opens from the URL of `adk-rust serve --store`, which keeps sessions, approvals, runs,
61/// modes, rules and plan checkpoints in the same database. Its tables are
62/// `adk_kernel_processes`, `adk_kernel_spend` and `adk_kernel_usage`; [`migrate`](Self::migrate) records its
63/// steps in
64/// `_adk_kernel_process_migrations` under an advisory lock, so replicas starting together
65/// migrate one at a time.
66///
67/// Every change is a single statement, so replicas writing different fields of one row
68/// never lose each other's update.
69///
70/// # Example
71///
72/// ```rust,no_run
73/// # async fn example() -> adk_kernel::Result<()> {
74/// let store = adk_kernel::PostgresProcessStore::connect("postgres://localhost/app").await?;
75/// store.migrate().await?;
76/// # Ok(())
77/// # }
78/// ```
79#[derive(Debug, Clone)]
80pub struct PostgresProcessStore {
81    pool: sqlx::PgPool,
82}
83
84impl PostgresProcessStore {
85    /// A store over `pool`, such as the one the session service and the run store use.
86    pub fn new(pool: sqlx::PgPool) -> Self {
87        Self { pool }
88    }
89
90    /// The pool the store writes to.
91    pub fn pool(&self) -> &sqlx::PgPool {
92        &self.pool
93    }
94
95    /// Connects to `database_url` with a pool of its own.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`KernelError::Store`] when the server cannot be reached.
100    pub async fn connect(database_url: &str) -> Result<Self> {
101        let pool =
102            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
103                backend: "postgres",
104                reason: format!("could not connect: {error}"),
105            })?;
106        Ok(Self::new(pool))
107    }
108
109    /// Creates or upgrades the store's table.
110    ///
111    /// The steps run under a session-level advisory lock keyed by the registry table, held
112    /// on a connection opened beside the pool, so a one-connection pool still runs the
113    /// statements and replicas starting together migrate one at a time.
114    ///
115    /// # Errors
116    ///
117    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
118    /// migrated by a newer release.
119    pub async fn migrate(&self) -> Result<()> {
120        migrate_locked(self.pool.clone(), REGISTRY_TABLE, MIGRATIONS).await
121    }
122}
123
124/// Runs `migrations` recorded in `registry` under an advisory lock keyed by `registry`.
125/// Boxed so the future is checked for `Send` here, with concrete lifetimes, rather than
126/// inside callers' `async_trait` methods.
127pub(super) fn migrate_locked(
128    pool: sqlx::PgPool,
129    registry: &'static str,
130    migrations: &'static [(i64, &'static str, &'static str)],
131) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
132    use sqlx::Connection as _;
133
134    let store_error = |action: &str, error: &dyn std::fmt::Display| KernelError::Store {
135        backend: "postgres",
136        reason: format!("could not {action}: {error}"),
137    };
138    Box::pin(async move {
139        let key = registry
140            .bytes()
141            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
142                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
143            })
144            .cast_signed();
145        let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
146            .await
147            .map_err(|error| store_error("connect for the migration lock", &error))?;
148        sqlx::query("SELECT pg_advisory_lock($1)")
149            .bind(key)
150            .execute(&mut lock)
151            .await
152            .map_err(|error| store_error("take the migration lock", &error))?;
153        let result = adk_session::migration::pg_runner::run_sql_migrations(
154            &pool,
155            registry,
156            migrations,
157            || async { Ok(false) },
158        )
159        .await
160        .map_err(|error| KernelError::Store { backend: "postgres", reason: error.message });
161        let _ = lock.close().await;
162        result
163    })
164}
165
166sql_process_store!(PostgresProcessStore, "postgres");