1use std::future::Future;
31use std::pin::Pin;
32use std::sync::Arc;
33use std::sync::Mutex as SyncMutex;
34use std::sync::atomic::{AtomicBool, Ordering};
35use std::time::Duration;
36
37use camel_api::transaction::{
38 BeginFuture, FinalizeFuture, TransactionError, TransactionOutcome, TransactionSession,
39 TransactionState,
40};
41use sqlx::Any;
42use sqlx::AnyPool;
43use sqlx::pool::PoolConnection;
44use tokio::sync::Mutex as AsyncMutex;
45
46const FINALIZE_GRACE: Duration = Duration::from_secs(5);
51
52const SQL_BEGIN: &str = "BEGIN";
53const SQL_COMMIT: &str = "COMMIT";
54const SQL_ROLLBACK: &str = "ROLLBACK";
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62enum TxPhase {
63 Clean,
65 BeginPending,
67 Open,
69 CommitInFlight,
71 RollbackInFlight,
73 Done,
75 Detached,
77}
78
79#[must_use]
83fn project(phase: TxPhase) -> TransactionState {
84 match phase {
85 TxPhase::Clean | TxPhase::BeginPending => TransactionState::Fresh,
86 TxPhase::Open => TransactionState::Active,
87 TxPhase::CommitInFlight | TxPhase::RollbackInFlight => TransactionState::Finalizing,
88 TxPhase::Done => TransactionState::Done,
89 TxPhase::Detached => TransactionState::Detached,
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97enum DbSeverity {
98 Error,
99 Other,
100}
101
102#[derive(Debug, Clone)]
104pub(crate) struct DbAnswer {
105 severity: DbSeverity,
106 code: Option<String>,
107 message: String,
108}
109
110#[derive(Debug, Clone)]
112pub(crate) enum TxIoFailure {
113 Database(DbAnswer),
115 Lost,
118}
119
120enum CommitDisposition {
122 Rejected {
126 reason: String,
128 },
129 Lost,
132}
133
134#[must_use]
136fn commit_disposition(failure: &TxIoFailure) -> CommitDisposition {
137 let TxIoFailure::Database(answer) = failure else {
138 return CommitDisposition::Lost;
139 };
140 let reject_class = answer
141 .code
142 .as_deref()
143 .is_some_and(|code| code.starts_with("23") || code.starts_with("40"));
144 if answer.severity == DbSeverity::Error && reject_class {
145 CommitDisposition::Rejected {
146 reason: match answer.code.as_deref() {
147 Some(code) => format!("SQLSTATE {code}: {}", answer.message),
148 None => answer.message.clone(),
149 },
150 }
151 } else {
152 CommitDisposition::Lost
153 }
154}
155
156type ExecFuture<'a> = Pin<Box<dyn Future<Output = Result<(), TxIoFailure>> + Send + 'a>>;
158
159pub(crate) trait TxIo: Send + 'static {
166 fn exec(&mut self, sql: &'static str) -> ExecFuture<'_>;
171
172 fn detach(&mut self);
175
176 fn release(self: Box<Self>);
179}
180
181struct AnyConnIo {
183 conn: Option<PoolConnection<Any>>,
184}
185
186impl TxIo for AnyConnIo {
187 fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
188 Box::pin(async move {
189 let Some(conn) = self.conn.as_mut() else {
190 return Err(TxIoFailure::Lost);
191 };
192 match sqlx::query(sqlx::AssertSqlSafe(sql))
193 .execute(&mut **conn)
194 .await
195 {
196 Ok(_) => Ok(()),
197 Err(error) => Err(to_io_failure(&error)),
198 }
199 })
200 }
201
202 fn detach(&mut self) {
203 if let Some(conn) = self.conn.take() {
207 drop(conn.detach());
208 }
209 }
210
211 fn release(self: Box<Self>) {
212 drop(self);
214 }
215}
216
217struct DetachedIo;
221
222impl TxIo for DetachedIo {
223 fn exec(&mut self, _sql: &'static str) -> ExecFuture<'_> {
224 Box::pin(std::future::ready(Err(TxIoFailure::Lost)))
225 }
226
227 fn detach(&mut self) {}
228
229 fn release(self: Box<Self>) {}
230}
231
232struct CheckedOutBackend {
242 io: Option<Box<dyn TxIo>>,
243}
244
245impl CheckedOutBackend {
246 fn arm(io: Box<dyn TxIo>) -> Self {
248 Self { io: Some(io) }
249 }
250
251 fn disarm(mut self) -> Box<dyn TxIo> {
254 match self.io.take() {
255 Some(io) => io,
256 None => {
257 tracing::error!(
263 "checked-out backend missing at the with_io hand-off; \
264 the session continues on the lost placeholder"
265 );
266 Box::new(DetachedIo)
267 }
268 }
269 }
270}
271
272impl TxIo for CheckedOutBackend {
273 fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
274 let Some(io) = self.io.as_mut() else {
275 return Box::pin(std::future::ready(Err(TxIoFailure::Lost)));
276 };
277 io.exec(sql)
278 }
279
280 fn detach(&mut self) {
281 if let Some(mut io) = self.io.take() {
284 io.detach();
285 }
286 }
287
288 fn release(mut self: Box<Self>) {
289 if let Some(io) = self.io.take() {
290 io.release();
291 }
292 }
293}
294
295impl Drop for CheckedOutBackend {
296 fn drop(&mut self) {
297 if let Some(mut io) = self.io.take() {
298 io.detach();
299 }
300 }
301}
302
303fn to_io_failure(error: &sqlx::Error) -> TxIoFailure {
305 match error {
306 sqlx::Error::Database(db) => TxIoFailure::Database(DbAnswer {
307 severity: db_severity(&**db),
308 code: db.code().as_deref().map(str::to_owned),
309 message: db.message().to_owned(),
310 }),
311 _ => TxIoFailure::Lost,
314 }
315}
316
317#[cfg(feature = "postgres")]
321fn db_severity(db: &dyn sqlx::error::DatabaseError) -> DbSeverity {
322 match db.try_downcast_ref::<sqlx::postgres::PgDatabaseError>() {
323 Some(pg) if pg.severity() == sqlx::postgres::PgSeverity::Error => DbSeverity::Error,
324 _ => DbSeverity::Other,
325 }
326}
327
328#[cfg(not(feature = "postgres"))]
330fn db_severity(_db: &dyn sqlx::error::DatabaseError) -> DbSeverity {
331 DbSeverity::Other
332}
333
334pub(crate) trait TxTimer: Send + Sync + 'static {
342 fn now(&self) -> tokio::time::Instant;
344
345 fn sleep_until(
347 &self,
348 deadline: tokio::time::Instant,
349 ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
350}
351
352struct TokioTimer;
354
355impl TxTimer for TokioTimer {
356 fn now(&self) -> tokio::time::Instant {
357 tokio::time::Instant::now()
358 }
359
360 fn sleep_until(
361 &self,
362 deadline: tokio::time::Instant,
363 ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
364 Box::pin(tokio::time::sleep_until(deadline))
365 }
366}
367
368#[derive(Debug)]
370enum StmtOutcome {
371 Ack,
373 Deadline,
375 Failed(TxIoFailure),
377}
378
379async fn run_statement(
386 io: &mut dyn TxIo,
387 sql: &'static str,
388 deadline: tokio::time::Instant,
389 timer: &dyn TxTimer,
390) -> StmtOutcome {
391 tokio::select! {
392 biased;
393 _ = timer.sleep_until(deadline) => StmtOutcome::Deadline,
394 result = io.exec(sql) => match result {
395 Ok(()) => StmtOutcome::Ack,
396 Err(failure) => StmtOutcome::Failed(failure),
397 },
398 }
399}
400
401fn elapsed_ms(timer: &dyn TxTimer, since: tokio::time::Instant) -> u64 {
403 u64::try_from(timer.now().saturating_duration_since(since).as_millis()).unwrap_or(u64::MAX)
404}
405
406pub struct SqlTxSession {
419 datasource: Arc<str>,
420 slot: AsyncMutex<Box<dyn TxIo>>,
423 phase: SyncMutex<TxPhase>,
425 rollback_only: AtomicBool,
427 timer: Arc<dyn TxTimer>,
429 acquire_deadline: Duration,
431 finalize_grace: Duration,
434 max_connections: u32,
436}
437
438impl SqlTxSession {
439 pub(crate) fn with_io(
445 datasource: impl Into<Arc<str>>,
446 io: Box<dyn TxIo>,
447 timer: Arc<dyn TxTimer>,
448 acquire_deadline: Duration,
449 finalize_grace: Duration,
450 max_connections: u32,
451 ) -> Self {
452 Self {
453 datasource: datasource.into(),
454 slot: AsyncMutex::new(io),
455 phase: SyncMutex::new(TxPhase::Clean),
456 rollback_only: AtomicBool::new(false),
457 timer,
458 acquire_deadline,
459 finalize_grace,
460 max_connections,
461 }
462 }
463
464 pub(crate) async fn open(
478 datasource: impl Into<Arc<str>>,
479 pool: &AnyPool,
480 block_abs: tokio::time::Instant,
481 acquire_deadline: Duration,
482 timer: Arc<dyn TxTimer>,
483 ) -> Result<Self, TransactionError> {
484 let datasource = datasource.into();
485 let max_connections = crate::pool_factory::pool_max_connections(pool);
486 let open_start = timer.now();
487 let acquire_abs = open_start + acquire_deadline;
488
489 let conn = tokio::select! {
490 biased;
491 _ = timer.sleep_until(block_abs) => {
492 if acquire_abs < block_abs {
499 return Err(TransactionError::PoolExhausted {
500 datasource: datasource.to_string(),
501 max_connections,
502 waited_ms: elapsed_ms(timer.as_ref(), open_start),
503 });
504 }
505 return Err(TransactionError::Timeout {
506 datasource: datasource.to_string(),
507 elapsed_ms: elapsed_ms(timer.as_ref(), open_start),
511 });
512 }
513 _ = timer.sleep_until(acquire_abs) => {
514 return Err(TransactionError::PoolExhausted {
515 datasource: datasource.to_string(),
516 max_connections,
517 waited_ms: elapsed_ms(timer.as_ref(), open_start),
518 });
519 }
520 acquired = pool.acquire() => {
521 acquired.map_err(|_| TransactionError::PoolExhausted {
522 datasource: datasource.to_string(),
523 max_connections,
524 waited_ms: elapsed_ms(timer.as_ref(), open_start),
525 })?
526 }
527 };
528
529 let backend = CheckedOutBackend::arm(Box::new(AnyConnIo { conn: Some(conn) }));
535 Self::admit(
536 datasource,
537 backend,
538 block_abs,
539 acquire_abs,
540 acquire_deadline,
541 max_connections,
542 timer,
543 )
544 .await
545 }
546
547 async fn admit(
552 datasource: Arc<str>,
553 backend: CheckedOutBackend,
554 block_abs: tokio::time::Instant,
555 acquire_abs: tokio::time::Instant,
556 acquire_deadline: Duration,
557 max_connections: u32,
558 timer: Arc<dyn TxTimer>,
559 ) -> Result<Self, TransactionError> {
560 let mut backend = backend;
561 admission_hygiene(
562 &mut backend,
563 Arc::clone(&timer),
564 &datasource,
565 max_connections,
566 block_abs,
567 acquire_abs,
568 )
569 .await?;
570
571 Ok(Self::with_io(
572 datasource,
573 backend.disarm(),
574 timer,
575 acquire_deadline,
576 FINALIZE_GRACE,
577 max_connections,
578 ))
579 }
580
581 pub async fn open_on_pool(
589 datasource: impl Into<Arc<str>>,
590 pool: &AnyPool,
591 block_abs: tokio::time::Instant,
592 acquire_deadline: Duration,
593 ) -> Result<Self, TransactionError> {
594 Self::open(
595 datasource,
596 pool,
597 block_abs,
598 acquire_deadline,
599 Arc::new(TokioTimer),
600 )
601 .await
602 }
603
604 #[doc(hidden)]
621 pub async fn exec_statement_for_test(&self, sql: &'static str) -> Result<(), String> {
622 let Ok(mut slot) = self.slot.try_lock() else {
623 return Err(TransactionError::Busy {
624 datasource: self.datasource.to_string(),
625 }
626 .to_string());
627 };
628 match slot.exec(sql).await {
629 Ok(()) => Ok(()),
630 Err(TxIoFailure::Database(answer)) => Err(format!(
631 "statement `{sql}` failed: SQLSTATE {}: {}",
632 answer.code.as_deref().unwrap_or("-"),
633 answer.message
634 )),
635 Err(TxIoFailure::Lost) => Err(format!(
636 "statement `{sql}` lost the connection (outcome unknown)"
637 )),
638 }
639 }
640
641 fn phase(&self) -> TxPhase {
642 *self
643 .phase
644 .lock()
645 .unwrap_or_else(std::sync::PoisonError::into_inner)
646 }
647
648 fn store_phase(&self, phase: TxPhase) {
649 *self
650 .phase
651 .lock()
652 .unwrap_or_else(std::sync::PoisonError::into_inner) = phase;
653 }
654
655 fn detach_slot(&self, slot: &mut tokio::sync::MutexGuard<'_, Box<dyn TxIo>>) {
658 slot.detach();
659 let _ = std::mem::replace(&mut **slot, Box::new(DetachedIo));
660 self.store_phase(TxPhase::Detached);
661 }
662
663 async fn begin_inner(&self) -> Result<(), TransactionError> {
670 let datasource = self.datasource.to_string();
671 let Ok(mut slot) = self.slot.try_lock() else {
672 return Err(TransactionError::Busy { datasource });
675 };
676 match self.phase() {
677 TxPhase::Open => return Ok(()),
678 TxPhase::Clean => {}
679 _ => return Err(TransactionError::SessionAborted { datasource }),
680 }
681 self.store_phase(TxPhase::BeginPending);
684 let begin_start = self.timer.now();
685 let deadline = begin_start + self.acquire_deadline;
686 match run_statement(&mut **slot, SQL_BEGIN, deadline, self.timer.as_ref()).await {
687 StmtOutcome::Ack => {
688 self.store_phase(TxPhase::Open);
689 Ok(())
690 }
691 StmtOutcome::Deadline => {
692 self.detach_slot(&mut slot);
694 Err(TransactionError::PoolExhausted {
695 datasource,
696 max_connections: self.max_connections,
697 waited_ms: elapsed_ms(self.timer.as_ref(), begin_start),
698 })
699 }
700 StmtOutcome::Failed(_) => {
701 self.detach_slot(&mut slot);
704 Err(TransactionError::RollbackUncertain { datasource })
705 }
706 }
707 }
708
709 async fn commit_inner(&self) -> Result<TransactionOutcome, TransactionError> {
711 let datasource = self.datasource.to_string();
712 if self.phase() != TxPhase::Open {
714 return Err(TransactionError::SessionAborted { datasource });
715 }
716 let Ok(mut slot) = self.slot.try_lock() else {
717 tracing::error!(
721 datasource = %self.datasource,
722 "commit while the session slot is held; the commit outcome cannot be verified"
723 );
724 return Err(TransactionError::CommitUncertain { datasource });
725 };
726 let finalize_start = self.timer.now();
727 let grace_deadline = finalize_start + self.finalize_grace;
728 self.store_phase(TxPhase::CommitInFlight);
732 match run_statement(&mut **slot, SQL_COMMIT, grace_deadline, self.timer.as_ref()).await {
733 StmtOutcome::Ack => {
734 self.store_phase(TxPhase::Done);
735 release_to_pool(&mut slot);
736 Ok(TransactionOutcome::Committed)
737 }
738 StmtOutcome::Deadline => {
739 self.detach_slot(&mut slot);
741 Err(TransactionError::CommitUncertain { datasource })
742 }
743 StmtOutcome::Failed(failure) => match commit_disposition(&failure) {
744 CommitDisposition::Lost => {
745 self.detach_slot(&mut slot);
749 Err(TransactionError::CommitUncertain { datasource })
750 }
751 CommitDisposition::Rejected { reason } => {
752 match run_statement(
760 &mut **slot,
761 SQL_ROLLBACK,
762 grace_deadline,
763 self.timer.as_ref(),
764 )
765 .await
766 {
767 StmtOutcome::Ack => {
768 self.store_phase(TxPhase::Done);
769 release_to_pool(&mut slot);
770 Err(TransactionError::CommitFailed { datasource, reason })
774 }
775 StmtOutcome::Deadline | StmtOutcome::Failed(_) => {
776 self.detach_slot(&mut slot);
777 tracing::warn!(
780 datasource = %self.datasource,
781 "COMMIT was rejected and the cleanup ROLLBACK was \
782 not acknowledged; the connection is detached and \
783 the typed CommitFailed stands"
784 );
785 Err(TransactionError::CommitFailed { datasource, reason })
786 }
787 }
788 }
789 },
790 }
791 }
792
793 async fn rollback_inner(&self) -> Result<TransactionOutcome, TransactionError> {
797 let datasource = self.datasource.to_string();
798 match self.phase() {
799 TxPhase::Clean => {
800 debug_assert!(
803 !self.is_rollback_only(),
804 "R2 clean rollback with rollback_only set: the flag is unreachable in Clean"
805 );
806 let Ok(mut slot) = self.slot.try_lock() else {
807 tracing::error!(
809 datasource = %self.datasource,
810 "clean rollback while the session slot is held; the connection cannot be returned"
811 );
812 return Err(TransactionError::RollbackUncertain { datasource });
813 };
814 self.store_phase(TxPhase::Done);
815 release_to_pool(&mut slot);
816 Ok(TransactionOutcome::RolledBack)
817 }
818 TxPhase::BeginPending => {
819 let Ok(mut slot) = self.slot.try_lock() else {
821 tracing::error!(
823 datasource = %self.datasource,
824 "rollback while the session slot is held; the connection cannot be detached"
825 );
826 return Err(TransactionError::RollbackUncertain { datasource });
827 };
828 self.detach_slot(&mut slot);
829 Err(TransactionError::RollbackUncertain { datasource })
830 }
831 TxPhase::Open => {
832 let Ok(mut slot) = self.slot.try_lock() else {
833 tracing::error!(
835 datasource = %self.datasource,
836 "rollback while the session slot is held; the connection cannot be rolled back"
837 );
838 return Err(TransactionError::RollbackUncertain { datasource });
839 };
840 let finalize_start = self.timer.now();
841 let grace_deadline = finalize_start + self.finalize_grace;
842 self.store_phase(TxPhase::RollbackInFlight);
843 match run_statement(
844 &mut **slot,
845 SQL_ROLLBACK,
846 grace_deadline,
847 self.timer.as_ref(),
848 )
849 .await
850 {
851 StmtOutcome::Ack => {
852 self.store_phase(TxPhase::Done);
853 release_to_pool(&mut slot);
854 Ok(TransactionOutcome::RolledBack)
855 }
856 StmtOutcome::Deadline | StmtOutcome::Failed(_) => {
857 self.detach_slot(&mut slot);
859 Err(TransactionError::RollbackUncertain { datasource })
860 }
861 }
862 }
863 TxPhase::Detached => {
864 Err(TransactionError::RollbackUncertain { datasource })
866 }
867 TxPhase::CommitInFlight | TxPhase::RollbackInFlight | TxPhase::Done => {
868 tracing::error!(
872 datasource = %self.datasource,
873 "defensive finalization entry: session is already finalizing or done; \
874 no SQL sent, no detachment performed"
875 );
876 Err(TransactionError::RollbackUncertain { datasource })
877 }
878 }
879 }
880}
881
882fn release_to_pool(slot: &mut tokio::sync::MutexGuard<'_, Box<dyn TxIo>>) {
884 let io = std::mem::replace(&mut **slot, Box::new(DetachedIo));
885 io.release();
886}
887
888async fn admission_hygiene(
896 io: &mut dyn TxIo,
897 timer: Arc<dyn TxTimer>,
898 datasource: &str,
899 max_connections: u32,
900 block_abs: tokio::time::Instant,
901 acquire_abs: tokio::time::Instant,
902) -> Result<(), TransactionError> {
903 let hygiene_start = timer.now();
904 let result = tokio::select! {
905 biased;
906 _ = timer.sleep_until(block_abs) => {
907 if acquire_abs < block_abs {
912 Err(TransactionError::PoolExhausted {
913 datasource: datasource.to_owned(),
914 max_connections,
915 waited_ms: elapsed_ms(timer.as_ref(), hygiene_start),
916 })
917 } else {
918 Err(TransactionError::Timeout {
919 datasource: datasource.to_owned(),
920 elapsed_ms: elapsed_ms(timer.as_ref(), hygiene_start),
924 })
925 }
926 }
927 _ = timer.sleep_until(acquire_abs) => Err(TransactionError::PoolExhausted {
928 datasource: datasource.to_owned(),
929 max_connections,
930 waited_ms: elapsed_ms(timer.as_ref(), hygiene_start),
931 }),
932 ack = io.exec(SQL_ROLLBACK) => match ack {
933 Ok(()) => Ok(()),
934 Err(_) => Err(TransactionError::RollbackUncertain {
935 datasource: datasource.to_owned(),
936 }),
937 },
938 };
939 match result {
940 Ok(()) => Ok(()),
941 Err(error) => {
942 io.detach();
943 Err(error)
944 }
945 }
946}
947
948impl Drop for SqlTxSession {
949 fn drop(&mut self) {
950 if matches!(self.phase(), TxPhase::Done | TxPhase::Detached) {
957 return;
958 }
959 match self.slot.try_lock() {
960 Ok(mut slot) => {
961 slot.detach();
962 let _ = std::mem::replace(&mut *slot, Box::new(DetachedIo));
963 }
964 Err(_) => {
965 tracing::error!(
967 datasource = %self.datasource,
968 "session dropped while its statement slot is held; \
969 the connection cannot be detached from here"
970 );
971 }
972 }
973 }
974}
975
976impl TransactionSession for SqlTxSession {
977 fn datasource(&self) -> &str {
978 &self.datasource
979 }
980
981 fn state(&self) -> TransactionState {
982 project(self.phase())
983 }
984
985 fn begin(&self) -> BeginFuture<'_> {
986 Box::pin(self.begin_inner())
987 }
988
989 fn set_rollback_only(&self) {
990 self.rollback_only.store(true, Ordering::Relaxed);
991 }
992
993 fn is_rollback_only(&self) -> bool {
994 self.rollback_only.load(Ordering::Relaxed)
995 }
996
997 fn commit(&self) -> FinalizeFuture<'_> {
998 Box::pin(self.commit_inner())
999 }
1000
1001 fn rollback(&self) -> FinalizeFuture<'_> {
1002 Box::pin(self.rollback_inner())
1003 }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008 use std::collections::HashMap;
1009 use std::sync::Mutex as SyncMutex;
1010 use std::task::{Context, Poll, Waker};
1011
1012 use super::*;
1013 use futures::task::noop_waker;
1014
1015 const ACQUIRE: Duration = Duration::from_millis(50);
1016 const GRACE: Duration = Duration::from_secs(5);
1017 const MAX_CONNECTIONS: u32 = 4;
1018
1019 #[derive(Debug, Clone)]
1021 enum Scripted {
1022 Ack,
1023 Pending,
1025 Fail(TxIoFailure),
1026 }
1027
1028 #[derive(Debug, Default)]
1030 struct FakeShared {
1031 responses: HashMap<&'static str, Scripted>,
1032 issued: Vec<&'static str>,
1033 detached: bool,
1034 released: bool,
1035 }
1036
1037 struct FakeIo {
1039 shared: Arc<SyncMutex<FakeShared>>,
1040 }
1041
1042 impl FakeIo {
1043 fn channel() -> (Box<dyn TxIo>, Arc<SyncMutex<FakeShared>>) {
1044 let shared = Arc::new(SyncMutex::new(FakeShared::default()));
1045 (
1046 Box::new(FakeIo {
1047 shared: Arc::clone(&shared),
1048 }),
1049 shared,
1050 )
1051 }
1052
1053 fn script(sql: &'static str, answer: Scripted, shared: &SyncMutex<FakeShared>) {
1054 shared
1055 .lock()
1056 .unwrap_or_else(std::sync::PoisonError::into_inner)
1057 .responses
1058 .insert(sql, answer);
1059 }
1060 }
1061
1062 impl TxIo for FakeIo {
1063 fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
1064 Box::pin(async move {
1065 self.shared
1068 .lock()
1069 .unwrap_or_else(std::sync::PoisonError::into_inner)
1070 .issued
1071 .push(sql);
1072 let scripted = self
1073 .shared
1074 .lock()
1075 .unwrap_or_else(std::sync::PoisonError::into_inner)
1076 .responses
1077 .get(&sql)
1078 .cloned()
1079 .unwrap_or(Scripted::Ack);
1080 match scripted {
1081 Scripted::Ack => Ok(()),
1082 Scripted::Pending => std::future::pending().await,
1083 Scripted::Fail(failure) => Err(failure),
1084 }
1085 })
1086 }
1087
1088 fn detach(&mut self) {
1089 self.shared
1090 .lock()
1091 .unwrap_or_else(std::sync::PoisonError::into_inner)
1092 .detached = true;
1093 }
1094
1095 fn release(self: Box<Self>) {
1096 self.shared
1097 .lock()
1098 .unwrap_or_else(std::sync::PoisonError::into_inner)
1099 .released = true;
1100 }
1101 }
1102
1103 fn issued_of(shared: &SyncMutex<FakeShared>) -> Vec<&'static str> {
1104 shared
1105 .lock()
1106 .unwrap_or_else(std::sync::PoisonError::into_inner)
1107 .issued
1108 .clone()
1109 }
1110
1111 fn is_detached(shared: &SyncMutex<FakeShared>) -> bool {
1112 shared
1113 .lock()
1114 .unwrap_or_else(std::sync::PoisonError::into_inner)
1115 .detached
1116 }
1117
1118 fn is_released(shared: &SyncMutex<FakeShared>) -> bool {
1119 shared
1120 .lock()
1121 .unwrap_or_else(std::sync::PoisonError::into_inner)
1122 .released
1123 }
1124
1125 fn db_error(severity: DbSeverity, code: &str, message: &str) -> TxIoFailure {
1126 TxIoFailure::Database(DbAnswer {
1127 severity,
1128 code: Some(code.to_owned()),
1129 message: message.to_owned(),
1130 })
1131 }
1132
1133 fn test_session(io: Box<dyn TxIo>, timer: Arc<dyn TxTimer>) -> SqlTxSession {
1134 SqlTxSession::with_io("pg", io, timer, ACQUIRE, GRACE, MAX_CONNECTIONS)
1135 }
1136
1137 fn poll_once_pending<F: Future>(pinned: &mut Pin<&mut F>) -> bool {
1139 let waker: Waker = noop_waker();
1140 let mut cx = Context::from_waker(&waker);
1141 matches!(pinned.as_mut().poll(&mut cx), Poll::Pending)
1142 }
1143
1144 struct AlwaysElapsed;
1147
1148 impl TxTimer for AlwaysElapsed {
1149 fn now(&self) -> tokio::time::Instant {
1150 tokio::time::Instant::now()
1151 }
1152
1153 fn sleep_until(
1154 &self,
1155 _deadline: tokio::time::Instant,
1156 ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
1157 Box::pin(std::future::ready(()))
1158 }
1159 }
1160
1161 #[test]
1163 fn phase_projection_matches_604c_table() {
1164 let rows = [
1165 (TxPhase::Clean, TransactionState::Fresh),
1166 (TxPhase::BeginPending, TransactionState::Fresh),
1167 (TxPhase::Open, TransactionState::Active),
1168 (TxPhase::CommitInFlight, TransactionState::Finalizing),
1169 (TxPhase::RollbackInFlight, TransactionState::Finalizing),
1170 (TxPhase::Done, TransactionState::Done),
1171 (TxPhase::Detached, TransactionState::Detached),
1172 ];
1173 for (phase, expected) in rows {
1174 assert_eq!(
1175 project(phase),
1176 expected,
1177 "604c §A projection mismatch for {phase:?}"
1178 );
1179 }
1180 }
1181
1182 #[tokio::test]
1185 async fn begin_is_idempotent_when_open() {
1186 let (io, shared) = FakeIo::channel();
1187 let session = test_session(io, Arc::new(TokioTimer));
1188 session.begin().await.expect("first begin acknowledges");
1189 assert_eq!(session.state(), TransactionState::Active);
1190
1191 let second = session.begin().await;
1192 assert_eq!(second, Ok(()), "begin on Open is an idempotent no-op");
1193 assert_eq!(
1194 issued_of(&shared),
1195 vec![SQL_BEGIN],
1196 "the idempotent call must not send BEGIN again"
1197 );
1198 assert_eq!(session.state(), TransactionState::Active);
1199 }
1200
1201 #[tokio::test]
1204 async fn begin_from_non_clean_phases_is_aborted() {
1205 let (io, shared) = FakeIo::channel();
1207 let session = test_session(io, Arc::new(TokioTimer));
1208 session.rollback().await.expect("clean rollback");
1209 let error = session.begin().await.expect_err("begin from Done aborts");
1210 assert_eq!(
1211 error,
1212 TransactionError::SessionAborted {
1213 datasource: "pg".to_owned()
1214 }
1215 );
1216 assert!(
1217 issued_of(&shared).is_empty(),
1218 "the aborted begin must send no SQL"
1219 );
1220
1221 let (io, shared) = FakeIo::channel();
1224 FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1225 let session = test_session(io, Arc::new(TokioTimer));
1226 {
1227 let mut begin = std::pin::pin!(session.begin());
1228 assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
1229 }
1230 let error = session
1231 .begin()
1232 .await
1233 .expect_err("begin from BeginPending aborts");
1234 assert_eq!(
1235 error,
1236 TransactionError::SessionAborted {
1237 datasource: "pg".to_owned()
1238 }
1239 );
1240 assert_eq!(
1241 issued_of(&shared),
1242 vec![SQL_BEGIN],
1243 "the aborted attempt must not send another BEGIN"
1244 );
1245 }
1246
1247 #[tokio::test(start_paused = true)]
1256 async fn begin_racing_detach_never_overwrites_detached() {
1257 let (io, shared) = FakeIo::channel();
1258 FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1259 let session = test_session(io, Arc::new(TokioTimer));
1260
1261 let mut first = std::pin::pin!(session.begin());
1263 assert!(poll_once_pending(&mut first), "the BEGIN write must stall");
1264 assert_eq!(issued_of(&shared), vec![SQL_BEGIN]);
1265
1266 let racing = session.begin().await;
1268 assert_eq!(
1269 racing,
1270 Err(TransactionError::Busy {
1271 datasource: "pg".to_owned()
1272 }),
1273 "the raced begin is rejected on the held slot before any phase read"
1274 );
1275
1276 let first_outcome = first.await;
1278 assert_eq!(
1279 first_outcome,
1280 Err(TransactionError::PoolExhausted {
1281 datasource: "pg".to_owned(),
1282 max_connections: MAX_CONNECTIONS,
1283 waited_ms: ACQUIRE.as_millis() as u64,
1284 }),
1285 "the stalled begin detaches per §B.4"
1286 );
1287 assert_eq!(session.state(), TransactionState::Detached);
1288
1289 let third = session.begin().await;
1292 assert_eq!(
1293 third,
1294 Err(TransactionError::SessionAborted {
1295 datasource: "pg".to_owned()
1296 }),
1297 "begin on a Detached session aborts, never overwrites the terminal phase"
1298 );
1299 assert_eq!(session.state(), TransactionState::Detached);
1300 assert_eq!(
1301 issued_of(&shared),
1302 vec![SQL_BEGIN],
1303 "neither raced begin sent SQL"
1304 );
1305 }
1306
1307 #[tokio::test(start_paused = true)]
1311 async fn begin_own_timeout_reports_pool_exhausted_detaches() {
1312 let (io, shared) = FakeIo::channel();
1313 FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1314 let session = test_session(io, Arc::new(TokioTimer));
1315
1316 let error = session.begin().await.expect_err("begin deadline");
1317 assert_eq!(
1318 error,
1319 TransactionError::PoolExhausted {
1320 datasource: "pg".to_owned(),
1321 max_connections: MAX_CONNECTIONS,
1322 waited_ms: ACQUIRE.as_millis() as u64,
1325 }
1326 );
1327 assert!(
1328 ACQUIRE > Duration::ZERO,
1329 "the begin deadline must be a positive bound the wait is measured against"
1330 );
1331 assert_eq!(session.state(), TransactionState::Detached);
1332 assert_eq!(
1333 issued_of(&shared),
1334 vec![SQL_BEGIN],
1335 "no cleanup SQL after the begin timeout"
1336 );
1337 assert!(is_detached(&shared), "the begin timeout detaches");
1338 assert!(
1339 !is_released(&shared),
1340 "a detached connection is never re-pooled"
1341 );
1342
1343 let result = session.rollback().await;
1345 assert_eq!(
1346 result,
1347 Err(TransactionError::RollbackUncertain {
1348 datasource: "pg".to_owned()
1349 })
1350 );
1351 assert_eq!(issued_of(&shared), vec![SQL_BEGIN], "R1 sends no SQL");
1352 }
1353
1354 #[tokio::test]
1357 async fn begin_driver_error_detaches_reports_rollback_uncertain() {
1358 let (io, shared) = FakeIo::channel();
1359 FakeIo::script(
1360 SQL_BEGIN,
1361 Scripted::Fail(db_error(DbSeverity::Other, "08006", "connection failure")),
1362 &shared,
1363 );
1364 let session = test_session(io, Arc::new(TokioTimer));
1365
1366 let error = session.begin().await.expect_err("begin driver error");
1367 assert_eq!(
1368 error,
1369 TransactionError::RollbackUncertain {
1370 datasource: "pg".to_owned()
1371 }
1372 );
1373 assert_eq!(session.state(), TransactionState::Detached);
1374 assert_eq!(
1375 issued_of(&shared),
1376 vec![SQL_BEGIN],
1377 "no cleanup SQL after a begin driver error"
1378 );
1379 assert!(is_detached(&shared));
1380 }
1381
1382 #[tokio::test]
1386 async fn injected_timer_times_out_begin() {
1387 let (io, shared) = FakeIo::channel();
1388 let session = test_session(io, Arc::new(AlwaysElapsed));
1389
1390 let error = session.begin().await.expect_err("injected deadline");
1391 assert_eq!(
1392 error,
1393 TransactionError::PoolExhausted {
1394 datasource: "pg".to_owned(),
1395 max_connections: MAX_CONNECTIONS,
1396 waited_ms: 0,
1397 }
1398 );
1399 assert_eq!(session.state(), TransactionState::Detached);
1400 assert!(
1401 issued_of(&shared).is_empty(),
1402 "an already-elapsed deadline cancels the write before the driver sees it"
1403 );
1404 assert!(is_detached(&shared));
1405 }
1406
1407 #[tokio::test]
1413 async fn transacted_commit_classifier_table() {
1414 let rows: Vec<(&str, TxIoFailure, TransactionError, bool)> = vec![
1415 (
1416 "23503 integrity violation",
1417 db_error(DbSeverity::Error, "23503", "foreign key violated"),
1418 TransactionError::CommitFailed {
1419 datasource: "pg".to_owned(),
1420 reason: "SQLSTATE 23503: foreign key violated".to_owned(),
1421 },
1422 true,
1423 ),
1424 (
1425 "40001 transaction abort class",
1426 db_error(DbSeverity::Error, "40001", "could not serialize access"),
1427 TransactionError::CommitFailed {
1428 datasource: "pg".to_owned(),
1429 reason: "SQLSTATE 40001: could not serialize access".to_owned(),
1430 },
1431 true,
1432 ),
1433 (
1434 "57P01 backend fatal",
1435 db_error(
1436 DbSeverity::Other,
1437 "57P01",
1438 "terminating connection due to administrator command",
1439 ),
1440 TransactionError::CommitUncertain {
1441 datasource: "pg".to_owned(),
1442 },
1443 false,
1444 ),
1445 (
1446 "57014 query canceled (class 57)",
1447 db_error(
1448 DbSeverity::Error,
1449 "57014",
1450 "canceling statement due to user request",
1451 ),
1452 TransactionError::CommitUncertain {
1453 datasource: "pg".to_owned(),
1454 },
1455 false,
1456 ),
1457 (
1458 "08006 connection failure (class 08)",
1459 db_error(DbSeverity::Error, "08006", "connection failure"),
1460 TransactionError::CommitUncertain {
1461 datasource: "pg".to_owned(),
1462 },
1463 false,
1464 ),
1465 (
1466 "io transport error",
1467 TxIoFailure::Lost,
1468 TransactionError::CommitUncertain {
1469 datasource: "pg".to_owned(),
1470 },
1471 false,
1472 ),
1473 ];
1474
1475 for (name, commit_failure, expected, cleanup_issued) in rows {
1476 let (io, shared) = FakeIo::channel();
1477 FakeIo::script(SQL_COMMIT, Scripted::Fail(commit_failure), &shared);
1478 let session = test_session(io, Arc::new(TokioTimer));
1479 session.begin().await.expect("BEGIN must acknowledge");
1480 assert_eq!(session.state(), TransactionState::Active, "row {name}");
1481
1482 let result = session.commit().await;
1483 assert_eq!(result, Err(expected), "row {name}");
1484
1485 let expected_issued = if cleanup_issued {
1486 vec![SQL_BEGIN, SQL_COMMIT, SQL_ROLLBACK]
1487 } else {
1488 vec![SQL_BEGIN, SQL_COMMIT]
1489 };
1490 assert_eq!(issued_of(&shared), expected_issued, "row {name}");
1491 if cleanup_issued {
1492 assert!(
1493 is_released(&shared),
1494 "cleanup acknowledged: connection returned to the pool (row {name})"
1495 );
1496 assert!(
1497 !is_detached(&shared),
1498 "no detach after an acknowledged cleanup (row {name})"
1499 );
1500 assert_eq!(session.state(), TransactionState::Done, "row {name}");
1501 } else {
1502 assert!(is_detached(&shared), "detach immediately (row {name})");
1503 assert!(
1504 !is_released(&shared),
1505 "no rollback claim and no re-pool (row {name})"
1506 );
1507 assert_eq!(session.state(), TransactionState::Detached, "row {name}");
1508 }
1509 }
1510 }
1511
1512 #[tokio::test]
1514 async fn commit_requires_open_sends_no_sql() {
1515 let (io, shared) = FakeIo::channel();
1517 let session = test_session(io, Arc::new(TokioTimer));
1518 let error = session
1519 .commit()
1520 .await
1521 .expect_err("commit from Clean aborts");
1522 assert_eq!(
1523 error,
1524 TransactionError::SessionAborted {
1525 datasource: "pg".to_owned()
1526 }
1527 );
1528 assert!(
1529 issued_of(&shared).is_empty(),
1530 "the aborted commit must send no SQL"
1531 );
1532
1533 let (io, shared) = FakeIo::channel();
1535 let session = test_session(io, Arc::new(TokioTimer));
1536 session.begin().await.expect("BEGIN must acknowledge");
1537 session.rollback().await.expect("rollback acknowledges");
1538 let error = session.commit().await.expect_err("commit from Done aborts");
1539 assert_eq!(
1540 error,
1541 TransactionError::SessionAborted {
1542 datasource: "pg".to_owned()
1543 }
1544 );
1545 assert_eq!(
1546 issued_of(&shared),
1547 vec![SQL_BEGIN, SQL_ROLLBACK],
1548 "the aborted commit must send no SQL"
1549 );
1550 }
1551
1552 #[tracing_test::traced_test]
1555 #[tokio::test]
1556 async fn defensive_finalization_entry_logs_error_without_detach_claim() {
1557 let (io, shared) = FakeIo::channel();
1559 FakeIo::script(SQL_COMMIT, Scripted::Pending, &shared);
1560 let session = test_session(io, Arc::new(TokioTimer));
1561 session.begin().await.expect("BEGIN must acknowledge");
1562 {
1563 let mut commit = std::pin::pin!(session.commit());
1564 assert!(poll_once_pending(&mut commit), "COMMIT must stay pending");
1565 assert_eq!(session.state(), TransactionState::Finalizing);
1566 }
1567
1568 let result = session.rollback().await;
1569 assert_eq!(
1570 result,
1571 Err(TransactionError::RollbackUncertain {
1572 datasource: "pg".to_owned()
1573 }),
1574 "defensive Finalizing entry returns Err, never an outcome claim"
1575 );
1576 assert_eq!(
1577 session.state(),
1578 TransactionState::Finalizing,
1579 "the defensive entry changes no phase"
1580 );
1581 assert!(logs_contain("defensive finalization entry"));
1582 assert_eq!(
1583 issued_of(&shared),
1584 vec![SQL_BEGIN, SQL_COMMIT],
1585 "no SQL on the defensive path"
1586 );
1587 assert!(
1588 !is_detached(&shared),
1589 "the defensive entry must NOT claim detachment happened"
1590 );
1591 assert!(!is_released(&shared));
1592
1593 let (io, shared) = FakeIo::channel();
1595 let session = test_session(io, Arc::new(TokioTimer));
1596 session.begin().await.expect("BEGIN must acknowledge");
1597 assert_eq!(session.rollback().await, Ok(TransactionOutcome::RolledBack));
1598 let result = session.rollback().await;
1599 assert_eq!(
1600 result,
1601 Err(TransactionError::RollbackUncertain {
1602 datasource: "pg".to_owned()
1603 }),
1604 "defensive Done entry returns Err, never an outcome claim"
1605 );
1606 assert_eq!(
1607 session.state(),
1608 TransactionState::Done,
1609 "the defensive entry changes no phase"
1610 );
1611 assert!(logs_contain("defensive finalization entry"));
1612 assert_eq!(
1613 issued_of(&shared),
1614 vec![SQL_BEGIN, SQL_ROLLBACK],
1615 "no SQL on the defensive path"
1616 );
1617 assert!(
1618 !is_detached(&shared),
1619 "the Done entry adds no detach: the connection was already released by the first rollback"
1620 );
1621 }
1622
1623 #[tokio::test]
1626 async fn r2_clean_rollback_returns_connection_clean() {
1627 let (io, shared) = FakeIo::channel();
1628 let session = test_session(io, Arc::new(TokioTimer));
1629 assert_eq!(session.state(), TransactionState::Fresh);
1630 assert!(!session.is_rollback_only());
1631
1632 let result = session.rollback().await;
1633 assert_eq!(result, Ok(TransactionOutcome::RolledBack));
1634 assert_eq!(session.state(), TransactionState::Done);
1635 assert!(
1636 issued_of(&shared).is_empty(),
1637 "R2 sends no SQL: nothing was begun"
1638 );
1639 assert!(
1640 is_released(&shared),
1641 "the connection is returned to the pool clean"
1642 );
1643 assert!(!is_detached(&shared));
1644 }
1645
1646 #[tokio::test]
1650 async fn rollback_only_flag_and_open_rollback_acks() {
1651 let (io, shared) = FakeIo::channel();
1652 let session = test_session(io, Arc::new(TokioTimer));
1653 assert!(!session.is_rollback_only());
1654 session.set_rollback_only();
1655 assert!(session.is_rollback_only());
1656
1657 session.begin().await.expect("BEGIN must acknowledge");
1658 let result = session.rollback().await;
1659 assert_eq!(result, Ok(TransactionOutcome::RolledBack));
1660 assert_eq!(issued_of(&shared), vec![SQL_BEGIN, SQL_ROLLBACK]);
1661 assert!(
1662 session.is_rollback_only(),
1663 "finalization does not clear the flag"
1664 );
1665 }
1666
1667 #[tokio::test]
1670 async fn busy_slot_try_lock_reports_busy() {
1671 let (io, shared) = FakeIo::channel();
1672 let session = test_session(io, Arc::new(TokioTimer));
1673
1674 let held = session
1675 .slot
1676 .try_lock()
1677 .expect("the slot must be free before the fixture holds it");
1678 let error = session.begin().await.expect_err("held slot");
1679 assert_eq!(
1680 error,
1681 TransactionError::Busy {
1682 datasource: "pg".to_owned()
1683 }
1684 );
1685 assert!(
1686 issued_of(&shared).is_empty(),
1687 "a busy-rejected begin sends no SQL"
1688 );
1689 drop(held);
1690
1691 session.begin().await.expect("begin after the slot frees");
1692 assert_eq!(issued_of(&shared), vec![SQL_BEGIN]);
1693 }
1694
1695 #[tokio::test]
1699 async fn transacted_hygiene_unacknowledged() {
1700 let (mut io, shared) = FakeIo::channel();
1701 FakeIo::script(
1702 SQL_ROLLBACK,
1703 Scripted::Fail(db_error(DbSeverity::Error, "08006", "connection failure")),
1704 &shared,
1705 );
1706 let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
1707 let now = timer.now();
1708
1709 let error = admission_hygiene(
1710 &mut *io,
1711 Arc::clone(&timer),
1712 "pg",
1713 MAX_CONNECTIONS,
1714 now + Duration::from_secs(60),
1715 now + ACQUIRE,
1716 )
1717 .await
1718 .expect_err("unacknowledged hygiene");
1719 assert_eq!(
1720 error,
1721 TransactionError::RollbackUncertain {
1722 datasource: "pg".to_owned()
1723 }
1724 );
1725 assert_eq!(
1726 issued_of(&shared),
1727 vec![SQL_ROLLBACK],
1728 "exactly one ROLLBACK attempt, BEGIN never sent"
1729 );
1730 assert!(is_detached(&shared), "unacknowledged hygiene detaches");
1731 }
1732
1733 #[tokio::test]
1739 async fn sqlite_pool_begin_commit_and_rollback_smoke() {
1740 sqlx::any::install_default_drivers();
1741 let pool = sqlx::any::AnyPoolOptions::new() .max_connections(2)
1743 .connect("sqlite::memory:")
1744 .await
1745 .expect("in-memory sqlite pool");
1746 let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
1747
1748 let conn = pool.acquire().await.expect("first connection"); let session = SqlTxSession::with_io(
1750 "pg",
1751 Box::new(AnyConnIo { conn: Some(conn) }),
1752 Arc::clone(&timer),
1753 ACQUIRE,
1754 GRACE,
1755 2,
1756 );
1757 session.begin().await.expect("real BEGIN");
1758 assert_eq!(session.state(), TransactionState::Active);
1759 let outcome = session.commit().await.expect("real COMMIT");
1760 assert_eq!(outcome, TransactionOutcome::Committed);
1761 assert_eq!(session.state(), TransactionState::Done);
1762
1763 let conn = pool.acquire().await.expect("second connection"); let session = SqlTxSession::with_io(
1765 "pg",
1766 Box::new(AnyConnIo { conn: Some(conn) }),
1767 timer,
1768 ACQUIRE,
1769 GRACE,
1770 2,
1771 );
1772 session.begin().await.expect("real BEGIN");
1773 let outcome = session.rollback().await.expect("real ROLLBACK");
1774 assert_eq!(outcome, TransactionOutcome::RolledBack);
1775 assert_eq!(session.state(), TransactionState::Done);
1776
1777 sqlx::query("SELECT 1")
1779 .execute(&pool)
1780 .await
1781 .expect("pool usable after finalization");
1782 pool.close().await;
1783 }
1784
1785 #[tokio::test]
1788 async fn forced_drop_detaches_without_sql() {
1789 assert_forced_drop_from_open().await;
1790 }
1791
1792 #[tokio::test]
1799 async fn transacted_forced_drop_inline() {
1800 assert_forced_drop_from_open().await;
1801 }
1802
1803 async fn assert_forced_drop_from_open() {
1804 let (io, shared) = FakeIo::channel();
1805 let session = test_session(io, Arc::new(TokioTimer));
1806 session.begin().await.expect("BEGIN must acknowledge");
1807 assert_eq!(session.state(), TransactionState::Active);
1808
1809 drop(session);
1810 assert_eq!(issued_of(&shared), vec![SQL_BEGIN], "R0 sends no SQL");
1811 assert!(is_detached(&shared), "R0 detaches synchronously");
1812 assert!(!is_released(&shared), "R0 never returns the connection");
1813 }
1814
1815 #[tokio::test]
1819 async fn transacted_begin_pending_deadline() {
1820 let (io, shared) = FakeIo::channel();
1821 FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
1822 let session = test_session(io, Arc::new(TokioTimer));
1823
1824 {
1828 let mut begin = std::pin::pin!(session.begin());
1829 assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
1830 assert_eq!(
1831 session.state(),
1832 TransactionState::Fresh,
1833 "BeginPending projects lossily onto Fresh"
1834 );
1835 }
1836
1837 let result = session.rollback().await;
1838 assert_eq!(
1839 result,
1840 Err(TransactionError::RollbackUncertain {
1841 datasource: "pg".to_owned()
1842 }),
1843 "R3: protocol position unknown, nothing acknowledged"
1844 );
1845 assert_eq!(
1846 issued_of(&shared),
1847 vec![SQL_BEGIN],
1848 "R3 sends no SQL: no ROLLBACK on an unacknowledged BEGIN"
1849 );
1850 assert!(is_detached(&shared), "R3 detaches the connection");
1851 assert!(
1852 !is_released(&shared),
1853 "a detached connection is never returned to the pool"
1854 );
1855 assert_eq!(session.state(), TransactionState::Detached);
1856 }
1857
1858 #[tokio::test(start_paused = true)]
1862 async fn transacted_stalled_commit() {
1863 let (io, shared) = FakeIo::channel();
1864 FakeIo::script(SQL_COMMIT, Scripted::Pending, &shared);
1865 let session = test_session(io, Arc::new(TokioTimer));
1866 session.begin().await.expect("BEGIN must acknowledge");
1867
1868 let result = session.commit().await;
1869 assert_eq!(
1870 result,
1871 Err(TransactionError::CommitUncertain {
1872 datasource: "pg".to_owned()
1873 }),
1874 "grace elapsed: the commit outcome is uncertain"
1875 );
1876 assert_eq!(
1877 issued_of(&shared),
1878 vec![SQL_BEGIN, SQL_COMMIT],
1879 "no cleanup ROLLBACK after a stalled COMMIT"
1880 );
1881 assert!(is_detached(&shared), "the grace expiry detaches");
1882 assert!(
1883 !is_released(&shared),
1884 "a detached connection is never re-pooled"
1885 );
1886 assert_eq!(session.state(), TransactionState::Detached);
1887 }
1888
1889 #[tokio::test(start_paused = true)]
1893 async fn transacted_stalled_rollback() {
1894 let (io, shared) = FakeIo::channel();
1895 FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
1896 let session = test_session(io, Arc::new(TokioTimer));
1897 session.begin().await.expect("BEGIN must acknowledge");
1898
1899 let result = session.rollback().await;
1900 assert_eq!(
1901 result,
1902 Err(TransactionError::RollbackUncertain {
1903 datasource: "pg".to_owned()
1904 }),
1905 "grace elapsed: the rollback is not acknowledged"
1906 );
1907 assert_eq!(
1908 issued_of(&shared),
1909 vec![SQL_BEGIN, SQL_ROLLBACK],
1910 "exactly one ROLLBACK attempt within the grace"
1911 );
1912 assert!(is_detached(&shared), "the grace expiry detaches");
1913 assert!(
1914 !is_released(&shared),
1915 "a detached connection is never re-pooled"
1916 );
1917 assert_eq!(session.state(), TransactionState::Detached);
1918 }
1919
1920 #[tracing_test::traced_test]
1928 #[tokio::test(start_paused = true)]
1929 async fn commit_cleanup_unacknowledged_keeps_commit_failed() {
1930 let (io, shared) = FakeIo::channel();
1931 FakeIo::script(
1932 SQL_COMMIT,
1933 Scripted::Fail(db_error(DbSeverity::Error, "23503", "foreign key violated")),
1934 &shared,
1935 );
1936 FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
1937 let session = test_session(io, Arc::new(TokioTimer));
1938 session.begin().await.expect("BEGIN must acknowledge");
1939
1940 let result = session.commit().await;
1941 assert_eq!(
1942 result,
1943 Err(TransactionError::CommitFailed {
1944 datasource: "pg".to_owned(),
1945 reason: "SQLSTATE 23503: foreign key violated".to_owned(),
1946 }),
1947 "the typed commit failure stands; cleanup uncertainty never replaces it"
1948 );
1949 assert_eq!(
1950 issued_of(&shared),
1951 vec![SQL_BEGIN, SQL_COMMIT, SQL_ROLLBACK],
1952 "exactly one cleanup ROLLBACK attempt within the remaining grace"
1953 );
1954 assert!(is_detached(&shared), "unacknowledged cleanup detaches");
1955 assert!(
1956 !is_released(&shared),
1957 "the connection is never returned to the pool with unknown state"
1958 );
1959 assert_eq!(session.state(), TransactionState::Detached);
1960 assert!(
1961 logs_contain("not acknowledged"),
1962 "the cleanup uncertainty is observable through the warn! log"
1963 );
1964 }
1965
1966 #[tokio::test(start_paused = true)]
1969 async fn hygiene_deadline_reports_timeout_elapsed_from_start() {
1970 let (mut io, shared) = FakeIo::channel();
1971 FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
1972 let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
1973 let now = timer.now();
1974 let block_deadline = Duration::from_millis(10);
1975
1976 let error = admission_hygiene(
1977 &mut *io,
1978 Arc::clone(&timer),
1979 "pg",
1980 MAX_CONNECTIONS,
1981 now + block_deadline,
1982 now + Duration::from_secs(60),
1983 )
1984 .await
1985 .expect_err("block deadline elapses while hygiene is pending");
1986 assert_eq!(
1987 error,
1988 TransactionError::Timeout {
1989 datasource: "pg".to_owned(),
1990 elapsed_ms: block_deadline.as_millis() as u64,
1991 },
1992 "elapsed must measure from the hygiene start (> 0), not from the deadline"
1993 );
1994 assert_eq!(
1995 issued_of(&shared),
1996 vec![SQL_ROLLBACK],
1997 "exactly one ROLLBACK attempt, BEGIN never sent"
1998 );
1999 assert!(
2000 is_detached(&shared),
2001 "deadline expiry during hygiene detaches"
2002 );
2003 }
2004
2005 async fn hygiene_deadline_case(block: Duration, acquire: Duration) -> TransactionError {
2010 let (mut io, shared) = FakeIo::channel();
2011 FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
2012 let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
2013 let now = timer.now();
2014
2015 let error = admission_hygiene(
2016 &mut *io,
2017 Arc::clone(&timer),
2018 "pg",
2019 MAX_CONNECTIONS,
2020 now + block,
2021 now + acquire,
2022 )
2023 .await
2024 .expect_err("hygiene stays pending past both deadlines");
2025 assert_eq!(
2026 issued_of(&shared),
2027 vec![SQL_ROLLBACK],
2028 "exactly one ROLLBACK attempt, BEGIN never sent"
2029 );
2030 assert!(
2031 is_detached(&shared),
2032 "deadline expiry during hygiene detaches"
2033 );
2034 assert!(
2035 !is_released(&shared),
2036 "a detached connection is never re-pooled"
2037 );
2038 error
2039 }
2040
2041 #[tokio::test(start_paused = true)]
2048 async fn transacted_hygiene_deadline_expiry() {
2049 let cases: [(&str, Duration, Duration, TransactionError); 3] = [
2050 (
2051 "acquire-first: acquire 10 ms < block 60 s",
2052 Duration::from_secs(60),
2053 Duration::from_millis(10),
2054 TransactionError::PoolExhausted {
2055 datasource: "pg".to_owned(),
2056 max_connections: MAX_CONNECTIONS,
2057 waited_ms: 10,
2058 },
2059 ),
2060 (
2061 "block-first: block 10 ms < acquire 60 s",
2062 Duration::from_millis(10),
2063 Duration::from_secs(60),
2064 TransactionError::Timeout {
2065 datasource: "pg".to_owned(),
2066 elapsed_ms: 10,
2067 },
2068 ),
2069 (
2070 "tie: both 10 ms — the biased block arm wins",
2071 Duration::from_millis(10),
2072 Duration::from_millis(10),
2073 TransactionError::Timeout {
2074 datasource: "pg".to_owned(),
2075 elapsed_ms: 10,
2076 },
2077 ),
2078 ];
2079
2080 for (label, block, acquire, expected) in cases {
2081 let error = hygiene_deadline_case(block, acquire).await;
2082 assert_eq!(error, expected, "{label}");
2083 }
2084 }
2085
2086 #[tokio::test(start_paused = true)]
2094 async fn open_future_dropped_mid_hygiene_detaches_at_checkout() {
2095 let (io, shared) = FakeIo::channel();
2096 FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
2097 let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
2098 let now = timer.now();
2099
2100 {
2103 let mut open = std::pin::pin!(SqlTxSession::admit(
2104 "pg".into(),
2105 CheckedOutBackend::arm(io),
2106 now + Duration::from_secs(60),
2107 now + Duration::from_secs(60),
2108 ACQUIRE,
2109 MAX_CONNECTIONS,
2110 Arc::clone(&timer),
2111 ));
2112 assert!(poll_once_pending(&mut open), "hygiene must stay pending");
2113 assert_eq!(
2114 issued_of(&shared),
2115 vec![SQL_ROLLBACK],
2116 "exactly one ROLLBACK attempt, BEGIN never sent"
2117 );
2118 }
2119
2120 assert!(
2121 is_detached(&shared),
2122 "a drop mid-hygiene detaches (R0 arms at checkout)"
2123 );
2124 assert!(
2125 !is_released(&shared),
2126 "the detached connection is never re-pooled"
2127 );
2128 }
2129
2130 #[tokio::test(start_paused = true)]
2134 async fn transacted_acquire_deadline_first() {
2135 let error = hygiene_deadline_case(Duration::from_secs(60), Duration::from_millis(10)).await;
2136 match error {
2137 TransactionError::PoolExhausted {
2138 datasource,
2139 max_connections,
2140 waited_ms,
2141 } => {
2142 assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
2143 assert_eq!(max_connections, MAX_CONNECTIONS);
2144 assert_eq!(waited_ms, 10, "waited_ms measures from the hygiene start");
2145 }
2146 other => panic!("expected typed PoolExhausted, got {other:?}"),
2147 }
2148 }
2149
2150 #[tokio::test(start_paused = true)]
2155 async fn transacted_block_deadline_first() {
2156 let error = hygiene_deadline_case(Duration::from_secs(30), Duration::from_secs(60)).await;
2157 assert_eq!(
2158 error,
2159 TransactionError::Timeout {
2160 datasource: "pg".to_owned(),
2161 elapsed_ms: 30_000,
2162 },
2163 "elapsed is measured from block entry, not from the deadline"
2164 );
2165 }
2166
2167 #[tokio::test(start_paused = true)]
2172 async fn transacted_deadline_tie() {
2173 let error = hygiene_deadline_case(Duration::from_secs(30), Duration::from_secs(30)).await;
2174 assert_eq!(
2175 error,
2176 TransactionError::Timeout {
2177 datasource: "pg".to_owned(),
2178 elapsed_ms: 30_000,
2179 },
2180 "the tie resolves to the block-deadline error, never PoolExhausted"
2181 );
2182 }
2183
2184 #[tokio::test(start_paused = true)]
2195 async fn transacted_deadline_both_elapsed_at_first_poll() {
2196 async fn case(block: Duration, acquire: Duration) -> TransactionError {
2197 let (mut io, shared) = FakeIo::channel();
2198 FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
2199 let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
2200 let now = timer.now();
2201 let hygiene = std::pin::pin!(admission_hygiene(
2202 &mut *io,
2203 Arc::clone(&timer),
2204 "pg",
2205 MAX_CONNECTIONS,
2206 now + block,
2207 now + acquire,
2208 ));
2209 tokio::time::sleep(block.max(acquire) + Duration::from_secs(1)).await;
2212 let error = hygiene.await.expect_err("both deadlines are spent");
2213 assert!(
2214 issued_of(&shared).is_empty(),
2215 "the race resolved before any I/O was polled"
2216 );
2217 assert!(is_detached(&shared), "the losing deadline detaches");
2218 error
2219 }
2220
2221 let error = case(Duration::from_secs(60), Duration::from_millis(10)).await;
2222 match error {
2223 TransactionError::PoolExhausted {
2224 datasource,
2225 max_connections,
2226 ..
2227 } => {
2228 assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
2229 assert_eq!(max_connections, MAX_CONNECTIONS);
2230 }
2231 other => panic!(
2232 "acquire_abs < block_abs with both elapsed must report PoolExhausted, got {other:?}"
2233 ),
2234 }
2235
2236 let error = case(Duration::from_millis(10), Duration::from_millis(10)).await;
2237 assert!(
2238 matches!(error, TransactionError::Timeout { .. }),
2239 "equal instants report Timeout on the tie, got {error:?}"
2240 );
2241 }
2242
2243 #[tokio::test]
2251 async fn transacted_open_race_both_deadlines_elapsed_at_first_poll() {
2252 sqlx::any::install_default_drivers();
2253 let pool = sqlx::any::AnyPoolOptions::new() .max_connections(2)
2255 .connect("sqlite::memory:")
2256 .await
2257 .expect("in-memory sqlite pool");
2258 let timer: Arc<dyn TxTimer> = Arc::new(AlwaysElapsed);
2259 let now = timer.now();
2260
2261 let open = SqlTxSession::open(
2264 "pg",
2265 &pool,
2266 now + Duration::from_secs(60),
2267 Duration::from_millis(10),
2268 Arc::clone(&timer),
2269 )
2270 .await;
2271 let error = match open {
2272 Err(error) => error,
2273 Ok(_) => panic!("both admission deadlines are spent"),
2274 };
2275 match error {
2276 TransactionError::PoolExhausted { datasource, .. } => {
2277 assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
2278 }
2279 other => panic!(
2280 "acquire_abs < block_abs with both elapsed must report PoolExhausted, got {other:?}"
2281 ),
2282 }
2283
2284 let open = SqlTxSession::open(
2286 "pg",
2287 &pool,
2288 now + Duration::from_millis(10),
2289 Duration::from_millis(10),
2290 timer,
2291 )
2292 .await;
2293 let error = match open {
2294 Err(error) => error,
2295 Ok(_) => panic!("both admission deadlines are spent"),
2296 };
2297 assert!(
2298 matches!(error, TransactionError::Timeout { .. }),
2299 "equal instants report Timeout on the tie, got {error:?}"
2300 );
2301 }
2302
2303 #[tokio::test]
2306 async fn forced_drop_from_clean_detaches_without_sql() {
2307 let (io, shared) = FakeIo::channel();
2308 let session = test_session(io, Arc::new(TokioTimer));
2309 assert_eq!(session.state(), TransactionState::Fresh);
2310
2311 drop(session);
2312 assert!(issued_of(&shared).is_empty(), "R0 from Clean sends no SQL");
2313 assert!(is_detached(&shared), "R0 detaches synchronously");
2314 assert!(!is_released(&shared), "R0 never returns the connection");
2315 }
2316
2317 #[tokio::test]
2320 async fn forced_drop_from_begin_pending_detaches_without_sql() {
2321 let (io, shared) = FakeIo::channel();
2322 FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
2323 let session = test_session(io, Arc::new(TokioTimer));
2324 {
2325 let mut begin = std::pin::pin!(session.begin());
2326 assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
2327 }
2328
2329 drop(session);
2330 assert_eq!(
2331 issued_of(&shared),
2332 vec![SQL_BEGIN],
2333 "R0 from BeginPending sends no further SQL"
2334 );
2335 assert!(is_detached(&shared), "R0 detaches synchronously");
2336 assert!(!is_released(&shared), "R0 never returns the connection");
2337 }
2338}