use of io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH 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.HttpHeaderNames.CONTENT_LENGTH 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.HttpHeaderNames.CONTENT_LENGTH in project servicetalk by apple.
the class HttpConnectionEmptyPayloadTest method headRequestContentEmpty.
@Test
void headRequestContentEmpty() throws Exception {
try (CompositeCloseable closeable = AsyncCloseables.newCompositeCloseable()) {
final int expectedContentLength = 128;
byte[] expectedPayload = new byte[expectedContentLength];
ThreadLocalRandom.current().nextBytes(expectedPayload);
ServerContext serverContext = closeable.merge(HttpServers.forAddress(localAddress(0)).ioExecutor(executionContextRule.ioExecutor()).executionStrategy(offloadNever()).listenStreamingAndAwait((ctx, req, factory) -> {
StreamingHttpResponse resp = factory.ok().payloadBody(from(HEAD.equals(req.method()) ? EMPTY_BUFFER : ctx.executionContext().bufferAllocator().newBuffer(expectedContentLength).writeBytes(expectedPayload)));
resp.addHeader(CONTENT_LENGTH, String.valueOf(expectedContentLength));
return succeeded(resp);
}));
StreamingHttpClient client = closeable.merge(forResolvedAddress(serverHostAndPort(serverContext)).ioExecutor(executionContextRule.ioExecutor()).protocols(h1().maxPipelinedRequests(3).build()).executor(executionContextRule.executor()).executionStrategy(defaultStrategy()).buildStreaming());
StreamingHttpConnection connection = closeable.merge(client.reserveConnection(client.get("/")).toFuture().get());
// Request HEAD, GET, HEAD to verify that we can keep reading data despite a HEAD request providing a hint
// about content-length (and not actually providing the content).
Single<StreamingHttpResponse> response1Single = connection.request(connection.newRequest(HEAD, "/"));
Single<StreamingHttpResponse> response2Single = connection.request(connection.get("/"));
Single<StreamingHttpResponse> response3Single = connection.request(connection.newRequest(HEAD, "/"));
StreamingHttpResponse response = awaitIndefinitelyNonNull(response1Single);
assertEquals(OK, response.status());
CharSequence contentLength = response.headers().get(CONTENT_LENGTH);
assertNotNull(contentLength);
assertEquals(expectedContentLength, parseInt(contentLength.toString()));
// Drain the current response content so we will be able to read the next response.
response.messageBody().ignoreElements().toFuture().get();
response = awaitIndefinitelyNonNull(response2Single);
assertEquals(OK, response.status());
contentLength = response.headers().get(CONTENT_LENGTH);
assertNotNull(contentLength);
assertEquals(expectedContentLength, parseInt(contentLength.toString()));
Buffer buffer = awaitIndefinitelyNonNull(response.payloadBody().collect(() -> connection.connectionContext().executionContext().bufferAllocator().newBuffer(), Buffer::writeBytes));
byte[] actualBytes = new byte[buffer.readableBytes()];
buffer.readBytes(actualBytes);
assertArrayEquals(expectedPayload, actualBytes);
response = awaitIndefinitelyNonNull(response3Single);
assertEquals(OK, response.status());
contentLength = response.headers().get(CONTENT_LENGTH);
assertNotNull(contentLength);
assertEquals(expectedContentLength, parseInt(contentLength.toString()));
response.messageBody().ignoreElements().toFuture().get();
}
}
use of io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH in project servicetalk by apple.
the class TestServiceStreaming method newEchoResponse.
private static StreamingHttpResponse newEchoResponse(final StreamingHttpRequest req, final StreamingHttpResponseFactory factory) {
final StreamingHttpResponse response = factory.ok().version(req.version()).transformMessageBody(pub -> pub.ignoreElements().merge(req.messageBody())).transform(new StatelessTrailersTransformer<>());
final CharSequence contentLength = req.headers().get(CONTENT_LENGTH);
if (contentLength != null) {
response.addHeader(CONTENT_LENGTH, contentLength);
}
final CharSequence contentType = req.headers().get(CONTENT_TYPE);
if (contentType != null) {
response.addHeader(CONTENT_TYPE, contentType);
}
final CharSequence transferEncoding = req.headers().get(TRANSFER_ENCODING);
if (transferEncoding != null) {
response.addHeader(TRANSFER_ENCODING, transferEncoding);
}
return response;
}
use of io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH in project servicetalk by apple.
the class DefaultContainerResponseWriter method sendResponse.
private void sendResponse(final long contentLength, @Nullable final Publisher<Buffer> content, final ContainerResponse containerResponse) {
final HttpResponseStatus status = getStatus(containerResponse);
final StreamingHttpResponse response;
if (content != null && !isHeadRequest()) {
final HttpExecutionStrategy executionStrategy = getResponseExecutionStrategy(request);
// TODO(scott): use request factory methods that accept a payload body to avoid overhead of payloadBody.
final Publisher<Buffer> payloadBody = (executionStrategy != null && executionStrategy.isSendOffloaded() ? content.subscribeOn(serviceCtx.executionContext().executor(), IoThreadFactory.IoThread::currentThreadIsIoThread) : content).beforeCancel(// Cleanup internal state if server cancels response body
this::cancelResponse);
response = responseFactory.newResponse(status).version(protocolVersion).payloadBody(payloadBody);
} else {
response = responseFactory.newResponse(status).version(protocolVersion);
}
final HttpHeaders headers = response.headers();
// If we use HTTP/2 protocol all headers MUST be in lower case
final boolean isH2 = response.version().major() == 2;
containerResponse.getHeaders().forEach((k, vs) -> vs.forEach(v -> {
headers.add(isH2 ? k.toLowerCase() : k, v == null ? emptyAsciiString() : asCharSequence(v));
}));
if (!headers.contains(CONTENT_LENGTH)) {
if (contentLength == UNKNOWN_RESPONSE_LENGTH) {
// We can omit Transfer-Encoding for HEAD per https://tools.ietf.org/html/rfc7231#section-4.3.2
if (!isHeadRequest() && !HTTP_1_0.equals(protocolVersion)) {
headers.set(TRANSFER_ENCODING, CHUNKED);
}
} else {
headers.set(CONTENT_LENGTH, contentLength == 0 ? ZERO : Long.toString(contentLength));
headers.removeIgnoreCase(TRANSFER_ENCODING, CHUNKED);
}
}
responseSubscriber.onSuccess(response);
}
Aggregations