Skip to content

Commit

Permalink
#48 - Atomically close connections.
Browse files Browse the repository at this point in the history
We now make sure to close connections only once by tracking the cleanup state. Flux.usingWhen/Mono.usingWhen do not ensure atomic cleanup in situations where the subscription completes and then the subscription is terminated.

This behavior has lead to closing a connection multiple times.

Related ticket: reactor/reactor-core#1486
  • Loading branch information
mp911de committed Jan 11, 2019
1 parent 2dfb1ff commit 836c5b4
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
Expand Down Expand Up @@ -122,15 +123,16 @@ public <T> Mono<T> inConnection(Function<Connection, Mono<T>> action) throws Dat

Assert.notNull(action, "Callback object must not be null");

Mono<Connection> connectionMono = getConnection();
// Create close-suppressing Connection proxy, also preparing returned Statements.
Mono<ConnectionCloseHolder> connectionMono = getConnection()
.map(it -> new ConnectionCloseHolder(it, this::closeConnection));

return Mono.usingWhen(connectionMono, it -> {

Connection connectionToUse = createConnectionProxy(it);
// Create close-suppressing Connection proxy
Connection connectionToUse = createConnectionProxy(it.connection);

return doInConnection(connectionToUse, action);
}, this::closeConnection, this::closeConnection, this::closeConnection) //
}, ConnectionCloseHolder::close, ConnectionCloseHolder::close, ConnectionCloseHolder::close) //
.onErrorMap(R2dbcException.class, ex -> translateException("execute", getSql(action), ex));
}

Expand All @@ -149,15 +151,16 @@ public <T> Flux<T> inConnectionMany(Function<Connection, Flux<T>> action) throws

Assert.notNull(action, "Callback object must not be null");

Mono<Connection> connectionMono = getConnection();
// Create close-suppressing Connection proxy, also preparing returned Statements.
Mono<ConnectionCloseHolder> connectionMono = getConnection()
.map(it -> new ConnectionCloseHolder(it, this::closeConnection));

return Flux.usingWhen(connectionMono, it -> {

Connection connectionToUse = createConnectionProxy(it);
// Create close-suppressing Connection proxy, also preparing returned Statements.
Connection connectionToUse = createConnectionProxy(it.connection);

return doInConnectionMany(connectionToUse, action);
}, this::closeConnection, this::closeConnection, this::closeConnection) //
}, ConnectionCloseHolder::close, ConnectionCloseHolder::close, ConnectionCloseHolder::close) //
.onErrorMap(R2dbcException.class, ex -> translateException("executeMany", getSql(action), ex));
}

Expand Down Expand Up @@ -1104,4 +1107,26 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
}
}
}

/**
* Holder for a connection that makes sure the close action is invoked atomically only once.
*/
@RequiredArgsConstructor
static class ConnectionCloseHolder extends AtomicBoolean {

final Connection connection;
final Function<Connection, Publisher<Void>> closeFunction;

Mono<Void> close() {

return Mono.defer(() -> {

if (compareAndSet(false, true)) {
return Mono.from(closeFunction.apply(connection));
}

return Mono.empty();
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* Copyright 2019 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
*
* http://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.data.r2dbc.function;

import static org.mockito.Mockito.*;

import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import org.springframework.data.r2dbc.support.R2dbcExceptionTranslator;

/**
* Unit tests for {@link DefaultDatabaseClient}.
*
* @author Mark Paluch
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultDatabaseClientUnitTests {

@Mock ConnectionFactory connectionFactory;
@Mock Connection connection;
@Mock ReactiveDataAccessStrategy strategy;
@Mock R2dbcExceptionTranslator translator;

@Before
public void before() {
when(connectionFactory.create()).thenReturn((Publisher) Mono.just(connection));
when(connection.close()).thenReturn(Mono.empty());
}

@Test // gh-48
public void shouldCloseConnectionOnlyOnce() {

DefaultDatabaseClient databaseClient = (DefaultDatabaseClient) DatabaseClient.builder()
.connectionFactory(connectionFactory).dataAccessStrategy(strategy).exceptionTranslator(translator).build();

Flux<Object> flux = databaseClient.inConnectionMany(it -> {
return Flux.empty();
});

flux.subscribe(new CoreSubscriber<Object>() {
Subscription subscription;

@Override
public void onSubscribe(Subscription s) {
s.request(1);
subscription = s;
}

@Override
public void onNext(Object o) {}

@Override
public void onError(Throwable t) {}

@Override
public void onComplete() {
subscription.cancel();
}
});

verify(connection, times(1)).close();
}
}

0 comments on commit 836c5b4

Please sign in to comment.