Gumdrop

Gumdrop gRPC Client & Server

Gumdrop provides gRPC support built on top of its HTTP client and server. gRPC runs over HTTP/2 with Content-Type: application/grpc. The implementation uses an event-oriented, schema-driven approach with no generated code and no com.google.protobuf dependency: you load a .proto file at run time, and messages are delivered to you as parse events and written as serialiser events, streaming through the HTTP connection without being built up as objects.

The protobuf wire format is read and written by jprotobuf, a small push-parsing codec for Protocol Buffers (org.bluezoo.protobuf, with ProtobufParser and ProtobufWriter). Gumdrop's ProtoModelAdapter and ProtoModelSerializer sit on top of it and add the schema from your .proto file, turning wire fields into named, typed events and back.

Both the client and the server handle unary and streaming calls (server, client and bidirectional), call metadata, deadlines and message compression. The server serves an RPC declared with stream in the .proto only if its GrpcServer says it can (isStreamingSupported(), false by default), so a service written for unary calls is never surprised: it answers such a call UNIMPLEMENTED (12) without the service seeing it. See Streaming RPCs, Call metadata, Deadlines and Compression.

Contents

Overview

Gumdrop’s gRPC support lives in org.bluezoo.gumdrop.grpc:

The client uses the HTTP client as-is (composition, not extension). The server integrates the same way every HttpServer application does: implement HttpStreamHandler and pass it to HttpServer.compose().streamHandler(...). Both HTTP/2 and HTTP/3 are supported.

Proto model and .proto parser

Before using gRPC, you need a Proto model from your .proto file. Use ProtoFileParser.parse(CharSequence) to parse a .proto definition:

import org.bluezoo.gumdrop.grpc.proto.*;

String protoSource = ""
    + "syntax = \"proto3\";\n"
    + "package example.v1;\n"
    + "message GetUserRequest {\n"
    + "  int32 user_id = 1;\n"
    + "}\n"
    + "message GetUserResponse {\n"
    + "  string name = 1;\n"
    + "  string email = 2;\n"
    + "}\n"
    + "service UserService {\n"
    + "  rpc GetUser(GetUserRequest) returns (GetUserResponse);\n"
    + "}\n";

ProtoFile protoFile = ProtoFileParser.parse(protoSource);

For loading from a file, use the push-style API:

ProtoFileParser parser = new ProtoFileParser();
try (FileChannel channel = FileChannel.open(Paths.get("service.proto"))) {
    ByteBuffer buffer = ByteBuffer.allocate(8192);
    while (channel.read(buffer) > 0) {
        buffer.flip();
        parser.receive(buffer);
        buffer.compact();
    }
}
ProtoFile protoFile = parser.close();

The Proto model provides:

The parser reads proto2 and proto3 syntax: messages (nested), enums, oneof, map, repeated and optional fields, and services with their rpc methods.

Event-oriented message handling

Gumdrop does not use generated protobuf classes. Instead, it uses an event-oriented API similar to JSONContentHandler and MimeHandler. Implement ProtoMessageHandler to receive semantic events:

public interface ProtoMessageHandler {
    void setLocator(ProtoLocator locator);
    void startMessage(String typeName) throws ProtoParseException;
    void endMessage() throws ProtoParseException;
    void field(String name, Object value) throws ProtoParseException;
    void startField(String name, String typeName) throws ProtoParseException;
    void endField() throws ProtoParseException;
}

For a message like GetUserResponse { name = "Alice"; email = "alice@example.com" }, the event sequence is:

startMessage("example.v1.GetUserResponse")
field("name", "Alice")
field("email", "alice@example.com")
endMessage()

startMessage and endMessage bracket a whole message as it is received, so endMessage() always means "this message is complete". A nested message is not bracketed by them; it is the content between startField and endField:

startMessage("example.v1.GetUserRequest")
field("user_id", 42)
startField("address", "example.v1.Address")
  field("street", "123 Main")
endField()
endMessage()

Use ProtoDefaultHandler as a base if you only need to override some methods.

gRPC server

Implement GrpcServer. For each call it is asked for a ProtoMessageHandler to receive the request message as events; return null for a path you do not implement, and the caller gets UNIMPLEMENTED (status 12). When the request message ends, answer through the GrpcCall:

import org.bluezoo.gumdrop.grpc.proto.*;
import org.bluezoo.gumdrop.grpc.server.*;
import org.bluezoo.protobuf.ProtobufWriter;

public class UserGrpcService implements GrpcServer {

    public ProtoMessageHandler startCall(String path, final GrpcCall call) {
        if (!"/example.v1.UserService/GetUser".equals(path)) {
            return null;                        // UNIMPLEMENTED
        }
        return new ProtoDefaultHandler() {
            private int userId;

            public void field(String name, Object value) {
                if ("user_id".equals(name)) {
                    userId = ((Number) value).intValue();
                }
            }

            public void endMessage() throws ProtoParseException {
                try {
                    GrpcResponseMessage message = call.openMessage(null);
                    ProtoModelSerializer serializer = message.getSerializer();
                    ProtobufWriter writer = message.getWriter();
                    serializer.startMessage(writer, "example.v1.GetUserResponse");
                    serializer.field(writer, "name", lookupName(userId));
                    serializer.field(writer, "email", lookupEmail(userId));
                    serializer.endMessage();
                    message.complete();        // frames and sends the response
                } catch (IOException e) {
                    call.sendError(e);
                }
            }
        };
    }
}

GrpcCall provides:

A successful call is an HTTP 200 whose response carries the framed message followed by a grpc-status: 0 trailer; a call that answers with one message ends itself after it. An error before any message has been sent is a "trailers-only" response: HTTP 200 with grpc-status and grpc-message and no body; after messages have been sent it is the status in the trailers. Requests that are not valid gRPC (an unknown RPC, a malformed frame, a message larger than the limit) get an ordinary HTTP 404 or 400.

Create a GrpcRequestHandler from the parsed ProtoFile and your service, and compose it onto an HttpServer (see below). It accepts POST requests with content-type: application/grpc whose path names an rpc in the .proto. maxMessageSize(long) sets the largest request message accepted (default 4 MB).

ProtoFile protoFile = ProtoFileParser.parse(protoSource);
GrpcRequestHandler grpcHandler =
        new GrpcRequestHandler(protoFile, new UserGrpcService()).maxMessageSize(1024 * 1024);

gRPC client

The gRPC client composes the HTTP client. Create an HttpClient, connect, then use GrpcClient for calls:

In the client examples on this page, gumdrop is the Gumdrop instance returned by Gumdrop.boot(); a client is given it when it connects.

import org.bluezoo.gumdrop.grpc.client.*;
import org.bluezoo.gumdrop.http.client.*;

final HttpClient httpClient = new HttpClient("localhost", 50051).secure(true);  // TLS for production

ProtoFile protoFile = ProtoFileParser.parse(protoSource);
final GrpcClient grpcClient = new GrpcClient(protoFile);

httpClient.connect(gumdrop, new HttpClientHandler() {
    public void onConnected(Endpoint endpoint) {
        ByteBuffer requestMessage = ...;     // serialised request (see Serialisation below)

        grpcClient.call(httpClient, "/example.v1.UserService/GetUser",
            requestMessage, new GrpcResponseHandler() {
                public ProtoMessageHandler startMessage(String messageTypeName) {
                    // return a handler for the response message's events
                    return new ProtoDefaultHandler() {
                        public void field(String name, Object value) {
                            System.out.println(name + " = " + value);
                        }
                    };
                }
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            });
    }
    public void onSecurityEstablished(SecurityInfo info) { }
    public void onError(Exception cause) { cause.printStackTrace(); }
    public void onDisconnected() { }
});

If the response type is known you can skip the response handler and pass the type name and a ProtoMessageHandler directly:

grpcClient.call(httpClient, "/example.v1.UserService/GetUser",
    requestMessage, "example.v1.GetUserResponse", new ProtoDefaultHandler() {
        public void field(String name, Object value) {
            if ("name".equals(name)) {
                System.out.println("User: " + value);
            }
        }
    });

call returns a GrpcClientCall; cancel() resets the request stream, and send and halfClose() stream requests (see below). The response is parsed as it arrives, without buffering the body. A non-success grpc-status from the server, a non-200 HTTP status or a truncated message is reported to onError as a GrpcException, whose getStatus() is the gRPC status (an HTTP status with no grpc-status is mapped as the gRPC specification says, so a 503 is UNAVAILABLE); the server's grpc-message is percent-decoded into its text. The handler's onComplete(int status, String message) is called once when the call ends with a gRPC status, whether OK or not (after onError, for a status other than OK); a call that fails without a status, such as a lost connection, is reported to onError alone.

The HTTP client negotiates HTTP/2 via ALPN when secure(true) is used (HTTP/2 is the default for TLS), and resolves host names through DnsResolver like every Gumdrop client. HTTP/3 is used automatically when the host advertises it in a DNS HTTPS record or Alt-Svc (see the HTTP client); call httpClient.versions(HttpVersion.HTTP_3) only to force it. For gRPC over cleartext HTTP/2, permit only HTTP_2_0 and use h2WithPriorKnowledge(true).

Streaming RPCs

Server. A GrpcServer that returns true from isStreamingSupported() receives calls to every RPC in startCall; call.getRpc() says which kind. Each request message is delivered to the returned handler as its own startMessage … endMessage sequence, so a client or bidirectional stream delivers many. If the handler also implements GrpcCallHandler, the framework calls its endRequests() when the client has sent its last message (the half-close, which also happens for a call that sent none) and cancelled() when the call is over without the handler having ended it: the client reset the stream, the connection failed, the deadline passed or the request was malformed. After cancelled() nothing sent reaches the client.

A handler can send any number of response messages with openMessage and complete(); the response headers go out with the first, and grpc-status goes in the trailers when the call ends. A call to an RPC with a single response message ends by itself after it; a call that streams its responses stays open until the handler calls close() or close(status, message) (or sendError), including to end with an error after some messages. For flow control, isReady() says whether the transport has drained what was sent, onReady(Runnable) registers a one-shot callback for when it can take more, and pauseRequests() and resumeRequests() slow a client that sends faster than the handler can work.

// Watch(WatchRequest) returns (stream Event)
class WatchHandler extends ProtoDefaultHandler implements GrpcCallHandler {
    private final GrpcCall call;
    WatchHandler(GrpcCall call) { this.call = call; }

    public void endMessage() {                   // the request message is complete
        sendEvent(call, "first");
        sendEvent(call, "second");
        call.close();                            // OK, in the trailers
    }

    public void cancelled() {
        // the client went away or the deadline passed: stop producing events
    }
}

Client. The call form that takes one request message sends it and half-closes, and delivers a stream of response messages if the RPC has one: startMessage of the handler is called for each, and onComplete ends the call. For an RPC that streams its requests, use the form that takes no message, and send them through the call:

GrpcClientCall call = grpcClient.call(httpClient, "/example.v1.Chat/Talk", responseHandler);
call.send(ByteBuffer.wrap(firstMessage));      // serialised, as for a unary call
call.send(ByteBuffer.wrap(secondMessage));
call.halfClose();                              // no more requests; the response goes on

The header section is sent at once, so the first message is not held back. send throws IllegalStateException once the request has ended (after halfClose(), or on a call made with its one message) and does nothing once the call has ended or been cancelled.

Call metadata

Metadata is the custom headers and trailers of a call, as GrpcMetadata: an ordered multimap whose keys are lower case letters, digits, -, _ and ., and whose values are printable ASCII. A key ending -bin carries bytes, which travel base64 encoded: use addBinary and getBinary for those. Keys beginning grpc-, content-type and te belong to the protocol and cannot be set.

Deadlines

Server. call.getDeadline() is the Instant from the client's grpc-timeout, or null. When it passes the framework ends the call with DEADLINE_EXCEEDED (4) and tells a GrpcCallHandler that it is cancelled.

Client. GrpcCallOptions.timeout(amount, unit) or deadline(Instant) sets how long the call may take, from when it starts. It is sent as grpc-timeout, and the client enforces it too: when it passes, the handler gets a GrpcException with DEADLINE_EXCEEDED and onComplete(4, ...), and the stream is cancelled, so the server is told to stop. On a transport that cannot schedule timers only the server enforces it.

GrpcCallOptions options = new GrpcCallOptions().timeout(5, TimeUnit.SECONDS);
options.getMetadata().add("x-request-id", "abc123");
grpcClient.call(httpClient, path, requestMessage, handler, options);

Compression

Each message is compressed on its own, as the gRPC protocol specifies: its flag byte is 1, and the grpc-encoding header names the algorithm for the call. A peer lists what it can decode in grpc-accept-encoding, which every Gumdrop request and response carries. The algorithms are gzip and deflate, which are the specification's and are on by default, and br (Brotli), which is not part of the gRPC specification: it is an extension that works only between peers that both support it, so it is never offered or used unless you ask for it. identity, no compression, is always allowed.

Receiving. A compressed message is decoded as it streams in, without being held whole, and a message may not expand beyond the maximum message size (4 MB by default, GrpcRequestHandler.maxMessageSize), so a small message cannot be a decompression bomb. A message that does is RESOURCE_EXHAUSTED (8); a corrupt or truncated one, or a compressed message with no grpc-encoding, is INTERNAL (13). A server answers a request in an encoding it does not offer UNIMPLEMENTED (12), in a response that lists the ones it does.

Sending. A server compresses response messages when the request's grpc-accept-encoding lists an algorithm it offers, taking the first of its own list. A message below a minimum size, or one that would not be smaller compressed, is sent as it is. A client compresses request messages with the algorithm it is given, which the server must be able to decode.

GrpcRequestHandler handler = new GrpcRequestHandler(protoFile, service)
        .encodings(Coding.GZIP, Coding.DEFLATE)   // decoded and offered, most wanted first
        .compressResponses(true)                  // the default
        .compressionThreshold(256);               // bytes, the default

GrpcClient client = new GrpcClient(protoFile)
        .encodings(Coding.GZIP, Coding.DEFLATE)   // what responses may be compressed with
        .compression(Coding.GZIP);                // compress requests; none by default

Serialisation and parsing

To serialise a request or parse a response, use the Proto model with jprotobuf's ProtobufWriter and ProtobufParser (wire format) and Gumdrop's ProtoModelAdapter / ProtoModelSerializer (schema-driven).

Serialising a request

ProtoModelSerializer writes protobuf from events. Drive it with startMessage, field, endMessage:

import org.bluezoo.gumdrop.grpc.proto.*;
import org.bluezoo.protobuf.ProtobufWriter;

ByteArrayOutputStream out = new ByteArrayOutputStream();
ProtobufWriter writer = new ProtobufWriter(out);
ProtoModelSerializer serializer = new ProtoModelSerializer(protoFile);

serializer.startMessage(writer, "example.v1.GetUserRequest");
serializer.field(writer, "user_id", 42);
serializer.endMessage();

ByteBuffer requestMessage = ByteBuffer.wrap(out.toByteArray());

Parsing a message by hand

ProtoModelAdapter bridges the low-level ProtobufParser to your ProtoMessageHandler. The gRPC client uses this internally when you pass a ProtoMessageHandler. For raw ByteBuffer responses, parse manually:

import org.bluezoo.gumdrop.grpc.proto.*;
import org.bluezoo.protobuf.ProtobufParser;

ProtoModelAdapter adapter = new ProtoModelAdapter(protoFile, myHandler);
ProtobufParser parser = new ProtobufParser(adapter);

adapter.startRootMessage("example.v1.GetUserResponse");
parser.receive(messageBuffer);
parser.close();
adapter.endRootMessage();

Integration with HTTP services

An HttpServer composes a single HttpStreamHandler. To serve both gRPC and other content (e.g. servlets, static files) on one port, route on content-type in an outer stream handler. The events that arrive before the content type (method, target, scheme, authority) are recorded with HttpMessageRecorder and replayed to whichever handler is chosen:

public final class GrpcOrHttpStreamHandler implements HttpStreamHandler {
    private final GrpcRequestHandler grpcHandler;
    private final HttpStreamHandler fallback;

    public GrpcOrHttpStreamHandler(ProtoFile protoFile, GrpcServer grpcService,
                                   HttpStreamHandler fallback) {
        this.grpcHandler = new GrpcRequestHandler(protoFile, grpcService);
        this.fallback = fallback;
    }

    public HttpRequestHandler openStream(final HttpResponse response) {
        return new DefaultHttpRequestHandler() {
            private final HttpMessageRecorder recorder = new HttpMessageRecorder();
            private HttpMessageHandler sink = recorder;
            private HttpRequestHandler delegate;

            private void choose(boolean grpc) {
                delegate = grpc ? grpcHandler.openStream(response)
                                : fallback.openStream(response);
                recorder.replay(delegate);
                sink = delegate;
            }

            public void version(HttpVersion version) { sink.version(version); }
            public void method(HttpMethod method) { sink.method(method); }
            public void target(ByteBuffer target) { sink.target(target); }
            public void scheme(ByteBuffer scheme) { sink.scheme(scheme); }
            public void authority(ByteBuffer authority) { sink.authority(authority); }
            public void protocol(ByteBuffer protocol) { sink.protocol(protocol); }
            public void contentDisposition(ContentDisposition cd) { sink.contentDisposition(cd); }
            public void longHeader(String name, long value) { sink.longHeader(name, value); }
            public void dateHeader(String name, java.time.Instant value) { sink.dateHeader(name, value); }

            public void contentType(ContentType type) {
                boolean first = (delegate == null);
                sink.contentType(type);
                if (first) {
                    choose(type.isMimeType("application/grpc"));
                }
            }

            public void header(String name, ByteBuffer value) { sink.header(name, value); }

            public void endHeaders() {
                if (delegate == null) {
                    choose(false);
                }
                sink.endHeaders();
            }

            public void bodyContent(ByteBuffer data) { sink.bodyContent(data); }
            public void endMessage() { sink.endMessage(); }
            public void error(HttpError error, String detail) { sink.error(error, detail); }
            public void failed(Exception cause) { sink.failed(cause); }
        };
    }
}

HttpServer server = HttpServer.compose()
        .secureEndpoint(50051, TlsConfig.keystore(Path.of("keystore.p12"), "changeit"))
        .streamHandler(new GrpcOrHttpStreamHandler(protoFile, grpcService,
                new ServletRequestHandler(container)))
        .server();

Standalone gRPC service

For a gRPC-only service, compose GrpcRequestHandler directly:

HttpServer server = HttpServer.compose()
        .secureEndpoint(50051, TlsConfig.keystore(Path.of("keystore.p12"), "changeit"))
        .streamHandler(new GrpcRequestHandler(protoFile, grpcService))
        .server();

Gumdrop gumdrop = Gumdrop.boot();
gumdrop.addServer(server);

gRPC requires HTTP/2. The listener negotiates HTTP/2 by ALPN when TLS is enabled; for gRPC over cleartext, add a plaintext Http2Listener, which accepts clients that start HTTP/2 with prior knowledge.


← Back to Main Page | HTTP Server & Client | Building microservices | Telemetry

Gumdrop gRPC