pub mod join;
use std::any::Any;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TransactionState {
Fresh,
Active,
Finalizing,
Done,
Detached,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TransactionOutcome {
Committed,
RolledBack,
Detached,
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum TransactionError {
#[error("no TransactionManager for datasource '{datasource}'")]
ManagerMissing {
datasource: String,
},
#[error(
"parallel split step '{step}' inside a transacted block on datasource '{datasource}' \
cannot join the transaction"
)]
ParallelInBlock {
step: String,
datasource: String,
},
#[error(
"multicast step '{step}' inside a transacted block on datasource '{datasource}' \
cannot join the transaction"
)]
MulticastInBlock {
step: String,
datasource: String,
},
#[error(
"wireTap step '{step}' inside a transacted block on datasource '{datasource}' \
cannot join the transaction"
)]
WireTapInBlock {
step: String,
datasource: String,
},
#[error(
"async handoff at step '{step}' inside a transacted block on datasource '{datasource}' \
cannot join the transaction"
)]
AsyncInBlock {
step: String,
datasource: String,
},
#[error(
"seda handoff at step '{step}' inside a transacted block on datasource '{datasource}' \
cannot join the transaction"
)]
SedaInBlock {
step: String,
datasource: String,
},
#[error(
"sql step '{step}' uses outputType=StreamList inside a transacted block \
on datasource '{datasource}'"
)]
StreamListInBlock {
step: String,
datasource: String,
},
#[error(
"sql step '{step}' targets datasource '{step_datasource}' but the transacted block \
is on datasource '{block_datasource}' (no two-phase commit)"
)]
ForeignDatasource {
step: String,
block_datasource: String,
step_datasource: String,
},
#[error(
"sql step '{step}' inside a transacted block has no named datasource \
(inline db_url cannot join the block transaction)"
)]
UnnamedDatasource {
step: String,
},
#[error("transacted block on datasource '{inner}' is nested inside another transacted block")]
NestedBlock {
inner: String,
},
#[error("transaction session on datasource '{datasource}' was aborted")]
SessionAborted {
datasource: String,
},
#[error(
"transacted block on datasource '{datasource}' handled a joined database error; \
the session is rollback-only"
)]
AbortedByHandledError {
datasource: String,
},
#[error(
"commit on datasource '{datasource}' is uncertain: the database did not acknowledge it"
)]
CommitUncertain {
datasource: String,
},
#[error("commit on datasource '{datasource}' failed: {reason}")]
CommitFailed {
datasource: String,
reason: String,
},
#[error(
"rollback on datasource '{datasource}' is uncertain: the database did not acknowledge it"
)]
RollbackUncertain {
datasource: String,
},
#[error(
"no connection available for datasource '{datasource}' after waiting {waited_ms} ms \
(max_connections={max_connections})"
)]
PoolExhausted {
datasource: String,
max_connections: u32,
waited_ms: u64,
},
#[error("transacted block on datasource '{datasource}' timed out after {elapsed_ms} ms")]
Timeout {
datasource: String,
elapsed_ms: u64,
},
#[error("transaction session on datasource '{datasource}' is busy")]
Busy {
datasource: String,
},
#[error("joined sql step on datasource '{datasource}' has no transaction session")]
JoinSessionMissing {
datasource: String,
},
#[error(
"transaction join scope mismatch on datasource '{datasource}': \
expected scope {expected_scope}, found scope {found_scope}"
)]
JoinScopeMismatch {
datasource: String,
expected_scope: u64,
found_scope: u64,
},
#[error("joined sql step '{step}' uses a runtime SQL source")]
RuntimeSqlInJoinedStep {
step: String,
},
#[error("joined sql step '{step}' issues transaction-control statement '{statement}'")]
TransactionControlSql {
step: String,
statement: String,
},
#[error("cannot prove transaction semantics for URL scheme '{scheme}'")]
DialectUnprovable {
scheme: String,
},
#[error(
"dialect '{dialect}' on datasource '{datasource}' does not support joined transactions"
)]
UnsupportedJoinDialect {
dialect: String,
datasource: String,
},
#[error(
"dynamic routing target at step '{step}' inside a transacted block \
cannot prove transaction membership"
)]
DynamicTargetUnprovable {
step: String,
},
}
pub type OpenSessionFuture<'a> = Pin<
Box<dyn Future<Output = Result<Arc<dyn TransactionSession>, TransactionError>> + Send + 'a>,
>;
pub type BeginFuture<'a> = Pin<Box<dyn Future<Output = Result<(), TransactionError>> + Send + 'a>>;
pub type FinalizeFuture<'a> =
Pin<Box<dyn Future<Output = Result<TransactionOutcome, TransactionError>> + Send + 'a>>;
pub trait TransactionManager: Any + Send + Sync + 'static {
fn datasource(&self) -> &str;
fn open_session(&self) -> OpenSessionFuture<'_>;
fn acquire_deadline(&self) -> Duration;
}
pub trait TransactionSession: Any + Send + Sync + 'static {
fn datasource(&self) -> &str;
fn state(&self) -> TransactionState;
fn begin(&self) -> BeginFuture<'_>;
fn set_rollback_only(&self);
fn is_rollback_only(&self) -> bool;
fn commit(&self) -> FinalizeFuture<'_>;
fn rollback(&self) -> FinalizeFuture<'_>;
}
#[cfg(test)]
mod tests {
use std::any::Any;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
pub(super) struct StubSession {
datasource: String,
state: TransactionState,
rollback_only: AtomicBool,
}
impl StubSession {
pub(super) fn new(datasource: &str) -> Self {
Self {
datasource: datasource.to_owned(),
state: TransactionState::Active,
rollback_only: AtomicBool::new(false),
}
}
}
impl TransactionSession for StubSession {
fn datasource(&self) -> &str {
&self.datasource
}
fn state(&self) -> TransactionState {
self.state
}
fn begin(&self) -> 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) -> FinalizeFuture<'_> {
Box::pin(std::future::ready(Ok(TransactionOutcome::Committed)))
}
fn rollback(&self) -> FinalizeFuture<'_> {
Box::pin(std::future::ready(Ok(TransactionOutcome::RolledBack)))
}
}
#[test]
fn port_traits_are_object_safe() {
fn _assert(_m: &dyn TransactionManager, _s: &dyn TransactionSession) {}
}
#[test]
fn session_port_upcasts_to_any_and_downcasts() {
let concrete = Arc::new(StubSession::new("pg"));
let port: Arc<dyn TransactionSession> = concrete.clone();
let erased: Arc<dyn Any + Send + Sync> = port;
let restored = Arc::downcast::<StubSession>(erased)
.expect("the session trait object must downcast to its concrete type");
assert_eq!(restored.datasource(), "pg");
assert!(
Arc::ptr_eq(&concrete, &restored),
"downcast must recover the same allocation, not a copy"
);
}
#[test]
fn rollback_doc_carries_total_contract() {
let source =
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/transaction.rs"))
.expect("camel-api source tree is present at test time");
let production = source
.split("#[cfg(test)]")
.next()
.unwrap_or("")
.lines()
.map(|line| {
let line = line.trim();
line.strip_prefix("///")
.or_else(|| line.strip_prefix("//!"))
.unwrap_or(line)
})
.collect::<Vec<_>>()
.join(" ");
let production = production.split_whitespace().collect::<Vec<_>>().join(" ");
assert!(
!production.is_empty(),
"the production half of transaction.rs must be non-empty"
);
for phrase in [
"Total over every lifecycle state",
"nothing begun (`Fresh`, BEGIN never sent)",
"BEGIN sent but unacknowledged",
"`Active`: ROLLBACK within the finalize grace",
"`Detached`, or a defensive `Finalizing`/`Done` entry",
"`error!` log for the defensive entry",
] {
assert!(
production.contains(phrase),
"rollback doc must carry the total-rollback contract phrase: {phrase}"
);
}
for phrase in [
"Precondition `Active`. Otherwise no SQL is sent and the call returns `Err(SessionAborted)`.",
"The owner SHALL call `commit` only when `state() == Active`.",
] {
assert!(
production.contains(phrase),
"commit doc must carry the precondition phrase: {phrase}"
);
}
assert!(
!production.contains("Roll back the block's transaction."),
"the pre-604d rollback doc must be replaced, not kept alongside the new contract"
);
}
#[test]
fn transaction_error_display_names_offender_and_datasource() {
let manager_missing = TransactionError::ManagerMissing {
datasource: "pg".into(),
};
let rendered = manager_missing.to_string();
assert!(
rendered.contains("pg") && rendered.contains("TransactionManager"),
"manager-missing display must name the datasource and the missing port: {rendered}"
);
let foreign = TransactionError::ForeignDatasource {
step: "s1".into(),
block_datasource: "pg".into(),
step_datasource: "audit".into(),
};
let rendered = foreign.to_string();
assert!(
rendered.contains("s1") && rendered.contains("pg") && rendered.contains("audit"),
"foreign-datasource display must name the step and both datasources: {rendered}"
);
let stream_list = TransactionError::StreamListInBlock {
step: "s2".into(),
datasource: "pg".into(),
};
let rendered = stream_list.to_string();
assert!(
rendered.contains("s2") && rendered.contains("pg"),
"stream-list display must name the step and the datasource: {rendered}"
);
}
#[test]
#[allow(clippy::match_single_binding)]
fn non_exhaustive_enums_accept_catch_all() {
let state = TransactionState::Fresh;
let outcome = TransactionOutcome::Committed;
let state_label = match state {
_ => "state",
};
let outcome_label = match outcome {
_ => "outcome",
};
assert_eq!(state_label, "state");
assert_eq!(outcome_label, "outcome");
}
}