use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex as SyncMutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use camel_api::transaction::{
BeginFuture, FinalizeFuture, TransactionError, TransactionOutcome, TransactionSession,
TransactionState,
};
use sqlx::Any;
use sqlx::AnyPool;
use sqlx::pool::PoolConnection;
use tokio::sync::Mutex as AsyncMutex;
const FINALIZE_GRACE: Duration = Duration::from_secs(5);
const SQL_BEGIN: &str = "BEGIN";
const SQL_COMMIT: &str = "COMMIT";
const SQL_ROLLBACK: &str = "ROLLBACK";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TxPhase {
Clean,
BeginPending,
Open,
CommitInFlight,
RollbackInFlight,
Done,
Detached,
}
#[must_use]
fn project(phase: TxPhase) -> TransactionState {
match phase {
TxPhase::Clean | TxPhase::BeginPending => TransactionState::Fresh,
TxPhase::Open => TransactionState::Active,
TxPhase::CommitInFlight | TxPhase::RollbackInFlight => TransactionState::Finalizing,
TxPhase::Done => TransactionState::Done,
TxPhase::Detached => TransactionState::Detached,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DbSeverity {
Error,
Other,
}
#[derive(Debug, Clone)]
pub(crate) struct DbAnswer {
severity: DbSeverity,
code: Option<String>,
message: String,
}
#[derive(Debug, Clone)]
pub(crate) enum TxIoFailure {
Database(DbAnswer),
Lost,
}
enum CommitDisposition {
Rejected {
reason: String,
},
Lost,
}
#[must_use]
fn commit_disposition(failure: &TxIoFailure) -> CommitDisposition {
let TxIoFailure::Database(answer) = failure else {
return CommitDisposition::Lost;
};
let reject_class = answer
.code
.as_deref()
.is_some_and(|code| code.starts_with("23") || code.starts_with("40"));
if answer.severity == DbSeverity::Error && reject_class {
CommitDisposition::Rejected {
reason: match answer.code.as_deref() {
Some(code) => format!("SQLSTATE {code}: {}", answer.message),
None => answer.message.clone(),
},
}
} else {
CommitDisposition::Lost
}
}
type ExecFuture<'a> = Pin<Box<dyn Future<Output = Result<(), TxIoFailure>> + Send + 'a>>;
pub(crate) trait TxIo: Send + 'static {
fn exec(&mut self, sql: &'static str) -> ExecFuture<'_>;
fn detach(&mut self);
fn release(self: Box<Self>);
}
struct AnyConnIo {
conn: Option<PoolConnection<Any>>,
}
impl TxIo for AnyConnIo {
fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
Box::pin(async move {
let Some(conn) = self.conn.as_mut() else {
return Err(TxIoFailure::Lost);
};
match sqlx::query(sqlx::AssertSqlSafe(sql))
.execute(&mut **conn)
.await
{
Ok(_) => Ok(()),
Err(error) => Err(to_io_failure(&error)),
}
})
}
fn detach(&mut self) {
if let Some(conn) = self.conn.take() {
drop(conn.detach());
}
}
fn release(self: Box<Self>) {
drop(self);
}
}
struct DetachedIo;
impl TxIo for DetachedIo {
fn exec(&mut self, _sql: &'static str) -> ExecFuture<'_> {
Box::pin(std::future::ready(Err(TxIoFailure::Lost)))
}
fn detach(&mut self) {}
fn release(self: Box<Self>) {}
}
struct CheckedOutBackend {
io: Option<Box<dyn TxIo>>,
}
impl CheckedOutBackend {
fn arm(io: Box<dyn TxIo>) -> Self {
Self { io: Some(io) }
}
fn disarm(mut self) -> Box<dyn TxIo> {
match self.io.take() {
Some(io) => io,
None => {
tracing::error!(
"checked-out backend missing at the with_io hand-off; \
the session continues on the lost placeholder"
);
Box::new(DetachedIo)
}
}
}
}
impl TxIo for CheckedOutBackend {
fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
let Some(io) = self.io.as_mut() else {
return Box::pin(std::future::ready(Err(TxIoFailure::Lost)));
};
io.exec(sql)
}
fn detach(&mut self) {
if let Some(mut io) = self.io.take() {
io.detach();
}
}
fn release(mut self: Box<Self>) {
if let Some(io) = self.io.take() {
io.release();
}
}
}
impl Drop for CheckedOutBackend {
fn drop(&mut self) {
if let Some(mut io) = self.io.take() {
io.detach();
}
}
}
fn to_io_failure(error: &sqlx::Error) -> TxIoFailure {
match error {
sqlx::Error::Database(db) => TxIoFailure::Database(DbAnswer {
severity: db_severity(&**db),
code: db.code().as_deref().map(str::to_owned),
message: db.message().to_owned(),
}),
_ => TxIoFailure::Lost,
}
}
#[cfg(feature = "postgres")]
fn db_severity(db: &dyn sqlx::error::DatabaseError) -> DbSeverity {
match db.try_downcast_ref::<sqlx::postgres::PgDatabaseError>() {
Some(pg) if pg.severity() == sqlx::postgres::PgSeverity::Error => DbSeverity::Error,
_ => DbSeverity::Other,
}
}
#[cfg(not(feature = "postgres"))]
fn db_severity(_db: &dyn sqlx::error::DatabaseError) -> DbSeverity {
DbSeverity::Other
}
pub(crate) trait TxTimer: Send + Sync + 'static {
fn now(&self) -> tokio::time::Instant;
fn sleep_until(
&self,
deadline: tokio::time::Instant,
) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}
struct TokioTimer;
impl TxTimer for TokioTimer {
fn now(&self) -> tokio::time::Instant {
tokio::time::Instant::now()
}
fn sleep_until(
&self,
deadline: tokio::time::Instant,
) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
Box::pin(tokio::time::sleep_until(deadline))
}
}
#[derive(Debug)]
enum StmtOutcome {
Ack,
Deadline,
Failed(TxIoFailure),
}
async fn run_statement(
io: &mut dyn TxIo,
sql: &'static str,
deadline: tokio::time::Instant,
timer: &dyn TxTimer,
) -> StmtOutcome {
tokio::select! {
biased;
_ = timer.sleep_until(deadline) => StmtOutcome::Deadline,
result = io.exec(sql) => match result {
Ok(()) => StmtOutcome::Ack,
Err(failure) => StmtOutcome::Failed(failure),
},
}
}
fn elapsed_ms(timer: &dyn TxTimer, since: tokio::time::Instant) -> u64 {
u64::try_from(timer.now().saturating_duration_since(since).as_millis()).unwrap_or(u64::MAX)
}
pub struct SqlTxSession {
datasource: Arc<str>,
slot: AsyncMutex<Box<dyn TxIo>>,
phase: SyncMutex<TxPhase>,
rollback_only: AtomicBool,
timer: Arc<dyn TxTimer>,
acquire_deadline: Duration,
finalize_grace: Duration,
max_connections: u32,
}
impl SqlTxSession {
pub(crate) fn with_io(
datasource: impl Into<Arc<str>>,
io: Box<dyn TxIo>,
timer: Arc<dyn TxTimer>,
acquire_deadline: Duration,
finalize_grace: Duration,
max_connections: u32,
) -> Self {
Self {
datasource: datasource.into(),
slot: AsyncMutex::new(io),
phase: SyncMutex::new(TxPhase::Clean),
rollback_only: AtomicBool::new(false),
timer,
acquire_deadline,
finalize_grace,
max_connections,
}
}
pub(crate) async fn open(
datasource: impl Into<Arc<str>>,
pool: &AnyPool,
block_abs: tokio::time::Instant,
acquire_deadline: Duration,
timer: Arc<dyn TxTimer>,
) -> Result<Self, TransactionError> {
let datasource = datasource.into();
let max_connections = crate::pool_factory::pool_max_connections(pool);
let open_start = timer.now();
let acquire_abs = open_start + acquire_deadline;
let conn = tokio::select! {
biased;
_ = timer.sleep_until(block_abs) => {
if acquire_abs < block_abs {
return Err(TransactionError::PoolExhausted {
datasource: datasource.to_string(),
max_connections,
waited_ms: elapsed_ms(timer.as_ref(), open_start),
});
}
return Err(TransactionError::Timeout {
datasource: datasource.to_string(),
elapsed_ms: elapsed_ms(timer.as_ref(), open_start),
});
}
_ = timer.sleep_until(acquire_abs) => {
return Err(TransactionError::PoolExhausted {
datasource: datasource.to_string(),
max_connections,
waited_ms: elapsed_ms(timer.as_ref(), open_start),
});
}
acquired = pool.acquire() => {
acquired.map_err(|_| TransactionError::PoolExhausted {
datasource: datasource.to_string(),
max_connections,
waited_ms: elapsed_ms(timer.as_ref(), open_start),
})?
}
};
let backend = CheckedOutBackend::arm(Box::new(AnyConnIo { conn: Some(conn) }));
Self::admit(
datasource,
backend,
block_abs,
acquire_abs,
acquire_deadline,
max_connections,
timer,
)
.await
}
async fn admit(
datasource: Arc<str>,
backend: CheckedOutBackend,
block_abs: tokio::time::Instant,
acquire_abs: tokio::time::Instant,
acquire_deadline: Duration,
max_connections: u32,
timer: Arc<dyn TxTimer>,
) -> Result<Self, TransactionError> {
let mut backend = backend;
admission_hygiene(
&mut backend,
Arc::clone(&timer),
&datasource,
max_connections,
block_abs,
acquire_abs,
)
.await?;
Ok(Self::with_io(
datasource,
backend.disarm(),
timer,
acquire_deadline,
FINALIZE_GRACE,
max_connections,
))
}
pub async fn open_on_pool(
datasource: impl Into<Arc<str>>,
pool: &AnyPool,
block_abs: tokio::time::Instant,
acquire_deadline: Duration,
) -> Result<Self, TransactionError> {
Self::open(
datasource,
pool,
block_abs,
acquire_deadline,
Arc::new(TokioTimer),
)
.await
}
#[doc(hidden)]
pub async fn exec_statement_for_test(&self, sql: &'static str) -> Result<(), String> {
let Ok(mut slot) = self.slot.try_lock() else {
return Err(TransactionError::Busy {
datasource: self.datasource.to_string(),
}
.to_string());
};
match slot.exec(sql).await {
Ok(()) => Ok(()),
Err(TxIoFailure::Database(answer)) => Err(format!(
"statement `{sql}` failed: SQLSTATE {}: {}",
answer.code.as_deref().unwrap_or("-"),
answer.message
)),
Err(TxIoFailure::Lost) => Err(format!(
"statement `{sql}` lost the connection (outcome unknown)"
)),
}
}
fn phase(&self) -> TxPhase {
*self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn store_phase(&self, phase: TxPhase) {
*self
.phase
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = phase;
}
fn detach_slot(&self, slot: &mut tokio::sync::MutexGuard<'_, Box<dyn TxIo>>) {
slot.detach();
let _ = std::mem::replace(&mut **slot, Box::new(DetachedIo));
self.store_phase(TxPhase::Detached);
}
async fn begin_inner(&self) -> Result<(), TransactionError> {
let datasource = self.datasource.to_string();
let Ok(mut slot) = self.slot.try_lock() else {
return Err(TransactionError::Busy { datasource });
};
match self.phase() {
TxPhase::Open => return Ok(()),
TxPhase::Clean => {}
_ => return Err(TransactionError::SessionAborted { datasource }),
}
self.store_phase(TxPhase::BeginPending);
let begin_start = self.timer.now();
let deadline = begin_start + self.acquire_deadline;
match run_statement(&mut **slot, SQL_BEGIN, deadline, self.timer.as_ref()).await {
StmtOutcome::Ack => {
self.store_phase(TxPhase::Open);
Ok(())
}
StmtOutcome::Deadline => {
self.detach_slot(&mut slot);
Err(TransactionError::PoolExhausted {
datasource,
max_connections: self.max_connections,
waited_ms: elapsed_ms(self.timer.as_ref(), begin_start),
})
}
StmtOutcome::Failed(_) => {
self.detach_slot(&mut slot);
Err(TransactionError::RollbackUncertain { datasource })
}
}
}
async fn commit_inner(&self) -> Result<TransactionOutcome, TransactionError> {
let datasource = self.datasource.to_string();
if self.phase() != TxPhase::Open {
return Err(TransactionError::SessionAborted { datasource });
}
let Ok(mut slot) = self.slot.try_lock() else {
tracing::error!(
datasource = %self.datasource,
"commit while the session slot is held; the commit outcome cannot be verified"
);
return Err(TransactionError::CommitUncertain { datasource });
};
let finalize_start = self.timer.now();
let grace_deadline = finalize_start + self.finalize_grace;
self.store_phase(TxPhase::CommitInFlight);
match run_statement(&mut **slot, SQL_COMMIT, grace_deadline, self.timer.as_ref()).await {
StmtOutcome::Ack => {
self.store_phase(TxPhase::Done);
release_to_pool(&mut slot);
Ok(TransactionOutcome::Committed)
}
StmtOutcome::Deadline => {
self.detach_slot(&mut slot);
Err(TransactionError::CommitUncertain { datasource })
}
StmtOutcome::Failed(failure) => match commit_disposition(&failure) {
CommitDisposition::Lost => {
self.detach_slot(&mut slot);
Err(TransactionError::CommitUncertain { datasource })
}
CommitDisposition::Rejected { reason } => {
match run_statement(
&mut **slot,
SQL_ROLLBACK,
grace_deadline,
self.timer.as_ref(),
)
.await
{
StmtOutcome::Ack => {
self.store_phase(TxPhase::Done);
release_to_pool(&mut slot);
Err(TransactionError::CommitFailed { datasource, reason })
}
StmtOutcome::Deadline | StmtOutcome::Failed(_) => {
self.detach_slot(&mut slot);
tracing::warn!(
datasource = %self.datasource,
"COMMIT was rejected and the cleanup ROLLBACK was \
not acknowledged; the connection is detached and \
the typed CommitFailed stands"
);
Err(TransactionError::CommitFailed { datasource, reason })
}
}
}
},
}
}
async fn rollback_inner(&self) -> Result<TransactionOutcome, TransactionError> {
let datasource = self.datasource.to_string();
match self.phase() {
TxPhase::Clean => {
debug_assert!(
!self.is_rollback_only(),
"R2 clean rollback with rollback_only set: the flag is unreachable in Clean"
);
let Ok(mut slot) = self.slot.try_lock() else {
tracing::error!(
datasource = %self.datasource,
"clean rollback while the session slot is held; the connection cannot be returned"
);
return Err(TransactionError::RollbackUncertain { datasource });
};
self.store_phase(TxPhase::Done);
release_to_pool(&mut slot);
Ok(TransactionOutcome::RolledBack)
}
TxPhase::BeginPending => {
let Ok(mut slot) = self.slot.try_lock() else {
tracing::error!(
datasource = %self.datasource,
"rollback while the session slot is held; the connection cannot be detached"
);
return Err(TransactionError::RollbackUncertain { datasource });
};
self.detach_slot(&mut slot);
Err(TransactionError::RollbackUncertain { datasource })
}
TxPhase::Open => {
let Ok(mut slot) = self.slot.try_lock() else {
tracing::error!(
datasource = %self.datasource,
"rollback while the session slot is held; the connection cannot be rolled back"
);
return Err(TransactionError::RollbackUncertain { datasource });
};
let finalize_start = self.timer.now();
let grace_deadline = finalize_start + self.finalize_grace;
self.store_phase(TxPhase::RollbackInFlight);
match run_statement(
&mut **slot,
SQL_ROLLBACK,
grace_deadline,
self.timer.as_ref(),
)
.await
{
StmtOutcome::Ack => {
self.store_phase(TxPhase::Done);
release_to_pool(&mut slot);
Ok(TransactionOutcome::RolledBack)
}
StmtOutcome::Deadline | StmtOutcome::Failed(_) => {
self.detach_slot(&mut slot);
Err(TransactionError::RollbackUncertain { datasource })
}
}
}
TxPhase::Detached => {
Err(TransactionError::RollbackUncertain { datasource })
}
TxPhase::CommitInFlight | TxPhase::RollbackInFlight | TxPhase::Done => {
tracing::error!(
datasource = %self.datasource,
"defensive finalization entry: session is already finalizing or done; \
no SQL sent, no detachment performed"
);
Err(TransactionError::RollbackUncertain { datasource })
}
}
}
}
fn release_to_pool(slot: &mut tokio::sync::MutexGuard<'_, Box<dyn TxIo>>) {
let io = std::mem::replace(&mut **slot, Box::new(DetachedIo));
io.release();
}
async fn admission_hygiene(
io: &mut dyn TxIo,
timer: Arc<dyn TxTimer>,
datasource: &str,
max_connections: u32,
block_abs: tokio::time::Instant,
acquire_abs: tokio::time::Instant,
) -> Result<(), TransactionError> {
let hygiene_start = timer.now();
let result = tokio::select! {
biased;
_ = timer.sleep_until(block_abs) => {
if acquire_abs < block_abs {
Err(TransactionError::PoolExhausted {
datasource: datasource.to_owned(),
max_connections,
waited_ms: elapsed_ms(timer.as_ref(), hygiene_start),
})
} else {
Err(TransactionError::Timeout {
datasource: datasource.to_owned(),
elapsed_ms: elapsed_ms(timer.as_ref(), hygiene_start),
})
}
}
_ = timer.sleep_until(acquire_abs) => Err(TransactionError::PoolExhausted {
datasource: datasource.to_owned(),
max_connections,
waited_ms: elapsed_ms(timer.as_ref(), hygiene_start),
}),
ack = io.exec(SQL_ROLLBACK) => match ack {
Ok(()) => Ok(()),
Err(_) => Err(TransactionError::RollbackUncertain {
datasource: datasource.to_owned(),
}),
},
};
match result {
Ok(()) => Ok(()),
Err(error) => {
io.detach();
Err(error)
}
}
}
impl Drop for SqlTxSession {
fn drop(&mut self) {
if matches!(self.phase(), TxPhase::Done | TxPhase::Detached) {
return;
}
match self.slot.try_lock() {
Ok(mut slot) => {
slot.detach();
let _ = std::mem::replace(&mut *slot, Box::new(DetachedIo));
}
Err(_) => {
tracing::error!(
datasource = %self.datasource,
"session dropped while its statement slot is held; \
the connection cannot be detached from here"
);
}
}
}
}
impl TransactionSession for SqlTxSession {
fn datasource(&self) -> &str {
&self.datasource
}
fn state(&self) -> TransactionState {
project(self.phase())
}
fn begin(&self) -> BeginFuture<'_> {
Box::pin(self.begin_inner())
}
fn set_rollback_only(&self) {
self.rollback_only.store(true, Ordering::Relaxed);
}
fn is_rollback_only(&self) -> bool {
self.rollback_only.load(Ordering::Relaxed)
}
fn commit(&self) -> FinalizeFuture<'_> {
Box::pin(self.commit_inner())
}
fn rollback(&self) -> FinalizeFuture<'_> {
Box::pin(self.rollback_inner())
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Mutex as SyncMutex;
use std::task::{Context, Poll, Waker};
use super::*;
use futures::task::noop_waker;
const ACQUIRE: Duration = Duration::from_millis(50);
const GRACE: Duration = Duration::from_secs(5);
const MAX_CONNECTIONS: u32 = 4;
#[derive(Debug, Clone)]
enum Scripted {
Ack,
Pending,
Fail(TxIoFailure),
}
#[derive(Debug, Default)]
struct FakeShared {
responses: HashMap<&'static str, Scripted>,
issued: Vec<&'static str>,
detached: bool,
released: bool,
}
struct FakeIo {
shared: Arc<SyncMutex<FakeShared>>,
}
impl FakeIo {
fn channel() -> (Box<dyn TxIo>, Arc<SyncMutex<FakeShared>>) {
let shared = Arc::new(SyncMutex::new(FakeShared::default()));
(
Box::new(FakeIo {
shared: Arc::clone(&shared),
}),
shared,
)
}
fn script(sql: &'static str, answer: Scripted, shared: &SyncMutex<FakeShared>) {
shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.responses
.insert(sql, answer);
}
}
impl TxIo for FakeIo {
fn exec(&mut self, sql: &'static str) -> ExecFuture<'_> {
Box::pin(async move {
self.shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.issued
.push(sql);
let scripted = self
.shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.responses
.get(&sql)
.cloned()
.unwrap_or(Scripted::Ack);
match scripted {
Scripted::Ack => Ok(()),
Scripted::Pending => std::future::pending().await,
Scripted::Fail(failure) => Err(failure),
}
})
}
fn detach(&mut self) {
self.shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.detached = true;
}
fn release(self: Box<Self>) {
self.shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.released = true;
}
}
fn issued_of(shared: &SyncMutex<FakeShared>) -> Vec<&'static str> {
shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.issued
.clone()
}
fn is_detached(shared: &SyncMutex<FakeShared>) -> bool {
shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.detached
}
fn is_released(shared: &SyncMutex<FakeShared>) -> bool {
shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.released
}
fn db_error(severity: DbSeverity, code: &str, message: &str) -> TxIoFailure {
TxIoFailure::Database(DbAnswer {
severity,
code: Some(code.to_owned()),
message: message.to_owned(),
})
}
fn test_session(io: Box<dyn TxIo>, timer: Arc<dyn TxTimer>) -> SqlTxSession {
SqlTxSession::with_io("pg", io, timer, ACQUIRE, GRACE, MAX_CONNECTIONS)
}
fn poll_once_pending<F: Future>(pinned: &mut Pin<&mut F>) -> bool {
let waker: Waker = noop_waker();
let mut cx = Context::from_waker(&waker);
matches!(pinned.as_mut().poll(&mut cx), Poll::Pending)
}
struct AlwaysElapsed;
impl TxTimer for AlwaysElapsed {
fn now(&self) -> tokio::time::Instant {
tokio::time::Instant::now()
}
fn sleep_until(
&self,
_deadline: tokio::time::Instant,
) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
Box::pin(std::future::ready(()))
}
}
#[test]
fn phase_projection_matches_604c_table() {
let rows = [
(TxPhase::Clean, TransactionState::Fresh),
(TxPhase::BeginPending, TransactionState::Fresh),
(TxPhase::Open, TransactionState::Active),
(TxPhase::CommitInFlight, TransactionState::Finalizing),
(TxPhase::RollbackInFlight, TransactionState::Finalizing),
(TxPhase::Done, TransactionState::Done),
(TxPhase::Detached, TransactionState::Detached),
];
for (phase, expected) in rows {
assert_eq!(
project(phase),
expected,
"604c §A projection mismatch for {phase:?}"
);
}
}
#[tokio::test]
async fn begin_is_idempotent_when_open() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("first begin acknowledges");
assert_eq!(session.state(), TransactionState::Active);
let second = session.begin().await;
assert_eq!(second, Ok(()), "begin on Open is an idempotent no-op");
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN],
"the idempotent call must not send BEGIN again"
);
assert_eq!(session.state(), TransactionState::Active);
}
#[tokio::test]
async fn begin_from_non_clean_phases_is_aborted() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
session.rollback().await.expect("clean rollback");
let error = session.begin().await.expect_err("begin from Done aborts");
assert_eq!(
error,
TransactionError::SessionAborted {
datasource: "pg".to_owned()
}
);
assert!(
issued_of(&shared).is_empty(),
"the aborted begin must send no SQL"
);
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
{
let mut begin = std::pin::pin!(session.begin());
assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
}
let error = session
.begin()
.await
.expect_err("begin from BeginPending aborts");
assert_eq!(
error,
TransactionError::SessionAborted {
datasource: "pg".to_owned()
}
);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN],
"the aborted attempt must not send another BEGIN"
);
}
#[tokio::test(start_paused = true)]
async fn begin_racing_detach_never_overwrites_detached() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
let mut first = std::pin::pin!(session.begin());
assert!(poll_once_pending(&mut first), "the BEGIN write must stall");
assert_eq!(issued_of(&shared), vec![SQL_BEGIN]);
let racing = session.begin().await;
assert_eq!(
racing,
Err(TransactionError::Busy {
datasource: "pg".to_owned()
}),
"the raced begin is rejected on the held slot before any phase read"
);
let first_outcome = first.await;
assert_eq!(
first_outcome,
Err(TransactionError::PoolExhausted {
datasource: "pg".to_owned(),
max_connections: MAX_CONNECTIONS,
waited_ms: ACQUIRE.as_millis() as u64,
}),
"the stalled begin detaches per §B.4"
);
assert_eq!(session.state(), TransactionState::Detached);
let third = session.begin().await;
assert_eq!(
third,
Err(TransactionError::SessionAborted {
datasource: "pg".to_owned()
}),
"begin on a Detached session aborts, never overwrites the terminal phase"
);
assert_eq!(session.state(), TransactionState::Detached);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN],
"neither raced begin sent SQL"
);
}
#[tokio::test(start_paused = true)]
async fn begin_own_timeout_reports_pool_exhausted_detaches() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
let error = session.begin().await.expect_err("begin deadline");
assert_eq!(
error,
TransactionError::PoolExhausted {
datasource: "pg".to_owned(),
max_connections: MAX_CONNECTIONS,
waited_ms: ACQUIRE.as_millis() as u64,
}
);
assert!(
ACQUIRE > Duration::ZERO,
"the begin deadline must be a positive bound the wait is measured against"
);
assert_eq!(session.state(), TransactionState::Detached);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN],
"no cleanup SQL after the begin timeout"
);
assert!(is_detached(&shared), "the begin timeout detaches");
assert!(
!is_released(&shared),
"a detached connection is never re-pooled"
);
let result = session.rollback().await;
assert_eq!(
result,
Err(TransactionError::RollbackUncertain {
datasource: "pg".to_owned()
})
);
assert_eq!(issued_of(&shared), vec![SQL_BEGIN], "R1 sends no SQL");
}
#[tokio::test]
async fn begin_driver_error_detaches_reports_rollback_uncertain() {
let (io, shared) = FakeIo::channel();
FakeIo::script(
SQL_BEGIN,
Scripted::Fail(db_error(DbSeverity::Other, "08006", "connection failure")),
&shared,
);
let session = test_session(io, Arc::new(TokioTimer));
let error = session.begin().await.expect_err("begin driver error");
assert_eq!(
error,
TransactionError::RollbackUncertain {
datasource: "pg".to_owned()
}
);
assert_eq!(session.state(), TransactionState::Detached);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN],
"no cleanup SQL after a begin driver error"
);
assert!(is_detached(&shared));
}
#[tokio::test]
async fn injected_timer_times_out_begin() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(AlwaysElapsed));
let error = session.begin().await.expect_err("injected deadline");
assert_eq!(
error,
TransactionError::PoolExhausted {
datasource: "pg".to_owned(),
max_connections: MAX_CONNECTIONS,
waited_ms: 0,
}
);
assert_eq!(session.state(), TransactionState::Detached);
assert!(
issued_of(&shared).is_empty(),
"an already-elapsed deadline cancels the write before the driver sees it"
);
assert!(is_detached(&shared));
}
#[tokio::test]
async fn transacted_commit_classifier_table() {
let rows: Vec<(&str, TxIoFailure, TransactionError, bool)> = vec![
(
"23503 integrity violation",
db_error(DbSeverity::Error, "23503", "foreign key violated"),
TransactionError::CommitFailed {
datasource: "pg".to_owned(),
reason: "SQLSTATE 23503: foreign key violated".to_owned(),
},
true,
),
(
"40001 transaction abort class",
db_error(DbSeverity::Error, "40001", "could not serialize access"),
TransactionError::CommitFailed {
datasource: "pg".to_owned(),
reason: "SQLSTATE 40001: could not serialize access".to_owned(),
},
true,
),
(
"57P01 backend fatal",
db_error(
DbSeverity::Other,
"57P01",
"terminating connection due to administrator command",
),
TransactionError::CommitUncertain {
datasource: "pg".to_owned(),
},
false,
),
(
"57014 query canceled (class 57)",
db_error(
DbSeverity::Error,
"57014",
"canceling statement due to user request",
),
TransactionError::CommitUncertain {
datasource: "pg".to_owned(),
},
false,
),
(
"08006 connection failure (class 08)",
db_error(DbSeverity::Error, "08006", "connection failure"),
TransactionError::CommitUncertain {
datasource: "pg".to_owned(),
},
false,
),
(
"io transport error",
TxIoFailure::Lost,
TransactionError::CommitUncertain {
datasource: "pg".to_owned(),
},
false,
),
];
for (name, commit_failure, expected, cleanup_issued) in rows {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_COMMIT, Scripted::Fail(commit_failure), &shared);
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
assert_eq!(session.state(), TransactionState::Active, "row {name}");
let result = session.commit().await;
assert_eq!(result, Err(expected), "row {name}");
let expected_issued = if cleanup_issued {
vec![SQL_BEGIN, SQL_COMMIT, SQL_ROLLBACK]
} else {
vec![SQL_BEGIN, SQL_COMMIT]
};
assert_eq!(issued_of(&shared), expected_issued, "row {name}");
if cleanup_issued {
assert!(
is_released(&shared),
"cleanup acknowledged: connection returned to the pool (row {name})"
);
assert!(
!is_detached(&shared),
"no detach after an acknowledged cleanup (row {name})"
);
assert_eq!(session.state(), TransactionState::Done, "row {name}");
} else {
assert!(is_detached(&shared), "detach immediately (row {name})");
assert!(
!is_released(&shared),
"no rollback claim and no re-pool (row {name})"
);
assert_eq!(session.state(), TransactionState::Detached, "row {name}");
}
}
}
#[tokio::test]
async fn commit_requires_open_sends_no_sql() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
let error = session
.commit()
.await
.expect_err("commit from Clean aborts");
assert_eq!(
error,
TransactionError::SessionAborted {
datasource: "pg".to_owned()
}
);
assert!(
issued_of(&shared).is_empty(),
"the aborted commit must send no SQL"
);
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
session.rollback().await.expect("rollback acknowledges");
let error = session.commit().await.expect_err("commit from Done aborts");
assert_eq!(
error,
TransactionError::SessionAborted {
datasource: "pg".to_owned()
}
);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN, SQL_ROLLBACK],
"the aborted commit must send no SQL"
);
}
#[tracing_test::traced_test]
#[tokio::test]
async fn defensive_finalization_entry_logs_error_without_detach_claim() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_COMMIT, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
{
let mut commit = std::pin::pin!(session.commit());
assert!(poll_once_pending(&mut commit), "COMMIT must stay pending");
assert_eq!(session.state(), TransactionState::Finalizing);
}
let result = session.rollback().await;
assert_eq!(
result,
Err(TransactionError::RollbackUncertain {
datasource: "pg".to_owned()
}),
"defensive Finalizing entry returns Err, never an outcome claim"
);
assert_eq!(
session.state(),
TransactionState::Finalizing,
"the defensive entry changes no phase"
);
assert!(logs_contain("defensive finalization entry"));
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN, SQL_COMMIT],
"no SQL on the defensive path"
);
assert!(
!is_detached(&shared),
"the defensive entry must NOT claim detachment happened"
);
assert!(!is_released(&shared));
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
assert_eq!(session.rollback().await, Ok(TransactionOutcome::RolledBack));
let result = session.rollback().await;
assert_eq!(
result,
Err(TransactionError::RollbackUncertain {
datasource: "pg".to_owned()
}),
"defensive Done entry returns Err, never an outcome claim"
);
assert_eq!(
session.state(),
TransactionState::Done,
"the defensive entry changes no phase"
);
assert!(logs_contain("defensive finalization entry"));
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN, SQL_ROLLBACK],
"no SQL on the defensive path"
);
assert!(
!is_detached(&shared),
"the Done entry adds no detach: the connection was already released by the first rollback"
);
}
#[tokio::test]
async fn r2_clean_rollback_returns_connection_clean() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
assert_eq!(session.state(), TransactionState::Fresh);
assert!(!session.is_rollback_only());
let result = session.rollback().await;
assert_eq!(result, Ok(TransactionOutcome::RolledBack));
assert_eq!(session.state(), TransactionState::Done);
assert!(
issued_of(&shared).is_empty(),
"R2 sends no SQL: nothing was begun"
);
assert!(
is_released(&shared),
"the connection is returned to the pool clean"
);
assert!(!is_detached(&shared));
}
#[tokio::test]
async fn rollback_only_flag_and_open_rollback_acks() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
assert!(!session.is_rollback_only());
session.set_rollback_only();
assert!(session.is_rollback_only());
session.begin().await.expect("BEGIN must acknowledge");
let result = session.rollback().await;
assert_eq!(result, Ok(TransactionOutcome::RolledBack));
assert_eq!(issued_of(&shared), vec![SQL_BEGIN, SQL_ROLLBACK]);
assert!(
session.is_rollback_only(),
"finalization does not clear the flag"
);
}
#[tokio::test]
async fn busy_slot_try_lock_reports_busy() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
let held = session
.slot
.try_lock()
.expect("the slot must be free before the fixture holds it");
let error = session.begin().await.expect_err("held slot");
assert_eq!(
error,
TransactionError::Busy {
datasource: "pg".to_owned()
}
);
assert!(
issued_of(&shared).is_empty(),
"a busy-rejected begin sends no SQL"
);
drop(held);
session.begin().await.expect("begin after the slot frees");
assert_eq!(issued_of(&shared), vec![SQL_BEGIN]);
}
#[tokio::test]
async fn transacted_hygiene_unacknowledged() {
let (mut io, shared) = FakeIo::channel();
FakeIo::script(
SQL_ROLLBACK,
Scripted::Fail(db_error(DbSeverity::Error, "08006", "connection failure")),
&shared,
);
let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
let now = timer.now();
let error = admission_hygiene(
&mut *io,
Arc::clone(&timer),
"pg",
MAX_CONNECTIONS,
now + Duration::from_secs(60),
now + ACQUIRE,
)
.await
.expect_err("unacknowledged hygiene");
assert_eq!(
error,
TransactionError::RollbackUncertain {
datasource: "pg".to_owned()
}
);
assert_eq!(
issued_of(&shared),
vec![SQL_ROLLBACK],
"exactly one ROLLBACK attempt, BEGIN never sent"
);
assert!(is_detached(&shared), "unacknowledged hygiene detaches");
}
#[tokio::test]
async fn sqlite_pool_begin_commit_and_rollback_smoke() {
sqlx::any::install_default_drivers();
let pool = sqlx::any::AnyPoolOptions::new() .max_connections(2)
.connect("sqlite::memory:")
.await
.expect("in-memory sqlite pool");
let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
let conn = pool.acquire().await.expect("first connection"); let session = SqlTxSession::with_io(
"pg",
Box::new(AnyConnIo { conn: Some(conn) }),
Arc::clone(&timer),
ACQUIRE,
GRACE,
2,
);
session.begin().await.expect("real BEGIN");
assert_eq!(session.state(), TransactionState::Active);
let outcome = session.commit().await.expect("real COMMIT");
assert_eq!(outcome, TransactionOutcome::Committed);
assert_eq!(session.state(), TransactionState::Done);
let conn = pool.acquire().await.expect("second connection"); let session = SqlTxSession::with_io(
"pg",
Box::new(AnyConnIo { conn: Some(conn) }),
timer,
ACQUIRE,
GRACE,
2,
);
session.begin().await.expect("real BEGIN");
let outcome = session.rollback().await.expect("real ROLLBACK");
assert_eq!(outcome, TransactionOutcome::RolledBack);
assert_eq!(session.state(), TransactionState::Done);
sqlx::query("SELECT 1")
.execute(&pool)
.await
.expect("pool usable after finalization");
pool.close().await;
}
#[tokio::test]
async fn forced_drop_detaches_without_sql() {
assert_forced_drop_from_open().await;
}
#[tokio::test]
async fn transacted_forced_drop_inline() {
assert_forced_drop_from_open().await;
}
async fn assert_forced_drop_from_open() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
assert_eq!(session.state(), TransactionState::Active);
drop(session);
assert_eq!(issued_of(&shared), vec![SQL_BEGIN], "R0 sends no SQL");
assert!(is_detached(&shared), "R0 detaches synchronously");
assert!(!is_released(&shared), "R0 never returns the connection");
}
#[tokio::test]
async fn transacted_begin_pending_deadline() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
{
let mut begin = std::pin::pin!(session.begin());
assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
assert_eq!(
session.state(),
TransactionState::Fresh,
"BeginPending projects lossily onto Fresh"
);
}
let result = session.rollback().await;
assert_eq!(
result,
Err(TransactionError::RollbackUncertain {
datasource: "pg".to_owned()
}),
"R3: protocol position unknown, nothing acknowledged"
);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN],
"R3 sends no SQL: no ROLLBACK on an unacknowledged BEGIN"
);
assert!(is_detached(&shared), "R3 detaches the connection");
assert!(
!is_released(&shared),
"a detached connection is never returned to the pool"
);
assert_eq!(session.state(), TransactionState::Detached);
}
#[tokio::test(start_paused = true)]
async fn transacted_stalled_commit() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_COMMIT, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
let result = session.commit().await;
assert_eq!(
result,
Err(TransactionError::CommitUncertain {
datasource: "pg".to_owned()
}),
"grace elapsed: the commit outcome is uncertain"
);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN, SQL_COMMIT],
"no cleanup ROLLBACK after a stalled COMMIT"
);
assert!(is_detached(&shared), "the grace expiry detaches");
assert!(
!is_released(&shared),
"a detached connection is never re-pooled"
);
assert_eq!(session.state(), TransactionState::Detached);
}
#[tokio::test(start_paused = true)]
async fn transacted_stalled_rollback() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
let result = session.rollback().await;
assert_eq!(
result,
Err(TransactionError::RollbackUncertain {
datasource: "pg".to_owned()
}),
"grace elapsed: the rollback is not acknowledged"
);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN, SQL_ROLLBACK],
"exactly one ROLLBACK attempt within the grace"
);
assert!(is_detached(&shared), "the grace expiry detaches");
assert!(
!is_released(&shared),
"a detached connection is never re-pooled"
);
assert_eq!(session.state(), TransactionState::Detached);
}
#[tracing_test::traced_test]
#[tokio::test(start_paused = true)]
async fn commit_cleanup_unacknowledged_keeps_commit_failed() {
let (io, shared) = FakeIo::channel();
FakeIo::script(
SQL_COMMIT,
Scripted::Fail(db_error(DbSeverity::Error, "23503", "foreign key violated")),
&shared,
);
FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
session.begin().await.expect("BEGIN must acknowledge");
let result = session.commit().await;
assert_eq!(
result,
Err(TransactionError::CommitFailed {
datasource: "pg".to_owned(),
reason: "SQLSTATE 23503: foreign key violated".to_owned(),
}),
"the typed commit failure stands; cleanup uncertainty never replaces it"
);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN, SQL_COMMIT, SQL_ROLLBACK],
"exactly one cleanup ROLLBACK attempt within the remaining grace"
);
assert!(is_detached(&shared), "unacknowledged cleanup detaches");
assert!(
!is_released(&shared),
"the connection is never returned to the pool with unknown state"
);
assert_eq!(session.state(), TransactionState::Detached);
assert!(
logs_contain("not acknowledged"),
"the cleanup uncertainty is observable through the warn! log"
);
}
#[tokio::test(start_paused = true)]
async fn hygiene_deadline_reports_timeout_elapsed_from_start() {
let (mut io, shared) = FakeIo::channel();
FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
let now = timer.now();
let block_deadline = Duration::from_millis(10);
let error = admission_hygiene(
&mut *io,
Arc::clone(&timer),
"pg",
MAX_CONNECTIONS,
now + block_deadline,
now + Duration::from_secs(60),
)
.await
.expect_err("block deadline elapses while hygiene is pending");
assert_eq!(
error,
TransactionError::Timeout {
datasource: "pg".to_owned(),
elapsed_ms: block_deadline.as_millis() as u64,
},
"elapsed must measure from the hygiene start (> 0), not from the deadline"
);
assert_eq!(
issued_of(&shared),
vec![SQL_ROLLBACK],
"exactly one ROLLBACK attempt, BEGIN never sent"
);
assert!(
is_detached(&shared),
"deadline expiry during hygiene detaches"
);
}
async fn hygiene_deadline_case(block: Duration, acquire: Duration) -> TransactionError {
let (mut io, shared) = FakeIo::channel();
FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
let now = timer.now();
let error = admission_hygiene(
&mut *io,
Arc::clone(&timer),
"pg",
MAX_CONNECTIONS,
now + block,
now + acquire,
)
.await
.expect_err("hygiene stays pending past both deadlines");
assert_eq!(
issued_of(&shared),
vec![SQL_ROLLBACK],
"exactly one ROLLBACK attempt, BEGIN never sent"
);
assert!(
is_detached(&shared),
"deadline expiry during hygiene detaches"
);
assert!(
!is_released(&shared),
"a detached connection is never re-pooled"
);
error
}
#[tokio::test(start_paused = true)]
async fn transacted_hygiene_deadline_expiry() {
let cases: [(&str, Duration, Duration, TransactionError); 3] = [
(
"acquire-first: acquire 10 ms < block 60 s",
Duration::from_secs(60),
Duration::from_millis(10),
TransactionError::PoolExhausted {
datasource: "pg".to_owned(),
max_connections: MAX_CONNECTIONS,
waited_ms: 10,
},
),
(
"block-first: block 10 ms < acquire 60 s",
Duration::from_millis(10),
Duration::from_secs(60),
TransactionError::Timeout {
datasource: "pg".to_owned(),
elapsed_ms: 10,
},
),
(
"tie: both 10 ms — the biased block arm wins",
Duration::from_millis(10),
Duration::from_millis(10),
TransactionError::Timeout {
datasource: "pg".to_owned(),
elapsed_ms: 10,
},
),
];
for (label, block, acquire, expected) in cases {
let error = hygiene_deadline_case(block, acquire).await;
assert_eq!(error, expected, "{label}");
}
}
#[tokio::test(start_paused = true)]
async fn open_future_dropped_mid_hygiene_detaches_at_checkout() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
let now = timer.now();
{
let mut open = std::pin::pin!(SqlTxSession::admit(
"pg".into(),
CheckedOutBackend::arm(io),
now + Duration::from_secs(60),
now + Duration::from_secs(60),
ACQUIRE,
MAX_CONNECTIONS,
Arc::clone(&timer),
));
assert!(poll_once_pending(&mut open), "hygiene must stay pending");
assert_eq!(
issued_of(&shared),
vec![SQL_ROLLBACK],
"exactly one ROLLBACK attempt, BEGIN never sent"
);
}
assert!(
is_detached(&shared),
"a drop mid-hygiene detaches (R0 arms at checkout)"
);
assert!(
!is_released(&shared),
"the detached connection is never re-pooled"
);
}
#[tokio::test(start_paused = true)]
async fn transacted_acquire_deadline_first() {
let error = hygiene_deadline_case(Duration::from_secs(60), Duration::from_millis(10)).await;
match error {
TransactionError::PoolExhausted {
datasource,
max_connections,
waited_ms,
} => {
assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
assert_eq!(max_connections, MAX_CONNECTIONS);
assert_eq!(waited_ms, 10, "waited_ms measures from the hygiene start");
}
other => panic!("expected typed PoolExhausted, got {other:?}"),
}
}
#[tokio::test(start_paused = true)]
async fn transacted_block_deadline_first() {
let error = hygiene_deadline_case(Duration::from_secs(30), Duration::from_secs(60)).await;
assert_eq!(
error,
TransactionError::Timeout {
datasource: "pg".to_owned(),
elapsed_ms: 30_000,
},
"elapsed is measured from block entry, not from the deadline"
);
}
#[tokio::test(start_paused = true)]
async fn transacted_deadline_tie() {
let error = hygiene_deadline_case(Duration::from_secs(30), Duration::from_secs(30)).await;
assert_eq!(
error,
TransactionError::Timeout {
datasource: "pg".to_owned(),
elapsed_ms: 30_000,
},
"the tie resolves to the block-deadline error, never PoolExhausted"
);
}
#[tokio::test(start_paused = true)]
async fn transacted_deadline_both_elapsed_at_first_poll() {
async fn case(block: Duration, acquire: Duration) -> TransactionError {
let (mut io, shared) = FakeIo::channel();
FakeIo::script(SQL_ROLLBACK, Scripted::Pending, &shared);
let timer: Arc<dyn TxTimer> = Arc::new(TokioTimer);
let now = timer.now();
let hygiene = std::pin::pin!(admission_hygiene(
&mut *io,
Arc::clone(&timer),
"pg",
MAX_CONNECTIONS,
now + block,
now + acquire,
));
tokio::time::sleep(block.max(acquire) + Duration::from_secs(1)).await;
let error = hygiene.await.expect_err("both deadlines are spent");
assert!(
issued_of(&shared).is_empty(),
"the race resolved before any I/O was polled"
);
assert!(is_detached(&shared), "the losing deadline detaches");
error
}
let error = case(Duration::from_secs(60), Duration::from_millis(10)).await;
match error {
TransactionError::PoolExhausted {
datasource,
max_connections,
..
} => {
assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
assert_eq!(max_connections, MAX_CONNECTIONS);
}
other => panic!(
"acquire_abs < block_abs with both elapsed must report PoolExhausted, got {other:?}"
),
}
let error = case(Duration::from_millis(10), Duration::from_millis(10)).await;
assert!(
matches!(error, TransactionError::Timeout { .. }),
"equal instants report Timeout on the tie, got {error:?}"
);
}
#[tokio::test]
async fn transacted_open_race_both_deadlines_elapsed_at_first_poll() {
sqlx::any::install_default_drivers();
let pool = sqlx::any::AnyPoolOptions::new() .max_connections(2)
.connect("sqlite::memory:")
.await
.expect("in-memory sqlite pool");
let timer: Arc<dyn TxTimer> = Arc::new(AlwaysElapsed);
let now = timer.now();
let open = SqlTxSession::open(
"pg",
&pool,
now + Duration::from_secs(60),
Duration::from_millis(10),
Arc::clone(&timer),
)
.await;
let error = match open {
Err(error) => error,
Ok(_) => panic!("both admission deadlines are spent"),
};
match error {
TransactionError::PoolExhausted { datasource, .. } => {
assert_eq!(datasource, "pg", "PoolExhausted names the datasource");
}
other => panic!(
"acquire_abs < block_abs with both elapsed must report PoolExhausted, got {other:?}"
),
}
let open = SqlTxSession::open(
"pg",
&pool,
now + Duration::from_millis(10),
Duration::from_millis(10),
timer,
)
.await;
let error = match open {
Err(error) => error,
Ok(_) => panic!("both admission deadlines are spent"),
};
assert!(
matches!(error, TransactionError::Timeout { .. }),
"equal instants report Timeout on the tie, got {error:?}"
);
}
#[tokio::test]
async fn forced_drop_from_clean_detaches_without_sql() {
let (io, shared) = FakeIo::channel();
let session = test_session(io, Arc::new(TokioTimer));
assert_eq!(session.state(), TransactionState::Fresh);
drop(session);
assert!(issued_of(&shared).is_empty(), "R0 from Clean sends no SQL");
assert!(is_detached(&shared), "R0 detaches synchronously");
assert!(!is_released(&shared), "R0 never returns the connection");
}
#[tokio::test]
async fn forced_drop_from_begin_pending_detaches_without_sql() {
let (io, shared) = FakeIo::channel();
FakeIo::script(SQL_BEGIN, Scripted::Pending, &shared);
let session = test_session(io, Arc::new(TokioTimer));
{
let mut begin = std::pin::pin!(session.begin());
assert!(poll_once_pending(&mut begin), "BEGIN must stay pending");
}
drop(session);
assert_eq!(
issued_of(&shared),
vec![SQL_BEGIN],
"R0 from BeginPending sends no further SQL"
);
assert!(is_detached(&shared), "R0 detaches synchronously");
assert!(!is_released(&shared), "R0 never returns the connection");
}
}