Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.transaction.reactive;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.lang.Nullable;
import org.springframework.transaction.IllegalTransactionStateException;
import org.springframework.transaction.InvalidTimeoutException;
import org.springframework.transaction.ReactiveTransaction;
import org.springframework.transaction.ReactiveTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionSuspensionNotSupportedException;
import org.springframework.transaction.UnexpectedRollbackException;
/**
* Abstract base class that implements Spring's standard reactive transaction workflow,
* serving as basis for concrete platform transaction managers.
*
*
This base class provides the following workflow handling:
*
*
determines if there is an existing transaction;
*
applies the appropriate propagation behavior;
*
suspends and resumes transactions if necessary;
*
checks the rollback-only flag on commit;
*
applies the appropriate modification on rollback
* (actual rollback or setting rollback-only);
*
triggers registered synchronization callbacks.
*
*
*
Subclasses have to implement specific template methods for specific
* states of a transaction, e.g.: begin, suspend, resume, commit, rollback.
* The most important of them are abstract and must be provided by a concrete
* implementation; for the rest, defaults are provided, so overriding is optional.
*
*
Transaction synchronization is a generic mechanism for registering callbacks
* that get invoked at transaction completion time. This is mainly used internally
* by the data access support classes for R2DBC, MongoDB, etc. The same mechanism can
* also be leveraged for custom synchronization needs in an application.
*
*
The state of this class is serializable, to allow for serializing the
* transaction strategy along with proxies that carry a transaction interceptor.
* It is up to subclasses if they wish to make their state to be serializable too.
* They should implement the {@code java.io.Serializable} marker interface in
* that case, and potentially a private {@code readObject()} method (according
* to Java serialization rules) if they need to restore any transient state.
*
* @author Mark Paluch
* @author Juergen Hoeller
* @since 5.2
* @see TransactionSynchronizationManager
*/
@SuppressWarnings("serial")
public abstract class AbstractReactiveTransactionManager implements ReactiveTransactionManager, Serializable {
protected transient Log logger = LogFactory.getLog(getClass());
//---------------------------------------------------------------------
// Implementation of ReactiveTransactionManager
//---------------------------------------------------------------------
/**
* This implementation handles propagation behavior. Delegates to
* {@code doGetTransaction}, {@code isExistingTransaction}
* and {@code doBegin}.
* @see #doGetTransaction
* @see #isExistingTransaction
* @see #doBegin
*/
@Override
public final Mono getReactiveTransaction(@Nullable TransactionDefinition definition) {
// Use defaults if no transaction definition given.
TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());
return TransactionSynchronizationManager.forCurrentTransaction()
.flatMap(synchronizationManager -> {
Object transaction = doGetTransaction(synchronizationManager);
// Cache debug flag to avoid repeated checks.
boolean debugEnabled = logger.isDebugEnabled();
if (isExistingTransaction(transaction)) {
// Existing transaction found -> check propagation behavior to find out how to behave.
return handleExistingTransaction(synchronizationManager, def, transaction, debugEnabled);
}
// Check definition settings for new transaction.
if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
return Mono.error(new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout()));
}
// No existing transaction found -> check propagation behavior to find out how to proceed.
if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
return Mono.error(new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'"));
}
else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
return TransactionContextManager.currentContext()
.map(TransactionSynchronizationManager::new)
.flatMap(nestedSynchronizationManager ->
suspend(nestedSynchronizationManager, null)
.map(Optional::of)
.defaultIfEmpty(Optional.empty())
.flatMap(suspendedResources -> {
if (debugEnabled) {
logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
}
return Mono.defer(() -> {
GenericReactiveTransaction status = newReactiveTransaction(
nestedSynchronizationManager, def, transaction, true,
debugEnabled, suspendedResources.orElse(null));
return doBegin(nestedSynchronizationManager, transaction, def)
.doOnSuccess(ignore -> prepareSynchronization(nestedSynchronizationManager, status, def))
.thenReturn(status);
}).onErrorResume(ErrorPredicates.RUNTIME_OR_ERROR,
ex -> resume(nestedSynchronizationManager, null, suspendedResources.orElse(null))
.then(Mono.error(ex)));
}));
}
else {
// Create "empty" transaction: no actual transaction, but potentially synchronization.
if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
logger.warn("Custom isolation level specified but no actual transaction initiated; " +
"isolation level will effectively be ignored: " + def);
}
return Mono.just(prepareReactiveTransaction(synchronizationManager, def, null, true, debugEnabled, null));
}
});
}
/**
* Create a ReactiveTransaction for an existing transaction.
*/
private Mono handleExistingTransaction(TransactionSynchronizationManager synchronizationManager,
TransactionDefinition definition, Object transaction, boolean debugEnabled) {
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
return Mono.error(new IllegalTransactionStateException(
"Existing transaction found for transaction marked with propagation 'never'"));
}
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
if (debugEnabled) {
logger.debug("Suspending current transaction");
}
Mono suspend = suspend(synchronizationManager, transaction);
return suspend.map(suspendedResources -> prepareReactiveTransaction(synchronizationManager,
definition, null, false, debugEnabled, suspendedResources)) //
.switchIfEmpty(Mono.fromSupplier(() -> prepareReactiveTransaction(synchronizationManager,
definition, null, false, debugEnabled, null)))
.cast(ReactiveTransaction.class);
}
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
if (debugEnabled) {
logger.debug("Suspending current transaction, creating new transaction with name [" +
definition.getName() + "]");
}
Mono suspendedResources = suspend(synchronizationManager, transaction);
return suspendedResources.flatMap(suspendedResourcesHolder -> {
GenericReactiveTransaction status = newReactiveTransaction(synchronizationManager,
definition, transaction, true, debugEnabled, suspendedResourcesHolder);
return doBegin(synchronizationManager, transaction, definition).doOnSuccess(ignore ->
prepareSynchronization(synchronizationManager, status, definition)).thenReturn(status)
.onErrorResume(ErrorPredicates.RUNTIME_OR_ERROR, beginEx ->
resumeAfterBeginException(synchronizationManager, transaction, suspendedResourcesHolder, beginEx)
.then(Mono.error(beginEx)));
});
}
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
if (debugEnabled) {
logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
}
// Nested transaction through nested begin and commit/rollback calls.
GenericReactiveTransaction status = newReactiveTransaction(synchronizationManager,
definition, transaction, true, debugEnabled, null);
return doBegin(synchronizationManager, transaction, definition).doOnSuccess(ignore ->
prepareSynchronization(synchronizationManager, status, definition)).thenReturn(status);
}
// PROPAGATION_REQUIRED, PROPAGATION_SUPPORTS, PROPAGATION_MANDATORY:
// regular participation in existing transaction.
if (debugEnabled) {
logger.debug("Participating in existing transaction");
}
return Mono.just(prepareReactiveTransaction(
synchronizationManager, definition, transaction, false, debugEnabled, null));
}
/**
* Create a new ReactiveTransaction for the given arguments,
* also initializing transaction synchronization as appropriate.
* @see #newReactiveTransaction
* @see #prepareReactiveTransaction
*/
private GenericReactiveTransaction prepareReactiveTransaction(
TransactionSynchronizationManager synchronizationManager, TransactionDefinition definition,
@Nullable Object transaction, boolean newTransaction, boolean debug, @Nullable Object suspendedResources) {
GenericReactiveTransaction status = newReactiveTransaction(synchronizationManager,
definition, transaction, newTransaction, debug, suspendedResources);
prepareSynchronization(synchronizationManager, status, definition);
return status;
}
/**
* Create a ReactiveTransaction instance for the given arguments.
*/
private GenericReactiveTransaction newReactiveTransaction(
TransactionSynchronizationManager synchronizationManager, TransactionDefinition definition,
@Nullable Object transaction, boolean newTransaction, boolean debug, @Nullable Object suspendedResources) {
return new GenericReactiveTransaction(transaction, newTransaction,
!synchronizationManager.isSynchronizationActive(),
definition.isReadOnly(), debug, suspendedResources);
}
/**
* Initialize transaction synchronization as appropriate.
*/
private void prepareSynchronization(TransactionSynchronizationManager synchronizationManager,
GenericReactiveTransaction status, TransactionDefinition definition) {
if (status.isNewSynchronization()) {
synchronizationManager.setActualTransactionActive(status.hasTransaction());
synchronizationManager.setCurrentTransactionIsolationLevel(
definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT ?
definition.getIsolationLevel() : null);
synchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly());
synchronizationManager.setCurrentTransactionName(definition.getName());
synchronizationManager.initSynchronization();
}
}
/**
* Suspend the given transaction. Suspends transaction synchronization first,
* then delegates to the {@code doSuspend} template method.
* @param synchronizationManager the synchronization manager bound to the current transaction
* @param transaction the current transaction object
* (or {@code null} to just suspend active synchronizations, if any)
* @return an object that holds suspended resources
* (or {@code null} if neither transaction nor synchronization active)
* @see #doSuspend
* @see #resume
*/
private Mono suspend(TransactionSynchronizationManager synchronizationManager,
@Nullable Object transaction) {
if (synchronizationManager.isSynchronizationActive()) {
Mono> suspendedSynchronizations = doSuspendSynchronization(synchronizationManager);
return suspendedSynchronizations.flatMap(synchronizations -> {
Mono> suspendedResources = (transaction != null ?
doSuspend(synchronizationManager, transaction).map(Optional::of).defaultIfEmpty(Optional.empty()) :
Mono.just(Optional.empty()));
return suspendedResources.map(it -> {
String name = synchronizationManager.getCurrentTransactionName();
synchronizationManager.setCurrentTransactionName(null);
boolean readOnly = synchronizationManager.isCurrentTransactionReadOnly();
synchronizationManager.setCurrentTransactionReadOnly(false);
Integer isolationLevel = synchronizationManager.getCurrentTransactionIsolationLevel();
synchronizationManager.setCurrentTransactionIsolationLevel(null);
boolean wasActive = synchronizationManager.isActualTransactionActive();
synchronizationManager.setActualTransactionActive(false);
return new SuspendedResourcesHolder(
it.orElse(null), synchronizations, name, readOnly, isolationLevel, wasActive);
}).onErrorResume(ErrorPredicates.RUNTIME_OR_ERROR,
ex -> doResumeSynchronization(synchronizationManager, synchronizations)
.cast(SuspendedResourcesHolder.class));
});
}
else if (transaction != null) {
// Transaction active but no synchronization active.
Mono> suspendedResources =
doSuspend(synchronizationManager, transaction).map(Optional::of).defaultIfEmpty(Optional.empty());
return suspendedResources.map(it -> new SuspendedResourcesHolder(it.orElse(null)));
}
else {
// Neither transaction nor synchronization active.
return Mono.empty();
}
}
/**
* Resume the given transaction. Delegates to the {@code doResume}
* template method first, then resuming transaction synchronization.
* @param synchronizationManager the synchronization manager bound to the current transaction
* @param transaction the current transaction object
* @param resourcesHolder the object that holds suspended resources,
* as returned by {@code suspend} (or {@code null} to just
* resume synchronizations, if any)
* @see #doResume
* @see #suspend
*/
private Mono resume(TransactionSynchronizationManager synchronizationManager,
@Nullable Object transaction, @Nullable SuspendedResourcesHolder resourcesHolder) {
Mono resume = Mono.empty();
if (resourcesHolder != null) {
Object suspendedResources = resourcesHolder.suspendedResources;
if (suspendedResources != null) {
resume = doResume(synchronizationManager, transaction, suspendedResources);
}
List suspendedSynchronizations = resourcesHolder.suspendedSynchronizations;
if (suspendedSynchronizations != null) {
synchronizationManager.setActualTransactionActive(resourcesHolder.wasActive);
synchronizationManager.setCurrentTransactionIsolationLevel(resourcesHolder.isolationLevel);
synchronizationManager.setCurrentTransactionReadOnly(resourcesHolder.readOnly);
synchronizationManager.setCurrentTransactionName(resourcesHolder.name);
return resume.then(doResumeSynchronization(synchronizationManager, suspendedSynchronizations));
}
}
return resume;
}
/**
* Resume outer transaction after inner transaction begin failed.
*/
private Mono resumeAfterBeginException(TransactionSynchronizationManager synchronizationManager,
Object transaction, @Nullable SuspendedResourcesHolder suspendedResources, Throwable beginEx) {
String exMessage = "Inner transaction begin exception overridden by outer transaction resume exception";
return resume(synchronizationManager, transaction, suspendedResources).doOnError(ErrorPredicates.RUNTIME_OR_ERROR,
ex -> logger.error(exMessage, beginEx));
}
/**
* Suspend all current synchronizations and deactivate transaction
* synchronization for the current transaction context.
* @param synchronizationManager the synchronization manager bound to the current transaction
* @return the List of suspended TransactionSynchronization objects
*/
private Mono> doSuspendSynchronization(
TransactionSynchronizationManager synchronizationManager) {
List suspendedSynchronizations = synchronizationManager.getSynchronizations();
return Flux.fromIterable(suspendedSynchronizations)
.concatMap(TransactionSynchronization::suspend)
.then(Mono.defer(() -> {
synchronizationManager.clearSynchronization();
return Mono.just(suspendedSynchronizations);
}));
}
/**
* Reactivate transaction synchronization for the current transaction context
* and resume all given synchronizations.
* @param synchronizationManager the synchronization manager bound to the current transaction
* @param suspendedSynchronizations a List of TransactionSynchronization objects
*/
private Mono doResumeSynchronization(TransactionSynchronizationManager synchronizationManager,
List suspendedSynchronizations) {
synchronizationManager.initSynchronization();
return Flux.fromIterable(suspendedSynchronizations)
.concatMap(synchronization -> synchronization.resume()
.doOnSuccess(ignore -> synchronizationManager.registerSynchronization(synchronization))).then();
}
/**
* This implementation of commit handles participating in existing
* transactions and programmatic rollback requests.
* Delegates to {@code isRollbackOnly}, {@code doCommit}
* and {@code rollback}.
* @see ReactiveTransaction#isRollbackOnly()
* @see #doCommit
* @see #rollback
*/
@Override
public final Mono commit(ReactiveTransaction transaction) {
if (transaction.isCompleted()) {
return Mono.error(new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction"));
}
return TransactionSynchronizationManager.forCurrentTransaction().flatMap(synchronizationManager -> {
GenericReactiveTransaction reactiveTx = (GenericReactiveTransaction) transaction;
if (reactiveTx.isRollbackOnly()) {
if (reactiveTx.isDebug()) {
logger.debug("Transactional code has requested rollback");
}
return processRollback(synchronizationManager, reactiveTx);
}
return processCommit(synchronizationManager, reactiveTx);
});
}
/**
* Process an actual commit.
* Rollback-only flags have already been checked and applied.
* @param synchronizationManager the synchronization manager bound to the current transaction
* @param status object representing the transaction
*/
private Mono processCommit(TransactionSynchronizationManager synchronizationManager,
GenericReactiveTransaction status) {
AtomicBoolean beforeCompletionInvoked = new AtomicBoolean();
Mono