How to use read timeouts on a RxNetty HttpClient when in a Proxy server environment
Hi,
I've been trying to add timeouts using Observable.timeout to a proxy server call (see #405 for more details on the proxy server) using RxNetty 0.4.x
A request happens like that:
Client -> Proxy -> Origin
The thing is, as I need to retain the ByteBuf to forward it to the origin and release it if the origin was never called, wherever I put my timeout I end up with either the ByteBuf being released although it shouldn't be or it leaking.
What I think happens in the first case is:
- The incoming request is received and starts being forwarded to the proxy
- The timeout occurs while the ByteBuf still hasn't been released
- It reaches the part were i check if ByteBuf is still references which it is so I release it.
- The client fails to release the ByteBuf and outputs a warning:
WARN ChannelOutboundBuffer:136 - Failed to mark a promise as success because it is done already: DefaultChannelPromise@19db3d86(failure(io.netty.handler.codec.EncoderException: io.netty.util.IllegalReferenceCountExce
ption: refCnt: 0, decrement: 1)
So I've tried releasing the ByteBuf earlier as soon as I know that the origin will be called. (If it's going to be called I don't release it else I do) but here comes the leak: if time spent to decide if we're going to call the origin is > timeout then the timeout occurs, unsubscription happens and the release never occurs. So I thought I could just add a check on the timeout's "other" observable so that it releases the ByteBuf but i'm actually uncertain of where I was in the chain: if i didn't yet release the ByteBuf is it because I was supposed to call the origin or because I haven't yet finished deciding what course I should take ? If it's the former, did the ByteBuf reach the client and will be released or did the unsubscription occur in the intermediate observables ?
Anyway, all this lead me to rollback my timeout changes and I thought I should just wait for RxNetty 0.5.x as it seems ByteBufs will then be much easier to manage.
Do you agree with that last statement or maybe did I miss something in my timeout/rx understanding ?
Thanks
Firstly, yes 0.5.x solves this particular problem of managing the various flows in which the ByteBuf lifecycle is to be managed, primarily because of the following:
- 0.5.x does not read the data from a socket unless it is subscribed to (HTTP content in this case). For your case, the inbound request content will only be read when the outbound client subscribes to the content, which will essentially be when it is about to write the content. Any
ByteBufread from the inbound connection will be written to netty. Netty will release theByteBufwhich is given thewrite()irrespective of whether it is actually written to the channel or not.
For your current problem with 0.4.x, the only way I have solved this is by aggressively buffering the content and releasing only the buffers that are not sent via onNext. The dispose (release of buffer) will then be done only after sending the response back to the Client in your case. (If I remember correctly, you had a similar code in place, but I may have been mistaken.)
If you do the above then a timeout can be put on the outbound client submit which would mean that on timeout it will unsubscribe (or never subscribe) and send an error back to the caller which will convert to sending a response to the Client, upon completion of which all unused buffers would be released.
i'm actually uncertain of where I was in the chain: if i didn't yet release the ByteBuf is it because I was supposed to call the origin or because I haven't yet finished deciding what course I should take
This is actually very hard to achieve unless you maintain complex state. The best way is what I mentioned above, cache and release unused after response sent.
Well, I think that's what I tried (and failed) to do.
Here is some sample code of what I did:
private Observable<Void> processRequest(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) {
final String uri = request.getUri();
final AtomicReference<ByteBuf> ref = new AtomicReference<>();
Observable<MyRequest> content = request.getContent()
.map(bb -> {
ref.set(bb.retain());
return ref.get();
})
.map(bb -> new MyRequest(uri, bb))
.cache();
return content
.compose(myRequestTransformer)
.switchIfEmpty(
content
.compose(o -> origin
.submit(HttpClientRequest
.createPost(uri)
.withContentSource(o.map(MyRequest::content))
)
.timeout(5, TimeUnit.MILLISECONDS, Observable.empty())
.map(r -> new MyResponse(r.getStatus(), r.getContent(), r.getHeaders().entries()))
.switchIfEmpty(Observable.just(MyResponse.TIMEOUT))
)
)
.flatMap(myResponse -> {
response.setStatus(myResponse.status);
if (myResponse.headers != null) {
for (Entry<String, String> header : myResponse.headers) {
response.getHeaders().add(header.getKey(), header.getValue());
}
}
return myResponse.content
.map(ByteBuf::retain)
.<Void> map(bb -> {
response.write(bb);
return null;
});
})
.onErrorReturn((t) -> {
int contentLength = 0;
if (t instanceof IllegalArgumentException) {
response.setStatus(HttpResponseStatus.BAD_REQUEST);
if (t.getMessage() != null) {
contentLength = t.getMessage().length();
response.writeString(t.getMessage());
}
}
else {
L.error("Something went wrong", t);
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
response.getHeaders().setContentLength(contentLength);
return null;
})
.finallyDo(() -> {
ByteBuf bb = ref.get();
if (bb.refCnt() > 0) {
bb.release();
}
});
}
Fore each request i get the following:
WARN ChannelOutboundBuffer:136 - Failed to mark a promise as success because it is done already: DefaultChannelPromise@6fe7cb03(failure(io.netty.handler.codec.EncoderException: io.netty.util.IllegalReferenceCountExc
eption: refCnt: 0, decrement: 1)
and rarely i also get
WARN ReferenceCountUtil:146 - Failed to release a message: CompositeByteBuf(freed, components=1)
io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
at io.netty.buffer.AbstractReferenceCountedByteBuf.release(AbstractReferenceCountedByteBuf.java:111)
at io.netty.util.ReferenceCountUtil.release(ReferenceCountUtil.java:84)
at io.netty.util.ReferenceCountUtil.safeRelease(ReferenceCountUtil.java:109)
at io.netty.channel.ChannelOutboundBuffer.remove0(ChannelOutboundBuffer.java:296)
at io.netty.channel.ChannelOutboundBuffer.failFlushed(ChannelOutboundBuffer.java:621
...
Is there something I'm doing wrong here ? FYI, initially, I wanted to set the timeout after the main switchIfEmpty that triggers the origin call so that anything done counts toward the timeout.
Fore each request i get the following:
You mean after putting a timeout, every request produces that warning?
Glancing through the code, I do not see any obvious problem that will cause mismatched ByteBuf refs. Although, it will help me if you have a functional code, the code you provided has many missing classes.
Yes, I meant every request produces that warning.
I'll try to make a working example. Maybe simplify all that.
@Crystark can you please supply a working example. I am stuck with the exact same issue, but for me, I also transform the request.
Issue https://github.com/ReactiveX/RxNetty/issues/436 could be linked to this.
Timeouts have been fixed as of 0.4.16!