1use std::sync::atomic::{AtomicUsize, Ordering};
25
26use futures::future::BoxFuture;
27
28use crate::data::{AccessIntent, DataError, DataSource};
29
30pub enum DbDriver {
35 #[cfg(feature = "db-sqlx")]
36 Sqlx(sqlx::AnyPool),
37 #[cfg(feature = "db-seaorm")]
38 SeaOrm(sea_orm::DatabaseConnection),
39 #[cfg(feature = "db-diesel")]
40 Diesel(crate::data::drivers::diesel::DieselBlockingPool),
41}
42
43pub enum OwnedDbConn {
46 #[cfg(feature = "db-sqlx")]
47 Sqlx(sqlx::pool::PoolConnection<sqlx::Any>),
48 #[cfg(feature = "db-seaorm")]
49 SeaOrm(sea_orm::DatabaseConnection),
50 #[cfg(feature = "db-diesel")]
51 Diesel(crate::data::drivers::diesel::DieselBlockingPool),
52}
53
54pub struct ArclyDbPool {
59 name: &'static str,
60 primary: DbDriver,
61 replicas: Vec<DbDriver>,
62 rr: AtomicUsize,
63}
64
65impl ArclyDbPool {
66 pub fn new(name: &'static str, primary: DbDriver) -> Self {
67 Self {
68 name,
69 primary,
70 replicas: Vec::new(),
71 rr: AtomicUsize::new(0),
72 }
73 }
74
75 pub fn with_replica(mut self, replica: DbDriver) -> Self {
77 self.replicas.push(replica);
78 self
79 }
80
81 pub(crate) fn pick(&self, intent: AccessIntent) -> (&DbDriver, bool) {
85 match intent {
86 AccessIntent::Write => (&self.primary, false),
87 AccessIntent::Read if self.replicas.is_empty() => (&self.primary, false),
88 AccessIntent::Read => {
89 let i = self.rr.fetch_add(1, Ordering::Relaxed);
90 (&self.replicas[i % self.replicas.len()], true)
91 }
92 }
93 }
94
95 pub(crate) fn primary(&self) -> &DbDriver {
97 &self.primary
98 }
99
100 #[allow(unused_variables, unreachable_code)]
102 async fn acquire_driver(&self, driver: &DbDriver) -> Result<OwnedDbConn, DataError> {
103 match driver {
104 #[cfg(feature = "db-sqlx")]
105 DbDriver::Sqlx(pool) => Ok(OwnedDbConn::Sqlx(
106 pool.acquire().await.map_err(|e| DataError(e.to_string()))?,
107 )),
108 #[cfg(feature = "db-seaorm")]
109 DbDriver::SeaOrm(conn) => Ok(OwnedDbConn::SeaOrm(conn.clone())),
110 #[cfg(feature = "db-diesel")]
111 DbDriver::Diesel(pool) => Ok(OwnedDbConn::Diesel(pool.clone())),
112 #[allow(unreachable_patterns)]
113 _ => Err(DataError(
114 "no database driver feature enabled (db-sqlx / db-seaorm / db-diesel)".into(),
115 )),
116 }
117 }
118}
119
120impl DataSource for ArclyDbPool {
121 type Conn = OwnedDbConn;
122
123 fn acquire(&self, intent: AccessIntent) -> BoxFuture<'_, Result<Self::Conn, DataError>> {
128 Box::pin(async move {
129 let started = std::time::Instant::now();
130 let (driver, is_replica) = self.pick(intent);
131
132 let result = match self.acquire_driver(driver).await {
133 Ok(conn) => Ok(conn),
134 Err(replica_err) if is_replica => {
135 metrics::counter!("db_replica_fallback_total", "pool" => self.name)
136 .increment(1);
137 tracing::warn!(
138 pool = self.name,
139 error = %replica_err,
140 "replica acquire failed — falling back to primary"
141 );
142 self.acquire_driver(&self.primary).await
143 }
144 Err(e) => Err(e),
145 };
146
147 metrics::histogram!("db_acquire_seconds", "pool" => self.name)
148 .record(started.elapsed().as_secs_f64());
149 if result.is_err() {
150 metrics::counter!("db_acquire_errors_total", "pool" => self.name).increment(1);
151 }
152 result
153 })
154 }
155
156 fn name(&self) -> &'static str {
157 self.name
158 }
159}
160
161impl ArclyDbPool {
164 #[allow(unreachable_code)]
169 pub async fn ping(&self) -> Result<(), DataError> {
170 match self.primary() {
171 #[cfg(feature = "db-sqlx")]
172 DbDriver::Sqlx(pool) => {
173 sqlx::query_scalar::<_, i64>("SELECT 1")
174 .fetch_one(pool)
175 .await
176 .map_err(|e| DataError(e.to_string()))?;
177 Ok(())
178 }
179 #[cfg(feature = "db-seaorm")]
180 DbDriver::SeaOrm(conn) => conn.ping().await.map_err(|e| DataError(e.to_string())),
181 #[cfg(feature = "db-diesel")]
182 DbDriver::Diesel(pool) => pool.ping().await,
183 #[allow(unreachable_patterns)]
184 _ => Err(DataError("no database driver feature enabled".into())),
185 }
186 }
187}
188
189pub struct DbHealthCheck {
200 registry: &'static crate::data::DataSourceRegistry<ArclyDbPool>,
201}
202
203impl DbHealthCheck {
204 pub fn new(registry: &'static crate::data::DataSourceRegistry<ArclyDbPool>) -> Self {
205 Self { registry }
206 }
207}
208
209impl crate::observability::health::HealthCheck for DbHealthCheck {
210 fn check(&self) -> BoxFuture<'_, crate::observability::health::HealthStatus> {
211 use crate::observability::health::HealthStatus;
212 Box::pin(async move {
213 for (name, pool) in self.registry.iter() {
214 if let Err(e) = pool.ping().await {
215 let label = if name.is_empty() { "default" } else { name };
216 return HealthStatus::Unhealthy(format!("pool `{label}`: {e}"));
217 }
218 }
219 HealthStatus::Healthy
220 })
221 }
222}
223
224#[cfg(all(test, feature = "db-sqlx"))]
225mod tests {
226 use super::*;
227
228 async fn memory_pool() -> DbDriver {
229 sqlx::any::install_default_drivers();
230 DbDriver::Sqlx(
231 sqlx::any::AnyPoolOptions::new()
232 .max_connections(2)
233 .connect("sqlite::memory:")
234 .await
235 .expect("in-memory sqlite"),
236 )
237 }
238
239 fn dead_pool() -> DbDriver {
242 sqlx::any::install_default_drivers();
243 DbDriver::Sqlx(
244 sqlx::any::AnyPoolOptions::new()
245 .max_connections(1)
246 .acquire_timeout(std::time::Duration::from_millis(200))
247 .connect_lazy("sqlite:///nonexistent-dir/arcly-itest.db?mode=ro")
248 .expect("lazy pool builds without connecting"),
249 )
250 }
251
252 #[tokio::test]
253 async fn dead_replica_falls_back_to_primary_for_reads() {
254 let pool = ArclyDbPool::new("failover-test", memory_pool().await).with_replica(dead_pool());
255
256 for _ in 0..3 {
259 let conn = pool.acquire(AccessIntent::Read).await;
260 assert!(
261 conn.is_ok(),
262 "read must fall back to primary: {:?}",
263 conn.err().map(|e| e.to_string())
264 );
265 }
266 assert!(pool.acquire(AccessIntent::Write).await.is_ok());
268 }
269
270 #[tokio::test]
271 async fn ping_succeeds_on_live_primary_and_fails_on_dead() {
272 let live = ArclyDbPool::new("live", memory_pool().await);
273 assert!(live.ping().await.is_ok());
274
275 let dead = ArclyDbPool::new("dead", dead_pool());
276 assert!(dead.ping().await.is_err());
277 }
278}