Skip to content
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

Fix r2dbc connection pool returning multiple pooled objects pointing to same database connection #210

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
11 changes: 8 additions & 3 deletions src/main/java/io/r2dbc/pool/ConnectionPool.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
Expand Down Expand Up @@ -110,7 +111,7 @@ public ConnectionPool(ConnectionPoolConfiguration configuration) {
Function<Connection, Mono<Void>> allocateValidation = getValidationFunction(configuration);

Mono<Connection> create = Mono.defer(() -> {

AtomicBoolean emitting = new AtomicBoolean(true);
Mono<Connection> mono = this.connectionPool.acquire()
.flatMap(ref -> {

Expand Down Expand Up @@ -140,7 +141,10 @@ public ConnectionPool(ConnectionPoolConfiguration configuration) {
conn = conn.onErrorResume(throwable -> ref.invalidate().then(Mono.error(throwable)));

return Operators.discardOnCancel(conn, () -> {
ref.release().subscribe();
if (emitting.compareAndSet(true, false)) {
logger.debug("Discarding pooled reference as creation was disposed");
ref.release().subscribe();
}
return false;
});
})
Expand All @@ -167,7 +171,8 @@ public ConnectionPool(ConnectionPoolConfiguration configuration) {
return context.put(HOOK_ON_DROPPED, onNextDropped);
}).onErrorMap(TimeoutException.class, e -> new R2dbcTimeoutException(timeoutMessage, e));
}
return mono;
return mono
.doOnTerminate(() -> emitting.compareAndSet(true, false));
});
this.create = configuration.getAcquireRetry() > 0 ? create.retry(configuration.getAcquireRetry()) : create;
}
Expand Down
37 changes: 37 additions & 0 deletions src/test/java/io/r2dbc/pool/ConnectionPoolUnitTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.reactivestreams.Subscription;
import org.springframework.util.ReflectionUtils;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
Expand All @@ -47,8 +48,10 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
Expand All @@ -60,8 +63,10 @@
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
Expand Down Expand Up @@ -1119,6 +1124,38 @@ public void cancel() {

assertThat(closed).isTrue();
}

@Test
void shouldNotDuplicateObjectsDuringCancel() {
Set<Connection> uniqueConnections = ConcurrentHashMap.newKeySet();
ConnectionFactory connectionFactoryMock = mock(ConnectionFactory.class);

when(connectionFactoryMock.create()).thenReturn((Publisher)Mono.fromCallable(() -> {
ConnectionWithLifecycle connectionMock = mock(ConnectionWithLifecycle.class);
when(connectionMock.validate(any())).thenReturn(Mono.just(true));
when(connectionMock.postAllocate()).thenReturn(Mono.empty());
when(connectionMock.preRelease()).thenReturn(Mono.<Void>fromRunnable(() ->
uniqueConnections.remove(connectionMock))
);
return connectionMock;
}));

ConnectionPool pool = new ConnectionPool(ConnectionPoolConfiguration.builder(connectionFactoryMock)
.build());
CompletableFuture<Long> future = Flux.range(0, 32)
.flatMap(i -> Mono.fromCallable(() -> true)
.then(Mono.defer(() -> Mono.usingWhen(Flux.defer(pool::create),
c -> {
assertFalse(!uniqueConnections.add(((PooledConnection)c).unwrap()),
"duplicate connections returned from pool");
return Mono.delay(Duration.ofMillis(1));
},
Connection::close))))
.ignoreElements()
.toFuture();

assertThatNoException().isThrownBy(future::join);
}

interface ConnectionWithLifecycle extends Connection, Lifecycle {

Expand Down