Skip to main content

camel_component_sql/
manager.rs

1//! Datasource-scoped [`TransactionManager`] for joined `sql:` steps
2//! (sqltrans-exec step 9).
3//!
4//! One manager is registered per catalog datasource at bundle boot. Pool
5//! resolution is LAZY: the manager holds the boot's [`DatasourceCatalog`] and
6//! resolves the datasource's pool through the catalog's existing `OnceCell`
7//! path, exactly like the producer's named-datasource path — boot never
8//! connects. Opening a session is the session's admission sequence
9//! ([`SqlTxSession::open_on_pool`]): checkout + the one-time hygiene
10//! `ROLLBACK`, with the discard guard armed at checkout. `BEGIN` is never sent
11//! here (lazy begin, driven by [`camel_api::transaction::TransactionSession::begin`]).
12//!
13//! The port owns no block deadline: the segment computes `block_abs` at block
14//! entry and bounds the `open_session()` await itself, reporting `Timeout`
15//! with elapsed measured from entry. The manager therefore arms only its
16//! acquire deadline and passes an effectively-unbounded block instant to the
17//! session's `min(block_abs, acquire_abs)` admission race.
18//!
19//! [`DatasourceCatalog`]: camel_api::datasource::DatasourceCatalog
20
21use std::sync::Arc;
22use std::time::Duration;
23
24use camel_api::datasource::DatasourceCatalog;
25use camel_api::transaction::{
26    OpenSessionFuture, TransactionError, TransactionManager, TransactionSession,
27};
28use sqlx::AnyPool;
29use tokio::time::Instant;
30
31use crate::session::SqlTxSession;
32
33/// Bound for connection acquisition reported by [`TransactionManager::acquire_deadline`].
34///
35/// `DatasourceConfig` exposes no `acquire_timeout` field and
36/// [`crate::pool_factory::SqlPoolFactory`] never overrides the driver default,
37/// so the effective bound is sqlx's pool default (30 s, covering acquire and
38/// connect).
39pub const DEFAULT_ACQUIRE_DEADLINE: Duration = Duration::from_secs(30);
40
41/// Block instant used when only the acquire deadline is armed.
42///
43/// The block deadline belongs to the segment (the port carries none); a
44/// day-long bound is unreachable before any block timeout and keeps the
45/// session's biased admission race on the acquire arm.
46const NO_BLOCK_DEADLINE: Duration = Duration::from_secs(24 * 60 * 60);
47
48/// [`TransactionManager`] serving one catalog datasource.
49///
50/// The registry keys the manager by [`TransactionManager::datasource`]; every
51/// typed error the session raises already names that datasource.
52pub struct SqlTransactionManager {
53    datasource: String,
54    /// The boot's single datasource catalog: the pool is resolved through its
55    /// `OnceCell` path on first open, never at registration.
56    catalog: Arc<dyn DatasourceCatalog>,
57    acquire_deadline: Duration,
58}
59
60impl SqlTransactionManager {
61    /// Manager for `datasource`, resolving its pool through `catalog`.
62    #[must_use]
63    pub fn new(datasource: impl Into<String>, catalog: Arc<dyn DatasourceCatalog>) -> Self {
64        Self {
65            datasource: datasource.into(),
66            catalog,
67            acquire_deadline: DEFAULT_ACQUIRE_DEADLINE,
68        }
69    }
70
71    /// Override the acquire deadline (tests and embedders that own their pool
72    /// options).
73    #[must_use]
74    pub fn with_acquire_deadline(mut self, acquire_deadline: Duration) -> Self {
75        self.acquire_deadline = acquire_deadline;
76        self
77    }
78
79    /// Open a session bounded by `block_abs` (admission + hygiene).
80    async fn open_at(
81        &self,
82        block_abs: Instant,
83    ) -> Result<Arc<dyn TransactionSession>, TransactionError> {
84        let handle = self
85            .catalog
86            .get_pool(&self.datasource)
87            .await
88            .map_err(|error| self.unavailable(&error))
89            .and_then(|handle| {
90                handle
91                    .downcast::<AnyPool>()
92                    .map_err(|e| self.unavailable(&e))
93            })?;
94        let session = SqlTxSession::open_on_pool(
95            self.datasource.as_str(),
96            &handle,
97            block_abs,
98            self.acquire_deadline,
99        )
100        .await?;
101        Ok(Arc::new(session))
102    }
103
104    /// Defensive mapping for an unresolvable datasource pool.
105    ///
106    /// Load validation resolved this manager already, so a catalog/pool
107    /// failure here means the datasource cannot serve the block. The frozen
108    /// error family has no "datasource unavailable" variant; a missing manager
109    /// is the fail-closed shape (never an auto-commit fallback).
110    fn unavailable(&self, error: &impl std::fmt::Display) -> TransactionError {
111        // log-policy: system-broken
112        tracing::error!(
113            datasource = %self.datasource,
114            error = %error,
115            "transaction manager could not resolve the datasource pool"
116        );
117        TransactionError::ManagerMissing {
118            datasource: self.datasource.clone(),
119        }
120    }
121
122    /// Admission at an explicit block instant: the seam the step-6 residual
123    /// fixture drives to pin the block-deadline-first `Timeout`.
124    #[cfg(test)]
125    pub(crate) async fn open_session_at(
126        &self,
127        block_abs: Instant,
128    ) -> Result<Arc<dyn TransactionSession>, TransactionError> {
129        self.open_at(block_abs).await
130    }
131}
132
133impl TransactionManager for SqlTransactionManager {
134    fn datasource(&self) -> &str {
135        &self.datasource
136    }
137
138    fn open_session(&self) -> OpenSessionFuture<'_> {
139        Box::pin(async move { self.open_at(Instant::now() + NO_BLOCK_DEADLINE).await })
140    }
141
142    fn acquire_deadline(&self) -> Duration {
143        self.acquire_deadline
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use std::any::Any;
150    use std::sync::Arc;
151
152    use camel_api::datasource::{DatasourceConfig, DatasourceHandle, GetPoolFuture};
153    use camel_api::error::CamelError;
154    use sqlx::AnyPool;
155    use sqlx::any::AnyPoolOptions;
156
157    use super::*;
158
159    /// Catalog holding one pool, served for every name.
160    struct FixedCatalog {
161        pool: AnyPool,
162        config: DatasourceConfig,
163    }
164
165    impl DatasourceCatalog for FixedCatalog {
166        fn get_config(&self, _name: &str) -> Option<DatasourceConfig> {
167            Some(self.config.clone())
168        }
169
170        fn get_pool<'a>(&'a self, name: &'a str) -> GetPoolFuture<'a> {
171            let pool = self.pool.clone();
172            let name = name.to_string();
173            Box::pin(async move {
174                let inner: Arc<dyn Any + Send + Sync> = Arc::new(pool);
175                Ok(DatasourceHandle::new(name, "sqlx".to_string(), inner))
176            })
177        }
178
179        fn register_factory(
180            &self,
181            _kind: &str,
182            _factory: Arc<dyn camel_api::datasource::PoolFactory>,
183        ) -> Result<(), CamelError> {
184            Ok(())
185        }
186    }
187
188    fn datasource_config() -> DatasourceConfig {
189        DatasourceConfig {
190            db_url: "postgres://camel:camel@127.0.0.1:5432/camel".to_string(),
191            provider: Some("sqlx".to_string()),
192            max_connections: Some(1),
193            min_connections: Some(0),
194            idle_timeout_secs: None,
195            max_lifetime_secs: None,
196            ssl_mode: None,
197            ssl_root_cert: None,
198            ssl_cert: None,
199            ssl_key: None,
200            extra: std::collections::HashMap::new(),
201        }
202    }
203
204    /// A single-connection in-memory pool. SQLite never reaches the server
205    /// legs the fixtures block on (acquire/hygiene), so it is enough to hold
206    /// the pool's only connection and pin the admission deadlines.
207    async fn sqlite_pool() -> AnyPool {
208        sqlx::any::install_default_drivers();
209        AnyPoolOptions::new()
210            .max_connections(1)
211            .connect("sqlite::memory:")
212            // allow-test-wait: test-local in-memory sqlite connect; immediate, bounded by construction
213            .await
214            .expect("in-memory sqlite pool")
215    }
216
217    fn manager(pool: &AnyPool, acquire_deadline: Duration) -> SqlTransactionManager {
218        SqlTransactionManager::new(
219            "pg",
220            Arc::new(FixedCatalog {
221                pool: pool.clone(),
222                config: datasource_config(),
223            }),
224        )
225        .with_acquire_deadline(acquire_deadline)
226    }
227
228    #[tokio::test]
229    async fn manager_reports_datasource_and_default_acquire_deadline() {
230        let pool = sqlite_pool().await;
231        let catalog: Arc<dyn DatasourceCatalog> = Arc::new(FixedCatalog {
232            pool,
233            config: datasource_config(),
234        });
235        let manager = SqlTransactionManager::new("pg", catalog);
236        assert_eq!(manager.datasource(), "pg");
237        assert_eq!(
238            manager.acquire_deadline(),
239            DEFAULT_ACQUIRE_DEADLINE,
240            "the datasource config exposes no acquire_timeout; sqlx's 30 s default is the bound"
241        );
242        assert_eq!(DEFAULT_ACQUIRE_DEADLINE, Duration::from_secs(30));
243    }
244
245    /// Frozen admission clause, manager tier: the acquire deadline is the
246    /// first to elapse with a real pool → typed `PoolExhausted` naming the
247    /// datasource, the configured pool size, and the waited milliseconds.
248    #[tokio::test]
249    async fn manager_open_session_pool_exhausted_names_datasource() {
250        let pool = sqlite_pool().await;
251        // Hold the pool's only connection so checkout cannot resolve.
252        let _held = pool.acquire().await.expect("held connection"); // allow-test-wait: test-local sqlite pool's only connection is free; acquire resolves immediately
253        tokio::time::pause();
254        let manager = manager(&pool, Duration::from_millis(10));
255
256        let error = match manager.open_session().await {
257            Err(error) => error,
258            Ok(_) => panic!("an exhausted pool must fail the open"),
259        };
260
261        match error {
262            TransactionError::PoolExhausted {
263                datasource,
264                max_connections,
265                waited_ms,
266            } => {
267                assert_eq!(datasource, "pg");
268                assert_eq!(max_connections, 1);
269                // Tokio's paused clock rounds a deadline up by <1 ms after
270                // `pause()` lands mid-tick; the bound is the 10 ms deadline.
271                assert!(
272                    (10..=11).contains(&waited_ms),
273                    "waited_ms must measure the 10 ms acquire deadline, got {waited_ms}"
274                );
275            }
276            other => panic!("expected typed PoolExhausted, got {other:?}"),
277        }
278    }
279
280    /// Step-6 residual, manager tier: the block-deadline-first admission
281    /// reports typed `Timeout` with elapsed measured from entry (block entry
282    /// is the `open_session_at` call), never `PoolExhausted`.
283    #[tokio::test]
284    async fn manager_open_session_block_deadline_first_reports_timeout() {
285        let pool = sqlite_pool().await;
286        let _held = pool.acquire().await.expect("held connection"); // allow-test-wait: test-local sqlite pool's only connection is free; acquire resolves immediately
287        tokio::time::pause();
288        // The manager arms only its acquire deadline in production; this seam
289        // supplies the segment's block instant to pin the Timeout arm.
290        let manager = manager(&pool, Duration::from_secs(60));
291        let entry = Instant::now();
292
293        let error = match manager
294            .open_session_at(entry + Duration::from_millis(30))
295            .await
296        {
297            Err(error) => error,
298            Ok(_) => panic!("the block deadline must win the admission race"),
299        };
300
301        match error {
302            TransactionError::Timeout {
303                datasource,
304                elapsed_ms,
305            } => {
306                assert_eq!(datasource, "pg");
307                // Elapsed is measured from block entry (the `open_session_at`
308                // call); the paused clock may round the deadline up <1 ms.
309                assert!(
310                    (30..=31).contains(&elapsed_ms),
311                    "elapsed_ms must measure the 30 ms block deadline, got {elapsed_ms}"
312                );
313            }
314            other => panic!("expected typed Timeout (never PoolExhausted), got {other:?}"),
315        }
316    }
317}