adk_kernel/pairing/
postgres.rs1use super::sql::{REGISTRY_TABLE, sql_device_store};
5use crate::error::{KernelError, Result};
6
7const MIGRATIONS: &[(i64, &str, &str)] = &[
12 (
13 1,
14 "create kernel device and pairing-code tables",
15 "\
16CREATE TABLE IF NOT EXISTS adk_kernel_devices (\
17 id TEXT COLLATE \"C\" PRIMARY KEY, \
18 created_us BIGINT NOT NULL, \
19 record TEXT NOT NULL\
20);\
21CREATE TABLE IF NOT EXISTS adk_kernel_pairing_codes (\
22 code_hash TEXT COLLATE \"C\" PRIMARY KEY, \
23 expires_us BIGINT NOT NULL, \
24 record TEXT NOT NULL\
25);\
26CREATE INDEX IF NOT EXISTS adk_kernel_pairing_codes_expiry ON adk_kernel_pairing_codes (expires_us);",
27 ),
28 (
29 2,
30 "create the shared count of pairing claims",
31 "\
32CREATE TABLE IF NOT EXISTS adk_kernel_pairing_attempts (\
33 id INTEGER PRIMARY KEY, \
34 attempts BIGINT NOT NULL\
35);",
36 ),
37 (
38 3,
39 "create device attachments",
40 "\
41CREATE TABLE IF NOT EXISTS adk_kernel_device_attachments (\
42 holder TEXT COLLATE \"C\" NOT NULL, \
43 kind TEXT COLLATE \"C\" NOT NULL, \
44 key TEXT COLLATE \"C\" NOT NULL, \
45 updated_us BIGINT NOT NULL, \
46 record TEXT NOT NULL, \
47 PRIMARY KEY (holder, kind, key)\
48);",
49 ),
50];
51
52#[derive(Debug, Clone)]
72pub struct PostgresDeviceStore {
73 pool: sqlx::PgPool,
74}
75
76impl PostgresDeviceStore {
77 pub fn new(pool: sqlx::PgPool) -> Self {
79 Self { pool }
80 }
81
82 pub fn pool(&self) -> &sqlx::PgPool {
84 &self.pool
85 }
86
87 pub async fn connect(database_url: &str) -> Result<Self> {
93 let pool =
94 sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
95 backend: "postgres",
96 reason: format!("could not connect: {error}"),
97 })?;
98 Ok(Self::new(pool))
99 }
100
101 pub async fn migrate(&self) -> Result<()> {
109 migrate_locked(self.pool.clone(), REGISTRY_TABLE, MIGRATIONS).await
110 }
111}
112
113pub(crate) fn migrate_locked(
117 pool: sqlx::PgPool,
118 registry: &'static str,
119 migrations: &'static [(i64, &'static str, &'static str)],
120) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
121 use sqlx::Connection as _;
122
123 let store_error = |action: &str, error: &dyn std::fmt::Display| KernelError::Store {
124 backend: "postgres",
125 reason: format!("could not {action}: {error}"),
126 };
127 Box::pin(async move {
128 let key = registry
129 .bytes()
130 .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
131 (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
132 })
133 .cast_signed();
134 let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
135 .await
136 .map_err(|error| store_error("connect for the migration lock", &error))?;
137 sqlx::query("SELECT pg_advisory_lock($1)")
138 .bind(key)
139 .execute(&mut lock)
140 .await
141 .map_err(|error| store_error("take the migration lock", &error))?;
142 let result = adk_session::migration::pg_runner::run_sql_migrations(
143 &pool,
144 registry,
145 migrations,
146 || async { Ok(false) },
147 )
148 .await
149 .map_err(|error| KernelError::Store { backend: "postgres", reason: error.message });
150 let _ = lock.close().await;
151 result
152 })
153}
154
155sql_device_store!(PostgresDeviceStore, "postgres");