use of com.hotels.styx.api.LiveHttpResponse in project styx by ExpediaGroup.
the class StandardHttpPipelineTest method contextValuesAddedBeforeRequestCanBeRetrievedAfterward.
@Test
public void contextValuesAddedBeforeRequestCanBeRetrievedAfterward() {
HttpInterceptor addsToContext = (request, chain) -> {
chain.context().add("contextValue", "expected");
return chain.proceed(request);
};
AtomicReference<String> foundInContext = new AtomicReference<>();
HttpInterceptor takesFromContext = (request, chain) -> chain.proceed(request).map(response -> {
foundInContext.set(chain.context().get("contextValue", String.class));
return response;
});
StandardHttpPipeline pipeline = pipeline(addsToContext, takesFromContext);
LiveHttpResponse response = sendRequestTo(pipeline);
assertThat(response.status(), is(OK));
assertThat(foundInContext.get(), is("expected"));
}
use of com.hotels.styx.api.LiveHttpResponse in project styx by ExpediaGroup.
the class StandardHttpPipelineTest method interceptorsCanPassInformationThroughContextAfterRequest.
@Test
public void interceptorsCanPassInformationThroughContextAfterRequest() {
HttpInterceptor addsToContext = (request, chain) -> chain.proceed(request).map(response -> {
chain.context().add("contextValue", "expected");
return response;
});
AtomicReference<String> foundInContext = new AtomicReference<>();
HttpInterceptor takesFromContext = (request, chain) -> chain.proceed(request).map(response -> {
foundInContext.set(chain.context().get("contextValue", String.class));
return response;
});
// add + take happens on the way back, so order must be reserved
StandardHttpPipeline pipeline = pipeline(takesFromContext, addsToContext);
LiveHttpResponse response = sendRequestTo(pipeline);
assertThat(response.status(), is(OK));
assertThat(foundInContext.get(), is("expected"));
}
use of com.hotels.styx.api.LiveHttpResponse in project styx by ExpediaGroup.
the class HttpPipelineHandler method exceptionToResponse.
private LiveHttpResponse exceptionToResponse(Throwable cause, LiveHttpRequest request, CharSequence originsHeaderName) {
HttpResponseStatus status = status(cause instanceof PluginException ? cause.getCause() : cause);
String message = status.code() >= 500 ? "Site temporarily unavailable." : status.description();
LiveHttpResponse.Transformer builder = responseEnhancer.enhance(response(status).body(new ByteStream(Flux.just(new Buffer(message, UTF_8)))).build().newBuilder(), request).header(CONTENT_LENGTH, message.getBytes(UTF_8).length).header(CONNECTION, "close");
if (originsHeaderName != null && originFromException(cause) != null) {
return builder.header(originsHeaderName, originFromException(cause)).build();
} else {
return builder.build();
}
}
use of com.hotels.styx.api.LiveHttpResponse in project styx by ExpediaGroup.
the class HttpPipelineHandler method handleChannelException.
private State handleChannelException(ChannelHandlerContext ctx, Throwable cause) {
Throwable sslException = sslException(cause);
if (sslException != null) {
if (ctx.channel().isActive()) {
ctx.channel().close();
}
LOGGER.info("SSL handshake failure from incoming connection " + "cause=\"{}\", " + "serverAddress={}, " + "clientAddress={}", new Object[] { sslException.getMessage(), ctx.channel().localAddress(), ctx.channel().remoteAddress() });
return TERMINATED;
}
if (!isIoException(cause)) {
LiveHttpResponse response = exceptionToResponse(cause, ongoingRequest, originsHeaderName);
httpErrorStatusListener.proxyErrorOccurred(response.status(), cause);
if (ctx.channel().isActive()) {
respondAndClose(ctx, response);
}
}
return TERMINATED;
}
use of com.hotels.styx.api.LiveHttpResponse in project styx by ExpediaGroup.
the class HttpResponseWriter method write.
// CHECKSTYLE:OFF
public CompletableFuture<Void> write(LiveHttpResponse response) {
CompletableFuture<Void> future = new CompletableFuture<>();
try {
writeHeaders(response).addListener((ChannelFutureListener) writeOp -> {
if (writeOp.isSuccess()) {
writeOpsAcked.incrementAndGet();
} else {
LOGGER.warn("Unable to send response headers. Written content bytes {}/{} (ackd/sent). Write events {}/{} (ackd/writes). Exception={}", new Object[] { contentBytesAcked.get(), contentBytesWritten.get(), writeOpsAcked.get(), writeOps.get(), writeOp.cause() });
future.completeExceptionally(writeOp.cause());
}
});
response.body().subscribe(new BaseSubscriber<Buffer>() {
@Override
public void hookOnSubscribe(Subscription subscription) {
future.handle((ignore, cause) -> {
if (future.isCompletedExceptionally() && cause instanceof CancellationException) {
subscription.cancel();
}
return null;
});
subscription.request(1);
}
@Override
public void hookOnComplete() {
if (!future.isDone()) {
nettyWriteAndFlush(EMPTY_LAST_CONTENT).addListener((ChannelFutureListener) this::onWriteEmptyLastChunkOutcome);
contentCompleted.set(true);
completeIfAllSent(future);
}
}
@Override
public void hookOnError(Throwable cause) {
LOGGER.warn("Content observable error. Written content bytes {}/{} (ackd/sent). Write events {}/{} (ackd/writes). Exception={}", new Object[] { contentBytesAcked.get(), contentBytesWritten.get(), writeOpsAcked.get(), writeOps.get(), cause });
future.completeExceptionally(cause);
}
@Override
public void hookOnNext(Buffer buffer) {
ByteBuf byteBuf = Buffers.toByteBuf(buffer);
if (future.isDone()) {
byteBuf.release();
} else {
long bufSize = (long) byteBuf.readableBytes();
contentBytesWritten.addAndGet(bufSize);
nettyWriteAndFlush(new DefaultHttpContent(byteBuf)).addListener(it -> onWriteOutcome((ChannelFuture) it, bufSize));
}
}
private void onWriteOutcome(ChannelFuture writeOp, long bufSize) {
if (writeOp.isSuccess()) {
contentBytesAcked.addAndGet(bufSize);
writeOpsAcked.incrementAndGet();
request(1);
completeIfAllSent(future);
} else if (!future.isDone()) {
// Suppress messages if future has already failed, or completed for other reason:
cancel();
LOGGER.warn("Write error. Written content bytes {}/{} (ackd/sent). Write events {}/{} (ackd/writes), Exception={}", new Object[] { contentBytesAcked.get(), contentBytesWritten.get(), writeOpsAcked.get(), writeOps.get(), response, writeOp.cause() });
future.completeExceptionally(writeOp.cause());
}
}
private void onWriteEmptyLastChunkOutcome(ChannelFuture writeOp) {
writeOpsAcked.incrementAndGet();
completeIfAllSent(future);
cancel();
}
});
return future;
} catch (Throwable cause) {
LOGGER.warn("Failed to convert response headers. response={}, Cause={}", new Object[] { response, cause });
toObservable(response.body()).forEach(it -> Buffers.toByteBuf(it).release());
future.completeExceptionally(cause);
return future;
}
}
Aggregations