The Limen Book Playground limen-lang.org
Chapter 15

Web Services

Chapter 14 served a few requests with a handler that matched on the method and path. This chapter builds from there to a service you could put on a network: routes with ids in them, a JSON API with proper errors, handlers wrapped in other handlers, tests that need no socket, streamed responses, HTTP/2, and the limits a server needs when anyone can reach it.

One idea runs through all of it. A handler is a plain function from a request to a response. It holds the capabilities its closure captured and nothing else, so you can read from its code, and from limen caps, what any request could make it do.

Routes

Matching on (r.method, r.path) stops working once a path has an id in it. http.route takes a list of routes, each a pattern and a handler, and answers with the first that matches:

use http

fn api() -> List[http.Route] {
    [
        http.on("GET /hello/:name", |r, p| http.text(200, "hello, {p.get("name") ?? ""}")),
        http.on("GET /items/:id", |r, p| match p.int("id") {
            Some(id) => http.text(200, "item {id}"),
            None => http.text(404, "no item `{p.get("id") ?? ""}`"),
        }),
        http.on("DELETE /items/:id", |r, p| http.text(204, "")),
    ]
}

fn main(root: Root) {
    let routes = api()
    for (method, path) in [
        ("GET", "/hello/caf%C3%A9"),
        ("GET", "/items/7?full=1"),
        ("GET", "/items/seven"),
        ("PUT", "/items/7"),
        ("GET", "/orders"),
    ] {
        let req = http.Request { method, path, version: "HTTP/1.1", headers: [], body: "" }
        let r = http.route(req, routes)
        let allow = match r.header("allow") {
            Some(a) => " (Allow: {a})",
            None => "",
        }
        root.stdout.print("{method} {path} -> {r.status} {r.body.trim()}{allow}")
    }
}
Listing 15-1: Routes with captures examples/ch15-01-routes/main.lmn
$ limen run main.lmn
GET /hello/caf%C3%A9 -> 200 hello, café
GET /items/7?full=1 -> 200 item 7
GET /items/seven -> 404 no item `seven`
PUT /items/7 -> 405 method not allowed (Allow: GET, DELETE, HEAD)
GET /orders -> 404 not found

A pattern is a method and a path, or a path alone for any method. :name matches one segment of the path, and *name, at the end, matches the rest. The handler gets the request and the captured values, decoded: p.get("name") is an Option[Str], and p.int("id") is None when the segment isn't a number. The query string doesn't take part in matching, and a GET route answers HEAD too.

When nothing matches, route answers 404. When the path matches but the method doesn't, it answers 405 and lists the methods that would work, which is what HTTP asks for. http.on checks the pattern when the routes are made, so a typo panics there rather than on the first request.

The listing never opens a socket. http.route(r, routes) is itself a handler, given a request, so serving the routes is one line:

Err(http.serve_forever(l, |r| http.route(r, routes)))

A JSON API

Most services take JSON and answer JSON. json.decode reads a request body straight into a struct, as chapter 14 showed, and its error says what was wrong in words a client can act on. Here is a small API over notes kept in memory, in a module of its own:

// A small JSON API over notes kept in memory.
use http
use json

pub struct Note {
    id: Int,
    text: Str,
    tags: List[Str],
}

// What a client sends: the server picks the id.
struct NewNote {
    text: Str,
    tags: List[Str],
}

struct Problem {
    error: Str,
}

fn problem(status: Int, message: Str) -> http.Response {
    http.json(status, json.encode(Problem { error: message }))
}

fn added(notes: Map[Int, Note], new: NewNote) -> Map[Int, Note] {
    let id = notes.len() + 1
    let mut m = notes
    m[id] = Note { id, text: new.text.trim(), tags: new.tags }
    m
}

fn create(notes: Shared[Map[Int, Note]], body: Str) -> http.Response {
    let new: NewNote = match json.decode(body) {
        Ok(n) => n,
        Err(e) => { return problem(400, e) },
    }
    if new.text.trim().is_empty() {
        return problem(422, "`text` is empty")
    }
    let now = notes.update(|m| added(m, new))
    http.json(201, json.encode(now[now.len()]))
}

fn show(notes: Shared[Map[Int, Note]], p: http.Params) -> http.Response {
    match p.int("id").flat_map(|id| notes.get().get(id)) {
        Some(n) => http.json(200, json.encode(n)),
        None => problem(404, "no note `{p.get("id") ?? ""}`"),
    }
}

pub fn api(notes: Shared[Map[Int, Note]]) -> List[http.Route] {
    [
        http.on("POST /notes", |r, p| create(notes, r.body)),
        http.on("GET /notes/:id", |r, p| show(notes, p)),
    ]
Listing 15-2: A JSON API over notes examples/ch15-02-json-api/notes.lmn, lines 1 to 55

NewNote is what a client may send, and Note is what the API answers: a client can't choose its own id, because the struct it's decoded into has no such field. Members the struct doesn't have are ignored, so a client that sends more than you need still works.

Each failure gets the status that says whose fault it was. A body that isn't JSON, or lacks a field, is 400, with json.decode's message as the error. A body that decodes but makes no sense, an empty text, is 422. An id that isn't there is 404. problem writes every error in the same shape, {"error": "..."}, so a client has one thing to read. http.json sets the Content-Type header to application/json.

The notes live in a Shared[Map[Int, Note]] from chapter 13, because the server answers each connection in a task of its own and every task must see the same notes. notes.update adds a note in one step, so two requests at once can't both take id 2.

The program serves the API and calls it over the loopback interface:

use http
use notes

fn call(net: Net, base: Str, method: Str, path: Str, body: Str) -> Str {
    match http.request(net, method, base + path, [], body) {
        Ok(r) => "{method} {path} -> {r.status} {r.body}",
        Err(e) => "{method} {path} -> {e}",
    }
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let base = "http://127.0.0.1:{l.port()}"
    let net = root.net.only("127.0.0.1")
    let routes = notes.api(shared(map()))
    let results = group g {
        g.go(|| {
            let _ = http.serve(l, 6, |r| http.route(r, routes))
            []
        })
        g.go(|| [
            call(net, base, "POST", "/notes", `{"text": "buy milk", "tags": ["home"]}`),
            call(net, base, "POST", "/notes", `{"text": "buy milk"}`),
            call(net, base, "POST", "/notes", `{"text": " ", "tags": []}`),
            call(net, base, "POST", "/notes", "buy milk"),
            call(net, base, "GET", "/notes/1", ""),
            call(net, base, "GET", "/notes/2", ""),
        ])
    }
    for line in results[1] {
        root.stdout.print(line)
    }
    Ok(())
}
Listing 15-3: Serving the notes, and a client examples/ch15-02-json-api/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
POST /notes -> 201 {"id":1,"text":"buy milk","tags":["home"]}
POST /notes -> 400 {"error":"`tags` is missing"}
POST /notes -> 422 {"error":"`text` is empty"}
POST /notes -> 400 {"error":"expected a value at byte 0"}
GET /notes/1 -> 200 {"id":1,"text":"buy milk","tags":["home"]}
GET /notes/2 -> 404 {"error":"no note `2`"}

http.serve(l, 6, ...) serves six connections and stops, which is what a listing wants; the client opens one connection per request, so that's six requests. A real service calls serve_forever, which comes at the end of this chapter.

Testing handlers

A handler is a function, so a test can call it. Build an http.Request by hand, pass it to http.route, and look at the response: no socket, no port, no grant. The notes module ends with its tests:

// ---------- tests ----------

fn send(routes: List[http.Route], method: Str, path: Str, body: Str) -> http.Response {
    http.route(http.Request { method, path, version: "HTTP/1.1", headers: [], body }, routes)
}

test "a note is created, then read back" {
    let routes = api(shared(map()))
    let made = send(routes, "POST", "/notes", `{"text": " buy milk ", "tags": []}`)
    assert_eq(made.status, 201)
    assert_eq(made.header("content-type"), Some("application/json"))
    let got = send(routes, "GET", "/notes/1", "")
    assert_eq(json.decode(got.body), Ok(Note { id: 1, text: "buy milk", tags: [] }))
}

test "refused" for (body, status) in [
    ("buy milk", 400),
    (`{"text": "buy milk"}`, 400),
    (`{"text": "", "tags": []}`, 422),
] {
    assert_eq(send(api(shared(map())), "POST", "/notes", body).status, status)
}
Listing 15-4: Tests that call the routes directly examples/ch15-02-json-api/notes.lmn, lines 58 to 79
$ limen test notes.lmn
ok    a note is created, then read back (1ms)
ok    refused ("buy milk", 400) (0ms)
ok    refused (`{"text": "buy milk"}`, 400) (0ms)
ok    refused (`{"text": "", "tags": []}`, 422) (0ms)
4 tests, 0 failed (1ms)

Each test makes its own shared(map()), so it starts from no notes whatever the other tests did. The same approach scales to a whole API: in the compiler's repository, examples/todo_api.lmn tests five routes over SQLite this way, against a fresh in-memory database per test, and the final project in chapter 19 does the same.

Tests get no root (chapter 11), and these don't need one. That's not a trick of the test: the routes hold the notes and nothing else, so there's nothing for a test to fake.

Wrapping handlers

Logging, checking a token, timing a request: these apply to every route, and you don't want them written into each handler. Since a handler is a function, a function that takes a handler and returns a new one adds the behaviour around it:

use hash
use http

type Handler = fn(http.Request) -> http.Response

// A handler that passes the request on, then logs what was answered.
fn logged(log: fn(Str), next: Handler) -> Handler {
    |r| {
        let resp = next(r)
        log("{r.method} {r.path} {resp.status}")
        resp
    }
}

// A handler that answers 401 unless the request carries the token.
fn with_token(token: Str, next: Handler) -> Handler {
    let want = "Bearer {token}".to_bytes()
    |r| {
        let got = (r.header("authorization") ?? "").to_bytes()
        if hash.equal(got, want) { next(r) } else { http.text(401, "who are you?") }
    }
}

fn hello(r: http.Request) -> http.Response {
    http.text(200, "hello from {r.path}")
}

fn request(path: Str, token: Str) -> http.Request {
    let headers = if token == "" { [] } else { [http.Header { name: "Authorization", value: "Bearer {token}" }] }
    http.Request { method: "GET", path, version: "HTTP/1.1", headers, body: "" }
}

fn main(root: Root) {
    let token = root.env.get("API_TOKEN") ?? panic("API_TOKEN is not set")
    let app = logged(|line| root.stderr.print(line), with_token(token, hello))
    for (path, sent) in [("/a", token), ("/b", ""), ("/c", "guess")] {
        root.stdout.print(app(request(path, sent)).body)
    }
}
Listing 15-5: A handler wrapped for logging and a token examples/ch15-03-wrappers/main.lmn
$ API_TOKEN=s3cret limen run main.lmn --grant env=API_TOKEN
GET /a 200
hello from /a
GET /b 401
who are you?
GET /c 401
who are you?

logged and with_token each return a closure that calls next and does its own work before or after. They stack in the order you write them: logged(..., with_token(..., hello)) logs every request, the refused ones included, because logged is on the outside. with_token compares with hash.equal, which takes the same time however many bytes match, so the comparison doesn't tell an attacker how close a guess was. type Handler is only a name for the function type, to keep the signatures short.

Where does the token come from? The program reads it from the environment, with the env grant, and hands it to with_token as text. The wrapper never sees the environment, and the logger never sees the token. limen caps says as much:

$ limen caps main.lmn
logged      pure itself, runs callbacks
with_token  pure itself, runs callbacks
hello       pure
request     pure
main        Root

logged and with_token hold no capability: they're pure itself, runs callbacks, so what they can do is what the handler and the logging function they're given can do. hello is pure. Only main holds Root, and it decides that the logging function writes to standard error. A wrapper you take from a package works the same way: its signature, fn(fn(Str), Handler) -> Handler, is all the authority it gets.

Streaming

A handler that returns an http.Response builds the whole body before anything is sent. For a body that's large, or that arrives over time, such as a log being followed or events as they happen, a handler can write its response in pieces instead. http.serve_stream serves a connection with a handler that also gets the Conn:

use http

// Writes the response a line at a time, as the lines are ready.
fn countdown(r: http.Request, c: Conn) -> Result[(), IoError] {
    http.write_head(c, 200, [http.Header { name: "Content-Type", value: "text/plain" }])?
    for n in [5, 4, 3, 2, 1] {
        http.write_chunk(c, "{n}\n")?
    }
    http.write_chunk(c, "liftoff\n")?
    http.end_body(c)
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let url = "http://127.0.0.1:{l.port()}/countdown"
    let net = root.net.only("127.0.0.1")
    let out = root.stdout
    let _ = group g {
        g.go(|| {
            match l.accept() {
                Ok(c) => {
                    let _ = http.serve_stream(c, countdown)
                },
                Err(_) => (),
            }
        })
        g.go(|| {
            let r = http.request_lines(net, "GET", url, [], "", |line| {
                out.print("got {line}")
                line != "3"
            })
            match r {
                Ok(resp) => out.print("status {resp.status}, stopped early"),
                Err(e) => out.print("{e}"),
            }
        })
    }
    Ok(())
}
Listing 15-6: A response written in pieces, read a line at a time examples/ch15-04-stream/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
got 5
got 4
got 3
status 200, stopped early

http.write_head sends the status and headers with Transfer-Encoding: chunked, write_chunk sends a piece as soon as it's called, and end_body ends the response. A handler that returns an error, or panics, closes the connection, since half a response can't be taken back.

On the client side, http.request_lines passes each line of the body to a function as soon as it has arrived. The function returns true to go on and false to stop, and stopping closes the connection; here the client stops at 3, and the server's next write fails, which ends its handler. The response comes back with its status and an empty body, since the lines went to the function. A status outside 2xx comes back with its whole body, and the function isn't called. The kube module's watch reads a Kubernetes watch this way.

websocket.accept (chapter 14) takes the request and connection a serve_stream handler gets, for traffic that goes both ways.

HTTPS

Serving HTTPS changes one line. Read the certificate and key with the capability that holds them, and listen with root.listen.on_tls(address, cert, key) instead of on. Everything else in this chapter, serve, route, serve_stream and the time limits, works unchanged on the listener it returns. Chapter 14's TLS section has a whole program.

When the service runs behind a load balancer that ends TLS for it, on is the right call, and the certificate stays with the load balancer.

HTTP/2

HTTP/1.1 sends one request at a time on a connection. HTTP/2 sends many at once, each on a stream of its own, with headers compressed. The http2 module has both a client and a server:

use http2

fn hello(r: http2.Request) -> http2.Response {
    http2.text(200, "{r.method} {r.path} over HTTP/2")
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let address = "127.0.0.1:{l.port()}"
    let net = root.net.only("127.0.0.1")
    let results = group g {
        // one connection, served until the client closes it
        g.go(|| {
            match l.accept() {
                Ok(c) => {
                    let _ = http2.serve_conn(c, hello)
                },
                Err(_) => (),
            }
            []
        })
        g.go(|| {
            let c = match http2.connect_plain(net, address) {
                Ok(c) => c,
                Err(e) => { return ["{e}"] },
            }
            // three requests at once, each a stream on the one connection
            let answers = group h {
                for path in ["/a", "/b", "/c"] {
                    h.go(|| match c.get(path) {
                        Ok(r) => "{r.status} {r.body.to_str()}",
                        Err(e) => "{e}",
                    })
                }
            }
            c.close()
            answers
        })
    }
    for line in results[1] {
        root.stdout.print(line)
    }
    Ok(())
}
Listing 15-7: Three requests at once on one HTTP/2 connection examples/ch15-05-http2/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
200 GET /a over HTTP/2
200 GET /b over HTTP/2
200 GET /c over HTTP/2

http2.connect_plain(net, address) speaks HTTP/2 over plain TCP from the first byte, which servers inside a cluster and tests use. Across the internet, http2.connect(net, address) connects over TLS and agrees on HTTP/2 with the server as part of the handshake. The three tasks share one client, and their requests travel on one connection, interleaved. A request's body and the response's body are Bytes, hence r.body.to_str().

On the server, http2.serve_conn(c, handler) serves one connection until the client closes it, with a handler from http2.Request to http2.Response, each request in a task of its own. http2.serve_forever(l, handler) does it for every connection. For TLS, the listener must offer HTTP/2 to clients, root.listen.offering(["h2"])?.on_tls(address, cert, key)?. A handler that reads its request and writes its response as they go uses serve_calls, whose Call has read, send_head, send and finish; the client's counterpart is c.open.

gRPC is HTTP/2 underneath: a POST on a stream, a framed protobuf message as the body, and the status in trailers, the headers sent after the body. Chapter 17 builds on this module.

Running a service

http.serve_forever waits as long as a client likes. A client that opens a connection and sends one byte every few seconds holds a task for as long as it keeps going, and a few thousand of them hold a server. For a server that anyone can reach, use http.server(clock), which takes a Clock and gives back a Server with limits on each part of a connection:

use http

fn app(r: http.Request) -> http.Response {
    match r.path {
        "/boom" => panic("the handler has a bug"),
        _ => http.text(200, "fine"),
    }
}

// A client that starts a request and never finishes its headers.
fn slow(net: Net, address: Str) -> Result[Str, IoError] {
    let c = net.connect(address)?
    c.write("GET / HTTP/1.1\r\nHost: x\r\n")?
    let answer = c.read()?
    c.close()
    Ok(answer.lines()[0])
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let address = "127.0.0.1:{l.port()}"
    let net = root.net.only("127.0.0.1")
    let mut s = http.server(root.clock)
    s.head_ms = 200
    let results = group g {
        g.go(|| {
            let _ = s.serve(l, 3, app)
            []
        })
        g.go(|| {
            let mut lines: List[Str] = []
            for path in ["/boom", "/after"] {
                match http.get(net, "http://{address}{path}") {
                    Ok(r) => lines.push("GET {path}: {r.status} {r.body.trim()}"),
                    Err(e) => lines.push("GET {path}: {e}"),
                }
            }
            match slow(net, address) {
                Ok(line) => lines.push("slow client: {line}"),
                Err(e) => lines.push("slow client: {e}"),
            }
            lines
        })
    }
    for line in results[1] {
        root.stdout.print(line)
    }
    Ok(())
}
Listing 15-8: A server with limits, and a handler that panics examples/ch15-06-server/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
http: GET /boom: handler panicked: the handler has a bug
GET /boom: 500 internal error
GET /after: 200 fine
slow client: HTTP/1.1 408 Request Timeout

The defaults are 10 seconds for a request's line and headers, 30 for its body, 30 for writing the response, 60 for a kept-alive connection to send its next request, and 10 minutes for the whole connection. Server is a struct, so changing a limit is setting a field on a let mut s, as the listing does to give up on headers after 200 ms, and 0 turns one off. A request that runs out of time gets 408 and the connection is closed; a connection that's idle, or that never sent anything, is just closed. serve, serve_conn, serve_stream and serve_forever are methods on Server. http2.server(clock) is the same for HTTP/2, with its own limits.

The limits come from the clock, so a test can run them on virtual time, as chapter 11 did with timeouts. Underneath, a Conn has read_within(clock, ms) and write_within(clock, ms, s), which fail with "timed out after N ms" when the time runs out, for your own protocols.

A handler that panics doesn't take the server down. The server answers that request with 500 and goes on, as GET /after shows, and writes one line to standard error with the method, the path and the panic's message. To log it somewhere else, set s.log_panics = false and wrap the handler in one that catches the panic with catch (chapter 8), logs it your way, and answers 500 itself. A panic in one request never reaches another, since each connection is a task of its own and requests share only what their closures captured.

A real service then looks like this:

let s = http.server(root.clock)
let handler = logged(log, |r| http.route(r, routes))
Err(s.serve_forever(l, handler))

serve_forever returns only when the listener fails or is closed, by another task that holds it, and then returns that error. Each connection runs as a task that's freed when it ends, so a server's memory stays flat however long it runs. A program that wants to stop cleanly, at the end of a test or on a command, closes the listener: serve_forever stops accepting, waits for the connections it's serving, and returns.

Summary

A handler is a function from a request to a response, and that one fact does most of the work. http.route picks a handler by method and path, with captures, 404 and 405. json.decode and json.encode read and write bodies as structs, and each error gets the status that names whose fault it was. Wrappers add logging and tokens around any handler, and tests call handlers with no socket at all. serve_stream and request_lines move bodies in pieces, on_tls adds HTTPS, and http2 serves and sends many requests on one connection. http.server(clock) puts time limits on every connection, and through all of it a handler holds what its closure captured and nothing more.

Next: running services where they usually run, on Kubernetes.