Gumdrop

Building Microservices with Gumdrop

This guide explains how to build your own HTTP microservices using the Gumdrop framework. Unlike the servlet container, file server or WebSocket service, which are ready-to-use implementations, this page shows you how to create custom services from scratch using the HTTP server API. The examples stream: they parse requests with Gonzalez (XML) and jsonparser (JSON) as the bytes arrive, and write responses as they are produced, without holding a whole document in memory. All the code on this page is in examples/microservices, and builds and runs as shown at the end.

Contents

Overview

A Gumdrop microservice is an HttpServer composed with a custom HttpStreamHandler, which binds an HttpRequestHandler instance for each request. Handlers receive events in sequence:

version()              // HTTP version
method(HttpMethod)     // request method
target(ByteBuffer)     // request target (path and query)
contentType(ContentType) // if the request has one (typed header events follow:
                       // longHeader, dateHeader, contentDisposition)
header(name, value)    // every other field line, one event per line
endHeaders()           // header section complete
bodyContent(ByteBuffer) // body data chunks (zero or more; POST, PUT, etc.)
header(name, value)    // trailer fields, if any (a header after endHeaders)
endMessage()           // request complete

The events arrive on the connection's SelectorLoop, so a handler must never block. Values passed in a ByteBuffer are read-only views that are only valid during the call: copy or decode what you keep.

For efficient parsing, feed each bodyContent(ByteBuffer) chunk directly into a streaming parser. Do not accumulate the entire body in memory first. Both Gonzalez (XML) and jsonparser (JSON) support receive(ByteBuffer) for incremental parsing, and both have writers (XMLWriter and JSONWriter) that can write to a WritableByteChannel.

Example 1: an XML microservice

POST /echo with a small application/xml body is parsed by the Gonzalez push parser through a SAX ContentHandler, and the service answers with XML. The pieces are:

import java.io.IOException;
import java.nio.ByteBuffer;

import org.bluezoo.gonzalez.Parser;
import org.bluezoo.gonzalez.XMLWriter;
import org.bluezoo.gumdrop.Gumdrop;
import org.bluezoo.gumdrop.http.HttpMethod;
import org.bluezoo.gumdrop.http.HttpServer;
import org.bluezoo.gumdrop.http.server.DefaultHttpRequestHandler;
import org.bluezoo.gumdrop.http.server.HttpRequestHandler;
import org.bluezoo.gumdrop.http.server.HttpResponse;
import org.bluezoo.gumdrop.http.server.HttpStreamHandler;
import org.bluezoo.gumdrop.mime.ContentType;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import static java.nio.charset.StandardCharsets.UTF_8;

public final class XmlEchoService {

    /** Remembers the root element and the text of the request. */
    static final class EchoContentHandler extends DefaultHandler {
        private final StringBuilder text = new StringBuilder();
        private String rootElement;

        @Override
        public void startElement(String uri, String localName, String qName,
                                 Attributes atts) throws SAXException {
            if (rootElement == null) {
                rootElement = localName;
            }
            text.setLength(0);
        }

        @Override
        public void characters(char[] ch, int start, int length) {
            text.append(ch, start, length);
        }

        String getRootElement() {
            return rootElement;
        }

        String getText() {
            return text.toString().trim();
        }
    }

    /** Handles POST /echo: the body is parsed chunk by chunk as it arrives. */
    static final class XmlEchoHandler extends DefaultHttpRequestHandler {
        private final Parser parser = new Parser();
        private final EchoContentHandler contentHandler = new EchoContentHandler();
        private final HttpResponse response;
        private HttpMethod method;
        private String path;
        private ContentType contentType;
        private boolean accepted;

        XmlEchoHandler(HttpResponse response) {
            this.response = response;
        }

        @Override
        public void method(HttpMethod method) {
            this.method = method;
        }

        @Override
        public void target(ByteBuffer target) {
            // a read-only view that is only valid during this call
            path = UTF_8.decode(target).toString();
        }

        @Override
        public void contentType(ContentType contentType) {
            this.contentType = contentType;
        }

        @Override
        public void endHeaders() {
            if (!"/echo".equals(path)) {
                sendError(404, "Not Found");
                return;
            }
            if (method != HttpMethod.POST) {
                sendError(405, "Method Not Allowed");
                return;
            }
            if (contentType == null || !contentType.isMimeType("application/xml")) {
                sendError(415, "Unsupported Media Type");
                return;
            }
            parser.setContentHandler(contentHandler);
            try {
                parser.reset();
                accepted = true;
            } catch (SAXException e) {
                sendError(500, e.getMessage());
            }
        }

        @Override
        public void bodyContent(ByteBuffer data) {
            if (!accepted) {
                return;
            }
            try {
                parser.receive(data);
            } catch (SAXException e) {
                accepted = false;
                sendError(400, "Invalid XML: " + e.getMessage());
            }
        }

        @Override
        public void endMessage() {
            if (!accepted) {
                return;
            }
            try {
                parser.close();
                sendXmlResponse();
            } catch (SAXException e) {
                sendError(400, "Invalid XML: " + e.getMessage());
            } catch (IOException e) {
                response.cancel();
            }
        }

        /** Writes the answer straight to the response as the XML is produced. */
        private void sendXmlResponse() throws IOException {
            String root = contentHandler.getRootElement();
            String text = contentHandler.getText();

            response.status(200);
            response.contentType(new ContentType("application", "xml", null));
            XMLWriter xml = new XMLWriter(new BodyChannel(response), 8192);
            xml.writeStartElement(root != null ? root : "response");
            xml.writeDefaultNamespace("urn:example:echo");
            if (!text.isEmpty()) {
                xml.writeCharacters(text);
            }
            xml.writeEndElement();
            xml.close();
            response.endMessage();
        }

        private void sendError(int code, String message) {
            response.status(code);
            response.contentType(new ContentType("text", "plain", null));
            response.bodyContent(ByteBuffer.wrap(message.getBytes(UTF_8)));
            response.endMessage();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 9090;

        HttpServer server = HttpServer.compose()
                .plaintextListener(port)
                .streamHandler(new HttpStreamHandler() {
                    @Override
                    public HttpRequestHandler openStream(HttpResponse response) {
                        return new XmlEchoHandler(response);
                    }
                })
                .server();

        Gumdrop gumdrop = Gumdrop.boot();
        gumdrop.addServer(server);
        System.out.println("XML echo service on port " + port);
        gumdrop.join();
    }

    private XmlEchoService() {
    }

}

There is no router: the handler is bound to every request and answers 404 or 405 for anything but POST /echo. A server with several endpoints chooses a handler in its own endHeaders() once it has seen the method and target, and replays the events it has remembered to the one it chose; see request routing on the HTTP page.

Writing a response as it is produced

Gonzalez's XMLWriter and jsonparser's JSONWriter can write to a WritableByteChannel, buffering up to the size you give them and writing that out when it fills. BodyChannel turns those writes into response body chunks (or, for a client, request body chunks), so the response goes out in chunks as it is written and a large response is never held whole. A response with no Content-Length is sent chunked on HTTP/1.1 and as DATA frames on HTTP/2 and HTTP/3. Always finish with response.endMessage().

import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

import org.bluezoo.gumdrop.http.client.HttpRequest;
import org.bluezoo.gumdrop.http.server.HttpResponse;

/**
 * A {@link WritableByteChannel} whose writes are the body chunks of an HTTP
 * response or request, so that a streaming writer such as Gonzalez's
 * {@code XMLWriter} or jsonparser's {@code JSONWriter} sends its output as it
 * writes, not after building a whole document in memory.
 */
final class BodyChannel implements WritableByteChannel {

    private final HttpResponse response;
    private final HttpRequest request;
    private boolean open = true;

    /** A channel to the body of a response. */
    BodyChannel(HttpResponse response) {
        this.response = response;
        this.request = null;
    }

    /** A channel to the body of a request. */
    BodyChannel(HttpRequest request) {
        this.response = null;
        this.request = request;
    }

    @Override
    public int write(ByteBuffer src) {
        int n = src.remaining();
        if (n == 0) {
            return 0;
        }
        byte[] copy = new byte[n];
        src.get(copy);
        ByteBuffer chunk = ByteBuffer.wrap(copy);
        if (response != null) {
            response.bodyContent(chunk);
        } else {
            request.bodyContent(chunk);
        }
        return n;
    }

    @Override
    public boolean isOpen() {
        return open;
    }

    @Override
    public void close() {
        open = false;
    }

}

Example 2: a service that calls another microservice

This service receives POST /lookup with a JSON body {"query": "..."}, calls a downstream service (also JSON), and returns the downstream result. It shows:

FieldHandler picks one string field out of a JSON object, and is used for the request and for the downstream response. jsonparser delivers a string value in pieces (startStringValue, stringValueContent, endStringValue), so the handler collects the pieces only for the field it wants and skips every other string without holding it. JsonFeed hands each body chunk to the parser: the parser leaves a token that straddles the end of a chunk unconsumed and expects it back at the head of the next buffer, so JsonFeed keeps those bytes and appends the next chunk. LookupHandler parses the request in bodyContent and, in endMessage, starts the outbound call; its inner DownstreamResponse reads the downstream response as it arrives. The handler gets the Gumdrop instance from its constructor, as a client is given the runtime it connects on.

import java.nio.ByteBuffer;

import org.bluezoo.json.JSONException;
import org.bluezoo.json.JSONParser;

/**
 * Passes body chunks to a {@link JSONParser}. The parser leaves a token that
 * straddles the end of a chunk (a key, a literal, half of a multi-byte
 * character) unconsumed and expects it back at the head of the next buffer,
 * so the chunk is appended to those bytes here. The buffer is kept larger
 * than the longest key the parser allows, or the parser would refuse a
 * small chunk that holds an unfinished token.
 */
final class JsonFeed {

    private static final int BUFFER_SIZE = 8192;

    private final JSONParser parser;
    private ByteBuffer pending = ByteBuffer.allocate(BUFFER_SIZE);

    JsonFeed(JSONParser parser) {
        this.parser = parser;
    }

    void receive(ByteBuffer data) throws JSONException {
        int needed = pending.position() + data.remaining();
        if (pending.capacity() < needed) {
            ByteBuffer larger = ByteBuffer.allocate(needed);
            pending.flip();
            larger.put(pending);
            pending = larger;
        }
        pending.put(data);
        pending.flip();
        parser.receive(pending);
        pending.compact();
    }
}
import java.io.IOException;
import java.nio.ByteBuffer;

import org.bluezoo.gumdrop.Endpoint;
import org.bluezoo.gumdrop.Gumdrop;
import org.bluezoo.gumdrop.SecurityInfo;
import org.bluezoo.gumdrop.SelectorLoop;
import org.bluezoo.gumdrop.http.HttpClient;
import org.bluezoo.gumdrop.http.HttpMethod;
import org.bluezoo.gumdrop.http.HttpServer;
import org.bluezoo.gumdrop.http.client.DefaultHttpResponseHandler;
import org.bluezoo.gumdrop.http.client.HttpClientHandler;
import org.bluezoo.gumdrop.http.client.HttpRequest;
import org.bluezoo.gumdrop.http.server.DefaultHttpRequestHandler;
import org.bluezoo.gumdrop.http.server.HttpRequestHandler;
import org.bluezoo.gumdrop.http.server.HttpResponse;
import org.bluezoo.gumdrop.http.server.HttpStreamHandler;
import org.bluezoo.gumdrop.mime.ContentType;
import org.bluezoo.json.JSONDefaultHandler;
import org.bluezoo.json.JSONException;
import org.bluezoo.json.JSONParser;
import org.bluezoo.json.JSONWriter;

import static java.nio.charset.StandardCharsets.UTF_8;

public final class LookupService {

    /** Picks one string field out of a JSON object as it is parsed. */
    static final class FieldHandler extends JSONDefaultHandler {
        private final String wanted;
        private String currentKey;
        private String value;
        private StringBuilder capture;

        FieldHandler(String wanted) {
            this.wanted = wanted;
        }

        @Override
        public void key(String key) throws JSONException {
            currentKey = key;
        }

        @Override
        public void startStringValue() throws JSONException {
            if (wanted.equals(currentKey)) {
                capture = new StringBuilder();
            }
        }

        @Override
        public void stringValueContent(CharSequence content) throws JSONException {
            if (capture != null) {
                capture.append(content);
            }
        }

        @Override
        public void endStringValue() throws JSONException {
            if (capture != null) {
                value = capture.toString();
                capture = null;
            }
        }

        @Override
        public void endObject() throws JSONException {
            currentKey = null;
        }

        String getValue() {
            return value;
        }
    }

    /** Handles POST /lookup by calling the downstream service. */
    static final class LookupHandler extends DefaultHttpRequestHandler {
        private final Gumdrop gumdrop;
        private final String downstreamHost;
        private final int downstreamPort;
        private final HttpResponse response;
        private final JSONParser jsonParser = new JSONParser();
        private final JsonFeed jsonFeed = new JsonFeed(jsonParser);
        private final FieldHandler query = new FieldHandler("query");
        private HttpMethod method;
        private String path;
        private boolean accepted;
        private boolean answered;

        LookupHandler(HttpResponse response, Gumdrop gumdrop, String host, int port) {
            this.response = response;
            this.gumdrop = gumdrop;
            this.downstreamHost = host;
            this.downstreamPort = port;
        }

        @Override
        public void method(HttpMethod method) {
            this.method = method;
        }

        @Override
        public void target(ByteBuffer target) {
            path = UTF_8.decode(target).toString();
        }

        @Override
        public void endHeaders() {
            if (!"/lookup".equals(path)) {
                sendError(404, "Not Found");
            } else if (method != HttpMethod.POST) {
                sendError(405, "Method Not Allowed");
            } else {
                jsonParser.setContentHandler(query);
                jsonParser.reset();
                accepted = true;
            }
        }

        @Override
        public void bodyContent(ByteBuffer data) {
            if (!accepted) {
                return;
            }
            try {
                jsonFeed.receive(data);
            } catch (JSONException e) {
                accepted = false;
                sendError(400, "Invalid JSON: " + e.getMessage());
            }
        }

        @Override
        public void endMessage() {
            if (!accepted) {
                return;
            }
            try {
                jsonParser.close();
            } catch (JSONException e) {
                sendError(400, "Invalid JSON: " + e.getMessage());
                return;
            }
            String text = query.getValue();
            if (text == null || text.isEmpty()) {
                sendError(400, "Missing 'query' field");
                return;
            }
            callDownstream(text);
        }

        private void callDownstream(final String text) {
            // Run the outbound connection on the loop that carries this
            // request: no thread hand-offs, and no extra threads
            SelectorLoop loop = response.getSelectorLoop();
            final HttpClient client = (loop != null)
                    ? new HttpClient(loop, downstreamHost, downstreamPort)
                    : new HttpClient(downstreamHost, downstreamPort);
            // Carry the trace on so the two services appear in one trace
            client.trace(response.getTrace());

            client.connect(gumdrop, new HttpClientHandler() {
                @Override
                public void onConnected(Endpoint endpoint) {
                    HttpRequest request = client.post("/lookup",
                            new DownstreamResponse(client));
                    request.header("Content-Type", "application/json");
                    request.header("Accept", "application/json");
                    try {
                        JSONWriter json = new JSONWriter(new BodyChannel(request), 1024);
                        json.writeStartObject();
                        json.writeKey("query");
                        json.writeString(text);
                        json.writeEndObject();
                        json.close();
                    } catch (IOException e) {
                        request.cancel();
                        sendError(502, "Could not call downstream: " + e.getMessage());
                        return;
                    }
                    request.endMessage();
                }

                @Override
                public void onError(Exception cause) {
                    sendError(502, "Connection failed: " + cause.getMessage());
                }

                @Override
                public void onSecurityEstablished(SecurityInfo info) {
                }

                @Override
                public void onDisconnected() {
                }
            });
        }

        /** Reads the downstream JSON response as it arrives. */
        private final class DownstreamResponse extends DefaultHttpResponseHandler {
            private final HttpClient client;
            private final JSONParser parser = new JSONParser();
            private final JsonFeed feed = new JsonFeed(parser);
            private final FieldHandler result = new FieldHandler("result");
            private int status;
            private boolean failed;

            DownstreamResponse(HttpClient client) {
                this.client = client;
                parser.setContentHandler(result);
            }

            @Override
            public void status(int code) {
                status = code;
            }

            @Override
            public void bodyContent(ByteBuffer data) {
                if (failed || status != 200) {
                    return;
                }
                try {
                    feed.receive(data);
                } catch (JSONException e) {
                    failed = true;
                }
            }

            @Override
            public void endMessage() {
                client.close();
                try {
                    if (!failed && status == 200) {
                        parser.close();
                    }
                } catch (JSONException e) {
                    failed = true;
                }
                if (failed || status != 200) {
                    sendError(502, "Bad response from downstream (" + status + ")");
                } else {
                    sendResult(result.getValue());
                }
            }

            @Override
            public void failed(Exception ex) {
                client.close();
                sendError(502, "Downstream error: " + ex.getMessage());
            }
        }

        private void sendResult(String value) {
            if (answered) {
                return;
            }
            answered = true;
            response.status(200);
            response.contentType(new ContentType("application", "json", null));
            try {
                JSONWriter json = new JSONWriter(new BodyChannel(response), 1024);
                json.writeStartObject();
                json.writeKey("result");
                json.writeString(value != null ? value : "");
                json.writeEndObject();
                json.close();
            } catch (IOException e) {
                response.cancel();
                return;
            }
            response.endMessage();
        }

        private void sendError(int code, String message) {
            if (answered) {
                return;
            }
            answered = true;
            response.status(code);
            response.contentType(new ContentType("text", "plain", null));
            response.bodyContent(ByteBuffer.wrap(message.getBytes(UTF_8)));
            response.endMessage();
        }
    }

    /**
     * Usage: LookupService [port [downstream-host downstream-port]]
     */
    public static void main(String[] args) throws Exception {
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 9092;
        final String host = args.length > 1 ? args[1] : "localhost";
        final int downstreamPort = args.length > 2 ? Integer.parseInt(args[2]) : 9091;

        final Gumdrop gumdrop = Gumdrop.boot();
        HttpServer server = HttpServer.compose()
                .plaintextListener(port)
                .streamHandler(new HttpStreamHandler() {
                    @Override
                    public HttpRequestHandler openStream(HttpResponse response) {
                        return new LookupHandler(response, gumdrop, host, downstreamPort);
                    }
                })
                .server();
        gumdrop.addServer(server);
        System.out.println("lookup service on port " + port + ", downstream "
                + host + ":" + downstreamPort);
        gumdrop.join();
    }

    private LookupService() {
    }

}

SelectorLoop affinity

When creating the HttpClient, pass response.getSelectorLoop() so the outbound connection uses the same worker thread as the inbound request. This avoids context switches and keeps I/O on a single thread. If getSelectorLoop() returns null (for example in a unit test), the client uses Gumdrop's default worker assignment.

Calling services efficiently

The example opens a connection for each request to keep the code short. A real service would reuse connections: give the client a connectionPool(ClientEndpointPool), and use https to the downstream service, which also gives you HTTP/2 multiplexing (and HTTP/3 where the downstream advertises it). The downstream host name is resolved asynchronously by Gumdrop's own resolver, never with a blocking lookup; see DNS: hostname resolution in every Gumdrop client.

Building and running the examples

The three services are XmlEchoService (port 9090), DownstreamService (9091, which answers a lookup with the query reversed) and LookupService (9092, which calls the downstream service):

ant jar examples-compile
CP="build/examples:dist/gumdrop.jar:lib/*"
java -cp "$CP" XmlEchoService 9090 &
java -cp "$CP" DownstreamService 9091 &
java -cp "$CP" LookupService 9092 localhost 9091 &

curl -X POST -H 'Content-Type: application/xml' -d '<echo>Hello</echo>' \
     http://localhost:9090/echo
# <echo xmlns="urn:example:echo">Hello</echo>

curl -X POST -H 'Content-Type: application/json' -d '{"query":"hello"}' \
     http://localhost:9092/lookup
# {"result":"olleh"}

Configuration

Microservices are wired in Java, not XML (see Application composition). The examples listen on cleartext HTTP to stay short. For a real service use secureEndpoint, which serves HTTP/3, HTTP/2 and HTTP/1.1 on one port with one certificate:

HttpServer server = HttpServer.compose()
        .secureEndpoint(443, TlsConfig.pem(Path.of("cert.pem"), Path.of("key.pem")))
        .streamHandler(handler)
        .server();

Downstream configuration is just constructor arguments: there is no property injection framework to learn.

Summary

For more on the HTTP API, see HTTP Server & Client. For the HTTP client in detail, see the HTTP Client section.

Gumdrop