1
use crate::config::ConfigError;
2
use crate::telemetry::pools::{PoolKind, PoolUsage, record_acquire_error};
3
use cfg_if::cfg_if;
4
use sqlx::migrate::MigrateError;
5
use sqlx::pool::PoolConnection;
6
use sqlx::{PgPool, Postgres};
7
use thiserror::Error;
8

            
9
mod url;
10
pub use url::{admin_database_url, use_url};
11

            
12
cfg_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)]
30
pub 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

            
72
impl 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
30983
    pub fn is_unavailable(&self) -> bool {
77
30983
        matches!(
78
30983
            self,
79
            DBError::PoolBudgetExhausted
80
                | DBError::ConnectTimedOut
81
                | DBError::TenantQuarantined
82
                | DBError::TenantDisabled
83
                | DBError::UnknownTenant
84
6858
        ) || matches!(self, DBError::Sqlx(err) if is_pool_unavailable(err))
85
30983
    }
86
}
87

            
88
/// The pool refused to hand out a connection: it timed out or was closed.
89
#[must_use]
90
12973
pub fn is_pool_unavailable(err: &sqlx::Error) -> bool {
91
12973
    matches!(err, sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed)
92
12973
}
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))]
104
pub(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"))]
110
pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("../migrations");
111

            
112
180
pub async fn migrate_db() -> Result<(), DBError> {
113
180
    let pool = get_pool().await?;
114
180
    Ok(sqlx::migrate!("../migrations").run(&pool).await?)
115
180
}
116

            
117
1879433
pub async fn get_connection() -> Result<PoolConnection<Postgres>, DBError> {
118
1879433
    get_pool().await?.acquire().await.map_err(|error| {
119
1270
        record_acquire_error(PoolKind::Admin, &error);
120
1270
        error.into()
121
1270
    })
122
1879253
}
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.
128
51480
pub async fn execute_raw(sql: &str) -> Result<(), DBError> {
129
51480
    let pool = get_pool().await?;
130
51480
    sqlx::raw_sql(sqlx::AssertSqlSafe(sql))
131
51480
        .execute(&pool)
132
51480
        .await?;
133
51300
    Ok(())
134
51480
}
135

            
136
cfg_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
3
    pub fn test_pool_is_set() -> bool {
156
3
        DB_POOL.with_borrow(Option::is_some)
157
3
    }
158

            
159
6173
    async fn get_pool() -> Result<PgPool, DBError> {
160
6173
        DB_POOL
161
6173
            .with_borrow(Clone::clone)
162
6173
            .ok_or(DBError::TestPoolUnset)
163
6173
    }
164

            
165
    /// Connections of the admin pool, if it is open.
166
3
    pub(crate) fn admin_usage() -> Option<PoolUsage> {
167
3
        DB_POOL.with_borrow(|pool| pool.as_ref().map(PoolUsage::of))
168
3
    }
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
2507040
    pub fn test_pool_is_set() -> bool {
189
2507040
        DB_POOL.with_borrow(Option::is_some)
190
2507040
    }
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
1924920
    async fn get_pool() -> Result<PgPool, DBError> {
202
1924920
        if let Some(pool) = DB_POOL.with_borrow(Clone::clone) {
203
1647360
            return Ok(pool);
204
277560
        }
205
277560
        let url = url::current_url().ok_or(DBError::MissingUrl)?;
206
277560
        FALLBACK_POOL
207
55260
            .get_or_try_init(|| async {
208
55260
                tracing::debug!("Fallback pool initialization");
209
55260
                let options = PgPoolOptions::new()
210
55260
                    .max_connections(ADMIN_MAX_CONNECTIONS)
211
55260
                    .acquire_timeout(Duration::from_secs(10));
212
55260
                Ok(options.connect(url).await?)
213
110340
            })
214
277560
            .await
215
            .cloned()
216
1924740
    }
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

            
243
cfg_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
125033
    pub fn install_test_pool(pool: PgPool) -> TestPoolGuard {
251
125033
        DB_POOL.set(Some(pool));
252
125033
        TestPoolGuard(())
253
125033
    }
254

            
255
    /// Clears `DB_POOL` on drop. See [`install_test_pool`].
256
    pub struct TestPoolGuard(());
257

            
258
    impl Drop for TestPoolGuard {
259
125033
        fn drop(&mut self) {
260
125033
            DB_POOL.set(None);
261
125033
        }
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.
280
7380
pub async fn migrate_on(conn: &mut sqlx::PgConnection) -> Result<(), DBError> {
281
7380
    sqlx::migrate!("../migrations")
282
7380
        .run(conn)
283
7380
        .await
284
7380
        .map_err(DBError::from)
285
7380
}
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.
294
50760
pub async fn migrate_url(url: &str) -> Result<(), DBError> {
295
50760
    let pool = sqlx::postgres::PgPoolOptions::new()
296
50760
        .max_connections(1)
297
50760
        .acquire_timeout(std::time::Duration::from_secs(10))
298
50760
        .connect(url)
299
50760
        .await?;
300
50760
    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
50760
    pool.close().await;
305
50760
    result.map_err(DBError::from)
306
50760
}
307

            
308
#[cfg(test)]
309
mod db_tests;