diesel_async/transaction_manager.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
use diesel::connection::InstrumentationEvent;
use diesel::connection::TransactionManagerStatus;
use diesel::connection::{
InTransactionStatus, TransactionDepthChange, ValidTransactionManagerStatus,
};
use diesel::result::Error;
use diesel::QueryResult;
use scoped_futures::ScopedBoxFuture;
use std::borrow::Cow;
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::AsyncConnection;
// TODO: refactor this to share more code with diesel
/// Manages the internal transaction state for a connection.
///
/// You will not need to interact with this trait, unless you are writing an
/// implementation of [`AsyncConnection`].
#[async_trait::async_trait]
pub trait TransactionManager<Conn: AsyncConnection>: Send {
/// Data stored as part of the connection implementation
/// to track the current transaction state of a connection
type TransactionStateData;
/// Begin a new transaction or savepoint
///
/// If the transaction depth is greater than 0,
/// this should create a savepoint instead.
/// This function is expected to increment the transaction depth by 1.
async fn begin_transaction(conn: &mut Conn) -> QueryResult<()>;
/// Rollback the inner-most transaction or savepoint
///
/// If the transaction depth is greater than 1,
/// this should rollback to the most recent savepoint.
/// This function is expected to decrement the transaction depth by 1.
async fn rollback_transaction(conn: &mut Conn) -> QueryResult<()>;
/// Commit the inner-most transaction or savepoint
///
/// If the transaction depth is greater than 1,
/// this should release the most recent savepoint.
/// This function is expected to decrement the transaction depth by 1.
async fn commit_transaction(conn: &mut Conn) -> QueryResult<()>;
/// Fetch the current transaction status as mutable
///
/// Used to ensure that `begin_test_transaction` is not called when already
/// inside of a transaction, and that operations are not run in a `InError`
/// transaction manager.
#[doc(hidden)]
fn transaction_manager_status_mut(conn: &mut Conn) -> &mut TransactionManagerStatus;
/// Executes the given function inside of a database transaction
///
/// Each implementation of this function needs to fulfill the documented
/// behaviour of [`AsyncConnection::transaction`]
async fn transaction<'a, F, R, E>(conn: &mut Conn, callback: F) -> Result<R, E>
where
F: for<'r> FnOnce(&'r mut Conn) -> ScopedBoxFuture<'a, 'r, Result<R, E>> + Send + 'a,
E: From<Error> + Send,
R: Send,
{
Self::begin_transaction(conn).await?;
match callback(&mut *conn).await {
Ok(value) => {
Self::commit_transaction(conn).await?;
Ok(value)
}
Err(user_error) => match Self::rollback_transaction(conn).await {
Ok(()) => Err(user_error),
Err(Error::BrokenTransactionManager) => {
// In this case we are probably more interested by the
// original error, which likely caused this
Err(user_error)
}
Err(rollback_error) => Err(rollback_error.into()),
},
}
}
/// This methods checks if the connection manager is considered to be broken
/// by connection pool implementations
///
/// A connection manager is considered to be broken by default if it either
/// contains an open transaction (because you don't want to have connections
/// with open transactions in your pool) or when the transaction manager is
/// in an error state.
#[doc(hidden)]
fn is_broken_transaction_manager(conn: &mut Conn) -> bool {
check_broken_transaction_state(conn)
}
}
fn check_broken_transaction_state<Conn>(conn: &mut Conn) -> bool
where
Conn: AsyncConnection,
{
match Conn::TransactionManager::transaction_manager_status_mut(conn).transaction_state() {
// all transactions are closed
// so we don't consider this connection broken
Ok(ValidTransactionManagerStatus {
in_transaction: None,
..
}) => false,
// The transaction manager is in an error state
// Therefore we consider this connection broken
Err(_) => true,
// The transaction manager contains a open transaction
// we do consider this connection broken
// if that transaction was not opened by `begin_test_transaction`
Ok(ValidTransactionManagerStatus {
in_transaction: Some(s),
..
}) => !s.test_transaction,
}
}
/// An implementation of `TransactionManager` which can be used for backends
/// which use ANSI standard syntax for savepoints such as SQLite and PostgreSQL.
#[derive(Default, Debug)]
pub struct AnsiTransactionManager {
pub(crate) status: TransactionManagerStatus,
// this boolean flag tracks whether we are currently in the process
// of executing any transaction releated SQL (BEGIN, COMMIT, ROLLBACK)
// if we ever encounter a situation where this flag is set
// while the connection is returned to a pool
// that means the connection is broken as someone dropped the
// transaction future while these commands where executed
// and we cannot know the connection state anymore
//
// We ensure this by wrapping all calls to `.await`
// into `AnsiTransactionManager::critical_transaction_block`
// below
//
// See https://github.com/weiznich/diesel_async/issues/198 for
// details
pub(crate) is_broken: Arc<AtomicBool>,
}
impl AnsiTransactionManager {
fn get_transaction_state<Conn>(
conn: &mut Conn,
) -> QueryResult<&mut ValidTransactionManagerStatus>
where
Conn: AsyncConnection<TransactionManager = Self>,
{
conn.transaction_state().status.transaction_state()
}
/// Begin a transaction with custom SQL
///
/// This is used by connections to implement more complex transaction APIs
/// to set things such as isolation levels.
/// Returns an error if already inside of a transaction.
pub async fn begin_transaction_sql<Conn>(conn: &mut Conn, sql: &str) -> QueryResult<()>
where
Conn: AsyncConnection<TransactionManager = Self>,
{
let is_broken = conn.transaction_state().is_broken.clone();
let state = Self::get_transaction_state(conn)?;
match state.transaction_depth() {
None => {
Self::critical_transaction_block(&is_broken, conn.batch_execute(sql)).await?;
Self::get_transaction_state(conn)?
.change_transaction_depth(TransactionDepthChange::IncreaseDepth)?;
Ok(())
}
Some(_depth) => Err(Error::AlreadyInTransaction),
}
}
// This function should be used to await any connection
// related future in our transaction manager implementation
//
// It takes care of tracking entering and exiting executing the future
// which in turn is used to determine if it's safe to still use
// the connection in the event of a canceled transaction execution
async fn critical_transaction_block<F>(is_broken: &AtomicBool, f: F) -> F::Output
where
F: std::future::Future,
{
let was_broken = is_broken.swap(true, Ordering::Relaxed);
debug_assert!(
!was_broken,
"Tried to execute a transaction SQL on transaction manager that was previously cancled"
);
let res = f.await;
is_broken.store(false, Ordering::Relaxed);
res
}
}
#[async_trait::async_trait]
impl<Conn> TransactionManager<Conn> for AnsiTransactionManager
where
Conn: AsyncConnection<TransactionManager = Self>,
{
type TransactionStateData = Self;
async fn begin_transaction(conn: &mut Conn) -> QueryResult<()> {
let transaction_state = Self::get_transaction_state(conn)?;
let start_transaction_sql = match transaction_state.transaction_depth() {
None => Cow::from("BEGIN"),
Some(transaction_depth) => {
Cow::from(format!("SAVEPOINT diesel_savepoint_{transaction_depth}"))
}
};
let depth = transaction_state
.transaction_depth()
.and_then(|d| d.checked_add(1))
.unwrap_or(NonZeroU32::new(1).expect("It's not 0"));
conn.instrumentation()
.on_connection_event(InstrumentationEvent::begin_transaction(depth));
Self::critical_transaction_block(
&conn.transaction_state().is_broken.clone(),
conn.batch_execute(&start_transaction_sql),
)
.await?;
Self::get_transaction_state(conn)?
.change_transaction_depth(TransactionDepthChange::IncreaseDepth)?;
Ok(())
}
async fn rollback_transaction(conn: &mut Conn) -> QueryResult<()> {
let transaction_state = Self::get_transaction_state(conn)?;
let (
(rollback_sql, rolling_back_top_level),
requires_rollback_maybe_up_to_top_level_before_execute,
) = match transaction_state.in_transaction {
Some(ref in_transaction) => (
match in_transaction.transaction_depth.get() {
1 => (Cow::Borrowed("ROLLBACK"), true),
depth_gt1 => (
Cow::Owned(format!(
"ROLLBACK TO SAVEPOINT diesel_savepoint_{}",
depth_gt1 - 1
)),
false,
),
},
in_transaction.requires_rollback_maybe_up_to_top_level,
),
None => return Err(Error::NotInTransaction),
};
let depth = transaction_state
.transaction_depth()
.expect("We know that we are in a transaction here");
conn.instrumentation()
.on_connection_event(InstrumentationEvent::rollback_transaction(depth));
let is_broken = conn.transaction_state().is_broken.clone();
match Self::critical_transaction_block(&is_broken, conn.batch_execute(&rollback_sql)).await
{
Ok(()) => {
match Self::get_transaction_state(conn)?
.change_transaction_depth(TransactionDepthChange::DecreaseDepth)
{
Ok(()) => {}
Err(Error::NotInTransaction) if rolling_back_top_level => {
// Transaction exit may have already been detected by connection
// implementation. It's fine.
}
Err(e) => return Err(e),
}
Ok(())
}
Err(rollback_error) => {
let tm_status = Self::transaction_manager_status_mut(conn);
match tm_status {
TransactionManagerStatus::Valid(ValidTransactionManagerStatus {
in_transaction:
Some(InTransactionStatus {
transaction_depth,
requires_rollback_maybe_up_to_top_level,
..
}),
..
}) if transaction_depth.get() > 1 => {
// A savepoint failed to rollback - we may still attempt to repair
// the connection by rolling back higher levels.
// To make it easier on the user (that they don't have to really
// look at actual transaction depth and can just rely on the number
// of times they have called begin/commit/rollback) we still
// decrement here:
*transaction_depth = NonZeroU32::new(transaction_depth.get() - 1)
.expect("Depth was checked to be > 1");
*requires_rollback_maybe_up_to_top_level = true;
if requires_rollback_maybe_up_to_top_level_before_execute {
// In that case, we tolerate that savepoint releases fail
// -> we should ignore errors
return Ok(());
}
}
TransactionManagerStatus::Valid(ValidTransactionManagerStatus {
in_transaction: None,
..
}) => {
// we would have returned `NotInTransaction` if that was already the state
// before we made our call
// => Transaction manager status has been fixed by the underlying connection
// so we don't need to set_in_error
}
_ => tm_status.set_in_error(),
}
Err(rollback_error)
}
}
}
/// If the transaction fails to commit due to a `SerializationFailure` or a
/// `ReadOnlyTransaction` a rollback will be attempted. If the rollback succeeds,
/// the original error will be returned, otherwise the error generated by the rollback
/// will be returned. In the second case the connection will be considered broken
/// as it contains a uncommitted unabortable open transaction.
async fn commit_transaction(conn: &mut Conn) -> QueryResult<()> {
let transaction_state = Self::get_transaction_state(conn)?;
let transaction_depth = transaction_state.transaction_depth();
let (commit_sql, committing_top_level) = match transaction_depth {
None => return Err(Error::NotInTransaction),
Some(transaction_depth) if transaction_depth.get() == 1 => {
(Cow::Borrowed("COMMIT"), true)
}
Some(transaction_depth) => (
Cow::Owned(format!(
"RELEASE SAVEPOINT diesel_savepoint_{}",
transaction_depth.get() - 1
)),
false,
),
};
let depth = transaction_state
.transaction_depth()
.expect("We know that we are in a transaction here");
conn.instrumentation()
.on_connection_event(InstrumentationEvent::commit_transaction(depth));
let is_broken = conn.transaction_state().is_broken.clone();
match Self::critical_transaction_block(&is_broken, conn.batch_execute(&commit_sql)).await {
Ok(()) => {
match Self::get_transaction_state(conn)?
.change_transaction_depth(TransactionDepthChange::DecreaseDepth)
{
Ok(()) => {}
Err(Error::NotInTransaction) if committing_top_level => {
// Transaction exit may have already been detected by connection.
// It's fine
}
Err(e) => return Err(e),
}
Ok(())
}
Err(commit_error) => {
if let TransactionManagerStatus::Valid(ValidTransactionManagerStatus {
in_transaction:
Some(InTransactionStatus {
requires_rollback_maybe_up_to_top_level: true,
..
}),
..
}) = conn.transaction_state().status
{
match Self::critical_transaction_block(
&is_broken,
Self::rollback_transaction(conn),
)
.await
{
Ok(()) => {}
Err(rollback_error) => {
conn.transaction_state().status.set_in_error();
return Err(Error::RollbackErrorOnCommit {
rollback_error: Box::new(rollback_error),
commit_error: Box::new(commit_error),
});
}
}
}
Err(commit_error)
}
}
}
fn transaction_manager_status_mut(conn: &mut Conn) -> &mut TransactionManagerStatus {
&mut conn.transaction_state().status
}
fn is_broken_transaction_manager(conn: &mut Conn) -> bool {
conn.transaction_state().is_broken.load(Ordering::Relaxed)
|| check_broken_transaction_state(conn)
}
}