Skip to main content

adk_kernel/channels/
postgres.rs

1//! The PostgreSQL [`ChannelBindingStore`](super::ChannelBindingStore) (spec 3.3 §10 K1;
2//! features `channels`, `postgres`).
3
4use super::sql::{REGISTRY_TABLE, sql_channel_store};
5use crate::error::{KernelError, Result};
6
7/// Migrations of [`PostgresChannelBindingStore`], recorded in
8/// `_adk_kernel_channel_migrations`.
9///
10/// The key columns take the `C` collation, so lists order by the bytes of the UTF-8 text on
11/// every server, as the other backends do.
12const MIGRATIONS: &[(i64, &str, &str)] = &[(
13    1,
14    "create kernel channel binding and pairing-request tables",
15    "\
16CREATE TABLE IF NOT EXISTS adk_kernel_channel_bindings (\
17    id TEXT COLLATE \"C\" PRIMARY KEY, \
18    paired_us BIGINT NOT NULL, \
19    record TEXT NOT NULL\
20);\
21CREATE TABLE IF NOT EXISTS adk_kernel_channel_requests (\
22    channel TEXT COLLATE \"C\" NOT NULL, \
23    account TEXT COLLATE \"C\" NOT NULL, \
24    code_hash TEXT NOT NULL UNIQUE, \
25    requested_us BIGINT NOT NULL, \
26    expires_us BIGINT NOT NULL, \
27    record TEXT NOT NULL, \
28    PRIMARY KEY (channel, account)\
29);\
30CREATE INDEX IF NOT EXISTS adk_kernel_channel_requests_expiry ON adk_kernel_channel_requests (expires_us);",
31)];
32
33/// A [`ChannelBindingStore`](super::ChannelBindingStore) in PostgreSQL, shared by every
34/// replica (spec 3.3 §10 K1, features `channels`, `postgres`).
35///
36/// It opens from the URL of `adk-rust serve --store`. Its tables are
37/// `adk_kernel_channel_bindings` and `adk_kernel_channel_requests`;
38/// [`migrate`](Self::migrate) records its steps in `_adk_kernel_channel_migrations` under an
39/// advisory lock, so replicas starting together migrate one at a time.
40///
41/// # Example
42///
43/// ```rust,no_run
44/// # async fn example() -> adk_kernel::Result<()> {
45/// let store = adk_kernel::channels::PostgresChannelBindingStore::connect("postgres://localhost/app").await?;
46/// store.migrate().await?;
47/// # Ok(())
48/// # }
49/// ```
50#[derive(Debug, Clone)]
51pub struct PostgresChannelBindingStore {
52    pool: sqlx::PgPool,
53}
54
55impl PostgresChannelBindingStore {
56    /// A store over `pool`, such as the one the session service and the run store use.
57    pub fn new(pool: sqlx::PgPool) -> Self {
58        Self { pool }
59    }
60
61    /// The pool the store writes to.
62    pub fn pool(&self) -> &sqlx::PgPool {
63        &self.pool
64    }
65
66    /// Connects to `database_url` with a pool of its own.
67    ///
68    /// # Errors
69    ///
70    /// Returns [`KernelError::Store`] when the server cannot be reached.
71    pub async fn connect(database_url: &str) -> Result<Self> {
72        let pool =
73            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
74                backend: "postgres",
75                reason: format!("could not connect: {error}"),
76            })?;
77        Ok(Self::new(pool))
78    }
79
80    /// Creates or upgrades the store's tables, under a session-level advisory lock keyed
81    /// by the registry table.
82    ///
83    /// # Errors
84    ///
85    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
86    /// migrated by a newer release.
87    pub async fn migrate(&self) -> Result<()> {
88        crate::pairing::postgres::migrate_locked(self.pool.clone(), REGISTRY_TABLE, MIGRATIONS)
89            .await
90    }
91}
92
93sql_channel_store!(PostgresChannelBindingStore, "postgres");