Skip to content

fix: Ensure reactive transaction subsequent runs work during streaming #1636

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.neo4j.bolt.connection.AccessMode;
import org.neo4j.bolt.connection.AuthInfo;
import org.neo4j.bolt.connection.AuthTokens;
Expand Down Expand Up @@ -48,8 +49,8 @@ final class AdaptingDriverBoltConnection implements DriverBoltConnection {
}

@Override
public CompletionStage<DriverBoltConnection> onLoop() {
return connection.onLoop().exceptionally(errorMapper::mapAndTrow).thenApply(ignored -> this);
public <T> CompletionStage<T> onLoop(Supplier<T> supplier) {
return connection.onLoop(supplier);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.neo4j.bolt.connection.AccessMode;
import org.neo4j.bolt.connection.AuthInfo;
import org.neo4j.bolt.connection.BoltConnectionState;
Expand All @@ -32,7 +33,7 @@
import org.neo4j.driver.Value;

public interface DriverBoltConnection {
CompletionStage<DriverBoltConnection> onLoop();
<T> CompletionStage<T> onLoop(Supplier<T> supplier);

CompletionStage<DriverBoltConnection> route(
DatabaseName databaseName, String impersonatedUser, Set<String> bookmarks);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.neo4j.bolt.connection.AccessMode;
import org.neo4j.bolt.connection.AuthInfo;
import org.neo4j.bolt.connection.BoltConnectionState;
Expand All @@ -42,8 +43,8 @@ protected DelegatingBoltConnection(DriverBoltConnection delegate) {
}

@Override
public CompletionStage<DriverBoltConnection> onLoop() {
return delegate.onLoop().thenApply(ignored -> this);
public <T> CompletionStage<T> onLoop(Supplier<T> supplier) {
return delegate.onLoop(supplier);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
Expand Down Expand Up @@ -707,6 +710,7 @@ public AuthToken overrideAuthToken() {
}

public static class RunRxResponseHandler implements DriverResponseHandler {
private static final Lock NOOP_LOCK = new NoopLock();
final CompletableFuture<RxResultCursor> cursorFuture = new CompletableFuture<>();
private final Logging logging;
private final DriverBoltConnection connection;
Expand Down Expand Up @@ -763,8 +767,8 @@ public void onComplete() {
if (error != null) {
runFailed.set(true);
}
cursorFuture.complete(
new RxResultCursorImpl(connection, query, runSummary, error, bookmarkConsumer, true, logging));
cursorFuture.complete(new RxResultCursorImpl(
connection, NOOP_LOCK, query, runSummary, error, bookmarkConsumer, true, logging));
} else {
var message = ignoredCount > 0
? "Run exchange contains ignored messages."
Expand Down Expand Up @@ -793,4 +797,30 @@ public boolean handleSecurityException(AuthToken authToken, SecurityException ex
return false;
}
}

private static class NoopLock implements Lock {
@Override
public void lock() {}

@Override
public void lockInterruptibly() {}

@Override
public boolean tryLock() {
return true;
}

@Override
public boolean tryLock(long time, TimeUnit unit) {
return true;
}

@Override
public void unlock() {}

@Override
public Condition newCondition() {
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
import java.util.function.Function;
import org.neo4j.driver.Logger;
import org.neo4j.driver.Logging;
import org.neo4j.driver.internal.adaptedbolt.DriverBoltConnection;
Expand Down Expand Up @@ -48,81 +49,82 @@ public TerminationAwareBoltConnection(
public CompletionStage<DriverBoltConnection> clearAndReset() {
var future = new CompletableFuture<DriverBoltConnection>();
var thisVal = this;

delegate.onLoop()
.thenCompose(connection -> executor.execute(ignored -> connection
.clear()
.thenCompose(DriverBoltConnection::reset)
.thenCompose(conn -> conn.flush(new DriverResponseHandler() {
Throwable throwable = null;

@Override
public void onError(Throwable throwable) {
log.error("Unexpected error occurred while resetting connection", throwable);
throwableConsumer.accept(throwable);
this.throwable = throwable;
}

@Override
public void onComplete() {
if (throwable != null) {
future.completeExceptionally(throwable);
} else {
future.complete(thisVal);
}
}
}))))
delegate.onLoop(() -> executor.execute(ignored -> clearAndResetBolt(future)))
.thenCompose(Function.identity())
.whenComplete((ignored, throwable) -> {
if (throwable != null) {
throwableConsumer.accept(throwable);
future.completeExceptionally(throwable);
}
});

return future;
}

private CompletionStage<Void> clearAndResetBolt(CompletableFuture<DriverBoltConnection> future) {
var thisVal = this;
return delegate.clear()
.thenCompose(DriverBoltConnection::reset)
.thenCompose(conn -> conn.flush(new DriverResponseHandler() {
Throwable throwable = null;

@Override
public void onError(Throwable throwable) {
log.error("Unexpected error occurred while resetting connection", throwable);
throwableConsumer.accept(throwable);
this.throwable = throwable;
}

@Override
public void onComplete() {
if (throwable != null) {
future.completeExceptionally(throwable);
} else {
future.complete(thisVal);
}
}
}));
}

@Override
public CompletionStage<Void> flush(DriverResponseHandler handler) {
return delegate.onLoop()
.thenCompose(connection -> executor.execute(causeOfTermination -> {
if (causeOfTermination == null) {
log.trace("This connection is active, will flush");
var terminationAwareResponseHandler =
new TerminationAwareResponseHandler(logging, handler, executor, throwableConsumer);
return delegate.flush(terminationAwareResponseHandler).handle((ignored, flushThrowable) -> {
flushThrowable = Futures.completionExceptionCause(flushThrowable);
if (flushThrowable != null) {
if (log.isTraceEnabled()) {
log.error("The flush has failed", flushThrowable);
}
var flushThrowableRef = flushThrowable;
flushThrowable = executor.execute(existingThrowable -> {
if (existingThrowable != null) {
log.trace(
"The flush has failed, but there is an existing %s", existingThrowable);
return existingThrowable;
} else {
throwableConsumer.accept(flushThrowableRef);
return flushThrowableRef;
}
});
// rethrow
if (flushThrowable instanceof RuntimeException runtimeException) {
throw runtimeException;
} else {
throw new CompletionException(flushThrowable);
}
} else {
return ignored;
}
});
return delegate.onLoop(() -> executor.execute(causeOfTermination -> flushBolt(causeOfTermination, handler)))
.thenCompose(Function.identity());
}

private CompletionStage<Void> flushBolt(Throwable causeOfTermination, DriverResponseHandler handler) {
if (causeOfTermination == null) {
log.trace("This connection is active, will flush");
var terminationAwareResponseHandler =
new TerminationAwareResponseHandler(logging, handler, executor, throwableConsumer);
return delegate.flush(terminationAwareResponseHandler).handle((ignored, flushThrowable) -> {
flushThrowable = Futures.completionExceptionCause(flushThrowable);
if (flushThrowable != null) {
if (log.isTraceEnabled()) {
log.error("The flush has failed", flushThrowable);
}
var flushThrowableRef = flushThrowable;
flushThrowable = executor.execute(existingThrowable -> {
if (existingThrowable != null) {
log.trace("The flush has failed, but there is an existing %s", existingThrowable);
return existingThrowable;
} else {
throwableConsumer.accept(flushThrowableRef);
return flushThrowableRef;
}
});
// rethrow
if (flushThrowable instanceof RuntimeException runtimeException) {
throw runtimeException;
} else {
// there is an existing error
return connection
.clear()
.thenCompose(ignored -> CompletableFuture.failedStage(causeOfTermination));
throw new CompletionException(flushThrowable);
}
}));
} else {
return ignored;
}
});
} else {
// there is an existing error
return delegate.clear().thenCompose(ignored -> CompletableFuture.failedStage(causeOfTermination));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ private enum State {
private final ResultCursorsHolder resultCursors;
private final long fetchSize;
private final Lock lock = new ReentrantLock();
private final Lock connectionLock = new ReentrantLock();
private State state = State.ACTIVE;
private CompletableFuture<Void> commitFuture;
private CompletableFuture<Void> rollbackFuture;
Expand Down Expand Up @@ -257,9 +258,17 @@ public CompletionStage<ResultCursor> runAsync(Query query) {
public CompletionStage<RxResultCursor> runRx(Query query) {
ensureCanRunQueries();
var parameters = query.parameters().asMap(Values::value);
var responseHandler = new RunRxResponseHandler(logging, apiTelemetryWork, beginFuture, connection, query);
var flushStage =
connection.run(query.text(), parameters).thenCompose(ignored2 -> connection.flush(responseHandler));
var responseHandler =
new RunRxResponseHandler(logging, apiTelemetryWork, beginFuture, connection, connectionLock, query);
var flushStage = connection
.onLoop(() -> {
connectionLock.lock();
return connection
.run(query.text(), parameters)
.thenCompose(conn -> conn.flush(responseHandler))
.whenComplete((ignored, throwable) -> connectionLock.unlock());
})
.thenCompose(Function.identity());
return beginFuture.thenCompose(ignored -> {
var cursorStage = flushStage.thenCompose(flushResult -> responseHandler.cursorFuture);
resultCursors.add(cursorStage);
Expand Down Expand Up @@ -670,6 +679,7 @@ private static class RunRxResponseHandler implements DriverResponseHandler {
private final ApiTelemetryWork apiTelemetryWork;
private final CompletableFuture<UnmanagedTransaction> beginFuture;
private final DriverBoltConnection connection;
private final Lock connectionLock;
private final Query query;
private Throwable error;
private RunSummary runSummary;
Expand All @@ -680,11 +690,13 @@ private RunRxResponseHandler(
ApiTelemetryWork apiTelemetryWork,
CompletableFuture<UnmanagedTransaction> beginFuture,
DriverBoltConnection connection,
Lock connectionLock,
Query query) {
this.logging = logging;
this.apiTelemetryWork = apiTelemetryWork;
this.beginFuture = beginFuture;
this.connection = connection;
this.connectionLock = connectionLock;
this.query = query;
}

Expand Down Expand Up @@ -720,13 +732,13 @@ public void onIgnored() {
public void onComplete() {
if (error != null) {
if (!beginFuture.completeExceptionally(error)) {
cursorFuture.complete(
new RxResultCursorImpl(connection, query, null, error, bookmark -> {}, false, logging));
cursorFuture.complete(new RxResultCursorImpl(
connection, connectionLock, query, null, error, bookmark -> {}, false, logging));
}
} else {
if (runSummary != null) {
cursorFuture.complete(new RxResultCursorImpl(
connection, query, runSummary, null, bookmark -> {}, false, logging));
connection, connectionLock, query, runSummary, null, bookmark -> {}, false, logging));
} else {
var message =
ignoredCount > 0 ? "Run exchange contains ignored messages" : "Unexpected state during run";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.neo4j.bolt.connection.AccessMode;
import org.neo4j.bolt.connection.AuthInfo;
import org.neo4j.bolt.connection.AuthToken;
Expand All @@ -46,8 +47,8 @@ public ListeningBoltConnection(BoltConnection delegate, BoltConnectionListener b
}

@Override
public CompletionStage<BoltConnection> onLoop() {
return delegate.onLoop().thenApply(ignored -> this);
public <T> CompletionStage<T> onLoop(Supplier<T> supplier) {
return delegate.onLoop(supplier);
}

@Override
Expand Down
Loading