adk_kernel/control/store/postgres.rs
1//! The PostgreSQL [`ControlStore`](super::ControlStore) (spec 3.3 §10 K3, K4; feature
2//! `postgres`).
3
4use super::sql::{REGISTRY_TABLE, sql_control_store};
5use crate::error::{KernelError, Result};
6
7/// Migrations of [`PostgresControlStore`], recorded in `_adk_kernel_control_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 area settings and away cursor tables",
14 "\
15CREATE TABLE IF NOT EXISTS adk_kernel_area_settings (\
16 partition_id TEXT COLLATE \"C\" PRIMARY KEY, \
17 record TEXT NOT NULL\
18);\
19CREATE TABLE IF NOT EXISTS adk_kernel_away_cursors (\
20 user_id TEXT COLLATE \"C\" NOT NULL, \
21 viewer TEXT COLLATE \"C\" NOT NULL, \
22 seq BIGINT NOT NULL, \
23 record TEXT NOT NULL, \
24 PRIMARY KEY (user_id, viewer)\
25);",
26)];
27
28/// A [`ControlStore`](super::ControlStore) in PostgreSQL, shared by every replica (spec 3.3
29/// §10 K3, K4; feature `postgres`).
30///
31/// It opens from the URL of `adk-rust serve --store`. Its tables are
32/// `adk_kernel_area_settings` and `adk_kernel_away_cursors`; [`migrate`](Self::migrate)
33/// records its steps in `_adk_kernel_control_migrations` under an advisory lock, so replicas
34/// starting together migrate one at a time.
35///
36/// # Example
37///
38/// ```rust,no_run
39/// # async fn example() -> adk_kernel::Result<()> {
40/// let store = adk_kernel::control::PostgresControlStore::connect("postgres://localhost/app").await?;
41/// store.migrate().await?;
42/// # Ok(())
43/// # }
44/// ```
45#[derive(Debug, Clone)]
46pub struct PostgresControlStore {
47 pool: sqlx::PgPool,
48}
49
50impl PostgresControlStore {
51 /// A store over `pool`, such as the one the process store uses.
52 pub fn new(pool: sqlx::PgPool) -> Self {
53 Self { pool }
54 }
55
56 /// The pool the store writes to.
57 pub fn pool(&self) -> &sqlx::PgPool {
58 &self.pool
59 }
60
61 /// Connects to `database_url` with a pool of its own.
62 ///
63 /// # Errors
64 ///
65 /// Returns [`KernelError::Store`] when the server cannot be reached.
66 pub async fn connect(database_url: &str) -> Result<Self> {
67 let pool =
68 sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
69 backend: "postgres",
70 reason: format!("could not connect: {error}"),
71 })?;
72 Ok(Self::new(pool))
73 }
74
75 /// Creates or upgrades the store's tables, under a session-level advisory lock keyed
76 /// by the registry table.
77 ///
78 /// # Errors
79 ///
80 /// Returns [`KernelError::Store`] when a statement fails, or when the database was
81 /// migrated by a newer release.
82 pub async fn migrate(&self) -> Result<()> {
83 crate::pairing::postgres::migrate_locked(self.pool.clone(), REGISTRY_TABLE, MIGRATIONS)
84 .await
85 }
86}
87
88sql_control_store!(PostgresControlStore, "postgres");