Skip to content

Commit

Permalink
gRPC services to support closing (#903)
Browse files Browse the repository at this point in the history
__Motivation__

gRPC implementation does not wire close implementations (by implementing methods in `AsyncCloseable`, `GracefulAutoCloseable` or `AutoCloseable`) defines by services such that server closure will invoke the appropriate close methods on the service. Also, there is no way to specify close semantics while implementing interfaces for each RPC method.

__Modification__

- Defined two new interfaces; `Rpc` and `BlockingRpc` that are appropriately implemented by individual RPC methods.
- Introduced a `wrap()` method for each existing `Route` interface variant such that a lambda implementing the route can also define a detached close implementation and this method will attach the close implementation to the route implementation by wrapping.
- Modified gRPC code generation to utilize the above changes.
- Modified gRPC router to use these new functionality and wire close together through various route layers.
- Added tests to verify each close implementation variant.
- Fixed a bug in blocking -> async service conversions that were not implementing graceful close (required for this change).

__Result__

gRPC services can now implement close methods when required.
  • Loading branch information
Nitesh Kant committed Jan 3, 2020
1 parent b936679 commit 1634895
Show file tree
Hide file tree
Showing 10 changed files with 818 additions and 118 deletions.
Expand Up @@ -21,4 +21,8 @@
* A blocking <a href="https://www.grpc.io">gRPC</a> service.
*/
public interface BlockingGrpcService extends GracefulAutoCloseable {
@Override
default void close() throws Exception {
// noop
}
}

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Expand Up @@ -16,9 +16,16 @@
package io.servicetalk.grpc.api;

import io.servicetalk.concurrent.api.AsyncCloseable;
import io.servicetalk.concurrent.api.Completable;

import static io.servicetalk.concurrent.api.Completable.completed;

/**
* A <a href="https://www.grpc.io">gRPC</a> service.
*/
public interface GrpcService extends AsyncCloseable {
@Override
default Completable closeAsync() {
return completed();
}
}
@@ -0,0 +1,267 @@
/*
* Copyright © 2019 Apple Inc. and the ServiceTalk project 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 io.servicetalk.grpc.netty;

import io.servicetalk.concurrent.GracefulAutoCloseable;
import io.servicetalk.concurrent.api.AsyncCloseable;
import io.servicetalk.concurrent.api.Completable;
import io.servicetalk.concurrent.internal.ServiceTalkTestTimeout;
import io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTestBiDiStreamRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTestRequestStreamRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTestResponseStreamRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTestRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.BlockingTesterService;
import io.servicetalk.grpc.netty.TesterProto.Tester.TestBiDiStreamRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.TestRequestStreamRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.TestResponseStreamRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.TestRpc;
import io.servicetalk.grpc.netty.TesterProto.Tester.TesterService;
import io.servicetalk.transport.api.ServerContext;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import static io.servicetalk.concurrent.api.Completable.completed;
import static io.servicetalk.concurrent.api.Completable.defer;
import static io.servicetalk.grpc.netty.GrpcServers.forAddress;
import static io.servicetalk.grpc.netty.TesterProto.Tester.ServiceFactory;
import static io.servicetalk.transport.netty.internal.AddressUtils.localAddress;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

@RunWith(Parameterized.class)
public class ClosureTest {
@Rule
public final Timeout timeout = new ServiceTalkTestTimeout();

private final boolean closeGracefully;

public ClosureTest(final boolean closeGracefully) {
this.closeGracefully = closeGracefully;
}

@Parameterized.Parameters(name = "graceful? => {0}")
public static Collection<Boolean> data() {
return asList(true, false);
}

@Test
public void serviceImplIsClosed() throws Exception {
CloseSignal signal = new CloseSignal(1);
TesterService svc = setupCloseMock(mock(TesterService.class), signal);
startServerAndClose(new ServiceFactory(svc), signal);
verifyClosure(svc, 4 /* 4 rpc methods */);
signal.verifyCloseAtLeastCount(closeGracefully);
}

@Test
public void blockingServiceImplIsClosed() throws Exception {
CloseSignal signal = new CloseSignal(1);
BlockingTesterService svc = setupBlockingCloseMock(mock(BlockingTesterService.class), signal);
startServerAndClose(new ServiceFactory(svc), signal);
verifyClosure(svc, 4 /* 4 rpc methods */);
signal.verifyCloseAtLeastCount(closeGracefully);
}

@Test
public void rpcMethodsAreClosed() throws Exception {
CloseSignal signal = new CloseSignal(4);
TestRpc testRpc = setupCloseMock(mock(TestRpc.class), signal);
TestRequestStreamRpc testRequestStreamRpc = setupCloseMock(mock(TestRequestStreamRpc.class), signal);
TestResponseStreamRpc testResponseStreamRpc = setupCloseMock(mock(TestResponseStreamRpc.class), signal);
TestBiDiStreamRpc testBiDiStreamRpc = setupCloseMock(mock(TestBiDiStreamRpc.class), signal);
startServerAndClose(new ServiceFactory.Builder()
.test(testRpc)
.testRequestStream(testRequestStreamRpc)
.testResponseStream(testResponseStreamRpc)
.testBiDiStream(testBiDiStreamRpc)
.build(), signal);
verifyClosure(testRpc);
verifyClosure(testRequestStreamRpc);
verifyClosure(testResponseStreamRpc);
verifyClosure(testBiDiStreamRpc);
signal.verifyClose(closeGracefully);
}

@Test
public void blockingRpcMethodsAreClosed() throws Exception {
CloseSignal signal = new CloseSignal(4);
BlockingTestRpc testRpc = setupBlockingCloseMock(mock(BlockingTestRpc.class), signal);
BlockingTestRequestStreamRpc testRequestStreamRpc =
setupBlockingCloseMock(mock(BlockingTestRequestStreamRpc.class), signal);
BlockingTestResponseStreamRpc testResponseStreamRpc =
setupBlockingCloseMock(mock(BlockingTestResponseStreamRpc.class), signal);
BlockingTestBiDiStreamRpc testBiDiStreamRpc =
setupBlockingCloseMock(mock(BlockingTestBiDiStreamRpc.class), signal);
startServerAndClose(new ServiceFactory.Builder()
.testBlocking(testRpc)
.testRequestStreamBlocking(testRequestStreamRpc)
.testResponseStreamBlocking(testResponseStreamRpc)
.testBiDiStreamBlocking(testBiDiStreamRpc)
.build(), signal);
verifyClosure(testRpc);
verifyClosure(testRequestStreamRpc);
verifyClosure(testResponseStreamRpc);
verifyClosure(testBiDiStreamRpc);
signal.verifyClose(closeGracefully);
}

@Test
public void mixedModeRpcMethodsAreClosed() throws Exception {
CloseSignal signal = new CloseSignal(4);
TestRpc testRpc = setupCloseMock(mock(TestRpc.class), signal);
TestRequestStreamRpc testRequestStreamRpc = setupCloseMock(mock(TestRequestStreamRpc.class), signal);
BlockingTestResponseStreamRpc testResponseStreamRpc =
setupBlockingCloseMock(mock(BlockingTestResponseStreamRpc.class), signal);
BlockingTestBiDiStreamRpc testBiDiStreamRpc =
setupBlockingCloseMock(mock(BlockingTestBiDiStreamRpc.class), signal);
startServerAndClose(new ServiceFactory.Builder()
.test(testRpc)
.testRequestStream(testRequestStreamRpc)
.testResponseStreamBlocking(testResponseStreamRpc)
.testBiDiStreamBlocking(testBiDiStreamRpc)
.build(), signal);
verifyClosure(testRpc);
verifyClosure(testRequestStreamRpc);
verifyClosure(testResponseStreamRpc);
verifyClosure(testBiDiStreamRpc);
signal.verifyClose(closeGracefully);
}

private <T extends AsyncCloseable> T setupCloseMock(final T autoCloseable, final AsyncCloseable closeSignal) {
when(autoCloseable.closeAsync()).thenReturn(closeSignal.closeAsync());
when(autoCloseable.closeAsyncGracefully()).thenReturn(closeSignal.closeAsyncGracefully());
return autoCloseable;
}

private <T extends GracefulAutoCloseable> T setupBlockingCloseMock(final T autoCloseable,
final AsyncCloseable closeSignal)
throws Exception {
doAnswer(__ -> closeSignal.closeAsync().toFuture().get()).when(autoCloseable).close();
doAnswer(__ -> closeSignal.closeAsyncGracefully().toFuture().get()).when(autoCloseable).closeGracefully();
return autoCloseable;
}

private void verifyClosure(AsyncCloseable closeable) {
verifyClosure(closeable, 1);
}

private void verifyClosure(AsyncCloseable closeable, int times) {
// Async mode both methods are called but one is subscribed.
verify(closeable, times(times)).closeAsyncGracefully();
verify(closeable, times(times)).closeAsync();
verifyNoMoreInteractions(closeable);
}

private void verifyClosure(GracefulAutoCloseable closeable) throws Exception {
verifyClosure(closeable, 1);
}

private void verifyClosure(GracefulAutoCloseable closeable, int times) throws Exception {
if (closeGracefully) {
verify(closeable, times(times)).closeGracefully();
} else {
verify(closeable, times(times)).close();
}
verifyNoMoreInteractions(closeable);
}

private void startServerAndClose(final ServiceFactory serviceFactory, final CloseSignal signal) throws Exception {
ServerContext serverContext = forAddress(localAddress(0))
.listenAndAwait(serviceFactory);

if (closeGracefully) {
serverContext.closeGracefully();
} else {
serverContext.close();
}

signal.await();
}

private static final class CloseSignal implements AsyncCloseable {
private final CountDownLatch latch;
private final int count;
private final AtomicInteger closeCount;
private final AtomicInteger gracefulCloseCount;
private final Completable close;
private final Completable closeGraceful;

CloseSignal(final int count) {
latch = new CountDownLatch(count);
this.count = count;
closeCount = new AtomicInteger();
gracefulCloseCount = new AtomicInteger();
close = defer(() -> {
closeCount.incrementAndGet();
latch.countDown();
return completed();
});
closeGraceful = defer(() -> {
gracefulCloseCount.incrementAndGet();
latch.countDown();
return completed();
});
}

void await() throws Exception {
latch.await();
}

void verifyClose(boolean graceful) {
assertThat("Unexpected graceful closures.", gracefulCloseCount.get(),
equalTo(graceful ? count : 0));
assertThat("Unexpected closures.", closeCount.get(), equalTo(graceful ? 0 : count));
}

void verifyCloseAtLeastCount(boolean graceful) {
if (graceful) {
assertThat("Unexpected graceful closures.", gracefulCloseCount.get(),
greaterThanOrEqualTo(count));
assertThat("Unexpected closures.", closeCount.get(), equalTo(0));
} else {
assertThat("Unexpected graceful closures.", gracefulCloseCount.get(),
equalTo(0));
assertThat("Unexpected closures.", closeCount.get(), greaterThanOrEqualTo(count));
}
}

@Override
public Completable closeAsync() {
return close;
}

@Override
public Completable closeAsyncGracefully() {
return closeGraceful;
}
}
}
Expand Up @@ -65,6 +65,7 @@
import java.util.concurrent.Future;

import static io.servicetalk.concurrent.api.AsyncCloseables.newCompositeCloseable;
import static io.servicetalk.concurrent.api.Completable.completed;
import static io.servicetalk.concurrent.api.SourceAdapters.toSource;
import static io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION;
import static io.servicetalk.transport.netty.internal.AddressUtils.localAddress;
Expand Down Expand Up @@ -135,7 +136,7 @@ public ErrorHandlingTest(TestMode testMode) throws Exception {
this.testMode = testMode;
cannedResponse = TestResponse.newBuilder().setMessage("foo").build();
ServiceFactory serviceFactory;
TesterService filter = mock(TesterService.class);
TesterService filter = mockTesterService();
StreamingHttpServiceFilterFactory serviceFilterFactory = IDENTITY_FILTER;
StreamingHttpClientFilterFactory clientFilterFactory = IDENTITY_CLIENT_FILTER;
switch (testMode) {
Expand Down Expand Up @@ -230,7 +231,7 @@ public ErrorHandlingTest(TestMode testMode) throws Exception {

private ServiceFactory configureFilter(final TesterService filter) {
final ServiceFactory serviceFactory;
final TesterService service = mock(TesterService.class);
final TesterService service = mockTesterService();
serviceFactory = new ServiceFactory(service);
serviceFactory.appendServiceFilter(original ->
new ErrorSimulatingTesterServiceFilter(original, filter));
Expand Down Expand Up @@ -265,7 +266,7 @@ public Single<TestResponse> test(final GrpcServiceContext ctx, final TestRequest
}

private ServiceFactory setupForServiceThrows(final Throwable toThrow) {
final TesterService service = mock(TesterService.class);
final TesterService service = mockTesterService();
setupForServiceThrows(service, toThrow);
return new ServiceFactory(service);
}
Expand All @@ -278,7 +279,7 @@ private void setupForServiceThrows(final TesterService service, final Throwable
}

private ServiceFactory setupForServiceEmitsError(final Throwable toThrow) {
final TesterService service = mock(TesterService.class);
final TesterService service = mockTesterService();
setupForServiceEmitsError(service, toThrow);
return new ServiceFactory(service);
}
Expand All @@ -291,7 +292,7 @@ private void setupForServiceEmitsError(final TesterService service, final Throwa
}

private ServiceFactory setupForServiceEmitsDataThenError(final Throwable toThrow) {
final TesterService service = mock(TesterService.class);
final TesterService service = mockTesterService();
setupForServiceEmitsDataThenError(service, toThrow);
return new ServiceFactory(service);
}
Expand Down Expand Up @@ -420,6 +421,13 @@ public void responseStreamingFromBlockingClient() throws Exception {
}
}

private TesterService mockTesterService() {
TesterService filter = mock(TesterService.class);
when(filter.closeAsync()).thenReturn(completed());
when(filter.closeAsyncGracefully()).thenReturn(completed());
return filter;
}

private void verifyStreamingResponse(final BlockingIterator<TestResponse> resp) {
switch (testMode) {
case ServiceEmitsDataThenError:
Expand Down

0 comments on commit 1634895

Please sign in to comment.