use of io.servicetalk.concurrent.api.Completable in project servicetalk by apple.
the class RetryWhenTest method setUp.
@SuppressWarnings("unchecked")
@BeforeEach
void setUp() {
source = new LegacyTestSingle<>(false, false);
shouldRetry = (BiIntFunction<Throwable, Completable>) mock(BiIntFunction.class);
retrySignal = new LegacyTestCompletable();
when(shouldRetry.apply(anyInt(), any())).thenAnswer(invocation -> {
retrySignal = new LegacyTestCompletable();
return retrySignal;
});
toSource(source.retryWhen(shouldRetry)).subscribe(subscriberRule);
}
use of io.servicetalk.concurrent.api.Completable in project servicetalk by apple.
the class RetryWhenTest method setUp.
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
shouldRetry = (BiIntFunction<Throwable, Completable>) mock(BiIntFunction.class);
retrySignal = new LegacyTestCompletable();
when(shouldRetry.apply(anyInt(), any())).thenAnswer(invocation -> {
retrySignal = new LegacyTestCompletable();
return retrySignal;
});
toSource(source.retryWhen(shouldRetry)).subscribe(subscriber);
}
use of io.servicetalk.concurrent.api.Completable in project servicetalk by apple.
the class TimeoutPublisherTest method concurrentTimeoutInvocation.
@Test
void concurrentTimeoutInvocation() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
AtomicReference<Throwable> causeRef = new AtomicReference<>();
// In order to simulate concurrent execution, we introduce an Executor that does not respect the delay for the
// first timer schedule. Internally, we expect the TimeoutPublisher to reschedule the timer. For that we use
// TestExecutor, which will allow us to advance the time and trigger the actual timeout, which will simulate
// concurrent execution.
toSource(publisher.timeout(10, MILLISECONDS, new Executor() {
private final AtomicInteger timerCount = new AtomicInteger();
@Override
public Cancellable schedule(final Runnable task, final long delay, final TimeUnit unit) {
int count = timerCount.incrementAndGet();
if (count <= 2) {
if (count == 1) {
try {
task.run();
} catch (Throwable cause) {
causeRef.compareAndSet(null, cause);
countDownToZero(latch);
}
latch.countDown();
} else {
try {
try {
testExecutor.schedule(task, delay, unit);
testExecutor.advanceTimeBy(delay, unit);
} catch (Throwable cause) {
causeRef.compareAndSet(null, cause);
countDownToZero(latch);
}
latch.countDown();
} catch (Throwable cause) {
causeRef.compareAndSet(null, cause);
countDownToZero(latch);
}
}
}
return IGNORE_CANCEL;
}
@Override
public long currentTime(final TimeUnit unit) {
return testExecutor.currentTime(unit);
}
@Override
public Completable closeAsync() {
throw new UnsupportedOperationException();
}
@Override
public Completable onClose() {
throw new UnsupportedOperationException();
}
@Override
public Cancellable execute(final Runnable task) throws RejectedExecutionException {
throw new UnsupportedOperationException();
}
})).subscribe(subscriber);
latch.await();
assertNull(causeRef.get());
assertThat(subscriber.awaitOnError(), instanceOf(TimeoutException.class));
}
use of io.servicetalk.concurrent.api.Completable in project servicetalk by apple.
the class GracefulConnectionClosureHandlingTest method setUp.
void setUp(HttpProtocol protocol, boolean initiateClosureFromClient, boolean useUds, boolean viaProxy) throws Exception {
this.protocol = protocol;
this.initiateClosureFromClient = initiateClosureFromClient;
if (useUds) {
Assumptions.assumeTrue(SERVER_CTX.ioExecutor().isUnixDomainSocketSupported(), "Server's IoExecutor does not support UnixDomainSocket");
Assumptions.assumeTrue(CLIENT_CTX.ioExecutor().isUnixDomainSocketSupported(), "Client's IoExecutor does not support UnixDomainSocket");
assumeFalse(viaProxy, "UDS cannot be used via proxy");
}
assumeFalse(protocol == HTTP_2 && viaProxy, "Proxy is not supported with HTTP/2");
HttpServerBuilder serverBuilder = (useUds ? forAddress(newSocketAddress()) : forAddress(localAddress(0))).protocols(protocol.config).ioExecutor(SERVER_CTX.ioExecutor()).executor(SERVER_CTX.executor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, () -> true).appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {
@Override
public Completable accept(final ConnectionContext context) {
if (!initiateClosureFromClient) {
((NettyConnectionContext) context).onClosing().whenFinally(onClosing::countDown).subscribe();
}
context.onClose().whenFinally(serverConnectionClosed::countDown).subscribe();
connectionAccepted.countDown();
return completed();
}
});
HostAndPort proxyAddress = null;
if (viaProxy) {
// Dummy proxy helps to emulate old intermediate systems that do not support half-closed TCP connections
proxyTunnel = new ProxyTunnel();
proxyAddress = proxyTunnel.startProxy();
serverBuilder.sslConfig(new ServerSslConfigBuilder(DefaultTestCerts::loadServerPem, DefaultTestCerts::loadServerKey).build());
} else {
proxyTunnel = null;
}
serverContext = serverBuilder.listenBlockingStreamingAndAwait((ctx, request, response) -> {
serverReceivedRequest.countDown();
response.addHeader(CONTENT_LENGTH, valueOf(RESPONSE_CONTENT.length()));
serverSendResponse.await();
try (HttpPayloadWriter<String> writer = response.sendMetaData(RAW_STRING_SERIALIZER)) {
// Subscribe to the request payload body before response writer closes
BlockingIterator<Buffer> iterator = request.payloadBody().iterator();
// Consume request payload body asynchronously:
ctx.executionContext().executor().submit(() -> {
int receivedSize = 0;
while (iterator.hasNext()) {
Buffer chunk = iterator.next();
assert chunk != null;
receivedSize += chunk.readableBytes();
}
serverReceivedRequestPayload.add(receivedSize);
}).beforeOnError(cause -> {
LOGGER.error("failure while reading request", cause);
serverReceivedRequestPayload.add(-1);
}).toFuture();
serverSendResponsePayload.await();
writer.write(RESPONSE_CONTENT);
}
});
serverContext.onClose().whenFinally(serverContextClosed::countDown).subscribe();
client = (viaProxy ? forSingleAddress(serverHostAndPort(serverContext)).proxyAddress(proxyAddress).sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).peerHost(serverPemHostname()).build()) : forResolvedAddress(serverContext.listenAddress())).protocols(protocol.config).executor(CLIENT_CTX.executor()).ioExecutor(CLIENT_CTX.ioExecutor()).executionStrategy(defaultStrategy()).enableWireLogging("servicetalk-tests-wire-logger", TRACE, Boolean.TRUE::booleanValue).appendConnectionFactoryFilter(ConnectionFactoryFilter.withStrategy(cf -> initiateClosureFromClient ? new OnClosingConnectionFactoryFilter<>(cf, onClosing) : cf, ExecutionStrategy.offloadNone())).buildStreaming();
connection = client.reserveConnection(client.get("/")).toFuture().get();
connection.onClose().whenFinally(clientConnectionClosed::countDown).subscribe();
// wait until server accepts connection
connectionAccepted.await();
toClose = initiateClosureFromClient ? connection : serverContext;
}
use of io.servicetalk.concurrent.api.Completable in project servicetalk by apple.
the class H2PriorKnowledgeFeatureParityTest method bindHttpEchoServer.
private InetSocketAddress bindHttpEchoServer(@Nullable StreamingHttpServiceFilterFactory filterFactory, @Nullable CountDownLatch connectionOnClosingLatch) throws Exception {
HttpServerBuilder serverBuilder = HttpServers.forAddress(localAddress(0)).protocols(h2PriorKnowledge ? h2Default() : h1Default());
if (filterFactory != null) {
serverBuilder.appendServiceFilter(filterFactory);
}
if (connectionOnClosingLatch != null) {
serverBuilder.appendConnectionAcceptorFilter(original -> new DelegatingConnectionAcceptor(original) {
@Override
public Completable accept(final ConnectionContext context) {
((NettyConnectionContext) context).onClosing().whenFinally(connectionOnClosingLatch::countDown).subscribe();
return completed();
}
});
}
h1ServerContext = serverBuilder.listenStreaming((ctx, request, responseFactory) -> {
StreamingHttpResponse resp;
if (request.headers().contains(EXPECT, CONTINUE)) {
if (request.headers().contains(EXPECT_FAIL_HEADER)) {
return succeeded(responseFactory.expectationFailed());
} else {
resp = responseFactory.continueResponse();
}
} else {
resp = responseFactory.ok();
}
resp = resp.transformMessageBody(pub -> pub.ignoreElements().merge(request.messageBody())).transform(new StatelessTrailersTransformer<>());
CharSequence contentType = request.headers().get(CONTENT_TYPE);
if (contentType != null) {
resp.setHeader(CONTENT_TYPE, contentType);
}
CharSequence contentLength = request.headers().get(CONTENT_LENGTH);
if (contentLength != null) {
resp.setHeader(CONTENT_LENGTH, contentLength);
}
CharSequence transferEncoding = request.headers().get(TRANSFER_ENCODING);
if (transferEncoding != null) {
resp.setHeader(TRANSFER_ENCODING, transferEncoding);
}
resp.headers().set(COOKIE, request.headers().valuesIterator(COOKIE));
return succeeded(resp);
}).toFuture().get();
return (InetSocketAddress) h1ServerContext.listenAddress();
}
Aggregations