camel_component_sql/
manager.rs1use 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
33pub const DEFAULT_ACQUIRE_DEADLINE: Duration = Duration::from_secs(30);
40
41const NO_BLOCK_DEADLINE: Duration = Duration::from_secs(24 * 60 * 60);
47
48pub struct SqlTransactionManager {
53 datasource: String,
54 catalog: Arc<dyn DatasourceCatalog>,
57 acquire_deadline: Duration,
58}
59
60impl SqlTransactionManager {
61 #[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 #[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 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 fn unavailable(&self, error: &impl std::fmt::Display) -> TransactionError {
111 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 #[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 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 async fn sqlite_pool() -> AnyPool {
208 sqlx::any::install_default_drivers();
209 AnyPoolOptions::new()
210 .max_connections(1)
211 .connect("sqlite::memory:")
212 .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 #[tokio::test]
249 async fn manager_open_session_pool_exhausted_names_datasource() {
250 let pool = sqlite_pool().await;
251 let _held = pool.acquire().await.expect("held connection"); 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 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 #[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"); tokio::time::pause();
288 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 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}