moon-http2

    Pure-MoonBit RFC 9113 HTTP/2 and RFC 7541 HPACK Sans-I/O protocol engine, native async h2c server, SVG wire timeline visualizer, and browser frame studio

    http2
    hpack
    rfc9113
    rfc7541
    sans-io
    protocol
    server
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    1 hour ago
    Downloads
    4

    #moon-http2

    Live Browser Workbench CI Mooncakes

    Pure-MoonBit Sans-I/O RFC 9113 HTTP/2 & RFC 7541 HPACK protocol engine, native async h2c server, native SVG frame-timeline / HPACK compression visualizer, and zero-upload browser workbench.

    • Zero third-party dependencies in the root Sans-I/O library (Sam-Hui-dot/moon-http2), verified across all four MoonBit targets (wasm, wasm-gc, js, native) with --deny-warn.
    • 147 / 147 official summerwind/h2spec v2.6.0 RFC 9113 conformance tests PASS (0 skipped, 0 failed) against the live native h2c server.
    • 14 / 14 official http2jp/hpack-test-case cross-implementation decode suites PASS (446 stories / 47,142 header blocks / 548,382 headers, 100% exact match) plus raw-data round-trip compression (1,162,372 B -> 361,250 B, -68.92%).
    • Node.js v24 node:http2 live concurrent interop PASS (51 concurrent multiplexed streams including 40 GETs, 10 POST echoes, 32 KB window-chunked response, and PING).
    • Zero-Upload Browser Workbench: https://sam-hui-dot.github.io/moon-http2/.

    #Verified External Oracle Results (demo/verify_h2.py)

    External OracleScopeResult
    summerwind/h2spec v2.6.0 (-S strict mode)All RFC 9113 framing, stream states, flow control, HPACK, HTTP semantics147 / 147 PASS (0 skipped, 0 failed)
    http2jp/hpack-test-case (cross-impl decode)14 implementations (nghttp2, go-hpack, haskell-http2-*, node-http2, python-hpack, swift-nio)446 stories / 47,142 blocks / 548,382 headers — 100% exact
    http2jp/hpack-test-case/raw-data (round-trip)32 stories / 3,384 blocks encoded with Huffman + dynamic table and decoded back1,162,372 B -> 361,250 B (-68.92%, 0 errors)
    Node.js node:http2 (live TCP h2c)40 GET + 10 POST echo + 32 KB chunked response + PING51 / 51 concurrent streams PASS

    #Architecture (0.1.0)

    • RFC 7541 HPACK (huffman.mbt, hpack.mbt): Complete Appendix B 257-symbol canonical Huffman table with strict §5.2 padding/EOS rejection, 61-entry static table, FIFO dynamic table (name + value + 32 octets), prefixed integers, and all 5 header field representations.
    • RFC 9113 Wire Framing (frame.mbt, error.mbt): All 10 standard frame types (DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, CONTINUATION) plus unknown extension frame handling and strict length/flag/padding validation.
    • Sans-I/O Multiplexing & Flow Control (stream.mbt, connection.mbt): 7-state stream lifecycle, pseudo-header & connection-header validation, content-length verification, connection + per-stream send/receive flow-control windows (including negative-window tracking on SETTINGS_INITIAL_WINDOW_SIZE shrinkage and automatic WINDOW_UPDATE replenishment), CONTINUATION exclusivity, and SETTINGS_MAX_CONCURRENT_STREAMS enforcement.
    • Visualization & Reports (viz.mbt, report.mbt): Native SVG client-server frame sequence timeline (render_timeline_svg), HPACK compression progression chart (render_hpack_svg), and text/Markdown/JSON reports.

    #Quick Start

    #1. MoonBit Library (wasm / wasm-gc / js / native)

    moon add Sam-Hui-dot/moon-http2@0.1.0

    let conn = @moon-http2.H2Connection::new_server()
    let server_settings = conn.take_outbound()
    let events = conn.feed(client_wire_bytes)
    for ev in events {
    match ev {
    RequestComplete(stream_id~, ..) =>
    conn.send_response(
    stream_id,
    200,
    extra_headers=[@moon-http2.header_field("content-type", "text/plain")],
    body=@moon-http2.ascii_to_bytes("hello from moon-http2"),
    )
    _ => ()
    }
    }
    let reply_bytes = conn.take_outbound()
    let svg = @moon-http2.render_timeline_svg(conn.frame_trace())

    #2. Native h2c Server & Verification

    # Run 4-target unit tests moon test --target wasm --deny-warn . moon test --target wasm-gc --deny-warn . moon test --target js --deny-warn . moon test --target native --deny-warn . # Build native CLI and run live h2c server moon build --target native --release --deny-warn cmd/main ./_build/native/release/build/cmd/main/main serve --port 8080 # Run all 3 external Oracles (http2jp/hpack-test-case + h2spec v2.6.0 + node:http2) python demo/verify_h2.py # Build zero-upload browser workbench python demo/build_web.py

    H2Error

    pub(all) suberror H2Error {
    ConnectionError(H2ErrorCode, String)
    StreamError(UInt, H2ErrorCode, String)
    CompressionError(String)
    InvalidInput(String)
    } derive(Eq,
    Debug
    )

    Errors raised during HTTP/2 frame parsing, HPACK coding, or protocol state transitions.

    H2Error::equal

    fn H2Error::equal(H2Error, H2Error) -> Bool
    automatically derived

    H2Error::not_equal

    fn H2Error::not_equal(x : H2Error, y : H2Error) -> Bool
    automatically derived

    H2Error::to_repr

    automatically derived

    DynamicTable

    pub struct DynamicTable {
    entries : Array[(String, String)]
    size_bytes : Int
    max_size : Int
    }

    HPACK FIFO dynamic header table with RFC 7541 §4.1 byte-size accounting (name + value + 32).

    DynamicTable::insert

    fn DynamicTable::insert(self : DynamicTable, name : String, value : String) -> Unit

    Insert a new (name, value) at dynamic index 1, evicting old entries as needed per RFC 7541 §4.4.

    DynamicTable::len

    fn DynamicTable::len(self : DynamicTable) -> Int

    Current number of entries in the dynamic table.

    DynamicTable::max_capacity

    fn DynamicTable::max_capacity(self : DynamicTable) -> Int

    Current maximum capacity of the dynamic table in octets.

    DynamicTable::new

    fn DynamicTable::new(max_size? : Int) -> DynamicTable

    Create an empty HPACK dynamic table bounded by max_size bytes (default 4096).

    DynamicTable::set_max_size

    fn DynamicTable::set_max_size(self : DynamicTable, new_max : Int) -> Unit

    Update the dynamic table max capacity and evict oldest entries until size_bytes <= new_max.

    DynamicTable::size

    fn DynamicTable::size(self : DynamicTable) -> Int

    Current dynamic table size in RFC 7541 octets.

    DynamicTable::snapshot

    fn DynamicTable::snapshot(self : DynamicTable) -> Array[(String, String)]

    Retrieve a copy of all current dynamic entries in newest-first order (index 62..).

    FrameTraceEntry

    pub(all) struct FrameTraceEntry {
    seq : Int
    direction : String
    kind : String
    stream_id : UInt
    payload_bytes : Int
    detail : String
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Recorded wire frame trace entry for SVG timeline rendering and diagnostics.

    FrameTraceEntry::equal

    automatically derived

    FrameTraceEntry::not_equal

    fn FrameTraceEntry::not_equal(x : FrameTraceEntry, y : FrameTraceEntry) -> Bool
    automatically derived

    FrameTraceEntry::to_json

    automatically derived

    FrameTraceEntry::to_repr

    automatically derived

    H2Connection

    pub struct H2Connection {
    preface_checked : Bool
    recv_buf :
    Buffer

    send_buf :
    Buffer

    hpack_dec : HpackDecoder
    hpack_enc : HpackEncoder
    streams : Map[UInt, H2Stream]
    last_remote_stream_id : UInt
    local_max_frame_size : Int
    remote_max_frame_size : Int
    local_initial_window : Int
    remote_initial_window : Int
    local_max_concurrent_streams : Int
    conn_send_window : Int
    conn_recv_window : Int
    conn_recv_consumed : Int
    expect_continuation_stream : UInt?
    continuation_end_stream : Bool
    continuation_buf :
    Buffer

    goaway_sent : Bool
    closed : Bool
    trace : Array[FrameTraceEntry]
    }

    Sans-I/O RFC 9113 HTTP/2 server connection state machine.

    H2Connection::feed

    fn H2Connection::feed(self : H2Connection, chunk : Bytes) -> Array[H2Event]

    Feed raw inbound wire bytes into the Sans-I/O HTTP/2 server connection. Automatically queues protocol responses (SETTINGS ACK, PING ACK, WINDOW_UPDATE, RST_STREAM, GOAWAY) and returns decoded application events.

    H2Connection::frame_trace

    fn H2Connection::frame_trace(self : H2Connection) -> Array[FrameTraceEntry]

    Return the recorded frame timeline trace for visualization.

    H2Connection::is_closed

    fn H2Connection::is_closed(self : H2Connection) -> Bool

    Return whether the connection has sent GOAWAY and should be closed after flushing outbound bytes.

    H2Connection::new_server

    fn H2Connection::new_server(max_concurrent_streams? : Int, initial_window_size? : Int, max_frame_size? : Int) -> H2Connection

    Create a new Sans-I/O HTTP/2 server connection and enqueue the initial server SETTINGS frame.

    H2Connection::send_goaway

    fn H2Connection::send_goaway(self : H2Connection, code : H2ErrorCode, debug_msg? : String) -> Unit

    Send a GOAWAY frame and mark the connection closed.

    H2Connection::send_response

    fn H2Connection::send_response(self : H2Connection, stream_id : UInt, status : Int, extra_headers? : Array[HeaderField], body? : Bytes) -> Unit

    Send an HTTP/2 response (HEADERS + chunked DATA frames respecting flow-control and MAX_FRAME_SIZE).

    H2Connection::take_outbound

    fn H2Connection::take_outbound(self : H2Connection) -> Bytes

    Drain all pending outbound wire bytes produced by the connection.

    H2ErrorCode

    pub(all) enum H2ErrorCode {
    NoError
    ProtocolError
    InternalError
    FlowControlError
    SettingsTimeout
    StreamClosed
    FrameSizeError
    RefusedStream
    Cancel
    CompressionError
    ConnectError
    EnhanceYourCalm
    InadequateSecurity
    Http11Required
    UnknownCode(UInt)
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Standard RFC 9113 §7 HTTP/2 32-bit error codes.

    H2ErrorCode::equal

    fn H2ErrorCode::equal(H2ErrorCode, H2ErrorCode) -> Bool
    automatically derived

    H2ErrorCode::from_u32

    fn H2ErrorCode::from_u32(raw : UInt) -> H2ErrorCode

    Decode a 32-bit RFC 9113 wire integer into an H2ErrorCode.

    H2ErrorCode::label

    fn H2ErrorCode::label(self : H2ErrorCode) -> String

    Human-readable canonical RFC 9113 error name.

    H2ErrorCode::not_equal

    fn H2ErrorCode::not_equal(x : H2ErrorCode, y : H2ErrorCode) -> Bool
    automatically derived

    H2ErrorCode::to_json

    automatically derived

    H2ErrorCode::to_repr

    automatically derived

    H2ErrorCode::to_u32

    fn H2ErrorCode::to_u32(self : H2ErrorCode) -> UInt

    Convert an H2ErrorCode to its 32-bit RFC 9113 wire integer value.

    H2Event

    pub(all) enum H2Event {
    SettingsUpdated(Array[SettingParam])
    RequestHeaders(stream_id~ : UInt, headers~ : Array[HeaderField], end_stream~ : Bool)
    RequestData(stream_id~ : UInt, data~ : Bytes, end_stream~ : Bool)
    RequestComplete(stream_id~ : UInt, headers~ : Array[HeaderField], body~ : Bytes)
    StreamReset(stream_id~ : UInt, code~ : H2ErrorCode)
    PingReceived(ack~ : Bool, opaque_data~ : Bytes)
    GoAwayReceived(last_stream_id~ : UInt, code~ : H2ErrorCode, debug_data~ : Bytes)
    WindowUpdated(stream_id~ : UInt, increment~ : UInt)
    } derive(Eq,
    Debug
    )

    High-level events emitted by H2Connection::feed for application handlers and visualizers.

    H2Event::equal

    fn H2Event::equal(H2Event, H2Event) -> Bool
    automatically derived

    H2Event::not_equal

    fn H2Event::not_equal(x : H2Event, y : H2Event) -> Bool
    automatically derived

    H2Event::to_repr

    automatically derived

    H2Frame

    pub(all) enum H2Frame {
    Data(stream_id~ : UInt, end_stream~ : Bool, data~ : Bytes, flow_len~ : Int)
    Headers(stream_id~ : UInt, end_stream~ : Bool, end_headers~ : Bool, priority~ : PrioritySpec?, fragment~ : Bytes)
    Priority(stream_id~ : UInt, spec~ : PrioritySpec)
    RstStream(stream_id~ : UInt, code~ : H2ErrorCode)
    Settings(ack~ : Bool, params~ : Array[SettingParam])
    PushPromise(stream_id~ : UInt, promised_stream_id~ : UInt, end_headers~ : Bool, fragment~ : Bytes)
    Ping(ack~ : Bool, opaque_data~ : Bytes)
    GoAway(last_stream_id~ : UInt, code~ : H2ErrorCode, debug_data~ : Bytes)
    WindowUpdate(stream_id~ : UInt, increment~ : UInt)
    Continuation(stream_id~ : UInt, end_headers~ : Bool, fragment~ : Bytes)
    Unknown(frame_type~ : Byte, flags~ : Byte, stream_id~ : UInt, payload~ : Bytes)
    } derive(Eq,
    Debug
    )

    Decoded RFC 9113 HTTP/2 frame covering all 10 standard frame types plus unknown extension frames.

    H2Frame::equal

    fn H2Frame::equal(H2Frame, H2Frame) -> Bool
    automatically derived

    H2Frame::kind_name

    fn H2Frame::kind_name(self : H2Frame) -> String

    Return the canonical RFC 9113 name of an H2Frame.

    H2Frame::not_equal

    fn H2Frame::not_equal(x : H2Frame, y : H2Frame) -> Bool
    automatically derived

    H2Frame::stream_id

    fn H2Frame::stream_id(self : H2Frame) -> UInt

    Return the stream identifier associated with an H2Frame.

    H2Frame::to_repr

    automatically derived

    H2Stream

    pub struct H2Stream {
    id : UInt
    state : StreamState
    send_window : Int
    recv_window : Int
    recv_consumed : Int
    expected_content_length : Int64?
    received_data_bytes : Int64
    headers_received : Bool
    req_headers : Array[HeaderField]
    req_body :
    Buffer

    pending_body : Bytes
    pending_offset : Int
    pending_end_stream : Bool
    }

    Per-stream state tracked by an H2Connection.

    HeaderField

    pub(all) struct HeaderField {
    name : String
    value : String
    sensitive : Bool
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Single HTTP/2 header field (name, value) with optional HPACK never-index sensitivity flag.

    HeaderField::equal

    fn HeaderField::equal(HeaderField, HeaderField) -> Bool
    automatically derived

    HeaderField::not_equal

    fn HeaderField::not_equal(x : HeaderField, y : HeaderField) -> Bool
    automatically derived

    HeaderField::to_json

    automatically derived

    HeaderField::to_repr

    automatically derived

    HpackDecoder

    pub struct HpackDecoder {
    table : DynamicTable
    max_allowed_table_size : Int
    }

    Stateful RFC 7541 HPACK decoder enforcing SETTINGS_HEADER_TABLE_SIZE and block-start table updates.

    HpackDecoder::decode

    fn HpackDecoder::decode(self : HpackDecoder, block : Bytes) -> Array[HeaderField] raise H2Error

    Decode a complete HPACK header block fragment into an ordered array of HeaderFields.

    HpackDecoder::new

    fn HpackDecoder::new(max_table_size? : Int) -> HpackDecoder

    Create a new HpackDecoder with max_allowed_table_size (default 4096).

    HpackDecoder::set_max_table_size_limit

    fn HpackDecoder::set_max_table_size_limit(self : HpackDecoder, limit : Int) -> Unit

    Update the HTTP/2 SETTINGS_HEADER_TABLE_SIZE ceiling enforced during decoding.

    HpackEncoder

    pub struct HpackEncoder {
    table : DynamicTable
    pending_size_update : Int?
    use_huffman : Bool
    }

    Stateful RFC 7541 HPACK encoder with automatic static/dynamic lookup and Huffman compression.

    HpackEncoder::encode

    fn HpackEncoder::encode(self : HpackEncoder, headers : Array[HeaderField]) -> Bytes

    Encode a list of header fields into an HPACK header block fragment.

    HpackEncoder::new

    fn HpackEncoder::new(max_size? : Int, use_huffman? : Bool) -> HpackEncoder

    Create a new HpackEncoder with initial table size max_size (default 4096).

    HpackEncoder::set_max_table_size

    fn HpackEncoder::set_max_table_size(self : HpackEncoder, new_max : Int) -> Unit

    Apply a peer SETTINGS_HEADER_TABLE_SIZE update to be emitted at the start of the next block.

    HpackSampleStat

    pub(all) struct HpackSampleStat {
    request_index : Int
    raw_bytes : Int
    encoded_bytes : Int
    dynamic_entries : Int
    dynamic_bytes : Int
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Per-request HPACK compression statistics entry for SVG visualization.

    HpackSampleStat::equal

    automatically derived

    HpackSampleStat::not_equal

    fn HpackSampleStat::not_equal(x : HpackSampleStat, y : HpackSampleStat) -> Bool
    automatically derived

    HpackSampleStat::to_json

    automatically derived

    HpackSampleStat::to_repr

    automatically derived

    PrioritySpec

    pub(all) struct PrioritySpec {
    exclusive : Bool
    dependency : UInt
    weight : Int
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Parsed priority metadata from a HEADERS (with PRIORITY flag) or PRIORITY frame.

    PrioritySpec::equal

    automatically derived

    PrioritySpec::not_equal

    fn PrioritySpec::not_equal(x : PrioritySpec, y : PrioritySpec) -> Bool
    automatically derived

    PrioritySpec::to_json

    automatically derived

    PrioritySpec::to_repr

    automatically derived

    SettingParam

    pub(all) struct SettingParam {
    id : UInt16
    value : UInt
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    Single key-value parameter inside a SETTINGS frame.

    SettingParam::equal

    automatically derived

    SettingParam::not_equal

    fn SettingParam::not_equal(x : SettingParam, y : SettingParam) -> Bool
    automatically derived

    SettingParam::to_json

    automatically derived

    SettingParam::to_repr

    automatically derived

    StreamState

    pub(all) enum StreamState {
    Idle
    ReservedLocal
    ReservedRemote
    Open
    HalfClosedLocal
    HalfClosedRemote
    Closed
    } derive(Eq,
    Debug
    ,
    ToJson
    )

    RFC 9113 §5.1 7-state HTTP/2 stream lifecycle.

    StreamState::equal

    fn StreamState::equal(StreamState, StreamState) -> Bool
    automatically derived

    StreamState::not_equal

    fn StreamState::not_equal(x : StreamState, y : StreamState) -> Bool
    automatically derived

    StreamState::to_json

    automatically derived

    StreamState::to_repr

    automatically derived

    CLIENT_PREFACE_STR

    let CLIENT_PREFACE_STR : String

    Standard RFC 9113 §3.5 HTTP/2 client connection preface (24 bytes).

    DEFAULT_INITIAL_WINDOW_SIZE

    let DEFAULT_INITIAL_WINDOW_SIZE : Int

    DEFAULT_MAX_FRAME_SIZE

    let DEFAULT_MAX_FRAME_SIZE : Int

    FLAG_ACK

    let FLAG_ACK : Byte

    FLAG_END_HEADERS

    let FLAG_END_HEADERS : Byte

    FLAG_END_STREAM

    let FLAG_END_STREAM : Byte

    RFC 9113 frame flag bitmasks.

    FLAG_PADDED

    let FLAG_PADDED : Byte

    FLAG_PRIORITY

    let FLAG_PRIORITY : Byte

    MAX_ALLOWED_FRAME_SIZE

    let MAX_ALLOWED_FRAME_SIZE : Int

    MAX_WINDOW_SIZE

    let MAX_WINDOW_SIZE : Int

    SETTING_ENABLE_PUSH

    let SETTING_ENABLE_PUSH : UInt16

    SETTING_HEADER_TABLE_SIZE

    let SETTING_HEADER_TABLE_SIZE : UInt16

    RFC 9113 §6.5.2 SETTINGS parameter identifiers.

    SETTING_INITIAL_WINDOW_SIZE

    let SETTING_INITIAL_WINDOW_SIZE : UInt16

    SETTING_MAX_CONCURRENT_STREAMS

    let SETTING_MAX_CONCURRENT_STREAMS : UInt16

    SETTING_MAX_FRAME_SIZE

    let SETTING_MAX_FRAME_SIZE : UInt16

    SETTING_MAX_HEADER_LIST_SIZE

    let SETTING_MAX_HEADER_LIST_SIZE : UInt16

    ascii_to_bytes

    fn ascii_to_bytes(s : String) -> Bytes

    Convert an ASCII string into raw Bytes.

    bytes_to_hex

    fn bytes_to_hex(bs : Bytes) -> String

    Encode raw Bytes into a lowercase hexadecimal string.

    decode_frame_at

    fn decode_frame_at(buf : Bytes, offset : Int, max_frame_size? : Int) -> (H2Frame, Int)? raise H2Error

    Try to decode one HTTP/2 frame starting at offset in buf. Returns None if fewer than 9 + payload_length bytes are available. Enforces all RFC 9113 §4 / §6 structural length, stream ID, flag, and padding rules.

    decode_frames

    fn decode_frames(raw : Bytes, max_frame_size? : Int) -> Array[H2Frame] raise H2Error

    Decode all complete HTTP/2 frames from a raw byte buffer (optionally skipping a leading client preface).

    encode_frame

    fn encode_frame(frame : H2Frame) -> Bytes

    Encode a single H2Frame to wire bytes.

    encode_frame_into

    fn encode_frame_into(buf :
    Buffer
    , frame : H2Frame) -> Unit

    Encode the 9-byte HTTP/2 frame header plus payload into buf.

    error_message

    fn error_message(error : Error) -> String

    Extract a concise human-readable diagnostic message from any HTTP/2 error.

    header_field

    fn header_field(name : String, value : String, sensitive? : Bool) -> HeaderField

    Construct a HeaderField.

    hex_to_bytes

    fn hex_to_bytes(hex : String) -> Bytes raise H2Error

    Decode a hexadecimal string (ignoring whitespace) into raw Bytes.

    huffman_decode

    fn huffman_decode(data : Bytes) -> Bytes raise H2Error

    Decode RFC 7541 Huffman-encoded octets strictly enforcing §5.2 padding and EOS rules.

    huffman_encode

    fn huffman_encode(data : Bytes) -> Bytes

    Encode raw octets using the RFC 7541 Appendix B static Huffman code and EOS padding.

    huffman_encoded_len

    fn huffman_encoded_len(data : Bytes) -> Int

    Return the exact Huffman-encoded byte length of raw octets without allocating output.

    render_hpack_svg

    fn render_hpack_svg(stats : Array[HpackSampleStat]) -> String

    Render HPACK compression ratio progression across consecutive requests as a native SVG chart.

    render_timeline_svg

    fn render_timeline_svg(entries : Array[FrameTraceEntry]) -> String

    Render an HTTP/2 connection's recorded frame exchange as a native SVG sequence timeline.

    render_trace_markdown

    fn render_trace_markdown(entries : Array[FrameTraceEntry]) -> String

    Format a frame timeline trace as a GitHub-flavored Markdown table.

    render_trace_text

    fn render_trace_text(entries : Array[FrameTraceEntry]) -> String

    Format a frame timeline trace as concise human-readable text.

    validate_request_headers

    fn validate_request_headers(stream_id : UInt, headers : Array[HeaderField], is_trailer : Bool) -> Int64? raise H2Error

    Validate RFC 9113 §8.1–§8.3 HTTP/2 request header block semantics. Returns Some(content_length) if a valid content-length header is present.