1use std::any::Any;
2use std::sync::Arc;
3use std::time::Duration;
4
5use camel_api::datasource::{CheckFuture, CloseFuture, CreatePoolFuture};
6use camel_api::datasource::{DatasourceConfig, DatasourceHandle, PoolFactory};
7use camel_api::error::CamelError;
8use camel_api::lifecycle::HealthStatus;
9use sqlx::AnyPool;
10use sqlx::any::AnyPoolOptions;
11
12use crate::config::{enrich_db_url_with_ssl_params, redact_db_url};
13
14fn is_sqlite_memory_url(url: &str) -> bool {
18 let lowered = url.to_lowercase();
19 lowered.starts_with("sqlite::memory:")
20 || lowered.starts_with("sqlite://:memory:")
21 || (lowered.starts_with("sqlite:") && lowered.contains("mode=memory"))
22}
23
24const IN_FLIGHT_DRAIN_WAIT: Duration = Duration::from_secs(10);
28const IN_FLIGHT_DRAIN_POLL: Duration = Duration::from_millis(5);
30
31pub struct SqlPoolFactory;
32
33pub(crate) fn pool_max_connections(pool: &AnyPool) -> u32 {
35 pool.options().get_max_connections()
36}
37
38impl PoolFactory for SqlPoolFactory {
39 fn create<'a>(&'a self, config: &'a DatasourceConfig) -> CreatePoolFuture<'a> {
40 Box::pin(async move {
41 sqlx::any::install_default_drivers();
44
45 let max_conn = config.max_connections.unwrap_or(5);
46 let min_conn = if is_sqlite_memory_url(&config.db_url) {
55 if config.min_connections.is_some_and(|m| m > 0) {
56 tracing::info!("datasource pool: min_connections ignored for in-memory sqlite");
58 }
59 0
60 } else {
61 config.min_connections.unwrap_or(1)
62 };
63 let idle_timeout = Duration::from_secs(config.idle_timeout_secs.unwrap_or(300));
64 let max_lifetime = Duration::from_secs(config.max_lifetime_secs.unwrap_or(1800));
65
66 let db_url = enrich_db_url_with_ssl_params(
67 &config.db_url,
68 config.ssl_mode.as_deref(),
69 config.ssl_root_cert.as_deref(),
70 config.ssl_cert.as_deref(),
71 config.ssl_key.as_deref(),
72 )?;
73
74 let pool = AnyPoolOptions::new()
75 .max_connections(max_conn)
76 .min_connections(min_conn)
77 .idle_timeout(idle_timeout)
78 .max_lifetime(max_lifetime)
79 .connect(&db_url)
80 .await
81 .map_err(|e| {
82 CamelError::ProcessorError(format!(
83 "failed to create datasource pool ({}): {}",
84 redact_db_url(&config.db_url),
85 e
86 ))
87 })?;
88
89 tracing::info!("datasource pool created: max_connections={}", max_conn);
90 Ok(Arc::new(pool) as Arc<dyn Any + Send + Sync>)
91 })
92 }
93
94 fn check<'a>(&'a self, handle: &'a DatasourceHandle) -> CheckFuture<'a> {
95 Box::pin(async move {
96 match handle.downcast::<AnyPool>() {
97 Ok(pool) => match sqlx::query("SELECT 1").execute(&*pool).await {
98 Ok(_) => HealthStatus::Healthy,
99 Err(e) => {
100 tracing::warn!("datasource '{}' health check failed: {}", handle.name, e);
102 HealthStatus::Unhealthy
103 }
104 },
105 Err(e) => {
106 tracing::warn!(
108 "datasource '{}' health check failed: pool downcast error: {}",
109 handle.name,
110 e
111 );
112 HealthStatus::Unhealthy
113 }
114 }
115 })
116 }
117
118 fn close<'a>(&'a self, handle: &'a DatasourceHandle) -> CloseFuture<'a> {
119 Box::pin(async move {
120 let pool = handle.downcast::<AnyPool>().map_err(|e| {
121 CamelError::ProcessorError(format!(
122 "datasource '{}': pool close downcast failed: {}",
123 handle.name, e
124 ))
125 })?;
126 pool.close().await;
129 let drain_deadline = std::time::Instant::now() + IN_FLIGHT_DRAIN_WAIT;
143 while pool.size() > 0 {
144 if std::time::Instant::now() >= drain_deadline {
145 return Err(CamelError::ProcessorError(format!(
153 "datasource '{}': pool did not drain within {}s ({} connection(s) \
154 still open) — the database may outlive its boot",
155 handle.name,
156 IN_FLIGHT_DRAIN_WAIT.as_secs(),
157 pool.size()
158 )));
159 }
160 tokio::time::sleep(IN_FLIGHT_DRAIN_POLL).await;
166 pool.close().await;
167 }
168 Ok(())
169 })
170 }
171
172 fn supported_schemes(&self) -> &[&str] {
173 &["postgres", "postgresql", "mysql", "sqlite"]
174 }
175
176 fn name(&self) -> &'static str {
177 "sqlx"
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184 use camel_component_api::test_support::timeout_wait;
185
186 #[test]
187 fn sql_pool_factory_name() {
188 let f = SqlPoolFactory;
189 assert_eq!(f.name(), "sqlx");
190 }
191
192 #[test]
193 fn sql_pool_factory_supported_schemes() {
194 let f = SqlPoolFactory;
195 assert!(f.supported_schemes().contains(&"postgres"));
196 assert!(f.supported_schemes().contains(&"mysql"));
197 assert!(f.supported_schemes().contains(&"sqlite"));
198 }
199
200 #[test]
201 fn sql_pool_factory_matches_postgres() {
202 let f = SqlPoolFactory;
203 let cfg = DatasourceConfig {
204 db_url: "postgres://localhost/test".into(),
205 provider: None,
206 max_connections: None,
207 min_connections: None,
208 idle_timeout_secs: None,
209 max_lifetime_secs: None,
210 ssl_mode: None,
211 ssl_root_cert: None,
212 ssl_cert: None,
213 ssl_key: None,
214 extra: std::collections::HashMap::new(),
215 };
216 assert!(f.matches(&cfg));
217 }
218
219 #[tokio::test]
220 async fn sql_pool_factory_close_closes_the_pool() {
221 let f = SqlPoolFactory;
222 let cfg = DatasourceConfig {
223 db_url: "sqlite::memory:?cache=shared".into(),
224 provider: None,
225 max_connections: None,
226 min_connections: None,
227 idle_timeout_secs: None,
228 max_lifetime_secs: None,
229 ssl_mode: None,
230 ssl_root_cert: None,
231 ssl_cert: None,
232 ssl_key: None,
233 extra: std::collections::HashMap::new(),
234 };
235 let inner = f.create(&cfg).await.unwrap();
236 let pool = Arc::downcast::<AnyPool>(Arc::clone(&inner)).unwrap();
237 let handle = DatasourceHandle::new("appdb".into(), f.name().into(), Arc::clone(&inner));
238
239 f.close(&handle).await.unwrap();
240 assert!(
241 pool.is_closed(),
242 "factory close must drain the sqlx pool (bd rc-25lup.4)"
243 );
244 }
245
246 #[tokio::test]
250 async fn sql_pool_factory_close_drains_pool_to_zero() {
251 let f = SqlPoolFactory;
252 let cfg = DatasourceConfig {
253 db_url: "sqlite:file:memdb_drain_zero?mode=memory&cache=shared".into(),
254 provider: None,
255 max_connections: Some(3),
256 min_connections: None,
257 idle_timeout_secs: None,
258 max_lifetime_secs: None,
259 ssl_mode: None,
260 ssl_root_cert: None,
261 ssl_cert: None,
262 ssl_key: None,
263 extra: std::collections::HashMap::new(),
264 };
265 let inner = f.create(&cfg).await.unwrap();
266 let pool = Arc::downcast::<AnyPool>(Arc::clone(&inner)).unwrap();
267
268 let mut conn1 = timeout_wait(
271 "first pool acquire",
272 Duration::from_secs(30),
273 pool.acquire(),
274 )
275 .await
276 .expect("first connection");
277 let mut conn2 = timeout_wait(
278 "second pool acquire",
279 Duration::from_secs(30),
280 pool.acquire(),
281 )
282 .await
283 .expect("second connection");
284 sqlx::query("SELECT 1")
285 .execute(&mut *conn1)
286 .await
287 .expect("SELECT 1 through first connection");
288 sqlx::query("SELECT 1")
289 .execute(&mut *conn2)
290 .await
291 .expect("SELECT 1 through second connection");
292 drop(conn1);
293 drop(conn2);
294
295 let handle = DatasourceHandle::new("appdb".into(), f.name().into(), inner);
296 f.close(&handle).await.expect("factory close must succeed");
297 assert!(pool.is_closed(), "factory close must leave the pool closed");
298 assert_eq!(
299 pool.size(),
300 0,
301 "factory close must drain the pool to zero connections"
302 );
303 }
304
305 #[tokio::test]
310 async fn named_shared_memory_uri_probe() {
311 use sqlx::Row;
312
313 let f = SqlPoolFactory;
314 let cfg = DatasourceConfig {
315 db_url: "sqlite:file:memdb_probe?mode=memory&cache=shared".into(),
316 provider: None,
317 max_connections: Some(3),
318 min_connections: None,
319 idle_timeout_secs: None,
320 max_lifetime_secs: None,
321 ssl_mode: None,
322 ssl_root_cert: None,
323 ssl_cert: None,
324 ssl_key: None,
325 extra: std::collections::HashMap::new(),
326 };
327 let inner = f.create(&cfg).await.unwrap();
328 let pool = Arc::downcast::<AnyPool>(Arc::clone(&inner)).unwrap();
329
330 sqlx::query("CREATE TABLE probe (v TEXT)")
331 .execute(&*pool)
332 .await
333 .expect("create");
334 let conn1 = timeout_wait(
337 "probe pool acquire",
338 Duration::from_secs(30),
339 pool.acquire(),
340 )
341 .await
342 .expect("conn1");
343 sqlx::query("INSERT INTO probe VALUES ('x')")
344 .execute(&*pool)
345 .await
346 .expect("insert on a second connection");
347 drop(conn1);
348
349 let row = sqlx::query("SELECT COUNT(*) FROM probe")
350 .fetch_one(&*pool)
351 .await
352 .expect("count");
353 let n = row.try_get::<i64, usize>(0).expect("count i64");
354 assert_eq!(
355 n, 1,
356 "named shared memory URI must share across pool connections"
357 );
358 }
359
360 #[test]
364 fn sqlite_memory_url_classifier_table() {
365 let cases: &[(&str, bool)] = &[
366 ("sqlite::memory:", true),
368 ("sqlite://:memory:", true),
369 ("sqlite:file:memdb1?mode=memory&cache=shared", true),
370 ("SQLITE::MEMORY:", true),
372 ("Sqlite:file:MEMDB2?MODE=MEMORY", true),
373 ("sqlite:file:demo_mode=memory.db", true),
375 ("sqlite:data.db", false),
377 ("sqlite:file:memory.db", false),
378 ("postgres://host/db?mode=memory", false),
379 ("sqlite:file::memory:?cache=shared", false),
382 ];
383 for (url, expected) in cases {
384 assert_eq!(
385 is_sqlite_memory_url(url),
386 *expected,
387 "classifier mismatch for {url:?}"
388 );
389 }
390 }
391}