h2
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).
| Function | Does |
|---|---|
client() -> Conn | A 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) -> i64 | A 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() -> ?Reply | The 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() -> ?u64 | A 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.
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
}fieldsare 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 everyfeed, since a WINDOW_UPDATE may let more go. - The server may have up to its
MAX_CONCURRENT_STREAMSstreams open;can_open()says whether another fits now.opentraps when it is false. max_headlimits a response’s headers as HTTP/2 counts them (name, value and 32 per field) andmax_bodyits body: past either, the stream is reset and fails (HeadTooLarge,BodyTooLarge); the connection goes on.- Errors:
H2Errorholds RFC 9113’s codes (Protocol,FlowControl,Refused,Cancel,Compression,Calm,Http11Required, …) andGoAway,Closed,HeadTooLarge,BodyTooLarge,Malformed. A connection error is returned byfeedonce, 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
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.
| Function | Does |
|---|---|
c.open_stream(method, scheme, authority, path, fields, sensitive, end, max_head) -> i64 | A new stream; end true sends no request body |
c.send_data(id, data, end) -> i64 | Request body bytes: how many were taken |
c.can_send(id) -> i64 | How 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),Datapieces,Trailerswhen the server sent them, thenEnd; a trailers-only answer (an error status in the head of a stream that ends at once) isResponsethenEnd.Resetends a stream any other way: the server’s RST_STREAM with its code (Cancelwhen it gave none),Closedwhen the transport ended,GoAwaywhen the server closed the connection without processing it (send it again elsewhere),Malformed,HeadTooLarge. - The response body is not held: each
Datais 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_headlimits the head as onopen; there is no body limit. - With
endfalse, send the body withsend_dataand end the stream with its last piece (orsend_data(id, "", true));can_sendsays how much fits now; the rest goes after you sendoutput()and feed the server’s window updates. openandopen_streamstreams share a connection;next_replygives only the former,next_eventonly the latter.ping(data)sends a PING with your 8 bytes; the server’s ACK comes back fromnext_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
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.
| Function | Does |
|---|---|
server(max_streams, max_head) -> Conn | A connection with our SETTINGS and window update queued: send them first |
c.next_event() -> ?Event | The 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) -> i64 | Response body bytes: how many were taken |
c.send_trailers(id, headers) | Trailers after the body: HEADERS that end the stream |
c.can_send(id) -> i64 | How many bytes send_data would take now |
c.reset(id, code) | Resets the stream (RST_STREAM) |
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 (schemeandpathare empty forCONNECT), the other headers in order with lowercase names, severalcookieheaders joined into one. Withhas_bodyfalse the client ended the stream with its head: noDataand noEndfollow. OtherwiseDatapieces come as the client sends them (each at most a frame, 16 KiB), thenEnd; 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
Dataevents, 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 withPROTOCOL_ERROR; if you have seen itsHeadyou get aReset. respondsends:status(200 to 999) and the headers you give, which must have lowercase names and none of HTTP/1.1’s connection headers.endends the stream there: a 204, a 304, the answer to aHEAD.send_datasends within the client’s windows and a bounded output buffer, and returns how much it took; withendthe stream ends once the last byte is taken (send_data(id, "", true)always ends it). Sendoutput(), feed what the client sends (its window updates), and offer the rest again;can_send(id)says whether there is room.send_trailersends the stream with trailing headers after the body (gRPC’sgrpc-status): lowercase names, no pseudo-headers. For a trailers-only answer, give the trailers torespondwithendtrue.- 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_streamsstreams at once are refused (REFUSED_STREAM: the client sends them again), and a request head overmax_headoctets (name, value and 32 per field) is reset withENHANCE_YOUR_CALM; neither is seen as an event. Resetends a stream: the client reset it (codeis its reason;Cancelwhen it gave none), it broke the protocol on it, or the connection failed (aResetfor every open stream) or ended (end_of_input:Closed).respondandsend_dataon a stream that is gone are accepted and dropped;can_sendsays 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 whenactive()is 0.goodbye()sends ours with the last stream taken; streams the client opens after it are ignored. respond,send_data,can_sendandresettrap on a stream id the client never opened and on a client connection;respondtraps on a stream already answered,send_databeforerespondand 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: