diff --git a/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/GrpcServerImpl.java b/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/GrpcServerImpl.java index a51becc6..8fd9153c 100644 --- a/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/GrpcServerImpl.java +++ b/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/GrpcServerImpl.java @@ -29,8 +29,6 @@ import java.util.function.Consumer; import java.util.stream.Collectors; -import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE; - /** * @author Julien Viet */ @@ -373,12 +371,9 @@ protected GrpcStream createGrpcStream(GrpcProtocol protocol, HttpServerRequest h if (!httpRequest.path().equals("/" + fullMethodName)) { return null; } - GrpcMessageDeframer deframer; - if (httpRequest.version() != HttpVersion.HTTP_2 && GrpcMediaType.isGrpcWebText(httpRequest.getHeader(CONTENT_TYPE))) { - deframer = new TextMessageDeframer(); - } else { - deframer = new Http2GrpcMessageDeframer(encoding, format); - } + GrpcMessageDeframer deframer = protocol == GrpcProtocol.WEB_TEXT + ? new TextMessageDeframer(encoding, format) + : new Http2GrpcMessageDeframer(encoding, format); outboundInvoker = new WebGrpcOutboundStream(httpRequest, protocol, deframer); break; case TRANSCODING: diff --git a/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/TextMessageDeframer.java b/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/TextMessageDeframer.java index 8e4c08c1..c53ab4d4 100644 --- a/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/TextMessageDeframer.java +++ b/vertx-grpc-server/src/main/java/io/vertx/grpc/server/impl/TextMessageDeframer.java @@ -1,70 +1,103 @@ package io.vertx.grpc.server.impl; +import io.netty.buffer.ByteBuf; import io.netty.handler.codec.base64.Base64; import io.vertx.core.buffer.Buffer; import io.vertx.core.internal.buffer.BufferInternal; -import io.vertx.grpc.common.GrpcMessage; -import io.vertx.grpc.common.MessageSizeOverflowException; +import io.vertx.grpc.common.InvalidMessagePayloadException; +import io.vertx.grpc.common.WireFormat; import io.vertx.grpc.common.impl.GrpcMessageDeframer; +import io.vertx.grpc.common.impl.Http2GrpcMessageDeframer; +/** + * Deframes a {@code application/grpc-web-text} request body. + * + *

A grpc-web-text body is a binary gRPC-Web body encoded in base64: the same sequence of length-prefixed frames + * ({@code [flag: 1 byte][length: 4 bytes][message]}), as text. This deframer only undoes the base64 and hands the + * decoded bytes to an {@link Http2GrpcMessageDeframer}, which splits them into messages exactly as it does for a + * binary body. A body can therefore carry any number of messages, over any HTTP version, and messages are delivered + * as soon as they are decoded instead of when the body ends.

+ * + *

Two properties of the base64 text shape the decoding:

+ * + */ class TextMessageDeframer implements GrpcMessageDeframer { - private long maxMessageSize; - private boolean processed; - private Buffer buffer; - private Object result; + private final Http2GrpcMessageDeframer deframer; + + private Buffer pending = BufferInternal.buffer(); + private InvalidMessagePayloadException failure; + + TextMessageDeframer(String encoding, WireFormat format) { + this.deframer = new Http2GrpcMessageDeframer(encoding, format); + } @Override public void maxMessageSize(long maxMessageSize) { - this.maxMessageSize = maxMessageSize; + deframer.maxMessageSize(maxMessageSize); } @Override public void update(Buffer chunk) { - if (processed) { - return; - } - if (buffer == null) { - buffer = chunk; - } else { - try { - buffer.appendBuffer(chunk); - } catch (IndexOutOfBoundsException e) { - // Work around because we cannot happend to slices - // java.lang.IndexOutOfBoundsException: writerIndex(270) + minWritableBytes(120) exceeds maxCapacity(270): UnpooledSlicedByteBuf(ridx: 0, widx: 270, cap: 270/270, unwrapped: VertxUnsafeHeapByteBuf(ridx: 0, widx: 0, cap: 270)) - // at io.netty.buffer@4.2.0.RC3/io.netty.buffer.AbstractByteBuf.ensureWritable0(AbstractByteBuf.java:294) - // at io.netty.buffer@4.2.0.RC3/io.netty.buffer.AbstractByteBuf.ensureWritable(AbstractByteBuf.java:280) - // at io.netty.buffer@4.2.0.RC3/io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1103) - // at io.vertx.core@5.0.0-SNAPSHOT/io.vertx.core.buffer.impl.BufferImpl.appendBuffer(BufferImpl.java:256) - // at io.vertx.core@5.0.0-SNAPSHOT/io.vertx.core.buffer.impl.BufferImpl.appendBuffer(BufferImpl.java:41) - buffer = buffer.copy(); - buffer.appendBuffer(chunk); - } - } - if (result == null && buffer.length() > maxMessageSize) { - result = new MessageSizeOverflowException(buffer.length()); - buffer = null; - processed = true; + if (pending != null) { + pending.appendBuffer(chunk); + // Decode the longest prefix made of whole 4 character groups (length rounded down to a multiple of 4) + decode(pending.length() & ~3); } } @Override public void end() { - if (!processed) { - BufferInternal decoded = BufferInternal.buffer(Base64.decode(((BufferInternal) buffer).getByteBuf())); - buffer = null; - result = GrpcMessage.message("identity", decoded.slice(5, decoded.length())); + if (pending != null) { + // No more text will come: decode what is left, the sender may have omitted the final padding + decode(pending.length()); + } + deframer.end(); + } + + /** + * Decode the first {@code len} characters of {@link #pending} into the binary deframer and keep the rest. + */ + private void decode(int len) { + ByteBuf text = ((BufferInternal) pending).getByteBuf(); + int from = 0; + while (from < len) { + // A piece ends after its padding, or at len when the text has no more padding + int to = text.indexOf(from, len, (byte) '='); + if (to < 0) { + to = len; + } + while (to < len && text.getByte(to) == '=') { + to++; + } + try { + deframer.update(BufferInternal.buffer(Base64.decode(text, from, to - from))); + } catch (IllegalArgumentException e) { + // Not base64: report it once from next() and ignore the rest of the body + failure = new InvalidMessagePayloadException(null, e); + pending = null; + return; + } + from = to; } + pending = pending.getBuffer(len, pending.length()); } @Override public Object next() { - if (result != null) { - Object ret = result; - result = null; + if (failure != null) { + Object ret = failure; + failure = null; return ret; - } else { - return null; } + // After a failure, messages already decoded are dropped: the call is cancelled anyway + return pending == null ? null : deframer.next(); } } diff --git a/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/BinaryServerHttp2Test.java b/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/BinaryServerHttp2Test.java new file mode 100644 index 00000000..2c8354c4 --- /dev/null +++ b/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/BinaryServerHttp2Test.java @@ -0,0 +1,12 @@ +package io.vertx.grpc.server.tests.web; + +import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.HttpVersion; + +public class BinaryServerHttp2Test extends BinaryServerTest { + + @Override + protected HttpClientOptions httpClientOptions() { + return new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2).setHttp2ClearTextUpgrade(false); + } +} diff --git a/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/ServerTestBase.java b/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/ServerTestBase.java index 7390dba2..699fc233 100644 --- a/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/ServerTestBase.java +++ b/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/ServerTestBase.java @@ -53,6 +53,7 @@ public abstract class ServerTestBase extends GrpcTestBase { public static final ServiceMethod EMPTY_CALL = ServiceMethod.server(TEST_SERVICE_NAME, "EmptyCall", EMPTY_ENCODER, EMPTY_DECODER); public static final ServiceMethod UNARY_CALL = ServiceMethod.server(TEST_SERVICE_NAME, "UnaryCall", ECHO_RESPONSE_ENCODER, ECHO_REQUEST_DECODER); public static final ServiceMethod STREAMING_CALL = ServiceMethod.server(TEST_SERVICE_NAME, "StreamingCall", STREAMING_RESPONSE_ENCODER, STREAMING_REQUEST_DECODER); + public static final ServiceMethod CONCAT_CALL = ServiceMethod.server(TEST_SERVICE_NAME, "ConcatCall", ECHO_RESPONSE_ENCODER, ECHO_REQUEST_DECODER); private static final String TEST_SERVICE = "/io.vertx.grpcweb.TestService"; @@ -94,7 +95,7 @@ public abstract class ServerTestBase extends GrpcTestBase { @Override public void setUp(TestContext should) { super.setUp(should); - httpClient = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(port)); + httpClient = vertx.createHttpClient(httpClientOptions().setDefaultPort(port)); GrpcServer grpcServer = GrpcServer.server(vertx, new GrpcServerOptions()); grpcServer.callHandler(EMPTY_CALL, request -> { copyHeaders(request.headers(), request.response().headers()); @@ -146,6 +147,11 @@ public void setUp(TestContext should) { response.end(); }); }); + grpcServer.callHandler(CONCAT_CALL, request -> { + StringBuilder payloads = new StringBuilder(); + request.handler(requestMsg -> payloads.append(requestMsg.getPayload())); + request.endHandler(v -> request.response().end(EchoResponse.newBuilder().setPayload(payloads.toString()).build())); + }); httpServer = vertx.createHttpServer(new HttpServerOptions().setPort(port)).requestHandler(grpcServer); httpServer.listen().onComplete(should.asyncAssertSuccess()); } @@ -173,6 +179,10 @@ public static void copyMetadata(MultiMap src, MultiMap dst, String... keys) { } } + protected HttpClientOptions httpClientOptions() { + return new HttpClientOptions(); + } + protected abstract MultiMap requestHeaders(); protected abstract CharSequence responseContentType(); @@ -456,6 +466,53 @@ public void testServerSideStreamingWithMetadata(TestContext should) { })); } + @Test + public void testClientSideStreaming(TestContext should) { + Random rnd = ThreadLocalRandom.current(); + List payloads = Arrays.asList("foo", "barbaz", IntStream.range(0, 1024).mapToObj(i -> "x").collect(joining()), ""); + httpClient.request(HttpMethod.POST, TEST_SERVICE + "/ConcatCall").compose(req -> { + req.setChunked(true); + req.headers().addAll(requestHeaders()); + Buffer buffer = Buffer.buffer(); + for (String payload : payloads) { + buffer.appendBuffer(encode(EchoRequest.newBuilder().setPayload(payload).build())); + } + // Make sure the server will get blocks of arbitrary size + int length = buffer.length(); + for (int pos = 0, written; pos < length; pos += written) { + written = Math.min(length - pos, 1 + rnd.nextInt(64)); + req.write(buffer.getBuffer(pos, pos + written)); + } + req.end(); + return req.response().compose(response -> response.body().map(response)); + }).onComplete(should.asyncAssertSuccess(response -> { + should.verify(v -> { + + assertEquals(200, response.statusCode()); + MultiMap headers = response.headers(); + assertTrue(headers.contains(CONTENT_TYPE, responseContentType(), true)); + + Buffer body = decodeBody(response.body().result()); + int pos = 0; + + Buffer prefix = body.getBuffer(pos, PREFIX_SIZE); + assertEquals(0x00, prefix.getUnsignedByte(0)); // Uncompressed message + int len = prefix.getInt(1); + pos += PREFIX_SIZE; + + EchoResponse echoResponse = parseEchoResponse(body.getBuffer(pos, pos + len)); + assertEquals(String.join("", payloads), echoResponse.getPayload()); + pos += len; + + Buffer trailer = body.getBuffer(pos, body.length()); + assertEquals(0x80, trailer.getUnsignedByte(0)); // Uncompressed trailer + len = trailer.getInt(1); + assertEquals(STATUS_OK, trailer.getBuffer(PREFIX_SIZE, PREFIX_SIZE + len).toString()); + + }); + })); + } + @Test public void testTrailersOnly(TestContext should) { httpClient.request(HttpMethod.POST, TEST_SERVICE + "/UnaryCall").compose(req -> { diff --git a/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/TextServerHttp2Test.java b/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/TextServerHttp2Test.java new file mode 100644 index 00000000..abd8bb46 --- /dev/null +++ b/vertx-grpc-server/src/test/java/io/vertx/grpc/server/tests/web/TextServerHttp2Test.java @@ -0,0 +1,12 @@ +package io.vertx.grpc.server.tests.web; + +import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.HttpVersion; + +public class TextServerHttp2Test extends TextServerTest { + + @Override + protected HttpClientOptions httpClientOptions() { + return new HttpClientOptions().setProtocolVersion(HttpVersion.HTTP_2).setHttp2ClearTextUpgrade(false); + } +}