+ final Optional<CompletionStage<Void>> maybeCanCommitFuture = userCohorts.canCommit(dataTreeCandidate);
+ if (!maybeCanCommitFuture.isPresent()) {
+ doUserPreCommit(futureCallback);
+ return;
+ }
+
+ maybeCanCommitFuture.get().whenComplete((noop, failure) -> {
+ if (failure != null) {
+ futureCallback.onFailure(failure);
+ } else {
+ doUserPreCommit(futureCallback);
+ }
+ });
+ }
+
+ private void doUserPreCommit(final FutureCallback<Void> futureCallback) {
+ final Optional<CompletionStage<Void>> maybePreCommitFuture = userCohorts.preCommit();
+ if (!maybePreCommitFuture.isPresent()) {
+ futureCallback.onSuccess(null);
+ return;
+ }
+
+ maybePreCommitFuture.get().whenComplete((noop, failure) -> {
+ if (failure != null) {
+ futureCallback.onFailure(failure);
+ } else {
+ futureCallback.onSuccess(null);
+ }
+ });
+ }
+
+ void successfulPreCommit(final DataTreeCandidateTip dataTreeCandidate) {
+ LOG.trace("Transaction {} prepared candidate {}", transaction, dataTreeCandidate);
+ this.candidate = Verify.verifyNotNull(dataTreeCandidate);
+ switchState(State.PRE_COMMIT_COMPLETE).onSuccess(dataTreeCandidate);
+ }
+
+ void failedPreCommit(final Throwable cause) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Transaction {} failed to prepare", transaction, cause);
+ } else {
+ LOG.error("Transaction {} failed to prepare", transactionId, cause);
+ }
+
+ userCohorts.abort();
+ switchState(State.FAILED).onFailure(cause);
+ }
+
+ void successfulCommit(final UnsignedLong journalIndex, final Runnable onComplete) {
+ final Optional<CompletionStage<Void>> maybeCommitFuture = userCohorts.commit();
+ if (!maybeCommitFuture.isPresent()) {
+ finishSuccessfulCommit(journalIndex, onComplete);
+ return;
+ }
+
+ maybeCommitFuture.get().whenComplete((noop, failure) -> {
+ if (failure != null) {
+ LOG.error("User cohorts failed to commit", failure);
+ }
+
+ finishSuccessfulCommit(journalIndex, onComplete);
+ });
+ }
+
+ private void finishSuccessfulCommit(final UnsignedLong journalIndex, final Runnable onComplete) {
+ switchState(State.COMMITTED).onSuccess(journalIndex);
+ onComplete.run();
+ }
+
+ void failedCommit(final Exception cause) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Transaction {} failed to commit", transaction, cause);
+ } else {
+ LOG.error("Transaction failed to commit", cause);
+ }
+
+ userCohorts.abort();
+ switchState(State.FAILED).onFailure(cause);
+ }
+
+ @Override
+ public State getState() {
+ return state;
+ }
+
+ void reportFailure(final Exception cause) {
+ if (nextFailure == null) {
+ this.nextFailure = requireNonNull(cause);
+ } else {
+ LOG.debug("Transaction {} already has a set failure, not updating it", transactionId, cause);
+ }
+ }
+
+ @Override
+ public boolean isFailed() {
+ return state == State.FAILED || nextFailure != null;
+ }
+
+ @Override
+ ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
+ return super.addToStringAttributes(toStringHelper).add("nextFailure", nextFailure);