Repository navigation
Design Streaming
Status: implemented, on HTTP/1.1 (Phase 7a) and HTTP/2 (7b). User guide: Streaming and SSE.
A response body written over time, after the handler returns, without holding the worker and without allocating per write. Two ways for bytes to arrive:
- push: timers on the stream, and sends or publishes from any thread (live events, tokens);
-
pull:
on_drain, called when everything written so far is out (a large generated body that must follow the client's pace).
Server-Sent Events are a stream with text/event-stream framing helpers on top; nothing in the engine is SSE-specific except the heartbeat.
It follows WebSocket, which already solved "a connection owned by callbacks after the handler returns":
| WebSocket | Stream |
|---|---|
c.ws_upgrade(h) writes the 101; finish sees x.ws and calls ws_open
|
c.stream/c.sse write the head; finish sees x.st and calls st_open
|
one http1.Ws per worker, lent per callback (ws_lend / ws_take) |
one http1.Stream per worker (st_lend / st_take) |
Conn.ws, ws_data, subs
|
Conn.st, st_data, the same subs
|
hub posts with op text/binary |
hub posts with op = stream_data, plus the target stream |
The Stream a callback holds has out set to the connection's write buffer. A write appends to it, framed as
one chunk on HTTP/1.1 and raw on HTTP/1.0, so nothing is copied twice and nothing is allocated. st_take takes
the buffer back. It then carries out what the callback queued (subscriptions, publishes, timers) and finishes
the stream if it ended.
Stream.after(ms, cb, arg) queues a StreamTimer. st_take pushes it on the worker's existing timer heap,
the one deferred responses use. The entry is the usual (fd, generation) plus the connection's stream serial and
cb/arg. The serial counts streams per connection: after one stream ends on a keep-alive connection and
another starts, a timer left from the first does not reach the second. Loop.fire tells a tick from a
deferred response by tick != 0.
tick is the callback's address kept as a u64. With a pointer field, every Timer in scope (the one
pop returns, the one fire holds) became a V -prod GC scope pin, which gcpin_check refuses. A function
is code; the GC never needs to see it.
Loop.flush writes wbuf, then a file being sent, then held HTTP/2 output. Last, if the connection streams,
it calls on_drain; if that wrote anything, it goes round again. After 256 KiB from on_drain in one flush,
the connection arms EPOLLOUT and yields, so a client on a fast link cannot hold the worker. EPOLLOUT fires on
the next turn of the loop, and the generator continues there.
http1.stream_post / sse_post build a WsPost with op = stream_data and the target StreamId. The
StreamId is {worker, fd, gen, stream}, a WsId plus the stream serial. Hub.post routes it unchanged.
Worker.deliver checks kinds: a stream post goes to st_push only when the connection still streams with
that serial; on a topic, only streams take stream posts and only WebSockets take WebSocket posts. The topic
table is shared, since names are names.
A slow client is bounded as for WebSocket: past four times max_pending unread, the connection closes.
-
Open.
st_opensavesclose_after(fromConnection: close, or HTTP/1.0's close-delimited body) intost_close, clears it so the head does not close the connection, and runson_open. -
End.
end()writes the last chunk.st_takeseesended, runsst_end(on_closewith writes dropped; publishes still go out, topics left) and restores the close. On a keep-alive connection, requests pipelined behind the stream are served next, from wherever the end happened (a timer,on_drain,on_open). -
Client gone.
Loop.closecallsst_end. -
Timeouts.
sweepskips streaming connections unless output is blocked (EPOLLOUT armed, under the write timeout). It sends due heartbeats on SSE streams. -
Input.
processparses nothing whilec.stis set. Input piling up to the read cap closes the connection, as behind a deferred response. -
handle_rawand tests.process_waitingruns a stream in place:on_drainwhile it writes, else its next timer, slept out. A stream with neither can never end and is closed.
The same API, a stream per HTTP/2 stream rather than per connection, so a browser can hold many SSE streams on
one connection. That is the main reason to have SSE over HTTP/2: browsers allow six HTTP/1.1 connections per
origin. The code is in engine/h2_stream.v.
-
State. The stream lives in its
H2Streamslot (st,st_data,st_sse,st_last,subs) from its HEADERS until it ends. Slots count against the 128 concurrent streams, so streams cannot outgrow them. -
Writes.
h2_st_lendlends the slot's ownoutasStream.out, unchunked;h2_st_takecounts what was added as held output, the same held output a response bigger than its window leaves.h2_pumpsends it as DATA within the windows, a frame per stream in turn. Nothing is copied twice: the callback writes into the slot, the pump frames it intowbuf. -
End.
end()runson_closeat once (as on HTTP/1.1) and clearsst. With nothing held, an empty DATA with END_STREAM goes now and the slot is freed; else the last frameh2_pumpsends carries END_STREAM, as for any held response. Whilestis set, a pump that empties the slot keeps it. -
Pull.
Loop.flushcallsh2_drainonce the socket tookwbufand the pump has nothing more to move: it runson_drainon each stream whose slot holds nothing, one call each per pass. A stream whose window is shut holds what it wrote, soon_drainwaits for the client's WINDOW_UPDATE. The 256 KiB per flush cap applies. -
Ids.
StreamId.streamis the HTTP/2 stream id. Ids are never reused on a connection, so a timer or a send for a stream that ended finds no slot with its id and is dropped, as the serial does on HTTP/1.1. Timers go on the same heap;st_ticktells the two byc.h2. -
Topics. A
Topicholds(conn, id)pairs,id0 for a WebSocket or an HTTP/1.1 stream, which is the connection itself. A publish skips only the stream it came from, not its neighbours on the connection.deliverwalks a topic from the end, because a stream reset while being written to leaves it on the spot. -
Cancel. RST_STREAM from the client, our own reset, and the connection closing all run
h2_st_endbefore the slot is released:on_close, topics left. -
Slow streams. Output a stream's window holds back past four times
max_pendingresets that stream (CANCEL). Flow control is per stream, so one stalled stream does not close the connection. New streams are refused while the held output of all of them passesmax_pending, as for responses. -
Timeouts.
h2_waitscovers streams as it does deferred responses: a connection that has nothing coming in part and nothing held back is not idle-timed out. Held output falls under the write timeout throughh2_held_deadline.sweepsends due heartbeats on SSE streams.
- Request-body streaming (reading an upload as it arrives). The body is still whole when the handler runs.
- Compression of streams. gzip leaves them alone.
- Trailers after the last chunk.