|
| 1 | +use std::{future::Future, sync::Arc, time::Duration}; |
| 2 | + |
| 3 | +use sqlx::{postgres::PgPoolOptions, Pool, Postgres}; |
| 4 | + |
| 5 | +use crate::retry::{next_backoff_delay, RetryConfig, RetryError}; |
| 6 | + |
| 7 | +/// A single DB node: connection pool plus shared health flags (used to prioritize nodes). |
| 8 | +#[derive(Debug)] |
| 9 | +struct DbNode { |
| 10 | + pool: Pool<Postgres>, |
| 11 | +} |
| 12 | + |
| 13 | +/// Database orchestrator for running reads/writes across multiple PostgreSQL nodes with retry/backoff. |
| 14 | +/// |
| 15 | +/// `DbOrchestrator` holds a list of database nodes (connection pools) and will |
| 16 | +/// retry transient failures with exponential backoff based on `retry_config`, |
| 17 | +/// |
| 18 | +/// ## Thread-safe `Clone` |
| 19 | +/// This type is cheap and thread-safe to clone: |
| 20 | +/// - `nodes` is `Vec<Arc<DbNode>>`, so cloning only increments `Arc` ref-counts and shares the same pools/nodes, |
| 21 | +/// - `sqlx::Pool<Postgres>` is internally reference-counted and designed to be cloned and used concurrently, |
| 22 | +/// - the node health flags are `AtomicBool`, so updates are safe from multiple threads/tasks. |
| 23 | +/// |
| 24 | +/// Clones share health state (the atomics) and the underlying pools, so all clones observe and influence |
| 25 | +/// the same “preferred node” ordering decisions. |
| 26 | +#[derive(Debug, Clone)] |
| 27 | +pub struct DbOrchestrator { |
| 28 | + nodes: Vec<Arc<DbNode>>, |
| 29 | + retry_config: RetryConfig, |
| 30 | +} |
| 31 | + |
| 32 | +#[derive(Debug)] |
| 33 | +pub enum DbOrchestratorError { |
| 34 | + InvalidNumberOfConnectionUrls, |
| 35 | + Sqlx(sqlx::Error), |
| 36 | +} |
| 37 | + |
| 38 | +impl std::fmt::Display for DbOrchestratorError { |
| 39 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 40 | + match self { |
| 41 | + Self::InvalidNumberOfConnectionUrls => { |
| 42 | + write!(f, "invalid number of connection URLs") |
| 43 | + } |
| 44 | + Self::Sqlx(e) => write!(f, "{e}"), |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl DbOrchestrator { |
| 50 | + pub fn try_new( |
| 51 | + connection_urls: &[String], |
| 52 | + retry_config: RetryConfig, |
| 53 | + ) -> Result<Self, DbOrchestratorError> { |
| 54 | + if connection_urls.is_empty() { |
| 55 | + return Err(DbOrchestratorError::InvalidNumberOfConnectionUrls); |
| 56 | + } |
| 57 | + |
| 58 | + let nodes = connection_urls |
| 59 | + .iter() |
| 60 | + .map(|url| { |
| 61 | + let pool = PgPoolOptions::new().max_connections(5).connect_lazy(url)?; |
| 62 | + |
| 63 | + Ok(Arc::new(DbNode { pool })) |
| 64 | + }) |
| 65 | + .collect::<Result<Vec<_>, sqlx::Error>>() |
| 66 | + .map_err(DbOrchestratorError::Sqlx)?; |
| 67 | + |
| 68 | + Ok(Self { |
| 69 | + nodes, |
| 70 | + retry_config, |
| 71 | + }) |
| 72 | + } |
| 73 | + |
| 74 | + pub async fn query<T, Q, Fut>(&self, query_fn: Q) -> Result<T, sqlx::Error> |
| 75 | + where |
| 76 | + Q: Fn(Pool<Postgres>) -> Fut, |
| 77 | + Fut: Future<Output = Result<T, sqlx::Error>>, |
| 78 | + { |
| 79 | + let mut attempts = 0; |
| 80 | + let mut delay = Duration::from_millis(self.retry_config.min_delay_millis); |
| 81 | + |
| 82 | + loop { |
| 83 | + match self.execute_once(&query_fn).await { |
| 84 | + Ok(value) => return Ok(value), |
| 85 | + Err(RetryError::Permanent(err)) => return Err(err), |
| 86 | + Err(RetryError::Transient(err)) => { |
| 87 | + if attempts >= self.retry_config.max_times { |
| 88 | + return Err(err); |
| 89 | + } |
| 90 | + |
| 91 | + tracing::warn!(attempt = attempts, delay_millis = delay.as_millis(), error = ?err, "retrying after backoff"); |
| 92 | + tokio::time::sleep(delay).await; |
| 93 | + delay = next_backoff_delay(delay, self.retry_config.clone()); |
| 94 | + attempts += 1; |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + async fn execute_once<T, Q, Fut>(&self, query_fn: &Q) -> Result<T, RetryError<sqlx::Error>> |
| 101 | + where |
| 102 | + Q: Fn(Pool<Postgres>) -> Fut, |
| 103 | + Fut: Future<Output = Result<T, sqlx::Error>>, |
| 104 | + { |
| 105 | + let mut last_error = None; |
| 106 | + |
| 107 | + for (idx, node) in self.nodes.iter().enumerate() { |
| 108 | + let pool = node.pool.clone(); |
| 109 | + |
| 110 | + match query_fn(pool).await { |
| 111 | + Ok(res) => { |
| 112 | + return Ok(res); |
| 113 | + } |
| 114 | + Err(err) => { |
| 115 | + if Self::is_connection_error(&err) { |
| 116 | + tracing::warn!(node_index = idx, error = ?err, "database query failed"); |
| 117 | + last_error = Some(err); |
| 118 | + } else { |
| 119 | + return Err(RetryError::Permanent(err)); |
| 120 | + } |
| 121 | + } |
| 122 | + }; |
| 123 | + } |
| 124 | + |
| 125 | + Err(RetryError::Transient( |
| 126 | + last_error.expect("write_op attempted without database nodes"), |
| 127 | + )) |
| 128 | + } |
| 129 | + |
| 130 | + fn is_connection_error(error: &sqlx::Error) -> bool { |
| 131 | + matches!( |
| 132 | + error, |
| 133 | + sqlx::Error::Io(_) |
| 134 | + | sqlx::Error::Tls(_) |
| 135 | + | sqlx::Error::Protocol(_) |
| 136 | + | sqlx::Error::PoolTimedOut |
| 137 | + | sqlx::Error::PoolClosed |
| 138 | + | sqlx::Error::WorkerCrashed |
| 139 | + | sqlx::Error::BeginFailed |
| 140 | + | sqlx::Error::Database(_) |
| 141 | + ) |
| 142 | + } |
| 143 | +} |
0 commit comments