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 #[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#[must_use]
90pub fn is_pool_unavailable(err: &sqlx::Error) -> bool {
91 matches!(err, sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed)
92}
93
94#[cfg(not(test))]
104pub(crate) const ADMIN_MAX_CONNECTIONS: u32 = 5;
105
106#[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
124pub 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 thread_local!(pub static DB_POOL: RefCell<Option<PgPool>> = const {
148 RefCell::new(None)
149 });
150
151 #[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 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 thread_local!(pub static DB_POOL: RefCell<Option<PgPool>> = const {
181 RefCell::new(None)
182 });
183
184 #[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 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 static DB_POOL: OnceCell<PgPool> = OnceCell::const_new();
221
222 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 #[must_use]
250 pub fn install_test_pool(pool: PgPool) -> TestPoolGuard {
251 DB_POOL.set(Some(pool));
252 TestPoolGuard(())
253 }
254
255 pub struct TestPoolGuard(());
257
258 impl Drop for TestPoolGuard {
259 fn drop(&mut self) {
260 DB_POOL.set(None);
261 }
262 }
263 }
264}
265
266pub 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
287pub 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 pool.close().await;
305 result.map_err(DBError::from)
306}
307
308#[cfg(test)]
309mod db_tests;