|
| 1 | +//! Bounded cold database startup for the run-once storage accounting worker. |
| 2 | +
|
| 3 | +use std::future::Future; |
| 4 | +use std::io::ErrorKind; |
| 5 | +use std::time::Duration; |
| 6 | + |
| 7 | +use anyhow::{Context, Result}; |
| 8 | +use buzz_db::{Db, DbConfig, DbError}; |
| 9 | +use tokio::time::{sleep, timeout, Instant}; |
| 10 | + |
| 11 | +const ACQUIRE_TIMEOUT: Duration = Duration::from_secs(30); |
| 12 | +const RETRY_DELAYS: [Duration; 2] = [Duration::from_secs(2), Duration::from_secs(5)]; |
| 13 | + |
| 14 | +/// Establish the worker's database pool before it acquires its accounting lease. |
| 15 | +pub(super) async fn connect_db() -> Result<Db> { |
| 16 | + let config = worker_config(crate::db_config_from_env()); |
| 17 | + connect_with_retry(|| Db::new(&config)).await |
| 18 | +} |
| 19 | + |
| 20 | +fn worker_config(config: DbConfig) -> DbConfig { |
| 21 | + DbConfig { |
| 22 | + max_connections: 1, |
| 23 | + // The worker detaches its lock-owning session. Do not open idle |
| 24 | + // replacements while that session scans S3 and publishes the result. |
| 25 | + min_connections: 0, |
| 26 | + acquire_timeout_secs: ACQUIRE_TIMEOUT.as_secs(), |
| 27 | + ..config |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +// Only initial connection establishment is retried. Once the command owns |
| 32 | +// the advisory lock, reconnecting would lose its publication fence. |
| 33 | +async fn connect_with_retry<T, Connect, Attempt>(mut connect: Connect) -> Result<T> |
| 34 | +where |
| 35 | + Connect: FnMut() -> Attempt, |
| 36 | + Attempt: Future<Output = buzz_db::Result<T>>, |
| 37 | +{ |
| 38 | + let started = Instant::now(); |
| 39 | + // Three attempts of at most 30s, plus 2s and 5s backoffs: at most 97s. |
| 40 | + for attempt in 0..=RETRY_DELAYS.len() { |
| 41 | + let attempt_started = Instant::now(); |
| 42 | + eprintln!( |
| 43 | + "{}", |
| 44 | + serde_json::json!({ |
| 45 | + "event": "storage_snapshot_db_connect_started", |
| 46 | + "stage": "db_connect", |
| 47 | + "attempt": attempt + 1, |
| 48 | + "timeout_ms": ACQUIRE_TIMEOUT.as_millis(), |
| 49 | + }) |
| 50 | + ); |
| 51 | + // Bound the entire initialization future, including session setup. |
| 52 | + let result = timeout(ACQUIRE_TIMEOUT, connect()) |
| 53 | + .await |
| 54 | + .unwrap_or_else(|_| Err(sqlx::Error::PoolTimedOut.into())); |
| 55 | + match result { |
| 56 | + Ok(db) => { |
| 57 | + eprintln!( |
| 58 | + "{}", |
| 59 | + serde_json::json!({ |
| 60 | + "event": "storage_snapshot_db_connect_completed", |
| 61 | + "stage": "db_connect", |
| 62 | + "attempt": attempt + 1, |
| 63 | + "attempt_elapsed_ms": attempt_started.elapsed().as_millis(), |
| 64 | + "elapsed_ms": started.elapsed().as_millis(), |
| 65 | + }) |
| 66 | + ); |
| 67 | + return Ok(db); |
| 68 | + } |
| 69 | + Err(error) => { |
| 70 | + let delay = RETRY_DELAYS |
| 71 | + .get(attempt) |
| 72 | + .copied() |
| 73 | + .filter(|_| retryable(&error)); |
| 74 | + let class = error_class(&error); |
| 75 | + // Avoid raw connection errors/URLs: configuration and driver |
| 76 | + // messages can contain credentials. Keep the source on the |
| 77 | + // returned error, but print only this bounded classification. |
| 78 | + eprintln!( |
| 79 | + "{}", |
| 80 | + serde_json::json!({ |
| 81 | + "event": "storage_snapshot_db_connect_failed", |
| 82 | + "stage": "db_connect", |
| 83 | + "attempt": attempt + 1, |
| 84 | + "attempt_elapsed_ms": attempt_started.elapsed().as_millis(), |
| 85 | + "elapsed_ms": started.elapsed().as_millis(), |
| 86 | + "error_class": class, |
| 87 | + "io_kind": match &error { |
| 88 | + DbError::Sqlx(sqlx::Error::Io(error)) => Some(format!("{:?}", error.kind())), |
| 89 | + _ => None, |
| 90 | + }, |
| 91 | + "sqlstate": match &error { |
| 92 | + DbError::Sqlx(sqlx::Error::Database(error)) => error.code(), |
| 93 | + _ => None, |
| 94 | + }, |
| 95 | + "retry_in_ms": delay.map(|value| value.as_millis()), |
| 96 | + }) |
| 97 | + ); |
| 98 | + match delay { |
| 99 | + Some(delay) => sleep(delay).await, |
| 100 | + None => { |
| 101 | + return Err(error).with_context(|| { |
| 102 | + format!( |
| 103 | + "storage snapshot database startup failed after {} attempt(s) and {}ms ({class})", |
| 104 | + attempt + 1, |
| 105 | + started.elapsed().as_millis(), |
| 106 | + ) |
| 107 | + }); |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + unreachable!("the last connection attempt always returns") |
| 114 | +} |
| 115 | + |
| 116 | +fn retryable(error: &DbError) -> bool { |
| 117 | + match error { |
| 118 | + DbError::Sqlx(sqlx::Error::PoolTimedOut) => true, |
| 119 | + // SQLx already backs off on connection refusal and transient server |
| 120 | + // errors. Other transport/resolver failures may also be transient; |
| 121 | + // allow only the bounded startup retries, excluding local input and |
| 122 | + // permission errors. Unknown resolver errors are not labeled as DNS. |
| 123 | + DbError::Sqlx(sqlx::Error::Io(error)) => !matches!( |
| 124 | + error.kind(), |
| 125 | + ErrorKind::InvalidInput |
| 126 | + | ErrorKind::InvalidData |
| 127 | + | ErrorKind::PermissionDenied |
| 128 | + | ErrorKind::NotFound |
| 129 | + | ErrorKind::Unsupported |
| 130 | + ), |
| 131 | + // Includes authentication, TLS, URL configuration and protocol errors. |
| 132 | + _ => false, |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +fn error_class(error: &DbError) -> &'static str { |
| 137 | + match error { |
| 138 | + DbError::Sqlx(sqlx::Error::PoolTimedOut) => "timeout", |
| 139 | + DbError::Sqlx(sqlx::Error::Io(_)) => "io", |
| 140 | + DbError::Sqlx(sqlx::Error::Tls(_)) => "tls", |
| 141 | + DbError::Sqlx(sqlx::Error::Configuration(_)) => "configuration", |
| 142 | + DbError::Sqlx(sqlx::Error::Database(error)) => { |
| 143 | + if error.code().is_some_and(|code| code.starts_with("28")) { |
| 144 | + "authentication" |
| 145 | + } else { |
| 146 | + "database" |
| 147 | + } |
| 148 | + } |
| 149 | + DbError::Sqlx(sqlx::Error::Protocol(_)) => "protocol", |
| 150 | + _ => "other", |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +#[cfg(test)] |
| 155 | +mod tests; |
0 commit comments