Skip to main content

server/
db.rs

1use crate::config::ConfigError;
2use crate::telemetry::pools::{PoolKind, PoolUsage, record_acquire_error};
3use cfg_if::cfg_if;
4use sqlx::migrate::MigrateError;
5use sqlx::pool::PoolConnection;
6use sqlx::{PgPool, Postgres};
7use thiserror::Error;
8
9mod url;
10pub use url::{admin_database_url, use_url};
11
12cfg_if! {
13    if #[cfg(test)] {
14    use std::cell::RefCell;
15    } else if #[cfg(feature = "test-utils")] {
16    use std::cell::RefCell;
17    use sqlx::postgres::PgPoolOptions;
18    use std::time::Duration;
19    use tokio::sync::OnceCell;
20
21    } else {
22    use sqlx::postgres::PgPoolOptions;
23    use std::time::Duration;
24    use tokio::sync::OnceCell;
25
26    }
27}
28
29#[derive(Debug, Error)]
30pub enum DBError {
31    #[error("Database error: {0}")]
32    Sqlx(#[from] sqlx::Error),
33    #[error("DB migration error: {0}")]
34    Migration(#[from] MigrateError),
35    #[error("Configuration access error")]
36    Config(#[from] ConfigError),
37    #[error("DATABASE_URL is not provided")]
38    MissingUrl,
39    #[error("The database URL was already set or already in use")]
40    UrlAlreadyResolved,
41    #[error("The database role lacks CREATEDB privilege")]
42    NoCreateDb,
43    #[error("Failed to generate an authentication keypair")]
44    KeyGen,
45    #[error("The database did not accept a connection in time")]
46    ConnectTimedOut,
47    #[error("No connection-pool slot became free in time")]
48    PoolBudgetExhausted,
49    #[error("This account is undergoing maintenance and is temporarily unavailable")]
50    TenantQuarantined,
51    #[error("This account is disabled")]
52    TenantDisabled,
53    #[error("This account has no tenant database")]
54    UnknownTenant,
55    #[error("A fleet migration worker did not finish: {0}")]
56    FleetWorkerLost(String),
57    #[error("{0}")]
58    GlobalSchemaStale(String),
59    #[error("The tag trim job could not lock a stable set of tag keys")]
60    TagTrimUnstable,
61    #[error("The data changed while saving; try again")]
62    WriteConflict,
63    #[error("Refusing to build a connection string from database name {0:?}")]
64    UnsafeDatabaseName(String),
65    #[error("The tenant pool registry lock was poisoned")]
66    RegistryPoisoned,
67    #[cfg(test)]
68    #[error("DB_POOL must be set; see local_db_sqlx_test macro")]
69    TestPoolUnset,
70}
71
72impl DBError {
73    /// The database cannot be reached right now: a pool or tenant condition,
74    /// not a fault in the request.
75    #[must_use]
76    pub fn is_unavailable(&self) -> bool {
77        matches!(
78            self,
79            DBError::PoolBudgetExhausted
80                | DBError::ConnectTimedOut
81                | DBError::TenantQuarantined
82                | DBError::TenantDisabled
83                | DBError::UnknownTenant
84        ) || matches!(self, DBError::Sqlx(err) if is_pool_unavailable(err))
85    }
86}
87
88/// The pool refused to hand out a connection: it timed out or was closed.
89#[must_use]
90pub fn is_pool_unavailable(err: &sqlx::Error) -> bool {
91    matches!(err, sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed)
92}
93
94/// Connections the global/admin pool may open, per process.
95///
96/// Read on every authenticated request (`jwt_auth` re-reads the user row), so
97/// this is the web tier's effective concurrency ceiling, not a background
98/// allowance. Budget per process is this plus the tenant registry's own
99/// ceiling; see ADR 0032.
100///
101/// Server's own `cfg(test)` arm asserts an injected `sqlx::test` pool and never
102/// builds one, so the constant does not exist there.
103#[cfg(not(test))]
104pub(crate) const ADMIN_MAX_CONNECTIONS: u32 = 5;
105
106/// Shared migration set. Exposed to tests (server's own and `tests-integration`)
107/// so every `#[sqlx::test(migrator = "...")]` site names this once instead of
108/// embedding all migrations per test.
109#[cfg(any(test, feature = "test-utils"))]
110pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("../migrations");
111
112pub async fn migrate_db() -> Result<(), DBError> {
113    let pool = get_pool().await?;
114    Ok(sqlx::migrate!("../migrations").run(&pool).await?)
115}
116
117pub async fn get_connection() -> Result<PoolConnection<Postgres>, DBError> {
118    get_pool().await?.acquire().await.map_err(|error| {
119        record_acquire_error(PoolKind::Admin, &error);
120        error.into()
121    })
122}
123
124/// Runs a multi-statement SQL script against the admin pool via the simple
125/// query protocol. Executed against the shared pool (not a
126/// `&mut PgConnection`) so the future stays `Send`/spawnable — the `&mut`
127/// executor form trips a higher-ranked-lifetime bound once `boot()` is spawned.
128pub async fn execute_raw(sql: &str) -> Result<(), DBError> {
129    let pool = get_pool().await?;
130    sqlx::raw_sql(sqlx::AssertSqlSafe(sql))
131        .execute(&pool)
132        .await?;
133    Ok(())
134}
135
136cfg_if! {
137    if #[cfg(test)] {
138    // Server's own tests rely on `local_db_sqlx_test` (supp_macro) injecting
139    // a sqlx::test pool into DB_POOL before commands run. Forgetting that
140    // setup is a programming error — panic loudly rather than silently
141    // sharing a real DATABASE_URL pool across tests, which would break the
142    // per-test isolation sqlx::test guarantees.
143    //
144    // The slot owns a pool handle rather than pointing at the test's own, so a
145    // task still running after the test body sees a closed pool instead of
146    // freed memory.
147    thread_local!(pub static DB_POOL: RefCell<Option<PgPool>> = const {
148        RefCell::new(None)
149    });
150
151    /// True when the current thread has installed a test pool. Server-side
152    /// callers consult this to decide between the test pool and the
153    /// per-user production pool.
154    #[must_use]
155    pub fn test_pool_is_set() -> bool {
156        DB_POOL.with_borrow(Option::is_some)
157    }
158
159    async fn get_pool() -> Result<PgPool, DBError> {
160        DB_POOL
161            .with_borrow(Clone::clone)
162            .ok_or(DBError::TestPoolUnset)
163    }
164
165    /// Connections of the admin pool, if it is open.
166    pub(crate) fn admin_usage() -> Option<PoolUsage> {
167        DB_POOL.with_borrow(|pool| pool.as_ref().map(PoolUsage::of))
168    }
169
170    } else if #[cfg(feature = "test-utils")] {
171    // Downstream consumers (the workspace `tests-integration` crate, and
172    // any web/sshd test that wants to drive a `server::command::*` flow
173    // against an isolated DB) install a sqlx::test pool via DB_POOL. When
174    // it is not installed we fall back to the production `DATABASE_URL`
175    // pool — that's the path web's existing tests take when compiled with
176    // `--all-features`, since they never set DB_POOL and instead let the
177    // production pool resolve via JWT'd handlers.
178    //
179    // The slot owns a pool handle for the same reason as the `cfg(test)` arm.
180    thread_local!(pub static DB_POOL: RefCell<Option<PgPool>> = const {
181        RefCell::new(None)
182    });
183
184    /// True when the current thread has installed a test pool. Used by
185    /// `User::get_connection` to choose between the test override and the
186    /// per-user production pool.
187    #[must_use]
188    pub fn test_pool_is_set() -> bool {
189        DB_POOL.with_borrow(Option::is_some)
190    }
191
192    static FALLBACK_POOL: OnceCell<PgPool> = OnceCell::const_new();
193
194    /// Connections of the admin pool, if it is open.
195    pub(crate) fn admin_usage() -> Option<PoolUsage> {
196        DB_POOL
197            .with_borrow(|pool| pool.as_ref().map(PoolUsage::of))
198            .or_else(|| FALLBACK_POOL.get().map(PoolUsage::of))
199    }
200
201    async fn get_pool() -> Result<PgPool, DBError> {
202        if let Some(pool) = DB_POOL.with_borrow(Clone::clone) {
203            return Ok(pool);
204        }
205        let url = url::current_url().ok_or(DBError::MissingUrl)?;
206        FALLBACK_POOL
207            .get_or_try_init(|| async {
208                tracing::debug!("Fallback pool initialization");
209                let options = PgPoolOptions::new()
210                    .max_connections(ADMIN_MAX_CONNECTIONS)
211                    .acquire_timeout(Duration::from_secs(10));
212                Ok(options.connect(url).await?)
213            })
214            .await
215            .cloned()
216    }
217
218    } else {
219    // Production: lazy-init from DATABASE_URL.
220    static DB_POOL: OnceCell<PgPool> = OnceCell::const_new();
221
222    /// Connections of the admin pool, if it is open.
223    pub(crate) fn admin_usage() -> Option<PoolUsage> {
224        DB_POOL.get().map(PoolUsage::of)
225    }
226
227    async fn get_pool() -> Result<PgPool, DBError> {
228        let url = url::current_url().ok_or(DBError::MissingUrl)?;
229        DB_POOL
230            .get_or_try_init(|| async {
231                tracing::debug!("Pool initialization");
232                let options = PgPoolOptions::new()
233                    .max_connections(ADMIN_MAX_CONNECTIONS)
234                    .acquire_timeout(Duration::from_secs(10));
235                Ok(options.connect(url).await?)
236            })
237            .await
238            .cloned()
239    }
240    }
241}
242
243cfg_if! {
244    if #[cfg(any(test, feature = "test-utils"))] {
245    /// Installs `pool` into `DB_POOL` until the returned guard drops.
246    ///
247    /// A pool left in `DB_POOL` outlives its test and keeps a permit of
248    /// sqlx's process-wide test master pool, deadlocking `cargo test`.
249    #[must_use]
250    pub fn install_test_pool(pool: PgPool) -> TestPoolGuard {
251        DB_POOL.set(Some(pool));
252        TestPoolGuard(())
253    }
254
255    /// Clears `DB_POOL` on drop. See [`install_test_pool`].
256    pub struct TestPoolGuard(());
257
258    impl Drop for TestPoolGuard {
259        fn drop(&mut self) {
260            DB_POOL.set(None);
261        }
262    }
263    }
264}
265
266// Provisioning helpers. The per-user DSN is derived from the admin
267// `DATABASE_URL`. Fully-qualified paths keep these independent of the per-arm
268// imports in the `cfg_if!` above so they compile under every cfg (server's own
269// `cfg(test)` never provisions, but the pure helpers stay unit-testable).
270
271/// Runs the migration set on an existing connection.
272///
273/// The fleet migrator already holds one per tenant for the claim lock, so
274/// opening a second just to migrate would double its connection cost — four
275/// workers would spend eight tenant connections against a budget of five
276/// (ADR 0032).
277///
278/// # Errors
279/// [`DBError::Migration`] if a migration fails or the applied set has drifted.
280pub async fn migrate_on(conn: &mut sqlx::PgConnection) -> Result<(), DBError> {
281    sqlx::migrate!("../migrations")
282        .run(conn)
283        .await
284        .map_err(DBError::from)
285}
286
287/// Runs the full migration set against the database at `url`. Used by
288/// provisioning to bring a freshly-created per-user database up to the
289/// (DDL-only) schema.
290///
291/// # Errors
292/// [`DBError::Sqlx`] on connect failure, [`DBError::Migration`] if a migration
293/// fails.
294pub async fn migrate_url(url: &str) -> Result<(), DBError> {
295    let pool = sqlx::postgres::PgPoolOptions::new()
296        .max_connections(1)
297        .acquire_timeout(std::time::Duration::from_secs(10))
298        .connect(url)
299        .await?;
300    let result = sqlx::migrate!("../migrations").run(&pool).await;
301    // Close the pool on BOTH paths before returning. A still-open connection to
302    // the per-user DB would otherwise block a compensating `DROP DATABASE` on
303    // the migration-failure path.
304    pool.close().await;
305    result.map_err(DBError::from)
306}
307
308#[cfg(test)]
309mod db_tests;