Skip to main content

camel_component_sql/
pool_factory.rs

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
14/// True for sqlite URLs whose database lives in memory: the bare
15/// `:memory:` host forms and the named shared-cache form
16/// (`sqlite:file:memdb_x?mode=memory&cache=shared`).
17fn 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
24/// How long `close` waits for in-flight connections to finish their
25/// async close after `pool.close()` resolved (sqlx 0.8.6 leaves them
26/// behind; bd rc-ywwz9).
27const IN_FLIGHT_DRAIN_WAIT: Duration = Duration::from_secs(10);
28/// Poll interval for that wait.
29const IN_FLIGHT_DRAIN_POLL: Duration = Duration::from_millis(5);
30
31pub struct SqlPoolFactory;
32
33/// Max connections configured on `pool`, for typed `PoolExhausted` naming.
34pub(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            // Install all compiled-in sqlx drivers so AnyPool can resolve them.
42            // This is idempotent; safe to call multiple times.
43            sqlx::any::install_default_drivers();
44
45            let max_conn = config.max_connections.unwrap_or(5);
46            // A `min_connections` maintainer on an in-memory sqlite pool
47            // fights the die-with-boot contract: sqlx 0.8.6's
48            // `try_min_connections` re-opens connections without checking
49            // `is_closed`, so a maintained pool can resurrect a connection
50            // after `close()` drains it and keep a named shared-cache
51            // database alive into the next boot in the same process
52            // (bd rc-ywwz9). Memory pools therefore never arm the
53            // maintainer, explicit setting included.
54            let min_conn = if is_sqlite_memory_url(&config.db_url) {
55                if config.min_connections.is_some_and(|m| m > 0) {
56                    // log-policy: outside-contract
57                    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                        // log-policy: outside-contract
101                        tracing::warn!("datasource '{}' health check failed: {}", handle.name, e);
102                        HealthStatus::Unhealthy
103                    }
104                },
105                Err(e) => {
106                    // log-policy: outside-contract
107                    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            // sqlx `close()` is infallible: it signals closure and drains
127            // idle connections; subsequent acquire calls fail closed.
128            pool.close().await;
129            // But `close().await` resolving does NOT mean the pool is
130            // empty (sqlx 0.8.6, verified by probe, bd rc-ywwz9): its
131            // acquire loop only blocks when every permit is held, so a
132            // connection still checked out inside a spawned
133            // `return_to_pool` task is left closing asynchronously —
134            // and it keeps a named shared-cache memory database alive
135            // into the next boot in the same process whenever the
136            // worker thread's close ack lags under load. Wait for the
137            // pool to actually reach size 0 (those tasks close their
138            // connection before returning; the min-connections clamp in
139            // `create` guarantees nothing resurrects it), bounded; a
140            // stall is an error — the pool would not be empty and the
141            // shutdown deadline still bounds the overall wait.
142            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                    // The convergence loop drains normal runs well inside
146                    // the bound (idle leftovers on the first extra pass,
147                    // in-flight closes within a few polls), so reaching
148                    // the cap means the pool genuinely did not drain —
149                    // report it: shutdown must not silently succeed while
150                    // a connection can keep a named shared-cache memory
151                    // database alive into the next boot (bd rc-ywwz9).
152                    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                // Yield so in-flight `return_to_pool` tasks progress, then
161                // drain again: a `close()` pass empties the idle queue
162                // (acked closes), the sleep lets checked-out connections
163                // finish their own async close. Both leftover shapes from
164                // the sqlx race converge here.
165                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    /// Contract (openspec pooldrain): `SqlPoolFactory::close` returns
247    /// successfully only after the pool has drained to zero connections,
248    /// verified against a pool that exercised two concurrent connections.
249    #[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        // Hold the first acquired connection while acquiring a second,
269        // so both pooled connections exist concurrently.
270        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    /// Probe (bd rc-25lup.4 review): does the named shared-memory URI
306    /// form genuinely share state across pooled connections? The
307    /// answer decides whether a lingering boot's connection could leak
308    /// rows into a later boot over the same URI.
309    #[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        // Force a second connection: hold one acquire while running the
335        // INSERT on another.
336        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    /// Truth table for the memory URL classifier (openspec pooldrain):
361    /// bare `:memory:` forms, named shared-cache `mode=memory` URLs,
362    /// uppercase scheme/query variants, and non-memory near misses.
363    #[test]
364    fn sqlite_memory_url_classifier_table() {
365        let cases: &[(&str, bool)] = &[
366            // True: bare memory forms and named shared-cache memory URLs.
367            ("sqlite::memory:", true),
368            ("sqlite://:memory:", true),
369            ("sqlite:file:memdb1?mode=memory&cache=shared", true),
370            // Uppercase scheme/query variants classify the same.
371            ("SQLITE::MEMORY:", true),
372            ("Sqlite:file:MEMDB2?MODE=MEMORY", true),
373            // Contrived: `mode=memory` inside a filename still matches.
374            ("sqlite:file:demo_mode=memory.db", true),
375            // False: ordinary paths, a `memory.db` filename, wrong scheme.
376            ("sqlite:data.db", false),
377            ("sqlite:file:memory.db", false),
378            ("postgres://host/db?mode=memory", false),
379            // rc-acrek boundary: `::memory:` inside a file path is not
380            // the bare `sqlite::memory:` form.
381            ("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}