h2

tape
import h2 from "h2";
import hpack from "hpack";

var c: h2.Conn = h2.client();
defer c.free();
let none: [0]hpack.Header = [];
let id: i64 = c.open("GET", "https", "example.com", "/", none[..], never, "", 65536, 1 << 20);
send(c.output());                     // your transport: a TLS stream that negotiated "h2"
c.advance_output(c.output().len);
while (true) {
    let n: i64 = receive(buf[..]);    // what the server sent
    if (n == 0) { c.end_of_input(); break; }
    c.feed(buf[0..n]) or { break; };
    send(c.output());                 // answers, window updates
    c.advance_output(c.output().len);
    let r: ?h2.Reply = c.next_reply();
    if (r != null) { io.println("{r!.status}: {r!.body.len} bytes"); break; }
}

h2 is HTTP/2 (RFC 9113) for a client and for a server (below), without the I/O: you feed it what the peer sent, send what it queues, and take finished streams. To make requests, use http’s Client, which runs h2 over every https connection whose server picks HTTP/2. h2 is for code that brings its own transport: a TLS stream whose ALPN chose h2, or a plain TCP connection where both sides know it is HTTP/2 (a gRPC server behind a proxy).

FunctionDoes
client() -> ConnA connection with its preface, SETTINGS and window update queued: send them first
c.open(method, scheme, authority, path, fields, sensitive, body, max_head, max_body) -> i64A request as a new stream; its id
c.feed(data)What the server sent: every whole frame is processed
c.output(), c.advance_output(n)What to send, and how much was sent
c.next_reply() -> ?ReplyThe next finished stream
c.end_of_input()The transport ended: open streams fail
c.can_open(), c.active(), c.finished(), c.error()Whether a stream can open now; streams open; whether none ever can again; the connection’s error
c.goodbye()GOAWAY with no error, before you close the transport
c.ping(data), c.next_pong() -> ?u64A PING with 8 bytes of your choosing; the ACKs as they come back (either side)
c.free()Releases it

Streams whose response you want as it comes, or whose request body you send over time (a gRPC stream): §Streams on the client, below.

tape
pub struct Reply {
    id: i64;
    status: i64;
    headers: hpack.Vec_Header;     // without the pseudo-headers, in order
    body: string;
    err: ?H2Error;                 // when the stream failed
    retry: bool;                   // the server did not process it: send it again elsewhere
}
  • fields are the request’s headers after the pseudo-headers, with lowercase names and none of HTTP/1.1’s connection headers (Connection, Keep-Alive, Transfer-Encoding, Upgrade, …). sensitive(name) says which are never indexed by compression (credentials).
  • The body is copied and sent as the server’s windows allow; send output() after every feed, since a WINDOW_UPDATE may let more go.
  • The server may have up to its MAX_CONCURRENT_STREAMS streams open; can_open() says whether another fits now. open traps when it is false.
  • max_head limits a response’s headers as HTTP/2 counts them (name, value and 32 per field) and max_body its body: past either, the stream is reset and fails (HeadTooLarge, BodyTooLarge); the connection goes on.
  • Errors: H2Error holds RFC 9113’s codes (Protocol, FlowControl, Refused, Cancel, Compression, Calm, Http11Required, …) and GoAway, Closed, HeadTooLarge, BodyTooLarge, Malformed. A connection error is returned by feed once, with every open stream failed; a stream error fails only that stream’s reply.

Not covered: server push (refused), priorities, the HTTP/1.1 Upgrade: h2c path.

Streams on the client

tape
let fs: [2]hpack.Header = [hpack.Header { name: "content-type"; value: "application/grpc"; },
                           hpack.Header { name: "te"; value: "trailers"; }];
let id: i64 = c.open_stream("POST", "http", "example.com", "/pkg.Svc/Call", fs[..], never, false, 65536);
c.send_data(id, request_bytes, true);     // the request body, within the windows
...
match (c.next_event()!) {
    h2.Event.Response { id; status; headers } => { /* the final head */ }
    h2.Event.Data { id; data } => { /* a piece of the response body */ }
    h2.Event.Trailers { id; headers } => { /* grpc-status is here */ }
    h2.Event.End { id } => { /* done */ }
    h2.Event.Reset { id; code } => { /* ended early: code says why */ }
    _ => {}
}

open_stream opens a stream like open, but its response comes through next_event as it happens instead of as one Reply, and its request body goes out through send_data, exactly as a response body does on the server side. Use it for a response you cannot or do not want to hold whole, for a request body that is produced over time, and for a bidirectional stream both sides write to for as long as they like.

FunctionDoes
c.open_stream(method, scheme, authority, path, fields, sensitive, end, max_head) -> i64A new stream; end true sends no request body
c.send_data(id, data, end) -> i64Request body bytes: how many were taken
c.can_send(id) -> i64How many bytes send_data would take now
c.reset(id, code)Resets the stream (RST_STREAM)
  • The events on a client connection are Response (the final head, 1xx skipped: the status and the headers with lowercase names), Data pieces, Trailers when the server sent them, then End; a trailers-only answer (an error status in the head of a stream that ends at once) is Response then End. Reset ends a stream any other way: the server’s RST_STREAM with its code (Cancel when it gave none), Closed when the transport ended, GoAway when the server closed the connection without processing it (send it again elsewhere), Malformed, HeadTooLarge.
  • The response body is not held: each Data is at most a frame, and the server’s windows are given back as you take the events, so a body of any size passes through. max_head limits the head as on open; there is no body limit.
  • With end false, send the body with send_data and end the stream with its last piece (or send_data(id, "", true)); can_send says how much fits now; the rest goes after you send output() and feed the server’s window updates.
  • open and open_stream streams share a connection; next_reply gives only the former, next_event only the latter.
  • ping(data) sends a PING with your 8 bytes; the server’s ACK comes back from next_pong() with the same bytes, in order. The timeout is yours: gRPC keepalive sends one every 15 s and gives up after 10 s. The server side can ping too.

The server side

tape
var c: h2.Conn = h2.server(100, 65536);
defer c.free();
send(c.output());                     // our SETTINGS first
c.advance_output(c.output().len);
while (true) {
    let n: i64 = receive(buf[..]);    // what the client sent
    if (n == 0) { c.end_of_input(); break; }
    c.feed(buf[0..n]) or { send(c.output()); break; };
    while (true) {
        let e: ?h2.Event = c.next_event();
        if (e == null) { break; }
        match (e!) {
            h2.Event.Head { id; .. } => {
                let fs: [1]hpack.Header = [hpack.Header { name: "content-type"; value: "text/plain"; }];
                c.respond(id, 200, fs[..], false);
                c.send_data(id, "hello", true);      // small: fits at once
            }
            h2.Event.Data { id; data } => { /* a piece of the request body */ }
            h2.Event.End { id } => { /* the request body ended */ }
            h2.Event.Reset { id; code } => { /* the stream is gone */ }
            _ => {}                                  // Response and Trailers: client streams only
        }
    }
    send(c.output());                 // answers, window updates, responses
    c.advance_output(c.output().len);
    if (c.finished() && c.active() == 0) { break; }
}

server(max_streams, max_head) makes the same Conn with the roles swapped, for a program that accepted a TLS connection whose ALPN chose h2: it expects the client’s preface, takes the streams the client opens, and tells you what happens on them as events. You feed it and send its output exactly as on the client side; feed, output, advance_output, end_of_input, error, finished, active, goodbye and free mean the same.

FunctionDoes
server(max_streams, max_head) -> ConnA connection with our SETTINGS and window update queued: send them first
c.next_event() -> ?EventThe next thing that happened, in order; several may come from one feed
c.respond(id, status, headers, end)The response’s head; end ends the stream without a body
c.send_data(id, data, end) -> i64Response body bytes: how many were taken
c.send_trailers(id, headers)Trailers after the body: HEADERS that end the stream
c.can_send(id) -> i64How many bytes send_data would take now
c.reset(id, code)Resets the stream (RST_STREAM)
tape
pub tagged Event {
    Head { id: i64; method: []const u8; scheme: []const u8; authority: []const u8; path: []const u8;
           headers: *const hpack.Vec_Header; has_body: bool; }
    Data { id: i64; data: []const u8; }     // a piece of the request body, in order
    End { id: i64; }                        // the request body ended
    Reset { id: i64; code: H2Error; }       // the stream ended early
    Response { id: i64; status: i64; headers: *const hpack.Vec_Header; }   // client streams only
    Trailers { id: i64; headers: *const hpack.Vec_Header; }               // client streams only
}
  • An event’s views are valid until the next next_event: copy what you keep.
  • Head: the pseudo-headers split out (scheme and path are empty for CONNECT), the other headers in order with lowercase names, several cookie headers joined into one. With has_body false the client ended the stream with its head: no Data and no End follow. Otherwise Data pieces come as the client sends them (each at most a frame, 16 KiB), then End; request trailers are dropped.
  • Request bodies stream: the client may send only what its windows allow (1 MiB per stream), and the windows are given back as you take Data events, so a body of any size passes through without being held whole.
  • A malformed request (pseudo-headers missing, repeated or after the others, an uppercase name, HTTP/1.1’s connection headers, a body that is not its content-length) is reset with PROTOCOL_ERROR; if you have seen its Head you get a Reset.
  • respond sends :status (200 to 999) and the headers you give, which must have lowercase names and none of HTTP/1.1’s connection headers. end ends the stream there: a 204, a 304, the answer to a HEAD.
  • send_data sends within the client’s windows and a bounded output buffer, and returns how much it took; with end the stream ends once the last byte is taken (send_data(id, "", true) always ends it). Send output(), feed what the client sends (its window updates), and offer the rest again; can_send(id) says whether there is room.
  • send_trailers ends the stream with trailing headers after the body (gRPC’s grpc-status): lowercase names, no pseudo-headers. For a trailers-only answer, give the trailers to respond with end true.
  • Answering before the request body has fully arrived is fine: once the response is complete the stream is reset with NO_ERROR, which tells the client to stop sending, and the rest of the body is dropped.
  • More than max_streams streams at once are refused (REFUSED_STREAM: the client sends them again), and a request head over max_head octets (name, value and 32 per field) is reset with ENHANCE_YOUR_CALM; neither is seen as an event.
  • Reset ends a stream: the client reset it (code is its reason; Cancel when it gave none), it broke the protocol on it, or the connection failed (a Reset for every open stream) or ended (end_of_input: Closed). respond and send_data on a stream that is gone are accepted and dropped; can_send says it takes anything.
  • PINGs are answered and PRIORITY frames ignored. A GOAWAY from the client makes finished() true while the open streams go on: close when active() is 0. goodbye() sends ours with the last stream taken; streams the client opens after it are ignored.
  • respond, send_data, can_send and reset trap on a stream id the client never opened and on a client connection; respond traps on a stream already answered, send_data before respond and after the stream’s end.

Not covered on the server side: server push, priorities, the Upgrade: h2c path, request trailers (dropped), informational (1xx) responses.

Last modified: