Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace rxjava for response body content #552

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
package com.hotels.styx.client.netty.connectionpool;

import com.google.common.annotations.VisibleForTesting;
import com.hotels.styx.api.extension.Origin;
import com.hotels.styx.api.exceptions.ResponseTimeoutException;
import com.hotels.styx.api.extension.Origin;
import com.hotels.styx.client.netty.ConsumerDisconnectedException;
import com.hotels.styx.common.StateMachine;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;
import org.reactivestreams.Subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscriber;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
Expand All @@ -41,7 +41,7 @@
import static com.hotels.styx.client.netty.connectionpool.FlowControllingHttpContentProducer.ProducerState.TERMINATED;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static rx.internal.operators.BackpressureUtils.getAndAddRequest;
import static reactor.core.publisher.Operators.addCap;

class FlowControllingHttpContentProducer {
private static final Logger LOGGER = LoggerFactory.getLogger(FlowControllingHttpContentProducer.class);
Expand All @@ -56,7 +56,7 @@ class FlowControllingHttpContentProducer {
private final Runnable delayedTearDownAction;

private final Queue<ByteBuf> readQueue = new ConcurrentLinkedDeque<>();
private final AtomicLong requested = new AtomicLong(Long.MAX_VALUE);
private final AtomicLong requested = new AtomicLong(0);
private final AtomicLong receivedChunks = new AtomicLong(0);
private final AtomicLong receivedBytes = new AtomicLong(0);
private final AtomicLong emittedChunks = new AtomicLong(0);
Expand Down Expand Up @@ -208,7 +208,7 @@ private ProducerState spuriousContentChunkEvent(ContentChunkEvent event) {
private ProducerState contentSubscribedInBufferingCompleted(ContentSubscribedEvent event) {
this.contentSubscriber = event.subscriber;
if (readQueue.size() == 0) {
this.contentSubscriber.onCompleted();
this.contentSubscriber.onComplete();
this.onCompleteAction.run();
return COMPLETED;
}
Expand All @@ -218,7 +218,7 @@ private ProducerState contentSubscribedInBufferingCompleted(ContentSubscribedEve
if (readQueue.size() > 0) {
return EMITTING_BUFFERED_CONTENT;
} else {
this.contentSubscriber.onCompleted();
this.contentSubscriber.onComplete();
this.onCompleteAction.run();
return COMPLETED;
}
Expand Down Expand Up @@ -296,7 +296,7 @@ private ProducerState contentEndEventWhileStreaming(ContentEndEvent event) {
if (readQueue.size() > 0) {
return EMITTING_BUFFERED_CONTENT;
} else {
this.contentSubscriber.onCompleted();
this.contentSubscriber.onComplete();
this.onCompleteAction.run();
return COMPLETED;
}
Expand All @@ -321,14 +321,24 @@ private ProducerState rxBackpressureRequestInEmittingBufferedContent(RxBackpress
// Don't `askForMore`. The response is fully received already.

if (readQueue.size() == 0) {
this.contentSubscriber.onCompleted();
this.contentSubscriber.onComplete();
this.onCompleteAction.run();
return COMPLETED;
} else {
return EMITTING_BUFFERED_CONTENT;
}
}

private static long getAndAddRequest(AtomicLong requested, long n) {
while (true) {
long current = requested.get();
long next = addCap(current, n);
if (requested.compareAndSet(current, next)) {
return current;
}
}
}

private ProducerState contentSubscribedEventWhileEmittingBufferedContent(ContentSubscribedEvent event) {
// A second subscription occurred for the content observable that already
// has a subscriber. Something is probably gone badly wrong. Therefore tear
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public Flux<LiveHttpResponse> execute(NettyConnection nettyConnection) {
requestTime = System.currentTimeMillis();
executeCount.incrementAndGet();

Flux<LiveHttpResponse> responseFlux = Flux.<LiveHttpResponse>create(sink -> {
Flux<LiveHttpResponse> responseFlux = Flux.create(sink -> {
if (nettyConnection.isConnected()) {
RequestBodyChunkSubscriber bodyChunkSubscriber = new RequestBodyChunkSubscriber(request, nettyConnection);
requestRequestBodyChunkSubscriber.set(bodyChunkSubscriber);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.hotels.styx.client.netty.connectionpool;

import com.google.common.annotations.VisibleForTesting;
import com.hotels.styx.api.Buffer;
import com.hotels.styx.api.Buffers;
import com.hotels.styx.api.ByteStream;
import com.hotels.styx.api.LiveHttpRequest;
Expand All @@ -33,11 +34,11 @@
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.timeout.IdleStateEvent;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import reactor.core.publisher.FluxSink;
import rx.Observable;
import rx.Producer;
import rx.Subscriber;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
Expand All @@ -51,7 +52,6 @@
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.stream.StreamSupport.stream;
import static org.slf4j.LoggerFactory.getLogger;
import static rx.RxReactiveStreams.toPublisher;

/**
* A netty channel handler that reads from a channel and pass the message to a {@link Subscriber}.
Expand Down Expand Up @@ -89,8 +89,7 @@ final class NettyToStyxResponsePropagator extends SimpleChannelInboundHandler {

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ensureContentProducerIsCreated(ctx);
contentProducer.ifPresent(producer -> producer.channelException(toStyxException(cause)));
getContentProducer(ctx).channelException(toStyxException(cause));
}

private RuntimeException toStyxException(Throwable cause) {
Expand All @@ -103,10 +102,8 @@ private RuntimeException toStyxException(Throwable cause) {

@Override
public void channelInactive(ChannelHandlerContext ctx) {
ensureContentProducerIsCreated(ctx);

TransportLostException cause = new TransportLostException(ctx.channel().remoteAddress(), origin);
contentProducer.ifPresent(producer -> producer.channelInactive(cause));
getContentProducer(ctx).channelInactive(cause);
}

private void scheduleResourcesTearDown(ChannelHandlerContext ctx) {
Expand All @@ -118,7 +115,7 @@ private void scheduleResourcesTearDown(ChannelHandlerContext ctx) {

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
ensureContentProducerIsCreated(ctx);
FlowControllingHttpContentProducer producer = getContentProducer(ctx);

if (msg instanceof io.netty.handler.codec.http.HttpResponse) {
io.netty.handler.codec.http.HttpResponse nettyResponse = (io.netty.handler.codec.http.HttpResponse) msg;
Expand All @@ -133,28 +130,24 @@ protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Except
// Can be started with flow controlling disabled
EventLoop eventLoop = ctx.channel().eventLoop();

Observable<ByteBuf> contentObservable = Observable
.create(new InitializeNettyContentProducerOnSubscribe(eventLoop, this.contentProducer.get()))
.doOnUnsubscribe(() -> {
eventLoop.submit(() -> this.contentProducer.ifPresent(FlowControllingHttpContentProducer::unsubscribe));
});
Publisher<Buffer> contentPublisher = new ContentPublisher(eventLoop, producer);

if ("close".equalsIgnoreCase(nettyResponse.headers().get(CONNECTION))) {
toBeClosed = true;
}

LiveHttpResponse response = toStyxResponse(nettyResponse, contentObservable, origin);
LiveHttpResponse response = toStyxResponse(nettyResponse, contentPublisher, origin);
this.sink.next(response);
}
if (msg instanceof HttpContent) {
ByteBuf content = ((ByteBufHolder) msg).content();
if (content.isReadable()) {
contentProducer.ifPresent(producer -> producer.newChunk(retain(content)));
producer.newChunk(retain(content));
}
if (msg instanceof LastHttpContent) {
// Note: Netty may send a LastHttpContent as a response to TCP connection close.
// In this case channelReadComplete event will _not_ follow the LastHttpContent.
contentProducer.ifPresent(FlowControllingHttpContentProducer::lastHttpContent);
producer.lastHttpContent();
if (toBeClosed) {
ctx.channel().close();
}
Expand All @@ -164,26 +157,27 @@ protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Except

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
ensureContentProducerIsCreated(ctx);
FlowControllingHttpContentProducer producer = getContentProducer(ctx);

if (evt instanceof IdleStateEvent) {
contentProducer.ifPresent(producer -> producer.channelInactive(
producer.channelInactive(
new ResponseTimeoutException(
origin,
"idleStateEvent",
producer.receivedBytes(),
producer.receivedChunks(),
producer.emittedBytes(),
producer.emittedChunks())));
producer.emittedChunks()));
} else {
super.userEventTriggered(ctx, evt);
}
}

private void ensureContentProducerIsCreated(ChannelHandlerContext ctx) {
private FlowControllingHttpContentProducer getContentProducer(ChannelHandlerContext ctx) {
if (!this.contentProducer.isPresent()) {
this.contentProducer = Optional.of(createProducer(ctx, request));
}
return this.contentProducer.get();
}

private FlowControllingHttpContentProducer createProducer(ChannelHandlerContext ctx, LiveHttpRequest request) {
Expand Down Expand Up @@ -224,45 +218,70 @@ static LiveHttpResponse.Builder toStyxResponse(io.netty.handler.codec.http.HttpR
return responseBuilder;
}

private static LiveHttpResponse toStyxResponse(io.netty.handler.codec.http.HttpResponse nettyResponse, Observable<ByteBuf> contentObservable, Origin origin) {
private static LiveHttpResponse toStyxResponse(io.netty.handler.codec.http.HttpResponse nettyResponse, Publisher<Buffer> contentPublisher, Origin origin) {
try {
return toStyxResponse(nettyResponse)
.body(new ByteStream(toPublisher(contentObservable.map(Buffers::fromByteBuf))))
.body(new ByteStream(contentPublisher))
.build();
} catch (IllegalArgumentException e) {
throw new BadHttpResponseException(origin, e);
}
}

private static class InitializeNettyContentProducerOnSubscribe implements Observable.OnSubscribe<ByteBuf> {
private final EventLoop eventLoop;
private final FlowControllingHttpContentProducer producer;
private static final class BufferSubscriber implements Subscriber<ByteBuf> {

InitializeNettyContentProducerOnSubscribe(EventLoop eventLoop, FlowControllingHttpContentProducer producer) {
this.eventLoop = eventLoop;
this.producer = producer;
private final Subscriber<? super Buffer> actual;

public BufferSubscriber(Subscriber<? super Buffer> actual) {
this.actual = actual;
}

@Override
public void call(Subscriber<? super ByteBuf> subscriber) {
ResponseContentProducer responseContentProducer = new ResponseContentProducer(eventLoop, this.producer);
subscriber.setProducer(responseContentProducer);
this.eventLoop.submit(() -> producer.onSubscribed(subscriber));
public void onSubscribe(Subscription s) {
actual.onSubscribe(s);
}

@Override
public void onNext(ByteBuf byteBuf) {
actual.onNext(Buffers.fromByteBuf(byteBuf));
}

@Override
public void onError(Throwable t) {
actual.onError(t);
}

@Override
public void onComplete() {
actual.onComplete();
}
}

private static class ResponseContentProducer implements Producer {
private static final class ContentPublisher implements Publisher<Buffer> {

private final EventLoop eventLoop;
private final FlowControllingHttpContentProducer producer;
private final FlowControllingHttpContentProducer contentProducer;

ResponseContentProducer(EventLoop eventLoop, FlowControllingHttpContentProducer producer) {
public ContentPublisher(EventLoop eventLoop, FlowControllingHttpContentProducer contentProducer) {
this.eventLoop = eventLoop;
this.producer = producer;
this.contentProducer = contentProducer;
}

@Override
public void request(long n) {
eventLoop.submit(() -> producer.request(n));
public void subscribe(Subscriber<? super Buffer> subscriber) {
BufferSubscriber bufferSubscriber = new BufferSubscriber(subscriber);
eventLoop.submit(() -> contentProducer.onSubscribed(bufferSubscriber));
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
eventLoop.submit(() -> contentProducer.request(n));
}

@Override
public void cancel() {
eventLoop.submit(contentProducer::unsubscribe);
}
});
}
}
}
Loading