use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.
the class BlockingStreamingToStreamingServiceTest method cancelAfterSendMetaDataPropagated.
@Test
void cancelAfterSendMetaDataPropagated() throws Exception {
CountDownLatch cancelLatch = new CountDownLatch(1);
CountDownLatch serviceTerminationLatch = new CountDownLatch(1);
CountDownLatch onErrorLatch = new CountDownLatch(1);
AtomicReference<Throwable> throwableRef = new AtomicReference<>();
BlockingStreamingHttpService syncService = (ctx, request, response) -> {
response.sendMetaData();
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Throwable t) {
throwableRef.set(t);
onErrorLatch.countDown();
} finally {
serviceTerminationLatch.countDown();
}
};
StreamingHttpService asyncService = toStreamingHttpService(syncService, offloadNone()).adaptor();
StreamingHttpResponse asyncResponse = asyncService.handle(mockCtx, reqRespFactory.get("/"), reqRespFactory).subscribeOn(executorExtension.executor()).toFuture().get();
assertMetaData(OK, asyncResponse);
toSource(asyncResponse.payloadBody()).subscribe(new Subscriber<Buffer>() {
@Override
public void onSubscribe(final Subscription s) {
s.cancel();
cancelLatch.countDown();
}
@Override
public void onNext(final Buffer s) {
}
@Override
public void onError(final Throwable t) {
}
@Override
public void onComplete() {
}
});
cancelLatch.await();
onErrorLatch.await();
assertThat(throwableRef.get(), instanceOf(InterruptedException.class));
serviceTerminationLatch.await();
}
use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.
the class DefaultMultiAddressUrlHttpClientBuilderTest method internalClientsUseDifferentExecutionContextWhenConfigured.
@Test
void internalClientsUseDifferentExecutionContextWhenConfigured() throws Exception {
HttpExecutionContext externalCtx = new HttpExecutionContextBuilder().ioExecutor(CTX.ioExecutor()).executor(CTX.executor()).bufferAllocator(PREFER_HEAP_ALLOCATOR).executionStrategy(offloadAll()).build();
HttpExecutionContext internalCtx = new HttpExecutionContextBuilder().ioExecutor(INTERNAL_CLIENT_CTX.ioExecutor()).executor(INTERNAL_CLIENT_CTX.executor()).bufferAllocator(PREFER_DIRECT_ALLOCATOR).executionStrategy(offloadNone()).build();
AtomicReference<HttpExecutionContext> actualInternalCtx = new AtomicReference<>();
try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).executionStrategy(offloadNone()).listenStreamingAndAwait((ctx, request, responseFactory) -> succeeded(responseFactory.ok()));
BlockingHttpClient blockingHttpClient = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> builder.executionStrategy(internalCtx.executionStrategy()).executor(internalCtx.executor()).ioExecutor(internalCtx.ioExecutor()).bufferAllocator(internalCtx.bufferAllocator()).appendClientFilter(client -> {
actualInternalCtx.set(client.executionContext());
return new StreamingHttpClientFilter(client) {
};
})).executor(externalCtx.executor()).ioExecutor(externalCtx.ioExecutor()).executionStrategy(externalCtx.executionStrategy()).bufferAllocator(externalCtx.bufferAllocator()).buildBlocking()) {
// Check external client
assertExecutionContext(externalCtx, blockingHttpClient.executionContext());
// Make a request to trigger the filter execution that extracts the execution context.
HttpResponse response = blockingHttpClient.request(blockingHttpClient.get("http://" + serverHostAndPort(serverContext)));
assertThat(response.status(), is(OK));
// Check internal client
assertExecutionContext(internalCtx, actualInternalCtx.get());
}
}
use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.
the class ConsumeRequestPayloadOnResponsePathTest method test.
private void test(final BiFunction<Single<StreamingHttpResponse>, StreamingHttpRequest, Single<StreamingHttpResponse>> consumeRequestPayload) throws Exception {
try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).appendServiceFilter(service -> new StreamingHttpServiceFilter(service) {
@Override
public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
return consumeRequestPayload.apply(delegate().handle(ctx, request, responseFactory), request);
}
}).listenStreamingAndAwait((ctx, request, responseFactory) -> {
final StreamingHttpResponse response = responseFactory.ok().addHeader(TRAILER, X_TOTAL_LENGTH).payloadBody(from("Response\n", "Payload\n", "Body\n"), appSerializerUtf8FixLen()).transform(new TrailersTransformer<AtomicInteger, Buffer>() {
@Override
public AtomicInteger newState() {
return new AtomicInteger();
}
@Override
public Buffer accept(final AtomicInteger total, final Buffer chunk) {
total.addAndGet(chunk.readableBytes());
return chunk;
}
@Override
public HttpHeaders payloadComplete(final AtomicInteger total, final HttpHeaders trailers) {
trailers.add(X_TOTAL_LENGTH, String.valueOf(total.get()));
return trailers;
}
@Override
public HttpHeaders catchPayloadFailure(final AtomicInteger __, final Throwable ___, final HttpHeaders trailers) {
return trailers;
}
});
return succeeded(response);
})) {
HttpResponse response;
try (BlockingHttpClient client = HttpClients.forSingleAddress(AddressUtils.serverHostAndPort(serverContext)).buildBlocking()) {
response = client.request(client.post("/").payloadBody(EXPECTED_REQUEST_PAYLOAD, textSerializerUtf8()));
serverLatch.await();
}
assertThat(response.status(), is(OK));
assertThat("Request payload body might be consumed by someone else", errorRef.get(), is(nullValue()));
assertThat(receivedPayload.toString(), is(EXPECTED_REQUEST_PAYLOAD));
assertThat(response.headers().contains(TRAILER, X_TOTAL_LENGTH), is(true));
assertThat(response.trailers().contains(X_TOTAL_LENGTH), is(true));
CharSequence trailerLength = response.trailers().get(X_TOTAL_LENGTH);
assertNotNull(trailerLength);
assertThat("Unexpected response payload: '" + response.payloadBody().toString(UTF_8) + "'", trailerLength.toString(), is(Integer.toString(response.payloadBody().readableBytes())));
}
}
use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.
the class AbstractEchoServerBasedHttpRequesterTest method makeRequestValidateResponseAndClose.
static void makeRequestValidateResponseAndClose(StreamingHttpRequester requester) throws ExecutionException, InterruptedException {
try {
StreamingHttpRequest request = requester.get("/request?foo=bar&foo=baz").payloadBody(from(DEFAULT_ALLOCATOR.fromAscii("Testing123")));
request.headers().set(HOST, "mock.servicetalk.io");
StreamingHttpResponse resp = awaitIndefinitelyNonNull(requester.request(request).retryWhen(retryWithExponentialBackoffFullJitter(10, t -> true, ofMillis(100), ofDays(10), CTX.executor())));
assertThat(resp.status(), equalTo(OK));
Single<String> respBody = resp.payloadBody().collect(StringBuilder::new, (sb, buf) -> {
sb.append(buf.toString(UTF_8));
return sb;
}).map(StringBuilder::toString);
HttpHeaders headers = resp.headers();
assertThat(headers.get("test-req-method"), hasToString(GET.toString()));
assertThat(headers.get("test-req-target"), hasToString("/request?foo=bar&foo=baz"));
assertThat(headers.get("test-req-header-host"), hasToString("mock.servicetalk.io"));
assertThat(headers.get("test-req-header-transfer-encoding"), equalTo(CHUNKED));
assertThat(respBody.toFuture().get(), equalTo("Testing123"));
} finally {
requester.closeAsync().toFuture().get();
}
}
use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.
the class RedirectingClientAndConnectionFilterTest method redirectFilterWithHostHeaderAbsoluteLocation.
@ParameterizedTest(name = "{displayName} [{index}] {0}-{1}")
@MethodSource("requesterTypes")
void redirectFilterWithHostHeaderAbsoluteLocation(final RequesterType type, final SecurityType security) throws Exception {
setUp(security);
BlockingHttpRequester client = asBlockingRequester(createFilter(type, (responseFactory, request) -> {
if (request.requestTarget().equals("/")) {
return succeeded(responseFactory.permanentRedirect().addHeader(LOCATION, "http://servicetalk.io:80/next"));
}
return succeeded(responseFactory.ok());
}, newFilterFactory()));
HttpRequest request = client.get("/").addHeader(HOST, "servicetalk.io:80");
HttpResponse response = client.request(request);
assertThat(response.status(), equalTo(PERMANENT_REDIRECT));
response = client.request(request.addHeader("X-REDIRECT", "TRUE"));
assertThat(response.status(), equalTo(OK));
}
Aggregations