adk_kernel/stores/
postgres.rs1use super::sql::{REGISTRY_TABLE, sql_process_store};
5use crate::error::{KernelError, Result};
6
7const 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#[derive(Debug, Clone)]
80pub struct PostgresProcessStore {
81 pool: sqlx::PgPool,
82}
83
84impl PostgresProcessStore {
85 pub fn new(pool: sqlx::PgPool) -> Self {
87 Self { pool }
88 }
89
90 pub fn pool(&self) -> &sqlx::PgPool {
92 &self.pool
93 }
94
95 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 pub async fn migrate(&self) -> Result<()> {
120 migrate_locked(self.pool.clone(), REGISTRY_TABLE, MIGRATIONS).await
121 }
122}
123
124pub(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");