use of io.servicetalk.http.api.HttpServerBuilder 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.http.api.HttpServerBuilder 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();
}
use of io.servicetalk.http.api.HttpServerBuilder in project servicetalk by apple.
the class ExecutionStrategyInContextTest method initClientAndServer.
private SingleAddressHttpClientBuilder<HostAndPort, InetSocketAddress> initClientAndServer(Function<HttpServerBuilder, Single<HttpServerContext>> serverStarter, boolean customStrategy) throws Exception {
HttpServerBuilder serverBuilder = HttpServers.forAddress(localAddress(0));
if (customStrategy) {
expectedServerStrategy = HttpExecutionStrategies.offloadAll();
serverBuilder.executionStrategy(expectedServerStrategy);
}
context = serverStarter.apply(serverBuilder).toFuture().get();
SingleAddressHttpClientBuilder<HostAndPort, InetSocketAddress> clientBuilder = forSingleAddress(serverHostAndPort(context));
if (customStrategy) {
expectedClientStrategy = HttpExecutionStrategies.offloadAll();
clientBuilder.executionStrategy(expectedClientStrategy);
}
return clientBuilder;
}
use of io.servicetalk.http.api.HttpServerBuilder in project servicetalk by apple.
the class HttpProtocolConfigTest method serverDoesNotSupportH2cUpgrade.
@Test
void serverDoesNotSupportH2cUpgrade() {
HttpServerBuilder builder = HttpServers.forAddress(localAddress(0)).protocols(h2Default(), h1Default());
Exception e = assertThrows(IllegalStateException.class, () -> builder.listenBlocking((ctx, request, responseFactory) -> responseFactory.noContent()));
assertEquals("Cleartext HTTP/1.1 -> HTTP/2 (h2c) upgrade is not supported", e.getMessage());
}
use of io.servicetalk.http.api.HttpServerBuilder in project servicetalk by apple.
the class HttpProtocolConfigTest method serverWithNullProtocolConfig.
@Test
void serverWithNullProtocolConfig() {
HttpServerBuilder builder = HttpServers.forAddress(localAddress(0));
assertThrows(NullPointerException.class, () -> builder.protocols(null));
}
Aggregations