From d2e439811ccf62aa9ed79bdf1dfeab2975d48ffd Mon Sep 17 00:00:00 2001 From: nmittler Date: Mon, 27 Apr 2015 12:59:16 -0700 Subject: [PATCH 1/2] Adding outbound flow control for Netty. --- core/src/main/java/io/grpc/Call.java | 17 ++- core/src/main/java/io/grpc/ChannelImpl.java | 17 ++- .../main/java/io/grpc/ClientInterceptors.java | 19 ++- .../src/main/java/io/grpc/ForwardingCall.java | 15 +- .../java/io/grpc/ForwardingCallListener.java | 4 +- .../java/io/grpc/ForwardingServerCall.java | 5 + .../io/grpc/ForwardingServerCallListener.java | 4 +- core/src/main/java/io/grpc/ServerCall.java | 17 ++- core/src/main/java/io/grpc/ServerImpl.java | 17 ++- .../grpc/transport/AbstractClientStream.java | 12 +- .../grpc/transport/AbstractServerStream.java | 18 ++- .../io/grpc/transport/AbstractStream.java | 133 +++++++++++++++++- .../main/java/io/grpc/transport/Stream.java | 22 +-- .../io/grpc/transport/StreamListener.java | 9 +- .../src/test/java/io/grpc/ServerImplTest.java | 5 +- .../transport/netty/NettyClientHandler.java | 6 +- .../transport/netty/NettyClientStream.java | 34 +++-- .../transport/netty/NettyServerStream.java | 16 ++- .../transport/netty/SendGrpcFrameCommand.java | 3 +- .../netty/NettyClientStreamTest.java | 37 +++-- .../netty/NettyServerHandlerTest.java | 3 + .../netty/NettyServerStreamTest.java | 32 +++-- .../transport/netty/NettyStreamTestBase.java | 84 +++++++++-- .../okhttp/OkHttpClientTransportTest.java | 14 +- .../okhttp/OkHttpReadableBufferTest.java | 7 +- .../src/test/java/io/grpc/stub/CallsTest.java | 2 +- 26 files changed, 425 insertions(+), 127 deletions(-) diff --git a/core/src/main/java/io/grpc/Call.java b/core/src/main/java/io/grpc/Call.java index 5ec51a1965d..dec2d8438dc 100644 --- a/core/src/main/java/io/grpc/Call.java +++ b/core/src/main/java/io/grpc/Call.java @@ -91,17 +91,12 @@ public abstract static class Listener { public abstract void onClose(Status status, Metadata.Trailers trailers); /** - * This indicates that the Call is now capable of sending the given number of messages (via + * This indicates that the Call is now capable of sending additional messages (via * {@link #sendPayload}) without requiring excessive buffering internally. This event is * just a suggestion and the application is free to ignore it, however doing so may * result in excessive buffering within the Call. - * - *

NOTE: this method is not yet implemented! - * - * @param numMessages the number of messages that can be sent without requiring excessive - * buffering. */ - public void onReady(int numMessages) {} + public void onReady() {} } /** @@ -151,4 +146,12 @@ public void onReady(int numMessages) {} * @throws IllegalStateException if call is {@link #halfClose}d or explicitly {@link #cancel}ed */ public abstract void sendPayload(RequestT payload); + + /** + * If {@code true}, indicates that the call is capable of sending additional messages + * without requiring excessive buffering internally. This event is + * just a suggestion and the application is free to ignore it, however doing so may + * result in excessive buffering within the call. + */ + public abstract boolean isReady(); } diff --git a/core/src/main/java/io/grpc/ChannelImpl.java b/core/src/main/java/io/grpc/ChannelImpl.java index 9e887002c9b..b4f6bff66fa 100644 --- a/core/src/main/java/io/grpc/ChannelImpl.java +++ b/core/src/main/java/io/grpc/ChannelImpl.java @@ -57,7 +57,7 @@ public final class ChannelImpl implements Channel { private static final Logger log = Logger.getLogger(ChannelImpl.class.getName()); private static class NoopClientStream implements ClientStream { - @Override public void writeMessage(InputStream message, int length, Runnable accepted) {} + @Override public void writeMessage(InputStream message, int length) {} @Override public void flush() {} @@ -66,6 +66,10 @@ private static class NoopClientStream implements ClientStream { @Override public void halfClose() {} @Override public void request(int numMessages) {} + + @Override public boolean isReady() { + return true; + } } private final ClientTransportFactory transportFactory; @@ -298,7 +302,7 @@ public void sendPayload(ReqT payload) { boolean failed = true; try { InputStream payloadIs = method.streamRequest(payload); - stream.writeMessage(payloadIs, available(payloadIs), null); + stream.writeMessage(payloadIs, available(payloadIs)); failed = false; } finally { if (failed) { @@ -313,6 +317,11 @@ public void sendPayload(ReqT payload) { } } + @Override + public boolean isReady() { + return stream.isReady(); + } + private class ClientStreamListenerImpl implements ClientStreamListener { private final Listener observer; private boolean closed; @@ -376,11 +385,11 @@ public void run() { } @Override - public void onReady(final int numMessages) { + public void onReady() { callExecutor.execute(new Runnable() { @Override public void run() { - observer.onReady(numMessages); + observer.onReady(); } }); } diff --git a/core/src/main/java/io/grpc/ClientInterceptors.java b/core/src/main/java/io/grpc/ClientInterceptors.java index 67864b257db..c8c1ae4d39e 100644 --- a/core/src/main/java/io/grpc/ClientInterceptors.java +++ b/core/src/main/java/io/grpc/ClientInterceptors.java @@ -129,19 +129,28 @@ public ForwardingCall(Call delegate) { private static final Call NOOP_CALL = new Call() { @Override - public void start(Listener responseListener, Metadata.Headers headers) { } + public void start(Listener responseListener, Metadata.Headers headers) {} @Override - public void request(int numMessages) { } + public void request(int numMessages) {} @Override - public void cancel() { } + public void cancel() {} @Override - public void halfClose() { } + public void halfClose() {} @Override - public void sendPayload(Object payload) { } + public void sendPayload(Object payload) {} + + /** + * Always returns {@code false}, since this is only used when the startup of the {@link Call} + * fails (i.e. the {@link Call} is closed). + */ + @Override + public boolean isReady() { + return false; + } }; /** diff --git a/core/src/main/java/io/grpc/ForwardingCall.java b/core/src/main/java/io/grpc/ForwardingCall.java index 6df55ab5ecd..fe0e0e505c7 100644 --- a/core/src/main/java/io/grpc/ForwardingCall.java +++ b/core/src/main/java/io/grpc/ForwardingCall.java @@ -42,27 +42,32 @@ public abstract class ForwardingCall extends Call { @Override public void start(Listener responseListener, Metadata.Headers headers) { - this.delegate().start(responseListener, headers); + delegate().start(responseListener, headers); } @Override public void request(int numMessages) { - this.delegate().request(numMessages); + delegate().request(numMessages); } @Override public void cancel() { - this.delegate().cancel(); + delegate().cancel(); } @Override public void halfClose() { - this.delegate().halfClose(); + delegate().halfClose(); } @Override public void sendPayload(ReqT payload) { - this.delegate().sendPayload(payload); + delegate().sendPayload(payload); + } + + @Override + public boolean isReady() { + return delegate().isReady(); } /** diff --git a/core/src/main/java/io/grpc/ForwardingCallListener.java b/core/src/main/java/io/grpc/ForwardingCallListener.java index ec0855ebcf4..640bdae9f22 100644 --- a/core/src/main/java/io/grpc/ForwardingCallListener.java +++ b/core/src/main/java/io/grpc/ForwardingCallListener.java @@ -56,8 +56,8 @@ public void onClose(Status status, Metadata.Trailers trailers) { } @Override - public void onReady(int numMessages) { - delegate().onReady(numMessages); + public void onReady() { + delegate().onReady(); } /** diff --git a/core/src/main/java/io/grpc/ForwardingServerCall.java b/core/src/main/java/io/grpc/ForwardingServerCall.java index 5d7bccfca04..05fac3901d0 100644 --- a/core/src/main/java/io/grpc/ForwardingServerCall.java +++ b/core/src/main/java/io/grpc/ForwardingServerCall.java @@ -55,6 +55,11 @@ public void sendPayload(RespT payload) { delegate().sendPayload(payload); } + @Override + public boolean isReady() { + return delegate().isReady(); + } + @Override public void close(Status status, Metadata.Trailers trailers) { delegate().close(status, trailers); diff --git a/core/src/main/java/io/grpc/ForwardingServerCallListener.java b/core/src/main/java/io/grpc/ForwardingServerCallListener.java index e4a68428416..72f86e430f6 100644 --- a/core/src/main/java/io/grpc/ForwardingServerCallListener.java +++ b/core/src/main/java/io/grpc/ForwardingServerCallListener.java @@ -62,8 +62,8 @@ public void onComplete() { } @Override - public void onReady(int numMessages) { - delegate().onReady(numMessages); + public void onReady() { + delegate().onReady(); } /** diff --git a/core/src/main/java/io/grpc/ServerCall.java b/core/src/main/java/io/grpc/ServerCall.java index e63412a5a08..39f81fa8100 100644 --- a/core/src/main/java/io/grpc/ServerCall.java +++ b/core/src/main/java/io/grpc/ServerCall.java @@ -93,17 +93,12 @@ public abstract static class Listener { public abstract void onComplete(); /** - * This indicates that the call is now capable of sending the given number of messages (via + * This indicates that the call is now capable of sending additional messages (via * {@link #sendPayload}) without requiring excessive buffering internally. This event is * just a suggestion and the application is free to ignore it, however doing so may * result in excessive buffering within the call. - * - *

NOTE: this method is not yet implemented! - * - * @param numMessages the number of messages that can be sent without requiring excessive - * buffering. */ - public void onReady(int numMessages) {} + public void onReady() {} } /** @@ -137,6 +132,14 @@ public void onReady(int numMessages) {} */ public abstract void sendPayload(ResponseT payload); + /** + * If {@code true}, indicates that the call is capable of sending additional messages + * without requiring excessive buffering internally. This event is + * just a suggestion and the application is free to ignore it, however doing so may + * result in excessive buffering within the call. + */ + public abstract boolean isReady(); + /** * Close the call with the provided status. No further sending or receiving will occur. If {@code * status} is not equal to {@link Status#OK}, then the call is said to have failed. diff --git a/core/src/main/java/io/grpc/ServerImpl.java b/core/src/main/java/io/grpc/ServerImpl.java index 4f3e3215f65..2ef2cbd7390 100644 --- a/core/src/main/java/io/grpc/ServerImpl.java +++ b/core/src/main/java/io/grpc/ServerImpl.java @@ -306,7 +306,7 @@ public void halfClosed() {} public void closed(Status status) {} @Override - public void onReady(int numMessages) {} + public void onReady() {} } /** @@ -387,11 +387,11 @@ public void run() { } @Override - public void onReady(final int numMessages) { + public void onReady() { callExecutor.execute(new Runnable() { @Override public void run() { - getListener().onReady(numMessages); + getListener().onReady(); } }); } @@ -421,7 +421,7 @@ public void sendHeaders(Metadata.Headers headers) { public void sendPayload(RespT payload) { try { InputStream message = methodDef.streamResponse(payload); - stream.writeMessage(message, message.available(), null); + stream.writeMessage(message, message.available()); stream.flush(); } catch (Throwable t) { close(Status.fromThrowable(t), new Metadata.Trailers()); @@ -429,6 +429,11 @@ public void sendPayload(RespT payload) { } } + @Override + public boolean isReady() { + return stream.isReady(); + } + @Override public void close(Status status, Metadata.Trailers trailers) { stream.close(status, trailers); @@ -491,11 +496,11 @@ public void closed(Status status) { } @Override - public void onReady(int numMessages) { + public void onReady() { if (cancelled) { return; } - listener.onReady(numMessages); + listener.onReady(); } } } diff --git a/core/src/main/java/io/grpc/transport/AbstractClientStream.java b/core/src/main/java/io/grpc/transport/AbstractClientStream.java index 8b1d0488280..e15283d563f 100644 --- a/core/src/main/java/io/grpc/transport/AbstractClientStream.java +++ b/core/src/main/java/io/grpc/transport/AbstractClientStream.java @@ -41,8 +41,6 @@ import java.util.logging.Level; import java.util.logging.Logger; -import javax.annotation.Nullable; - /** * The abstract base class for {@link ClientStream} implementations. */ @@ -72,6 +70,11 @@ protected AbstractClientStream(WritableBufferAllocator bufferAllocator, this.listener = Preconditions.checkNotNull(listener); } + @Override + protected final ClientStreamListener listener() { + return listener; + } + @Override protected void receiveMessage(InputStream is) { if (!listenerClosed) { @@ -79,11 +82,6 @@ protected void receiveMessage(InputStream is) { } } - @Override - public final void writeMessage(InputStream message, int length, @Nullable Runnable accepted) { - super.writeMessage(message, length, accepted); - } - /** * The transport implementation has detected a protocol error on the stream. Transports are * responsible for properly closing streams when protocol errors occur. diff --git a/core/src/main/java/io/grpc/transport/AbstractServerStream.java b/core/src/main/java/io/grpc/transport/AbstractServerStream.java index cd8e9ae8d37..e5a267e1676 100644 --- a/core/src/main/java/io/grpc/transport/AbstractServerStream.java +++ b/core/src/main/java/io/grpc/transport/AbstractServerStream.java @@ -40,8 +40,6 @@ import java.util.logging.Level; import java.util.logging.Logger; -import javax.annotation.Nullable; - /** * Abstract base class for {@link ServerStream} implementations. */ @@ -66,10 +64,20 @@ protected AbstractServerStream(WritableBufferAllocator bufferAllocator) { } /** - * Sets the listener to receive notifications. + * Sets the listener to receive notifications. Must be called in the context of the transport + * thread. */ public final void setListener(ServerStreamListener listener) { this.listener = Preconditions.checkNotNull(listener, "listener"); + + // Now that the stream has actually been initialized, call the listener's onReady callback if + // appropriate. + notifyIfReady(); + } + + @Override + protected ServerStreamListener listener() { + return this.listener; } @Override @@ -88,12 +96,12 @@ public void writeHeaders(Metadata.Headers headers) { } @Override - public final void writeMessage(InputStream message, int length, @Nullable Runnable accepted) { + public final void writeMessage(InputStream message, int length) { if (!headersSent) { writeHeaders(new Metadata.Headers()); headersSent = true; } - super.writeMessage(message, length, accepted); + super.writeMessage(message, length); } @Override diff --git a/core/src/main/java/io/grpc/transport/AbstractStream.java b/core/src/main/java/io/grpc/transport/AbstractStream.java index 44edca361cd..44afefba902 100644 --- a/core/src/main/java/io/grpc/transport/AbstractStream.java +++ b/core/src/main/java/io/grpc/transport/AbstractStream.java @@ -31,6 +31,8 @@ package io.grpc.transport; +import static com.google.common.base.Preconditions.checkArgument; + import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; @@ -38,11 +40,18 @@ import java.io.InputStream; import javax.annotation.Nullable; +import javax.annotation.concurrent.GuardedBy; /** * Abstract base class for {@link Stream} implementations. */ public abstract class AbstractStream implements Stream { + /** + * The default number of queued bytes for a given stream, below which + * {@link StreamListener#onReady()} will be called. + */ + public static final int DEFAULT_ONREADY_THRESHOLD = 32 * 1024; + /** * Indicates the phase of the GRPC stream in one direction. */ @@ -63,6 +72,25 @@ protected enum Phase { */ private Phase outboundPhase = Phase.HEADERS; + /** + * The number of queued bytes for a given stream, below which {@link StreamListener#onReady()} + * will be called. + */ + private int onReadyThreshold = DEFAULT_ONREADY_THRESHOLD; + + /** + * The number of bytes currently queued, waiting to be sent. When this falls below + */ + private int numSentBytesQueued; + + /** + * Indicates whether the listener is currently eligible for notification of + * {@link StreamListener#onReady()}. + */ + private boolean shouldNotifyOnReady = true; + + private final Object onReadyLock = new Object(); + AbstractStream(WritableBufferAllocator bufferAllocator) { MessageDeframer.Listener inboundMessageHandler = new MessageDeframer.Listener() { @Override @@ -104,19 +132,33 @@ public void deliverFrame(WritableBuffer frame, boolean endOfStream, boolean flus @Nullable public abstract IdT id(); + /** + * The number of queued bytes for a given stream, below which {@link StreamListener#onReady()} + * will be called. Defaults to {@link #DEFAULT_ONREADY_THRESHOLD}. + */ + public int getOnReadyThreshold() { + return onReadyThreshold; + } + + /** + * Sets the number of queued bytes for a given stream, below which + * {@link StreamListener#onReady()} will be called. If not called, defaults to + * {@link #DEFAULT_ONREADY_THRESHOLD}. + */ + public void setOnReadyThreshold(int onReadyThreshold) { + checkArgument(onReadyThreshold > 0, "onReadyThreshold must be > 0"); + this.onReadyThreshold = onReadyThreshold; + notifyIfReady(); + } + @Override - public void writeMessage(InputStream message, int length, @Nullable Runnable accepted) { + public void writeMessage(InputStream message, int length) { Preconditions.checkNotNull(message, "message"); Preconditions.checkArgument(length >= 0, "length must be >= 0"); outboundPhase(Phase.MESSAGE); if (!framer.isClosed()) { framer.writePayload(message, length); } - - // TODO(nmittler): add flow control. - if (accepted != null) { - accepted.run(); - } } @Override @@ -126,6 +168,18 @@ public final void flush() { } } + @Override + public final boolean isReady() { + if (listener() != null && outboundPhase() != Phase.STATUS) { + synchronized (onReadyLock) { + if (numSentBytesQueued < onReadyThreshold) { + return true; + } + } + } + return false; + } + /** * Closes the underlying framer. * @@ -149,6 +203,11 @@ public void dispose() { framer.dispose(); } + /** + * Gets the listener to this stream. + */ + protected abstract StreamListener listener(); + /** * Sends an outbound frame to the remote end point. * @@ -229,6 +288,68 @@ protected final void requestMessagesFromDeframer(int numMessages) { } } + /** + * Event handler to be called by the subclass when a number of bytes are being queued for sending + * to the remote endpoint. + * + * @param numBytes the number of bytes being sent. + */ + protected final void onSendingBytes(int numBytes) { + synchronized (onReadyLock) { + shouldNotifyOnReady = true; + numSentBytesQueued += numBytes; + } + } + + /** + * Event handler to be called by the subclass when a number of bytes has been sent to the remote + * endpoint. May call back the listener's {@link StreamListener#onReady()} handler if appropriate. + * This must be called from the transport thread, since the listener may be called back directly. + * + * @param numBytes the number of bytes that were sent. + */ + protected final void onSentBytes(int numBytes) { + boolean doNotify; + synchronized (onReadyLock) { + numSentBytesQueued -= numBytes; + doNotify = needToNotifyOnReady(); + } + if (doNotify) { + listener().onReady(); + } + } + + /** + * Utility method for subclasses which calls back the listener's {@link StreamListener#onReady()} + * handler if appropriate. This must be called from the transport thread, since the listener + * is called back directly. + */ + protected final void notifyIfReady() { + boolean doNotify; + synchronized (onReadyLock) { + doNotify = needToNotifyOnReady(); + } + if (doNotify) { + listener().onReady(); + } + } + + /** + * Determines whether or not we need to call the {@link StreamListener#onReady()} handler now. + * Calling this method has the side-effect of unsetting {@link #shouldNotifyOnReady} so the + * handler should always be invoked immediately after calling this method. + */ + @GuardedBy("onReadyLock") + private boolean needToNotifyOnReady() { + if (shouldNotifyOnReady && isReady()) { + // Returning true here counts as a call to the onReady callback, so + // unset the flag. + shouldNotifyOnReady = false; + return true; + } + return false; + } + final Phase inboundPhase() { return inboundPhase; } diff --git a/core/src/main/java/io/grpc/transport/Stream.java b/core/src/main/java/io/grpc/transport/Stream.java index 5cbbbbd3c8a..5c1b14faae4 100644 --- a/core/src/main/java/io/grpc/transport/Stream.java +++ b/core/src/main/java/io/grpc/transport/Stream.java @@ -33,8 +33,6 @@ import java.io.InputStream; -import javax.annotation.Nullable; - /** * A single stream of communication between two end-points within a transport. * @@ -55,20 +53,28 @@ public interface Stream { * by the Transport. This method will always return immediately and will not wait for the write to * complete. * - *

When the write is "accepted" by the transport, the given callback (if provided) will be - * called. The definition of what it means to be "accepted" is up to the transport implementation, - * but this is a general indication that the transport is capable of handling more out-bound data - * on the stream. If the stream/connection is closed for any reason before the write could be + *

+ * When the write is "accepted" by the transport, the given callback (if provided) will be called. + * The definition of what it means to be "accepted" is up to the transport implementation, but + * this is a general indication that the transport is capable of handling more out-bound data on + * the stream. If the stream/connection is closed for any reason before the write could be * accepted, the callback will never be invoked. * * @param message stream containing the serialized message to be sent * @param length the length of the {@link InputStream}. - * @param accepted an optional callback for when the transport has accepted the write. */ - void writeMessage(InputStream message, int length, @Nullable Runnable accepted); + void writeMessage(InputStream message, int length); /** * Flushes any internally buffered messages to the remote end-point. */ void flush(); + + /** + * If {@code true}, indicates that the transport is capable of sending additional messages + * without requiring excessive buffering internally. This event is + * just a suggestion and the application is free to ignore it, however doing so may + * result in excessive buffering within the transport. + */ + boolean isReady(); } diff --git a/core/src/main/java/io/grpc/transport/StreamListener.java b/core/src/main/java/io/grpc/transport/StreamListener.java index 5ede1907d84..4ce9f14c125 100644 --- a/core/src/main/java/io/grpc/transport/StreamListener.java +++ b/core/src/main/java/io/grpc/transport/StreamListener.java @@ -51,15 +51,10 @@ public interface StreamListener { void messageRead(InputStream message); /** - * This indicates that the transport is now capable of sending the given number of messages + * This indicates that the transport is now capable of sending additional messages * without requiring excessive buffering internally. This event is * just a suggestion and the application is free to ignore it, however doing so may * result in excessive buffering within the transport. - * - *

NOTE: this method is not yet implemented! - * - * @param numMessages the number of messages that can be sent without requiring excessive - * buffering. */ - void onReady(int numMessages); + void onReady(); } diff --git a/core/src/test/java/io/grpc/ServerImplTest.java b/core/src/test/java/io/grpc/ServerImplTest.java index fe7a072a93c..52327accb56 100644 --- a/core/src/test/java/io/grpc/ServerImplTest.java +++ b/core/src/test/java/io/grpc/ServerImplTest.java @@ -39,7 +39,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNull; import static org.mockito.Matchers.notNull; import static org.mockito.Matchers.same; import static org.mockito.Mockito.timeout; @@ -201,7 +200,7 @@ public ServerCall.Listener startCall(String fullMethodName, call.sendPayload(314); ArgumentCaptor inputCaptor = ArgumentCaptor.forClass(InputStream.class); - verify(stream).writeMessage(inputCaptor.capture(), eq(3), isNull(Runnable.class)); + verify(stream).writeMessage(inputCaptor.capture(), eq(3)); verify(stream).flush(); assertEquals(314, INTEGER_MARSHALLER.parse(inputCaptor.getValue()).intValue()); @@ -210,7 +209,7 @@ public ServerCall.Listener startCall(String fullMethodName, verify(callListener).onHalfClose(); call.sendPayload(50); - verify(stream).writeMessage(inputCaptor.capture(), eq(2), isNull(Runnable.class)); + verify(stream).writeMessage(inputCaptor.capture(), eq(2)); verify(stream, times(2)).flush(); assertEquals(50, INTEGER_MARSHALLER.parse(inputCaptor.getValue()).intValue()); diff --git a/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java b/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java index a6b2ab3f7b5..77c46982a32 100644 --- a/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java +++ b/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java @@ -258,14 +258,14 @@ private void createStream(CreateStreamCommand command, final ChannelPromise prom @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { - // Attach the client stream to the HTTP/2 stream object as user data. - Http2Stream http2Stream = connection().stream(streamId); - stream.setHttp2Stream(http2Stream); // The http2Stream will be null in case a stream buffered in the encoder // was canceled via RST_STREAM. + Http2Stream http2Stream = connection().stream(streamId); if (http2Stream != null) { http2Stream.setProperty(streamKey, stream); } + // Attach the client stream to the HTTP/2 stream object as user data. + stream.setHttp2Stream(http2Stream); } else { if (future.cause() instanceof GoAwayClosedStreamException) { GoAwayClosedStreamException e = (GoAwayClosedStreamException) future.cause(); diff --git a/netty/src/main/java/io/grpc/transport/netty/NettyClientStream.java b/netty/src/main/java/io/grpc/transport/netty/NettyClientStream.java index 0573f20d1bf..43010124e9a 100644 --- a/netty/src/main/java/io/grpc/transport/netty/NettyClientStream.java +++ b/netty/src/main/java/io/grpc/transport/netty/NettyClientStream.java @@ -33,13 +33,15 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; +import static io.netty.buffer.Unpooled.EMPTY_BUFFER; import io.grpc.transport.ClientStreamListener; import io.grpc.transport.Http2ClientStream; import io.grpc.transport.WritableBuffer; import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2Stream; @@ -49,7 +51,6 @@ * Client stream for a Netty transport. */ class NettyClientStream extends Http2ClientStream { - private final Channel channel; private final NettyClientHandler handler; private Http2Stream http2Stream; @@ -81,12 +82,17 @@ public void id(int id) { } /** - * Sets the underlying Netty {@link Http2Stream} for this stream. + * Sets the underlying Netty {@link Http2Stream} for this stream. This must be called in the + * context of the transport thread. */ public void setHttp2Stream(Http2Stream http2Stream) { checkNotNull(http2Stream, "http2Stream"); checkState(this.http2Stream == null, "Can only set http2Stream once"); this.http2Stream = http2Stream; + + // Now that the stream has actually been initialized, call the listener's onReady callback if + // appropriate. + notifyIfReady(); } /** @@ -117,13 +123,25 @@ protected void sendCancel() { @Override protected void sendFrame(WritableBuffer frame, boolean endOfStream, boolean flush) { - ByteBuf bytebuf; - if (frame == null) { - bytebuf = Unpooled.EMPTY_BUFFER; + ByteBuf bytebuf = frame == null ? EMPTY_BUFFER : ((NettyWritableBuffer) frame).bytebuf(); + final int numBytes = bytebuf.readableBytes(); + if (numBytes > 0) { + // Add the bytes to outbound flow control. + onSendingBytes(numBytes); + channel.write(new SendGrpcFrameCommand(this, bytebuf, endOfStream)).addListener( + new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + // Remove the bytes from outbound flow control, optionally notifying + // the client that they can send more bytes. + onSentBytes(numBytes); + } + }); } else { - bytebuf = ((NettyWritableBuffer) frame).bytebuf(); + // The frame is empty and will not impact outbound flow control. Just send it. + channel.write(new SendGrpcFrameCommand(this, bytebuf, endOfStream)); } - channel.write(new SendGrpcFrameCommand(this, bytebuf, endOfStream)); + if (flush) { channel.flush(); } diff --git a/netty/src/main/java/io/grpc/transport/netty/NettyServerStream.java b/netty/src/main/java/io/grpc/transport/netty/NettyServerStream.java index 6178cdd4929..1b82fc0769f 100644 --- a/netty/src/main/java/io/grpc/transport/netty/NettyServerStream.java +++ b/netty/src/main/java/io/grpc/transport/netty/NettyServerStream.java @@ -38,6 +38,8 @@ import io.grpc.transport.WritableBuffer; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2Stream; @@ -90,7 +92,19 @@ protected void internalSendHeaders(Metadata.Headers headers) { @Override protected void sendFrame(WritableBuffer frame, boolean endOfStream, boolean flush) { ByteBuf bytebuf = ((NettyWritableBuffer) frame).bytebuf(); - channel.write(new SendGrpcFrameCommand(this, bytebuf, endOfStream)); + final int numBytes = bytebuf.readableBytes(); + // Add the bytes to outbound flow control. + onSendingBytes(numBytes); + channel.write(new SendGrpcFrameCommand(this, bytebuf, endOfStream)).addListener( + new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + // Remove the bytes from outbound flow control, optionally notifying + // the client that they can send more bytes. + onSentBytes(numBytes); + } + }); + if (flush) { channel.flush(); } diff --git a/netty/src/main/java/io/grpc/transport/netty/SendGrpcFrameCommand.java b/netty/src/main/java/io/grpc/transport/netty/SendGrpcFrameCommand.java index 449b151989a..c98c5b38bfb 100644 --- a/netty/src/main/java/io/grpc/transport/netty/SendGrpcFrameCommand.java +++ b/netty/src/main/java/io/grpc/transport/netty/SendGrpcFrameCommand.java @@ -43,7 +43,8 @@ class SendGrpcFrameCommand extends DefaultByteBufHolder { private final AbstractStream stream; private final boolean endStream; - SendGrpcFrameCommand(AbstractStream stream, ByteBuf content, boolean endStream) { + SendGrpcFrameCommand(AbstractStream stream, ByteBuf content, + boolean endStream) { super(content); this.stream = stream; this.endStream = endStream; diff --git a/netty/src/test/java/io/grpc/transport/netty/NettyClientStreamTest.java b/netty/src/test/java/io/grpc/transport/netty/NettyClientStreamTest.java index 3a7c45c4e7a..da02a62d6bc 100644 --- a/netty/src/test/java/io/grpc/transport/netty/NettyClientStreamTest.java +++ b/netty/src/test/java/io/grpc/transport/netty/NettyClientStreamTest.java @@ -47,7 +47,6 @@ import io.grpc.Metadata; import io.grpc.Status; -import io.grpc.transport.AbstractStream; import io.grpc.transport.ClientStreamListener; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -61,6 +60,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import java.io.ByteArrayInputStream; import java.io.InputStream; /** @@ -106,16 +106,16 @@ public void cancelShouldStillSendCommandIfStreamNotCreatedToCancelCreation() { public void writeMessageShouldSendRequest() throws Exception { // Force stream creation. stream().id(STREAM_ID); - stream.writeMessage(input, input.available(), accepted); + byte[] msg = smallMessage(); + stream.writeMessage(new ByteArrayInputStream(msg), msg.length); stream.flush(); verify(channel).write(new SendGrpcFrameCommand(stream, messageFrame(MESSAGE), false)); verify(channel).flush(); - verify(accepted).run(); } @Test public void setStatusWithOkShouldCloseStream() { - stream().id(1); + stream().id(STREAM_ID); stream().transportReportStatus(Status.OK, true, new Metadata.Trailers()); verify(listener).closed(same(Status.OK), any(Metadata.Trailers.class)); assertTrue(stream.isClosed()); @@ -152,14 +152,14 @@ public void setStatusWithErrorShouldNotOverridePreviousError() { @Test public void inboundMessageShouldCallListener() throws Exception { // Receive headers first so that it's a valid GRPC response. - stream().id(1); + stream().id(STREAM_ID); stream().transportHeadersReceived(grpcResponseHeaders(), false); super.inboundMessageShouldCallListener(); } @Test public void inboundHeadersShouldCallListenerHeadersRead() throws Exception { - stream().id(1); + stream().id(STREAM_ID); Http2Headers headers = grpcResponseHeaders(); stream().transportHeadersReceived(headers, false); verify(listener).headersRead(any(Metadata.Headers.class)); @@ -167,7 +167,7 @@ public void inboundHeadersShouldCallListenerHeadersRead() throws Exception { @Test public void inboundTrailersClosesCall() throws Exception { - stream().id(1); + stream().id(STREAM_ID); stream().transportHeadersReceived(grpcResponseHeaders(), false); super.inboundMessageShouldCallListener(); stream().transportHeadersReceived(grpcResponseTrailers(Status.OK), true); @@ -175,7 +175,7 @@ public void inboundTrailersClosesCall() throws Exception { @Test public void inboundStatusShouldSetStatus() throws Exception { - stream().id(1); + stream().id(STREAM_ID); // Receive headers first so that it's a valid GRPC response. stream().transportHeadersReceived(grpcResponseHeaders(), false); @@ -189,7 +189,7 @@ public void inboundStatusShouldSetStatus() throws Exception { @Test public void invalidInboundHeadersCancelStream() throws Exception { - stream().id(1); + stream().id(STREAM_ID); Http2Headers headers = grpcResponseHeaders(); headers.remove(CONTENT_TYPE_HEADER); // Remove once b/16290036 is fixed. @@ -223,7 +223,7 @@ public void nonGrpcResponseShouldSetStatus() throws Exception { @Test public void deframedDataAfterCancelShouldBeIgnored() throws Exception { - stream().id(1); + stream().id(STREAM_ID); // Receive headers first so that it's a valid GRPC response. stream().transportHeadersReceived(grpcResponseHeaders(), false); @@ -257,7 +257,7 @@ public void deframedDataAfterCancelShouldBeIgnored() throws Exception { @Test public void dataFrameWithEosShouldDeframeAndThenFail() { - stream().id(1); + stream().id(STREAM_ID); stream().request(1); // Receive headers first so that it's a valid GRPC response. @@ -274,8 +274,16 @@ public void dataFrameWithEosShouldDeframeAndThenFail() { assertEquals(Status.Code.INTERNAL, captor.getValue().getCode()); } + @Test + public void setHttp2StreamShouldNotifyReady() { + stream().id(STREAM_ID); + verify(listener, never()).onReady(); + stream().setHttp2Stream(http2Stream); + verify(listener).onReady(); + } + @Override - protected AbstractStream createStream() { + protected NettyClientStream createStream() { NettyClientStream stream = new NettyClientStream(listener, channel, handler); assertTrue(stream.canSend()); assertTrue(stream.canReceive()); @@ -283,6 +291,11 @@ protected AbstractStream createStream() { return stream; } + @Override + protected void closeStream() { + stream().cancel(); + } + private ByteBuf simpleGrpcFrame() { return Unpooled.wrappedBuffer(new byte[] {0, 0, 0, 0, 2, 3, 14}); } diff --git a/netty/src/test/java/io/grpc/transport/netty/NettyServerHandlerTest.java b/netty/src/test/java/io/grpc/transport/netty/NettyServerHandlerTest.java index 90e8b6bb4ce..d4602222db9 100644 --- a/netty/src/test/java/io/grpc/transport/netty/NettyServerHandlerTest.java +++ b/netty/src/test/java/io/grpc/transport/netty/NettyServerHandlerTest.java @@ -186,6 +186,7 @@ private void inboundDataShouldForwardToStreamListener(boolean endStream) throws if (endStream) { verify(streamListener).halfClosed(); } + verify(streamListener, atLeastOnce()).onReady(); verifyNoMoreInteractions(streamListener); } @@ -199,6 +200,7 @@ public void clientHalfCloseShouldForwardToStreamListener() throws Exception { verify(streamListener).messageRead(captor.capture()); assertArrayEquals(new byte[0], ByteStreams.toByteArray(captor.getValue())); verify(streamListener).halfClosed(); + verify(streamListener, atLeastOnce()).onReady(); verifyNoMoreInteractions(streamListener); } @@ -209,6 +211,7 @@ public void clientCancelShouldForwardToStreamListener() throws Exception { handler.channelRead(ctx, rstStreamFrame(STREAM_ID, (int) Http2Error.CANCEL.code())); verify(streamListener, never()).messageRead(any(InputStream.class)); verify(streamListener).closed(Status.CANCELLED); + verify(streamListener, atLeastOnce()).onReady(); verifyNoMoreInteractions(streamListener); } diff --git a/netty/src/test/java/io/grpc/transport/netty/NettyServerStreamTest.java b/netty/src/test/java/io/grpc/transport/netty/NettyServerStreamTest.java index 7bf67a031e7..8f816d337ee 100644 --- a/netty/src/test/java/io/grpc/transport/netty/NettyServerStreamTest.java +++ b/netty/src/test/java/io/grpc/transport/netty/NettyServerStreamTest.java @@ -36,21 +36,20 @@ import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.same; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; import io.grpc.Metadata; import io.grpc.Status; -import io.grpc.transport.AbstractStream; import io.grpc.transport.ServerStreamListener; import io.netty.buffer.EmptyByteBuf; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2Headers; -import io.netty.handler.codec.http2.Http2Stream; import io.netty.util.AsciiString; import org.junit.Before; @@ -59,27 +58,33 @@ import org.junit.runners.JUnit4; import org.mockito.Mock; +import java.io.ByteArrayInputStream; + /** Unit tests for {@link NettyServerStream}. */ @RunWith(JUnit4.class) public class NettyServerStreamTest extends NettyStreamTestBase { @Mock protected ServerStreamListener serverListener; + @Mock private NettyServerHandler handler; - @Mock - private Http2Stream http2Stream; + private Metadata.Trailers trailers = new Metadata.Trailers(); - @Override @Before + @Override public void setUp() { super.setUp(); - when(http2Stream.id()).thenReturn(STREAM_ID); + + // Verify onReady notification and then reset it. + verify(listener()).onReady(); + reset(listener()); } @Test public void writeMessageShouldSendResponse() throws Exception { - stream.writeMessage(input, input.available(), accepted); + byte[] msg = smallMessage(); + stream.writeMessage(new ByteArrayInputStream(msg), msg.length); stream.flush(); Http2Headers headers = new DefaultHttp2Headers() .status(Utils.STATUS_OK) @@ -87,7 +92,6 @@ public void writeMessageShouldSendResponse() throws Exception { verify(channel).writeAndFlush(new SendResponseHeadersCommand(STREAM_ID, headers, false)); verify(channel).write(new SendGrpcFrameCommand(stream, messageFrame(MESSAGE), false)); verify(channel).flush(); - verify(accepted).run(); } @Test @@ -217,15 +221,21 @@ public void emptyFramerShouldSendNoPayload() throws Exception { } @Override - protected AbstractStream createStream() { + protected NettyServerStream createStream() { NettyServerStream stream = new NettyServerStream(channel, http2Stream, handler); stream.setListener(serverListener); assertTrue(stream.canReceive()); assertTrue(stream.canSend()); - verifyZeroInteractions(serverListener); + verify(serverListener, atLeastOnce()).onReady(); + verifyNoMoreInteractions(serverListener); return stream; } + @Override + protected void closeStream() { + stream().close(Status.ABORTED, new Metadata.Trailers()); + } + @Override protected ServerStreamListener listener() { return serverListener; diff --git a/netty/src/test/java/io/grpc/transport/netty/NettyStreamTestBase.java b/netty/src/test/java/io/grpc/transport/netty/NettyStreamTestBase.java index 5a08c321750..e9b5d3ada05 100644 --- a/netty/src/test/java/io/grpc/transport/netty/NettyStreamTestBase.java +++ b/netty/src/test/java/io/grpc/transport/netty/NettyStreamTestBase.java @@ -32,11 +32,14 @@ package io.grpc.transport.netty; import static io.grpc.transport.netty.NettyTestUtil.messageFrame; -import static io.netty.util.CharsetUtil.UTF_8; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -50,6 +53,7 @@ import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoop; +import io.netty.handler.codec.http2.Http2Stream; import org.junit.Before; import org.junit.Test; @@ -60,6 +64,7 @@ import org.mockito.stubbing.Answer; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; @@ -82,16 +87,14 @@ public abstract class NettyStreamTestBase { @Mock protected ChannelFuture future; - @Mock - protected Runnable accepted; - @Mock protected EventLoop eventLoop; @Mock protected ChannelPromise promise; - protected InputStream input; + @Mock + protected Http2Stream http2Stream; protected AbstractStream stream; @@ -100,7 +103,7 @@ public abstract class NettyStreamTestBase { public void setUp() { MockitoAnnotations.initMocks(this); - mockChannelFuture(true); + mockFuture(true); when(channel.write(any())).thenReturn(future); when(channel.writeAndFlush(any())).thenReturn(future); when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); @@ -108,6 +111,7 @@ public void setUp() { when(channel.eventLoop()).thenReturn(eventLoop); when(pipeline.firstContext()).thenReturn(ctx); when(eventLoop.inEventLoop()).thenReturn(true); + when(http2Stream.id()).thenReturn(STREAM_ID); doAnswer(new Answer() { @Override @@ -118,7 +122,6 @@ public Void answer(InvocationOnMock invocation) throws Throwable { } }).when(eventLoop).execute(any(Runnable.class)); - input = new ByteArrayInputStream(MESSAGE.getBytes(UTF_8)); stream = createStream(); } @@ -138,11 +141,76 @@ public void inboundMessageShouldCallListener() throws Exception { assertEquals(MESSAGE, NettyTestUtil.toString(captor.getValue())); } + @Test + public void shouldBeImmediatelyReadyForData() { + assertTrue(stream.isReady()); + } + + @Test + public void closedShouldNotBeReady() throws IOException { + assertTrue(stream.isReady()); + closeStream(); + assertFalse(stream.isReady()); + } + + @Test + public void notifiedOnReadyAfterWriteCompletes() throws IOException { + assertTrue(stream.isReady()); + byte[] msg = largeMessage(); + // The future is set up to automatically complete, indicating that the write is done. + stream.writeMessage(new ByteArrayInputStream(msg), msg.length); + stream.flush(); + assertTrue(stream.isReady()); + verify(listener()).onReady(); + } + + @Test + public void shouldBeReadyForDataAfterWritingSmallMessage() throws IOException { + // Make sure the writes don't complete so we "back up" + reset(future); + + assertTrue(stream.isReady()); + byte[] msg = smallMessage(); + stream.writeMessage(new ByteArrayInputStream(msg), msg.length); + stream.flush(); + assertTrue(stream.isReady()); + verify(listener(), never()).onReady(); + } + + @Test + public void shouldNotBeReadyForDataAfterWritingLargeMessage() throws IOException { + // Make sure the writes don't complete so we "back up" + reset(future); + + assertTrue(stream.isReady()); + byte[] msg = largeMessage(); + stream.writeMessage(new ByteArrayInputStream(msg), msg.length); + stream.flush(); + assertFalse(stream.isReady()); + verify(listener(), never()).onReady(); + } + + protected byte[] smallMessage() { + return MESSAGE.getBytes(); + } + + protected byte[] largeMessage() { + byte[] smallMessage = smallMessage(); + int size = smallMessage.length * 10 * 1024; + byte[] largeMessage = new byte[size]; + for (int ix = 0; ix < size; ix += smallMessage.length) { + System.arraycopy(smallMessage, 0, largeMessage, ix, smallMessage.length); + } + return largeMessage; + } + protected abstract AbstractStream createStream(); protected abstract StreamListener listener(); - private void mockChannelFuture(boolean succeeded) { + protected abstract void closeStream(); + + private void mockFuture(boolean succeeded) { when(future.isDone()).thenReturn(true); when(future.isCancelled()).thenReturn(false); when(future.isSuccess()).thenReturn(succeeded); diff --git a/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java b/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java index 37a7ef05f89..af2f3c46b78 100644 --- a/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java +++ b/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpClientTransportTest.java @@ -264,7 +264,7 @@ public void writeMessage() throws Exception { OkHttpClientStream stream = streams.get(3); InputStream input = new ByteArrayInputStream(message.getBytes(UTF_8)); assertEquals(12, input.available()); - stream.writeMessage(input, input.available(), null); + stream.writeMessage(input, input.available()); stream.flush(); ArgumentCaptor captor = ArgumentCaptor.forClass(Buffer.class); verify(frameWriter).data(eq(false), eq(3), captor.capture(), eq(12 + HEADER_LENGTH)); @@ -359,7 +359,7 @@ public void outboundFlowControl() throws Exception { // The first message should be sent out. int messageLength = Utils.DEFAULT_WINDOW_SIZE / 2 + 1; InputStream input = new ByteArrayInputStream(new byte[messageLength]); - stream.writeMessage(input, input.available(), null); + stream.writeMessage(input, input.available()); stream.flush(); verify(frameWriter).data( eq(false), eq(3), any(Buffer.class), eq(messageLength + HEADER_LENGTH)); @@ -367,7 +367,7 @@ public void outboundFlowControl() throws Exception { // The second message should be partially sent out. input = new ByteArrayInputStream(new byte[messageLength]); - stream.writeMessage(input, input.available(), null); + stream.writeMessage(input, input.available()); stream.flush(); int partiallySentSize = Utils.DEFAULT_WINDOW_SIZE - messageLength - HEADER_LENGTH; @@ -390,7 +390,7 @@ public void outboundFlowControlWithInitialWindowSizeChange() throws Exception { int messageLength = 20; setInitialWindowSize(HEADER_LENGTH + 10); InputStream input = new ByteArrayInputStream(new byte[messageLength]); - stream.writeMessage(input, input.available(), null); + stream.writeMessage(input, input.available()); stream.flush(); // part of the message can be sent. verify(frameWriter).data(eq(false), eq(3), any(Buffer.class), eq(HEADER_LENGTH + 10)); @@ -409,7 +409,7 @@ public void outboundFlowControlWithInitialWindowSizeChange() throws Exception { // Get 20 tokens back, still can't send any data. frameHandler.windowUpdate(3, 20); input = new ByteArrayInputStream(new byte[messageLength]); - stream.writeMessage(input, input.available(), null); + stream.writeMessage(input, input.available()); stream.flush(); // Only the previous two write operations happened. verify(frameWriter, times(2)).data(anyBoolean(), anyInt(), any(Buffer.class), anyInt()); @@ -476,7 +476,7 @@ public void receiveGoAway() throws Exception { InputStream input = new ByteArrayInputStream(sentMessage.getBytes(UTF_8)); assertEquals(22, input.available()); - stream.writeMessage(input, input.available(), null); + stream.writeMessage(input, input.available()); stream.flush(); ArgumentCaptor captor = ArgumentCaptor.forClass(Buffer.class); @@ -906,7 +906,7 @@ public void closed(Status status, Metadata.Trailers trailers) { } @Override - public void onReady(int numMessages) { + public void onReady() { } void waitUntilStreamClosed() throws InterruptedException { diff --git a/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpReadableBufferTest.java b/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpReadableBufferTest.java index 5d0a9166471..ee3628edc77 100644 --- a/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpReadableBufferTest.java +++ b/okhttp/src/test/java/io/grpc/transport/okhttp/OkHttpReadableBufferTest.java @@ -52,7 +52,12 @@ public class OkHttpReadableBufferTest extends ReadableBufferTestBase { @SuppressWarnings("resource") @Before public void setup() { - buffer = new OkHttpReadableBuffer(new Buffer().writeUtf8(msg)); + Buffer empty = new Buffer(); + try { + buffer = new OkHttpReadableBuffer(empty.writeUtf8(msg)); + } finally { + empty.close(); + } } @Override diff --git a/stub/src/test/java/io/grpc/stub/CallsTest.java b/stub/src/test/java/io/grpc/stub/CallsTest.java index a810ae405fc..fbc3ef22d73 100644 --- a/stub/src/test/java/io/grpc/stub/CallsTest.java +++ b/stub/src/test/java/io/grpc/stub/CallsTest.java @@ -33,7 +33,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import static org.mockito.Mockito.any; +import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import com.google.common.util.concurrent.ListenableFuture; From 00656280cafbf667ddb15eba8fd7394de0c18caf Mon Sep 17 00:00:00 2001 From: nmittler Date: Mon, 4 May 2015 11:51:59 -0700 Subject: [PATCH 2/2] Addressing comments. --- core/src/main/java/io/grpc/ChannelImpl.java | 6 +++++- core/src/main/java/io/grpc/transport/AbstractStream.java | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/io/grpc/ChannelImpl.java b/core/src/main/java/io/grpc/ChannelImpl.java index b4f6bff66fa..7532cd1a9f9 100644 --- a/core/src/main/java/io/grpc/ChannelImpl.java +++ b/core/src/main/java/io/grpc/ChannelImpl.java @@ -67,8 +67,12 @@ private static class NoopClientStream implements ClientStream { @Override public void request(int numMessages) {} + /** + * Always returns {@code false}, since this is only used when the startup of the {@link Call} + * fails (i.e. the {@link Call} is closed). + */ @Override public boolean isReady() { - return true; + return false; } } diff --git a/core/src/main/java/io/grpc/transport/AbstractStream.java b/core/src/main/java/io/grpc/transport/AbstractStream.java index 44afefba902..e2ba6de6550 100644 --- a/core/src/main/java/io/grpc/transport/AbstractStream.java +++ b/core/src/main/java/io/grpc/transport/AbstractStream.java @@ -296,8 +296,10 @@ protected final void requestMessagesFromDeframer(int numMessages) { */ protected final void onSendingBytes(int numBytes) { synchronized (onReadyLock) { - shouldNotifyOnReady = true; numSentBytesQueued += numBytes; + if (!isReady()) { + shouldNotifyOnReady = true; + } } }