use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use camel_api::CamelError;
use camel_api::Exchange;
use camel_api::OutcomePipeline;
use camel_api::OutcomeSegment;
use camel_api::PipelineOutcome;
use camel_api::TransactionState;
use camel_api::transaction::TransactionError;
use camel_api::transaction::TransactionManager;
use camel_api::transaction::TransactionOutcome;
use camel_api::transaction::TransactionSession;
use camel_api::transaction::join::BlockSession;
use camel_api::transaction::join::JoinScope;
use tokio_util::sync::CancellationToken;
use crate::lifecycle::adapters::route_compiler::CANCEL_TOKEN;
pub const DEFAULT_BLOCK_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Clone)]
pub struct TransactedSegment {
pub datasource: String,
pub block_timeout: Duration,
pub manager: Arc<dyn TransactionManager>,
pub body: OutcomeSegment,
scope_seq: Arc<AtomicU64>,
}
impl TransactedSegment {
#[must_use]
pub fn new(
datasource: impl Into<String>,
manager: Arc<dyn TransactionManager>,
body: OutcomeSegment,
) -> Self {
Self {
datasource: datasource.into(),
block_timeout: DEFAULT_BLOCK_TIMEOUT,
manager,
body,
scope_seq: Arc::new(AtomicU64::new(0)),
}
}
#[must_use]
pub fn with_block_timeout(mut self, block_timeout: Duration) -> Self {
self.block_timeout = block_timeout;
self
}
pub async fn run(&mut self, exchange: Exchange) -> PipelineOutcome {
let scope = JoinScope::new(self.scope_seq.fetch_add(1, Ordering::Relaxed));
self.run_in(exchange, scope).await
}
pub async fn run_with_scope(
&mut self,
exchange: Exchange,
scope: JoinScope,
) -> PipelineOutcome {
self.run_in(exchange, scope).await
}
async fn run_in(&mut self, exchange: Exchange, scope: JoinScope) -> PipelineOutcome {
let entry = tokio::time::Instant::now();
let block_abs = entry + self.block_timeout;
let datasource = self.datasource.clone();
let cancel = CANCEL_TOKEN.try_with(CancellationToken::clone).ok();
let open_start = tokio::time::Instant::now();
let session: Arc<dyn TransactionSession> = tokio::select! {
biased;
opened = self.manager.open_session() => match opened {
Ok(session) => session,
Err(e @ TransactionError::PoolExhausted { .. })
if tokio::time::Instant::now() >= block_abs =>
{
let acquire_abs = open_start + self.manager.acquire_deadline();
if block_abs <= acquire_abs {
return PipelineOutcome::Failed(CamelError::from(timeout_error(
&datasource,
entry,
)));
}
return PipelineOutcome::Failed(CamelError::from(e));
}
Err(e) => return PipelineOutcome::Failed(CamelError::from(e)),
},
_ = tokio::time::sleep_until(block_abs) => {
return PipelineOutcome::Failed(CamelError::from(timeout_error(&datasource, entry)));
}
};
let block_session =
BlockSession::new(self.datasource.as_str(), scope, Arc::clone(&session));
let body_end = tokio::select! {
biased;
_ = tokio::time::sleep_until(block_abs) => BodyEnd::Deadline,
_ = cancelled_or_pending(cancel.as_ref()) => BodyEnd::Cancelled,
outcome = block_session.enter(self.body.run(exchange)) => match outcome {
PipelineOutcome::Failed(e) => BodyEnd::Err(e),
outcome @ (PipelineOutcome::Completed(_) | PipelineOutcome::Stopped(_)) => {
BodyEnd::Ok(Box::new(outcome))
}
},
};
self.finalize(session, body_end, cancel.as_ref(), entry, block_abs)
.await
}
async fn finalize(
&self,
s: Arc<dyn TransactionSession>,
body_end: BodyEnd,
cancel: Option<&CancellationToken>,
entry: tokio::time::Instant,
block_abs: tokio::time::Instant,
) -> PipelineOutcome {
let datasource = self.datasource.clone();
let (mut primary, ok_outcome): (Option<CamelError>, Option<Box<PipelineOutcome>>) =
match body_end {
BodyEnd::Deadline => (Some(timeout_error(&datasource, entry).into()), None),
BodyEnd::Err(e) => (Some(e), None),
BodyEnd::Cancelled => (Some(CamelError::ConsumerStopping), None),
BodyEnd::Ok(_) if s.is_rollback_only() => (
Some(
TransactionError::AbortedByHandledError {
datasource: datasource.clone(),
}
.into(),
),
None,
),
BodyEnd::Ok(outcome) => (None, Some(outcome)),
};
if primary.is_none() && s.state() == TransactionState::Active {
let now = tokio::time::Instant::now();
if cancel.is_some_and(CancellationToken::is_cancelled) || now >= block_abs {
primary = Some(if now >= block_abs {
timeout_error(&datasource, entry).into()
} else {
CamelError::ConsumerStopping
});
} else {
return map_commit(s.commit().await, ok_outcome, &datasource);
}
}
let r = s.rollback().await;
match (primary, r) {
(None, Ok(_)) => {
*ok_outcome.expect("primary None implies the body ended Ok") }
(None, Err(u)) => PipelineOutcome::Failed(CamelError::from(u)),
(Some(p), Ok(_)) => PipelineOutcome::Failed(p),
(Some(p), Err(u)) => {
tracing::warn!(
datasource = %datasource,
cleanup = %u,
primary = %p,
"transacted block cleanup was not acknowledged; the primary error stands"
);
PipelineOutcome::Failed(p)
}
}
}
}
impl OutcomePipeline for TransactedSegment {
fn clone_box(&self) -> Box<dyn OutcomePipeline> {
Box::new(self.clone())
}
fn run<'a>(
&'a mut self,
exchange: Exchange,
) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
Box::pin(TransactedSegment::run(self, exchange))
}
}
enum BodyEnd {
Ok(Box<PipelineOutcome>),
Err(CamelError),
Deadline,
Cancelled,
}
fn timeout_error(datasource: &str, entry: tokio::time::Instant) -> TransactionError {
TransactionError::Timeout {
datasource: datasource.to_owned(),
elapsed_ms: u64::try_from(entry.elapsed().as_millis()).unwrap_or(u64::MAX),
}
}
async fn cancelled_or_pending(cancel: Option<&CancellationToken>) {
match cancel {
Some(token) => token.cancelled().await,
None => std::future::pending::<()>().await,
}
}
fn map_commit(
commit: Result<TransactionOutcome, TransactionError>,
body_outcome: Option<Box<PipelineOutcome>>,
datasource: &str,
) -> PipelineOutcome {
match commit {
Ok(TransactionOutcome::Committed) => {
body_outcome.map(|boxed| *boxed).unwrap_or_else(|| {
tracing::error!(
datasource,
"commit acknowledged but the body outcome was lost; reporting CommitUncertain"
);
PipelineOutcome::Failed(CamelError::Transaction(
TransactionError::CommitUncertain {
datasource: datasource.to_owned(),
},
))
})
}
Ok(outcome) => {
tracing::error!(
datasource,
?outcome,
"commit resolved to a non-Committed outcome; reporting CommitUncertain"
);
PipelineOutcome::Failed(CamelError::Transaction(TransactionError::CommitUncertain {
datasource: datasource.to_owned(),
}))
}
Err(e) => PipelineOutcome::Failed(CamelError::from(e)),
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Poll;
use std::time::Duration;
use camel_api::Message;
use camel_api::transaction::join::current_block_session;
use camel_component_api::test_support::log_capture;
use super::*;
const DS: &str = "pg";
fn ensure_global_tracing_default() {
static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
if INIT.set(()).is_ok() {
let _ = tracing::subscriber::set_global_default(tracing_subscriber::registry());
}
}
struct FakeSession {
commit_result: Result<TransactionOutcome, TransactionError>,
rollback_result: Result<TransactionOutcome, TransactionError>,
state: TransactionState,
rollback_only: AtomicBool,
calls: Mutex<Vec<&'static str>>,
commit_gate: Option<CancellationToken>,
}
impl FakeSession {
fn new(
state: TransactionState,
commit: Result<TransactionOutcome, TransactionError>,
rollback: Result<TransactionOutcome, TransactionError>,
) -> Arc<Self> {
Arc::new(Self {
commit_result: commit,
rollback_result: rollback,
state,
rollback_only: AtomicBool::new(false),
calls: Mutex::new(Vec::new()),
commit_gate: None,
})
}
fn gated(
commit: Result<TransactionOutcome, TransactionError>,
gate: CancellationToken,
) -> Arc<Self> {
Arc::new(Self {
commit_result: commit,
rollback_result: Ok(TransactionOutcome::RolledBack),
state: TransactionState::Active,
rollback_only: AtomicBool::new(false),
calls: Mutex::new(Vec::new()),
commit_gate: Some(gate),
})
}
fn with_flag(self: Arc<Self>) -> Arc<Self> {
self.rollback_only.store(true, Ordering::Relaxed);
self
}
fn record(&self, call: &'static str) {
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(call);
}
fn calls(&self) -> Vec<&'static str> {
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
}
impl TransactionSession for FakeSession {
fn datasource(&self) -> &str {
DS
}
fn state(&self) -> TransactionState {
self.state
}
fn begin(&self) -> camel_api::transaction::BeginFuture<'_> {
Box::pin(std::future::ready(Ok(())))
}
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) -> camel_api::transaction::FinalizeFuture<'_> {
self.record("commit");
let result = self.commit_result.clone();
match self.commit_gate.clone() {
Some(gate) => Box::pin(async move {
gate.cancelled().await;
result
}),
None => Box::pin(std::future::ready(result)),
}
}
fn rollback(&self) -> camel_api::transaction::FinalizeFuture<'_> {
self.record("rollback");
Box::pin(std::future::ready(self.rollback_result.clone()))
}
}
enum OpenScript {
Session(Arc<dyn TransactionSession>),
Fail(TransactionError),
Pending,
FailAfterFirstPoll(TransactionError),
}
struct FakeManager {
script: OpenScript,
acquire_deadline: Duration,
}
impl FakeManager {
fn script(script: OpenScript) -> Self {
Self {
script,
acquire_deadline: Duration::from_secs(5),
}
}
fn with_acquire_deadline(mut self, acquire_deadline: Duration) -> Self {
self.acquire_deadline = acquire_deadline;
self
}
}
impl TransactionManager for FakeManager {
fn datasource(&self) -> &str {
DS
}
fn acquire_deadline(&self) -> Duration {
self.acquire_deadline
}
fn open_session(&self) -> camel_api::transaction::OpenSessionFuture<'_> {
match &self.script {
OpenScript::Session(session) => {
let session = Arc::clone(session);
Box::pin(std::future::ready(Ok(session)))
}
OpenScript::Fail(e) => {
let e = e.clone();
Box::pin(std::future::ready(Err(e)))
}
OpenScript::Pending => Box::pin(std::future::pending()),
OpenScript::FailAfterFirstPoll(e) => {
let e = e.clone();
let mut polled = false;
Box::pin(std::future::poll_fn(move |_cx| {
if polled {
Poll::Ready(Err(e.clone()))
} else {
polled = true;
Poll::Pending
}
}))
}
}
}
}
#[derive(Clone)]
enum BodyScript {
Complete(&'static str),
Stop(&'static str),
Fail,
Hang,
CancelThenComplete(&'static str, CancellationToken),
Observe {
expected_session: Arc<dyn TransactionSession>,
seen: Arc<Mutex<Option<(String, u64)>>>,
},
}
impl OutcomePipeline for BodyScript {
fn clone_box(&self) -> Box<dyn OutcomePipeline> {
Box::new(self.clone())
}
fn run<'a>(
&'a mut self,
_exchange: Exchange,
) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
let script = self.clone();
Box::pin(async move {
match script {
BodyScript::Complete(text) => {
PipelineOutcome::Completed(Exchange::new(Message::new(text)))
}
BodyScript::Stop(text) => {
PipelineOutcome::Stopped(Exchange::new(Message::new(text)))
}
BodyScript::Fail => PipelineOutcome::Failed(CamelError::ProcessorError(
"body failed".to_owned(),
)),
BodyScript::Hang => std::future::pending::<PipelineOutcome>().await,
BodyScript::CancelThenComplete(text, token) => {
token.cancel();
PipelineOutcome::Completed(Exchange::new(Message::new(text)))
}
BodyScript::Observe {
expected_session,
seen,
} => {
let running = current_block_session()
.expect("the body task must see BLOCK_SESSION installed");
assert_eq!(
running.datasource(),
DS,
"the binding names the block datasource"
);
assert!(
Arc::ptr_eq(&running.session(), &expected_session),
"the body must see the block's own session allocation"
);
*seen
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
Some((running.datasource().to_owned(), running.scope().get()));
PipelineOutcome::Completed(Exchange::new(Message::new("observed")))
}
}
})
}
}
fn segment(
manager: FakeManager,
body: BodyScript,
block_timeout: Duration,
) -> TransactedSegment {
TransactedSegment::new(DS, Arc::new(manager), OutcomeSegment::new(Box::new(body)))
.with_block_timeout(block_timeout)
}
fn session_manager(session: Arc<FakeSession>) -> FakeManager {
FakeManager::script(OpenScript::Session(session))
}
fn tx_err(e: &CamelError) -> &TransactionError {
match e {
CamelError::Transaction(tx) => tx,
other => panic!("expected a Transaction error, got {other:?}"),
}
}
fn assert_failed_timeout(outcome: PipelineOutcome, min_elapsed_ms: u64) {
let PipelineOutcome::Failed(e) = outcome else {
panic!("expected Failed, got {outcome:?}");
};
match tx_err(&e) {
TransactionError::Timeout {
datasource,
elapsed_ms,
} => {
assert_eq!(datasource, DS);
assert!(
*elapsed_ms >= min_elapsed_ms,
"Timeout.elapsed_ms must measure from block entry: {elapsed_ms}"
);
}
other => panic!("expected Timeout, got {other:?}"),
}
}
fn assert_failed_tx(outcome: PipelineOutcome, expected: &TransactionError) {
let PipelineOutcome::Failed(e) = outcome else {
panic!("expected Failed, got {outcome:?}");
};
assert_eq!(tx_err(&e), expected, "typed primary mismatch");
}
fn assert_failed_processor(outcome: PipelineOutcome) {
let PipelineOutcome::Failed(CamelError::ProcessorError(message)) = outcome else {
panic!("expected Failed(ProcessorError), got {outcome:?}");
};
assert_eq!(message, "body failed", "the body error must stay primary");
}
fn assert_completed_text(outcome: PipelineOutcome, text: &str) {
let PipelineOutcome::Completed(ex) = outcome else {
panic!("expected Completed, got {outcome:?}");
};
assert_eq!(ex.input.body.as_text(), Some(text));
}
fn assert_stopped_text(outcome: PipelineOutcome, text: &str) {
let PipelineOutcome::Stopped(ex) = outcome else {
panic!("expected Stopped, got {outcome:?}");
};
assert_eq!(ex.input.body.as_text(), Some(text));
}
fn committed() -> Result<TransactionOutcome, TransactionError> {
Ok(TransactionOutcome::Committed)
}
fn rolled_back() -> Result<TransactionOutcome, TransactionError> {
Ok(TransactionOutcome::RolledBack)
}
fn uncertain() -> Result<TransactionOutcome, TransactionError> {
Err(TransactionError::RollbackUncertain {
datasource: DS.to_owned(),
})
}
enum Assert {
Completed,
Stopped,
}
#[tokio::test]
async fn transacted_fresh_rollback_precedence() {
let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Hang,
Duration::from_millis(30),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_timeout(outcome, 30);
assert_eq!(
session.calls(),
vec!["rollback"],
"commit is never consulted on a Deadline body"
);
let session = FakeSession::new(TransactionState::Fresh, committed(), uncertain());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Hang,
Duration::from_millis(30),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_timeout(outcome, 30);
assert_eq!(session.calls(), vec!["rollback"]);
let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Fail,
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_processor(outcome);
assert_eq!(
session.calls(),
vec!["rollback"],
"commit is never consulted on an Err body"
);
let session = FakeSession::new(TransactionState::Active, committed(), uncertain());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Fail,
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_processor(outcome);
assert_eq!(session.calls(), vec!["rollback"]);
let session = FakeSession::new(TransactionState::Fresh, committed(), uncertain());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Complete("ok"),
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_tx(
outcome,
&TransactionError::RollbackUncertain {
datasource: DS.to_owned(),
},
);
assert_eq!(
session.calls(),
vec!["rollback"],
"Fresh is not Active: the R7 gate must not reach commit"
);
let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Complete("ok"),
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_completed_text(outcome, "ok");
assert_eq!(session.calls(), vec!["rollback"]);
let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Stop("halted"),
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_stopped_text(outcome, "halted");
assert_eq!(session.calls(), vec!["rollback"]);
}
#[tokio::test]
async fn transacted_r7_commits_active_body() {
for (body, text, expect) in [
(BodyScript::Complete("ok"), "ok", Assert::Completed),
(BodyScript::Stop("halted"), "halted", Assert::Stopped),
] {
let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
let mut seg = segment(
session_manager(session.clone()),
body,
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
match expect {
Assert::Completed => assert_completed_text(outcome, text),
Assert::Stopped => assert_stopped_text(outcome, text),
}
assert_eq!(
session.calls(),
vec!["commit"],
"R7: exactly one COMMIT, no rollback"
);
}
}
#[tokio::test]
async fn transacted_r6_cutoff_cancels_before_commit() {
let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
let token = CancellationToken::new();
let mut seg = segment(
session_manager(session.clone()),
BodyScript::CancelThenComplete("ok", token.clone()),
Duration::from_secs(1),
);
let outcome = CANCEL_TOKEN
.scope(token, async move {
seg.run(Exchange::new(Message::new("m"))).await
})
.await;
let PipelineOutcome::Failed(e) = outcome else {
panic!("expected Failed, got {outcome:?}");
};
assert!(
matches!(e, CamelError::ConsumerStopping),
"R6 cutoff failure with the deadline unelapsed is the cancellation error, got {e:?}"
);
assert_eq!(
session.calls(),
vec!["rollback"],
"R6: COMMIT is never sent after a failed cutoff"
);
}
#[tokio::test]
async fn transacted_flag_only_rolls_back_ok_body() {
let session =
FakeSession::new(TransactionState::Active, committed(), rolled_back()).with_flag();
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Complete("ok"),
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_tx(
outcome,
&TransactionError::AbortedByHandledError {
datasource: DS.to_owned(),
},
);
assert_eq!(
session.calls(),
vec!["rollback"],
"R4: the flag alone forbids COMMIT"
);
}
#[tokio::test]
async fn transacted_deadline_tie_selects_timeout() {
let session = FakeSession::new(TransactionState::Active, committed(), rolled_back());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Complete("fast"),
Duration::ZERO,
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_timeout(outcome, 0);
assert_eq!(
session.calls(),
vec!["rollback"],
"commit is never consulted on a Deadline body"
);
}
#[tokio::test]
async fn transacted_cancelled_body_rolls_back_clean() {
let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
let token = CancellationToken::new();
token.cancel(); let mut seg = segment(
session_manager(session.clone()),
BodyScript::Hang,
Duration::from_secs(1),
);
let outcome = CANCEL_TOKEN
.scope(token, async move {
seg.run(Exchange::new(Message::new("m"))).await
})
.await;
let PipelineOutcome::Failed(e) = outcome else {
panic!("expected Failed, got {outcome:?}");
};
assert!(
matches!(e, CamelError::ConsumerStopping),
"a cancelled body race is the cancellation error, never Timeout, got {e:?}"
);
assert_eq!(
session.calls(),
vec!["rollback"],
"cancellation rolls back through the session's clean R2 path"
);
}
#[tokio::test]
async fn transacted_stalled_rollback_logs_cleanup_context() {
ensure_global_tracing_default();
let session = FakeSession::new(TransactionState::Active, committed(), uncertain());
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Hang,
Duration::from_millis(30),
);
let (outcome, captured) =
log_capture::capture_logs_async(seg.run(Exchange::new(Message::new("m")))).await;
assert_failed_timeout(outcome, 30);
assert_eq!(
session.calls(),
vec!["rollback"],
"commit is never consulted on a Deadline body"
);
assert!(
captured.contains("transacted block cleanup was not acknowledged"),
"the (Some(p), Err(u)) row carries the cleanup uncertainty in the log: {captured}"
);
assert!(
captured.contains("primary error stands"),
"the log states the primary error is not substituted: {captured}"
);
}
#[tokio::test]
async fn transacted_block_session_scopes_the_body() {
let session = FakeSession::new(TransactionState::Fresh, committed(), rolled_back());
let seen = Arc::new(Mutex::new(None));
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Observe {
expected_session: session,
seen: Arc::clone(&seen),
},
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_completed_text(outcome, "observed");
let (datasource, first_scope) = {
let guard = seen
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
guard
.clone()
.expect("the body recorded the installed binding")
};
assert_eq!(datasource, DS);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_completed_text(outcome, "observed");
let (_, second_scope) = {
let guard = seen
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
guard.clone().expect("the second run recorded its binding")
};
assert_eq!(
second_scope,
first_scope + 1,
"every block execution allocates a fresh scope id"
);
}
#[tokio::test]
async fn transacted_open_error_maps_to_exchange_failure() {
let mut seg = segment(
FakeManager::script(OpenScript::Fail(TransactionError::PoolExhausted {
datasource: DS.to_owned(),
max_connections: 1,
waited_ms: 5,
})),
BodyScript::Complete("ok"),
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_tx(
outcome,
&TransactionError::PoolExhausted {
datasource: DS.to_owned(),
max_connections: 1,
waited_ms: 5,
},
);
let mut seg = segment(
FakeManager::script(OpenScript::Fail(TransactionError::Timeout {
datasource: DS.to_owned(),
elapsed_ms: 7,
})),
BodyScript::Complete("ok"),
Duration::from_secs(1),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_tx(
outcome,
&TransactionError::Timeout {
datasource: DS.to_owned(),
elapsed_ms: 7,
},
);
let mut seg = segment(
FakeManager::script(OpenScript::Pending),
BodyScript::Complete("ok"),
Duration::from_millis(20),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_timeout(outcome, 20);
}
#[tokio::test]
async fn transacted_open_race_ready_open_decides_over_elapsed_deadline() {
let exhausted = TransactionError::PoolExhausted {
datasource: DS.to_owned(),
max_connections: 1,
waited_ms: 5,
};
let mut seg = segment(
FakeManager::script(OpenScript::FailAfterFirstPoll(exhausted.clone()))
.with_acquire_deadline(Duration::from_millis(5)),
BodyScript::Complete("ok"),
Duration::from_millis(20),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_tx(outcome, &exhausted);
}
#[tokio::test(start_paused = true)]
async fn transacted_open_pool_exhausted_adjudicated_by_absolute_instants() {
let exhausted = TransactionError::PoolExhausted {
datasource: DS.to_owned(),
max_connections: 1,
waited_ms: 5,
};
let mut seg = segment(
FakeManager::script(OpenScript::FailAfterFirstPoll(exhausted.clone())),
BodyScript::Complete("ok"),
Duration::from_millis(20),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_timeout(outcome, 20);
let mut seg = segment(
FakeManager::script(OpenScript::FailAfterFirstPoll(exhausted.clone()))
.with_acquire_deadline(Duration::from_millis(20)),
BodyScript::Complete("ok"),
Duration::from_millis(20),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_timeout(outcome, 20);
let mut seg = segment(
FakeManager::script(OpenScript::Fail(exhausted.clone())),
BodyScript::Complete("ok"),
Duration::from_millis(20),
);
let outcome = seg.run(Exchange::new(Message::new("m"))).await;
assert_failed_tx(outcome, &exhausted);
}
#[tokio::test]
async fn transacted_cancel_after_commit_ack() {
let token = CancellationToken::new();
let session = FakeSession::gated(Ok(TransactionOutcome::Committed), token.clone());
tokio::spawn({
let token = token.clone();
async move {
token.cancel();
}
});
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Complete("ok"),
Duration::from_secs(1),
);
let outcome = CANCEL_TOKEN
.scope(token, async move {
seg.run(Exchange::new(Message::new("m"))).await
})
.await;
assert_completed_text(outcome, "ok");
assert_eq!(
session.calls(),
vec!["commit"],
"post-handoff cancellation is never consulted: no rollback call"
);
}
#[tokio::test]
async fn transacted_cancel_after_commit_lost() {
let token = CancellationToken::new();
let session = FakeSession::gated(
Err(TransactionError::CommitUncertain {
datasource: DS.to_owned(),
}),
token.clone(),
);
tokio::spawn({
let token = token.clone();
async move {
token.cancel();
}
});
let mut seg = segment(
session_manager(session.clone()),
BodyScript::Complete("ok"),
Duration::from_secs(1),
);
let outcome = CANCEL_TOKEN
.scope(token, async move {
seg.run(Exchange::new(Message::new("m"))).await
})
.await;
assert_failed_tx(
outcome,
&TransactionError::CommitUncertain {
datasource: DS.to_owned(),
},
);
assert_eq!(
session.calls(),
vec!["commit"],
"a lost ACK after the cutoff is never reported as a rollback"
);
}
}