Mica::HTTP2 is the frame layer of HTTP/2 (RFC 9113) and Mica::HPACK its
header compression (RFC 7541), in pure Crystal with no I/O. They are the
parsing half of HTTP/2, and Connection is the sans-IO core on top of them
(stream states, flow-control windows, abuse counters). Amber owns sockets,
TLS, timers and scheduling.
FrameParser takes the bytes a peer sends, in chunks of any size, and
returns frames as they complete. A stream fed one byte at a time gives the
same frames and errors as the same stream fed at once.
parser = Mica::HTTP2::FrameParser.new(limits: Mica::HTTP2::FrameLimits::PUBLIC_SERVER, expect_preface: true)
parser.feed(chunk) do |frame|
if frame.is_a?(Mica::HTTP2::HeadersFrame)
# frame.field_block goes to the connection's HPACK decoder
end
end- A server parser (
expect_preface: true) checks the 24-byte client preface first and fails at the first byte that differs. - The ten frame types are structs:
DataFrame,HeadersFrame,PriorityFrame,RstStreamFrame,SettingsFrame,PushPromiseFrame,PingFrame,GoawayFrame,WindowUpdateFrame,ContinuationFrame. Each serializes itself withto_slice(max_frame_size:)orwrite(io, max_frame_size:), and a parsed frame serializes back to the same frame. The reserved bit is ignored on receipt and cleared on send. - Frames of unknown types, flags a type does not define and SETTINGS parameters the codec does not know are ignored, as RFC 9113 requires.
- Every rule one frame can break raises
FrameErrorwith the RFC 9113ErrorCodeandconnection_error?. After a connection error the parser raises it again on every call; after a stream error it has consumed the frame and goes on. A HEADERS frame that makes its stream depend on itself is a stream error that still carries the frame (FrameError#frame), so its field block can reach the HPACK decoder.
FrameLimits is a required argument, with three presets.
| Limit | PUBLIC_SERVER |
INTERNAL_SERVER |
CLIENT |
|---|---|---|---|
max_frame_size (our SETTINGS_MAX_FRAME_SIZE) |
16,384 | 16,384 | 16,384 |
max_header_block_bytes (HEADERS or PUSH_PROMISE plus CONTINUATION) |
32,768 | 131,072 | 131,072 |
max_continuation_frames per header block |
16 | 64 | 64 |
A frame longer than max_frame_size fails with FRAME_SIZE_ERROR as soon
as its 9-byte header arrives, before its payload is buffered (Mica treats
every oversized frame as a connection error). A header block passing
either block limit raises FrameLimitError (ENHANCE_YOUR_CALM) when the
frame that passes it arrives: the CONTINUATION flood answer of the plan.
decoder = Mica::HPACK::Decoder.new(limits: Mica::HPACK::DecodeLimits::PUBLIC_SERVER)
decoder.decode(field_block) # => Array(Mica::HPACK::Header)
encoder = Mica::HPACK::Encoder.new # peer's table size 4,096, Huffman on
encoder.encode([Mica::HPACK::Header.new(":status", "200")])- One decoder and one encoder per connection, each owned by one fiber (the reader and the writer).
decoder.max_table_size = nonce the peer acknowledges the SETTINGS frame that advertised SETTINGS_HEADER_TABLE_SIZEn; whennis below the table's size, the next block must start with a size update.encoder.max_table_size = nwhen the peer's SETTINGS_HEADER_TABLE_SIZE changes; the next block starts with the size updates.- The encoder sends
cookie,set-cookie,authorization,proxy-authorizationand anyHeadermarkednever_indexedas never-indexed literals, so they never enter a table. It Huffman-codes a string when that is no longer than the string, and its output is deterministic. - Decoding errors (
DecodingErrorand its subclassesTruncatedBlockError,IntegerOverflowError,HuffmanError,InvalidIndexError,TableSizeError) are COMPRESSION_ERROR connection errors; the decoder refuses later blocks.
| Limit | PUBLIC_SERVER |
INTERNAL_SERVER |
CLIENT |
|---|---|---|---|
max_header_list_bytes (decoded, name + value + 32 per field) |
16,384 | 65,536 | 65,536 |
max_header_block_bytes (encoded) |
32,768 | 131,072 | 131,072 |
max_table_bytes (largest SETTINGS_HEADER_TABLE_SIZE we advertise) |
4,096 | 4,096 | 4,096 |
| Work | 100,000 + 64 per block byte | same | same |
The list limit counts decoded bytes as they are produced. A block that
expands through table references (an HPACK bomb) yields only the fields
within the limit; the decoder finishes the block so its table stays in step
with the peer's, then raises DecodeLimitError with table_intact? true,
so the error can be a stream error (HTTP 431). Integers allow at most 5
continuation octets and values up to 2^31-1; Huffman strings that contain
EOS, pad with more than 7 bits or pad with anything but ones are rejected.
Connection is the sans-IO core of one HTTP/2 connection (milestone H2.3),
shaped like Python's h2: bytes from the socket go in through
receive_data and come out as events; the bytes to write come out of
data_to_send. It keeps the stream states of RFC 9113 section 5.1,
SETTINGS and their acknowledgments, both directions' flow-control windows,
GOAWAY bookkeeping, one HPACK decoder and one encoder, and the abuse
counters. It does no I/O, reads no clock and starts no fibers; Amber owns
sockets, TLS, timers and scheduling.
limits = Mica::HTTP2::ConnectionLimits::PUBLIC_SERVER
connection = Mica::HTTP2::Connection.new(Mica::HTTP2::Role::Server, limits)
socket.write(connection.data_to_send) # our SETTINGS and WINDOW_UPDATE
loop do
read = socket.read(buffer)
break if read == 0
connection.receive_data(buffer[0, read]).each do |event|
case event
when Mica::HTTP2::RequestReceived
response = [Mica::HPACK::Header.new(":status", "200"), Mica::HPACK::Header.new("content-type", "text/plain")]
connection.send_headers(event.stream_id, response)
# Queues what the windows allow; send the rest after WindowUpdated.
connection.send_data(event.stream_id, "hello".to_slice, end_stream: true)
when Mica::HTTP2::DataReceived
# Credit the peer once the body bytes are consumed.
connection.acknowledge_received_data(event.stream_id, event.flow_controlled_length)
when Mica::HTTP2::ConnectionTerminated
# A connection error (ours, remote? false) or the peer's GOAWAY.
end
end
socket.write(connection.data_to_send)
break if connection.closed?
end- Block forms that reuse buffers.
receive_data(bytes) { |event| ... }yields the events in order instead of returning a new list, anddata_to_send { |bytes| ... }yields the queued bytes (it does not yield when nothing is queued) and then clears that buffer for reuse, so the slice is valid only inside the block: write or copy it there. The core keeps two outbound buffers, so frames the block queues (it may call back into the connection) come out of the next call. A buffer that grew pastConnection::RETAINED_BUFFER_BYTESIZE(4 KiB), or an event list with room for more thanConnection::RETAINED_EVENT_COUNT(64) events, is let go after use. A connection keeps up to three buffers of at mostRETAINED_BUFFER_BYTESIZEeach and two event lists of at mostRETAINED_EVENT_COUNTevents each between calls, so an idle connection holds at mostConnection::MAX_RETAINED_BYTESIZE(18,432 bytes, 18 KiB) of them, however large a burst it sent or read before. A server that answers one small request per read makes no new event list and no new outbound buffer per request. - Events (structs under
Mica::HTTP2::Event):RequestReceived,ResponseReceivedandInformationalResponseReceived(client side),DataReceived,TrailersReceived,StreamEnded(the peer half-closed the stream),StreamReset,WindowUpdated,SettingsChanged,SettingsAcknowledged,PingReceived,PingAcknowledged,PriorityUpdated(an RFC 9218priorityfield) andConnectionTerminated. - Errors from the peer never raise. A stream error queues RST_STREAM
and returns
StreamReset(remote?false). A connection error queues GOAWAY with the RFC 9113 code and the last stream id, returnsConnectionTerminated, and every laterreceive_datareturns nothing. The application's own mistakes (DATA on a closed stream, DATA before HEADERS) raiseConnectionStateError,StreamClosedErrororConnectionClosedError. - Field rules. Every header block is checked against RFC 9113 sections
8.2 and 8.3 before it becomes an event (
FieldRules, public so an HTTP/1.1 bridge can apply the same rules): lowercase names with no control bytes, values without NUL, CR, LF or surrounding whitespace, no connection-specific fields, TE onlytrailers, pseudo-header fields first and once,:method,:schemeand an origin-form:path(or CONNECT with:authorityonly),hostequal to:authority. WithConnectionLimits#allows_extended_connect?a server also takes an extended CONNECT (RFC 8441)::protocolon CONNECT only, with:scheme,:pathand:authority; the stream then carries a tunnel (a WebSocket, for:protocol websocket) as DATA both ways.Connection#allows_extended_connect?is true on a server connection whose limits allow it. The core counts DATA bytes againstcontent-length. A malformed request becomes a PROTOCOL_ERROR stream reset and never aRequestReceived. Outgoing names are lowercased and connection-specific fields left out. - Flow control.
send_dataqueues at mostlocal_flow_control_window(stream_id)bytes, split to the peer's SETTINGS_MAX_FRAME_SIZE, and returns the count; the rest waits forWindowUpdated. A SETTINGS_INITIAL_WINDOW_SIZE change moves every open stream's window, below zero if need be. Received DATA (padding included) is charged to the stream and the connection;acknowledge_received_datareturns the credit in WINDOW_UPDATE frames once half a window is consumed, and the core returns padding and the bytes of reset streams itself. - SETTINGS. Ours go out at once. A raise applies at once, a cut (a
smaller table or window) when the peer acknowledges it. The peer's
settings apply in order and are acknowledged; a server's
SETTINGS_ENABLE_PUSH 1 and any PUSH_PROMISE are PROTOCOL_ERROR (push is
off on both sides). A server whose limits allow extended CONNECT sends
SETTINGS_ENABLE_CONNECT_PROTOCOL 1; a client sends
:protocolonly oncepeer_enable_connect_protocol?is true, and a peer that turns it from 1 back to 0 is a PROTOCOL_ERROR. - Drain.
closewith no arguments sends GOAWAY with 2^31-1; a secondclose, one round trip later (send apingand wait forPingAcknowledged), sends the highest stream id the peer opened, and later streams are ignored while open ones finish.closed?turns true when we may close the connection: after a connection error, or once our final GOAWAY is out and no stream is open. After the peer's GOAWAY the peer closes, and frames it still sends are answered.close(error_code)ends the connection at once. - Clients.
Role::Clientqueues the preface, opens a request stream withsend_headers(next_stream_id, request), keeps to the server's SETTINGS_MAX_CONCURRENT_STREAMS, and reports the server's GOAWAY by resetting our streams above its last id with REFUSED_STREAM, which are safe to retry. - Idle or stalled.
partial_frame_buffered?is true while the core holds part of a frame (or of the preface) or a header block waits for CONTINUATION. Some complete frames produce no event (PRIORITY, unknown types, WINDOW_UPDATE on a closed stream); false means everything received was handled, so a read timeout can tell an idle connection from one stuck mid-frame. - One owner. A connection is not concurrency-safe: the reader and the writers hold one lock, or are one fiber.
ConnectionLimits is a required argument, with three presets (plan
section 2.5).
| Limit | PUBLIC_SERVER |
INTERNAL_SERVER |
CLIENT |
|---|---|---|---|
frame_limits, hpack_limits |
PUBLIC_SERVER |
INTERNAL_SERVER |
CLIENT |
max_concurrent_streams (SETTINGS) |
100 | 250 | 100 |
initial_window_size (SETTINGS, per stream) |
65,535 | 1,048,576 | 1,048,576 |
connection_window_size |
1,048,576 | 16,777,216 | 16,777,216 |
max_header_list_bytes (SETTINGS) |
16,384 | 65,536 | 65,536 |
max_resets_per_window |
200 | 1,000 | 200 |
reset_ratio_floor |
100 | 250 | 100 |
max_control_frames_per_window |
1,000 | 10,000 | 1,000 |
max_streams_per_connection |
10,000 | 1,000,000 | 1,000,000 |
max_outbound_queue_bytes |
1,048,576 | 4,194,304 | 1,048,576 |
abuse_window / abuse_window_frames |
10 s / 100,000 | same | same |
allows_extended_connect? (SETTINGS_ENABLE_CONNECT_PROTOCOL) |
false |
false |
false (ignored by a client) |
How the core answers the attacks of plan section 2.4:
| Attack | Answer |
|---|---|
| Rapid Reset (CVE-2023-44487) | The peer's RST_STREAM frames count per window; past max_resets_per_window, or past reset_ratio_floor while resets are over half the streams opened in the window, GOAWAY ENHANCE_YOUR_CALM |
| MadeYouReset (CVE-2025-8671) | The resets the core sends for protocol errors count in the same window |
| Control-frame floods (CVE-2019-9512, 9515, 9518) | PING, SETTINGS, PRIORITY and empty DATA frames past max_control_frames_per_window: GOAWAY ENHANCE_YOUR_CALM |
| CONTINUATION flood (VU#421644) | FrameLimits: a header block past its byte or CONTINUATION limit is ENHANCE_YOUR_CALM |
| HPACK bomb (CVE-2016-6581) | HPACK::DecodeLimits: a request header list past the limit is answered 431 and reset with NO_ERROR, the table kept in step; a block the table cannot survive is a connection error |
| Unread answers (CVE-2019-9517) | Answers the core queues (acknowledgments, resets) past max_outbound_queue_bytes since the last data_to_send: ENHANCE_YOUR_CALM; send_data stops at the room left |
| Endless connections | The stream that reaches max_streams_per_connection is announced as the last with a graceful GOAWAY |
The core reads no clock, so a window ends after abuse_window of the time
the caller passes to tick(now_monotonic), or, until the first tick,
after abuse_window_frames received frames. Resets the application asks
for with reset_stream do not count. Timeouts (preface, SETTINGS
acknowledgment, idle, PING) are the caller's.
A library that cannot depend on the Mica shard carries a pinned copy of HTTP/2, HPACK and the core they use:
/usr/bin/ruby scripts/vendor_into.rb --commit COMMIT --component http2 --namespace Amber --destination ../amber/src/amber/vendorand requires "<destination>/mica/http2" (Amber::Mica::HTTP2::Connection).
One destination holds one copy, so a library that also carries the
compression codecs lists both: --component compression,http2. The script
runs crystal tool format on the renamed sources before pinning them
(MICA_CRYSTAL, else crystal-alpha, else crystal), so the copy passes the
carrier's format check. MICA_VENDORED.json records that formatter's command
and --version; a re-run into the same destination with another formatter
fails, so the pins never change from layout alone. Set MICA_CRYSTAL to the
recorded compiler, or pass --allow-formatter-change to re-pin on purpose.
- RFC 7541 Appendix C: all 16 examples of C.2 to C.6 decode to their
headers and table sizes, and the encoder reproduces their bytes
(
spec/hpack/appendix_c_spec.cr). - http2jp/hpack-test-case at
8a1406e7d14bfcb6c046021f13cc15cfb162726d: every story of the 14 implementation directories (446 stories, 47,142 header blocks) decodes to its expected headers, and the encoder's blocks for the 32 raw-data stories decode back./usr/bin/ruby conformance/hpack/fetch_test_case.rbfetches it (sha256 checked by the script and by the spec; CI fetches it). Pin:spec/vectors/hpack/SOURCES.md. - Requirement catalogs:
spec/requirements/http2.tsv(frame codec and connection core),spec/requirements/hpack.tsvandspec/requirements/h2spec.tsv. - h2spec v2.6.0
(
70ac2294010887f48b18e2d64f5cccd48421fad1): every case of itsgeneric,http2andhpackgroups (44, 95 and 8: the 146 of a default run plus the one--strictcase) is replayed against the connection core with the same frames and must get the answer h2spec accepts: the response, or the RFC 9113 code as a stream or connection error (spec/http2/h2spec_cases_spec.cr). Running h2spec itself over a socket belongs to Amber (H2.4). - Attack replays for each attack of plan section 2.4
(
spec/http2/attack_replay_spec.cr). - Differential against nghttp2 1.71.0's HPACK, out of tree
(
fuzz/hpack_nghttp2/build.shbuilds the library from its release tarball, checked by sha256, andharness.c;fuzz/hpack_differential.crdrives it): nghttp2 decodes Mica's blocks (encode), Mica decodes nghttp2's (deflate), and both decode random and mutated blocks (decode). fuzz/http2_campaign.cr: random and mutated frame streams parsed at once and in random chunks, and random header blocks, with allocation bounds.fuzz/http2_connection_campaign.cr: random request sequences (valid and malformed requests, bodies, resets, window updates, settings, pings, some bytes mutated) fed to a server connection at once and in random chunks, which must give the same events and output, and again to a connection whose application answers, acknowledges and resets, whose windows must stay within bounds and whose closed streams must stay closed. The same properties run with fixed seeds inspec/http2/connection_property_spec.cr.
fuzz/hpack_nghttp2/build.sh /tmp/nghttp2
crystal-alpha build --release fuzz/hpack_differential.cr -o bin/hpack_differential
bin/hpack_differential /tmp/nghttp2/bin/hpack_nghttp2 encode 20261122 1000000
crystal-alpha build --release fuzz/http2_campaign.cr -o bin/http2_campaign
bin/http2_campaign 20261122 2000000
crystal-alpha build --release fuzz/http2_connection_campaign.cr -o bin/http2_connection_campaign
bin/http2_connection_campaign 20261203 2000000bench/hpack/ decodes the hpack-test-case corpus with Mica and with
nghttp2 1.71.0, each a release build in its own process, in interleaved
rounds:
/usr/bin/ruby bench/hpack/make_corpus.rb bench/data/hpack/corpus.bin
crystal-alpha build --release bench/hpack/mica_runner.cr -o bench/bin/hpack/mica_runner
cc -O2 -I/tmp/nghttp2/prefix/include bench/hpack/nghttp2_runner.c /tmp/nghttp2/prefix/lib/libnghttp2.a -o bench/bin/hpack/nghttp2_runner
/usr/bin/ruby bench/hpack/run_ab.rb bench/bin/hpack/mica_runner bench/bin/hpack/nghttp2_runner bench/data/hpack/corpus.bin 10 bench/data/hpack/runOn m4-mini-01 (Apple M4 Mac mini, 10 cores), 10 rounds, each keeping each engine's median of 15 timed passes over every story of the 14 implementation directories (548,382 fields, 8,436,756 block bytes, one decoder per story):
| Engine | Median pass | Block MB/s |
|---|---|---|
| Mica | 22.90 ms | 368.4 |
| nghttp2 1.71.0 | 31.42 ms | 268.5 |
Mica decodes 1.37× as fast as nghttp2 (median of the per-round ratios 1.373; bootstrap 95% interval 1.344 to 1.441). Both decoders produce the same field count and field bytes on every pass.