# HTTP/1.1 request parser

`justjavac/http_parser` is an incremental, byte-oriented, pure MoonBit
adaptation of uWebSockets [`HttpParser.h`](https://github.com/uNetworking/uWebSockets/blob/05e6c8b55b4d28293cf23570f0f61318f8600560/src/HttpParser.h),
including chunked framing and request/query helpers. It parses HTTP/1.1
**requests**, streams body fragments, and handles pipelined requests. Production
code uses MoonBit and standard SIMD intrinsics, with no FFI or native dependencies.

The pinned upstream revision is `05e6c8b55b4d28293cf23570f0f61318f8600560`.
Upstream behavior is preserved with the documented ownership and safety changes
below. This is a request parser; socket transport, HTTP responses, routing,
WebSocket frames, decompression, and optional PROXY protocol parsing are outside
its API. Transfer codings preceding `chunked` are passed through after dechunking.

## Install and import

From this repository, `moon.work` selects the local module. For a consumer of a
published version, add `justjavac/http_parser` to its own module:

```text
moon add justjavac/http_parser
```

```text
import {
  "justjavac/http_parser" @http_parser,
}
```

The package requires the current MoonBit SIMD API. Validated with
`moon 0.1.20261120`, `moonc v0.10.22+7b085e9a4-nightly` (2026-11-22), and
Node.js 24 for JavaScript. The library does not require third-party packages.
See [pkg.generated.mbti](pkg.generated.mbti) for the generated public interface
and [README.mbt.md](README.mbt.md) for checked examples.

## Parse requests

```mbt
let parser = @http_parser.Parser::new()
let requests : Array[@http_parser.Request] = []
let input : Bytes = b"GET /search?hello=a%20b+c&debug HTTP/1.1\r\nHost: example.com\r\n\r\n"
let result = parser.feed(
  input,
  on_request=request => {
    requests.push(request)
    @http_parser.Continue
  },
  on_body=(_, _) => @http_parser.Continue,
)
assert_eq(result, @http_parser.Consumed(input.length()))
parser.finish()
assert_eq(requests[0].get_url(), b"/search"[:])
assert_eq(requests[0].get_header(b"host"), Some(b"example.com"[:]))
assert_eq(requests[0].get_query_value(b"hello"), Some(@http_parser.Value(b"a b c")))
assert_eq(requests[0].get_query_value(b"debug"), Some(@http_parser.Valueless))
```

Feed any immutable `BytesView`, including unaligned subviews, without padding or
NUL termination. Input boundaries may split any request line, field, delimiter,
chunk size, extension, payload, or trailer. The parser retains incomplete heads
up to its configured limit and does not accumulate body data. It emits multiple
requests in order when one input contains a pipeline.

`Consumed(n)` means all `n` supplied bytes have been parsed or buffered. It does
not imply that a request or body is complete. `Stopped(n)` means a callback
returned `Stop`; advance the input by `result.consumed()` bytes before resuming.
Counts and offsets are bytes, with no UTF-16 indexing.

### Body callbacks

| Framing | Callback `remaining` | Completion |
| --- | --- | --- |
| No body / Content-Length zero | `0UL` with an empty view | Exactly one body-end event |
| Fixed length | Exact `UInt64` bytes left after the fragment | Final fragment has zero remaining |
| Chunked | `18446744073709551615UL` for payload | Empty view with zero at the zero chunk |

A fixed-length head arriving without payload initially emits an empty view
with the full remaining length. Further empty feeds do not repeat that event.
Chunked trailers are skipped after the body-end event, so `is_idle()` can still
be false when the body has ended. `finish()` validates that the full head, body,
and trailer section have completed at EOF; unfinished input raises
`UnexpectedEof`. An idle `finish()` does not close the parser.

Callbacks return `Continue` or `Stop` and cannot raise through this API.
Request callbacks run after header syntax, Host, and simultaneous TE/CL checks,
but before detailed Content-Length or Transfer-Encoding validation. Thus a
request callback can hand off an upgrade before interpreting its body framing.
Body callbacks consistently honor `Stop`, including chunked and empty events.
Already emitted callbacks are not rolled back when later bytes raise an error.

### Pause and protocol handoff

```mbt
let parser = @http_parser.Parser::new()
let input : Bytes = b"GET /upgrade HTTP/1.1\r\nHost: h\r\n\r\n\x81\x02hi"
let result = parser.feed(
  input,
  on_request=_ => @http_parser.Stop,
  on_body=(_, _) => @http_parser.Continue,
)
let protocol_input = input[result.consumed():]
assert_eq(protocol_input, b"\x81\x02hi"[:])
```

For handoff, retain the suffix and discard or reset this HTTP parser. For an
HTTP pause, feed the suffix, possibly empty, to the same parser with continuing
callbacks; the request callback is not repeated. Pending body validation makes
the parser non-idle until resumed. `feed`, `copy`, `reset`, and `finish` reject
reentry on the same parser from one of its callbacks with `ReentrantCall`.

## Request helpers and ownership

Wire data is immutable and retainable after callbacks, later feeds, parser reset,
and EOF. Header names are normalized to lowercase; values trim only SP and HTAB.
Allowed obs-text and DEL bytes are retained even at value boundaries. Header
iteration preserves order and duplicates. Bytes may contain invalid UTF-8;
decode explicitly in the application when a particular field requires text.

| Method | Result / semantics |
| --- | --- |
| `get_case_sensitive_method()` | Original method bytes and case |
| `get_method()` | Compatibility bytes, each ORed with 32, without mutating the original |
| `get_url()` / `get_full_url()` | Target before the first `?` / complete target |
| `get_header(b"lowercase-name")` | First exact normalized-name match; `None` differs from an empty field |
| `headers()` | Iterator of normalized byte names and trimmed byte values |
| `are_identical(name, expected)` | Every occurrence equals `expected`; true when absent |
| `get_query()` | Raw bytes after `?`; `None` differs from `Some(b"")` |
| `get_query_value(key)` | First raw-key match: `None`, `Valueless`, or `Value(Bytes)` |
| `is_ancient()` | Always false; HTTP/1.0 is not accepted |

Query keys are case sensitive and **not decoded**. Values replace `+` with SP
and apply upstream's permissive percent arithmetic without validating hex digits:
`%G0` produces NUL and `%/0` produces byte `0xf0`. A truncated escape returns
`None`. Encoded UTF-8, embedded NUL, missing values, flags (`?debug`), and explicit
empty values (`?debug=`) stay distinguishable. Repeated lookup never changes
the target or other entries. This helper is not a strict percent-decoding API.

Routing metadata is supplied by the application. `set_yield` changes a flag
initially false; `set_parameters(ArrayView[Bytes])` supplies indexed parameters;
`set_parameter_offsets(Map[String, Int])` supplies case-sensitive name offsets.
`get_parameter` and `get_named_parameter` safely return `None` for absent,
negative, or out-of-range indices. Setter containers are copied, and immutable
byte values can be shared.

Assignment aliases mutable routing metadata and parser state. `Request::copy`
creates independent metadata while sharing immutable wire bytes;
`Parser::copy` independently copies the buffered head, cursor, pending metadata,
limits, algorithm, and sticky errors. `reset` discards framing and errors while
retaining configuration. Retaining a partial body view can keep its entire
immutable backing input alive; request heads own only their head storage.

## Accepted grammar and limits

This port follows the pinned upstream variant, rather than introducing a new
strict RFC parser:

- Request lines require exactly ` HTTP/1.1\r\n`. Targets start with `/`, or are
  exactly `*` for uppercase `OPTIONS`. Target bytes are visible ASCII 33..126;
  raw UTF-8, DEL, and controls are rejected. Methods use upstream's permissive
  ASCII scan, which can accept empty methods, punctuation, and DEL.
- Field names use RFC tchar, disallow empty names and whitespace before `:`.
  Values allow HTAB and bytes >=32, including obs-text and DEL. CRLF ends fields;
  bare LF, folded fields, and other controls are rejected.
- Exactly one nonempty Host is required. Its bytes cannot be below 33 or contain
  `, @ / ? #`. This is the upstream byte check, not full authority/IDNA validation.
- Presence of both Transfer-Encoding and Content-Length is an error, even when
  either value is empty. Duplicate Content-Length values must match byte-for-byte
  after trimming (`001` differs from `1`); values contain 1..18 decimal digits.
- Only the first Transfer-Encoding field controls framing. Its case-insensitive
  final seven bytes must be `chunked`; upstream also accepts `notchunked`.
  Other transfer-coding tokens are not independently validated.
- Chunk payload CRLF is strict, including split boundaries. Upstream's permissive
  size-line/extension behavior is retained: empty size means zero, some size lines
  accept bare LF, and a CRLF can finish an unclosed extension quote. Trailer lines
  are skipped with the upstream state transitions, not returned as request fields;
  bare LF at their start or inside their contents is rejected.

Default limits are **4096 bytes per complete request head** and **98 actual
fields**, matching upstream's 100-slot storage with its two reserved slots.
Both constructor limits must be positive and can be changed with
`Parser::new(max_header_bytes=..., max_headers=...)`. The byte limit includes the
request line and final blank line and is inclusive for complete heads.
Incomplete heads reaching the limit fail. The limits are deterministic per
parser and do not read upstream's environment variable.

Fixed body lengths are limited to **2^56 - 1** (`72057594037927935UL`). Chunk
payload lengths are limited to **2^56 - 3** (`72057594037927933UL`), avoiding
upstream's overflow when adding payload CRLF to a packed state register.
Trailers and bodies are streamed without allocation proportional to their size;
the parser does not impose a smaller application body or trailer-byte limit.

Wire errors, including header limits and unfinished EOF, correspond to upstream
400 Bad Request and raise a descriptive `ParseError`. They are sticky until
`reset`: later feeds emit no callbacks. `InvalidLimits` and `ReentrantCall`
describe API misuse rather than wire input. Invalid head syntax is diagnosed
when the delimiter completes, the head limit is reached, or EOF is checked;
error timing can differ from upstream's padded speculative scans.

## Explicit upstream differences

The [352 oracle fixtures](upstream_vectors_test.mbt) preserve signed-char C++
results and test these deliberate changes explicitly:

1. Input is immutable and bounded; padding and pointer lifetimes are replaced
   by retainable request data and byte-counted callback stops.
2. Header trimming preserves obs-text. Signed-char upstream builds incorrectly
   trim bytes >=128 at field ends, including Host; this port trims only SP/HTAB.
3. Valid `OPTIONS *` works at every fragment boundary; upstream rejects it when
   a read ends immediately after the asterisk.
4. Zero-length fixed bodies always emit one end event, including fragmented
   heads; upstream's fallback path can omit the event.
5. Original method, Transfer-Encoding case, and query bytes never mutate.
   Query decoding is repeatable rather than in-place/NUL-terminated.
6. Chunk sizes cannot overflow into state flags. All body callbacks honor stop,
   errors remain typed/sticky, and reset/copy/EOF have explicit safe semantics.
7. Non-ASCII methods are rejected consistently, avoiding platform-dependent
   signed `char` behavior. Safe parameter bounds use array lengths instead of
   upstream's inclusive pointer index convention.

## Backends and validation

All four backends implement the same API. Native and linear-memory `wasm` can
use bounded sixteen-byte V128 scans for header delimiters, targets, and field
values with `algorithm=Simd`. Short tails, `wasm-gc`, and `js` use scalar code.
`Auto` currently selects scalar pending a complete cross-platform benchmark
snapshot; selecting SIMD does not imply every byte uses a vector instruction.
Native builds need a platform C compiler; JavaScript tests need Node.js.
CI prepares MSVC on Windows and Node.js 24, and tests Linux, macOS ARM64, and Windows.

```text
moon check http_parser --target all --deny-warn
moon test http_parser --target all
moon test http_parser --target native --enable-coverage
moon run scripts/coverage_report.mbtx local http_parser
moon -C benchmarks test http_parser --target all
moon run scripts/benchmark.mbtx http_parser
```

Tests cover all 256 bytes in independent target/name/value predicates, vector
tails and unaligned subviews, every two-part split, one-byte streams, pipelining,
fixed/chunked payloads, extensions/trailers, duplicate framing fields, header and
56-bit size limits, EOF, retained views, independent copying/reset, routing,
queries, and reentrant/paused callbacks. The optional development oracle requires
a clean checkout at the pinned revision and a GCC/Clang-compatible C++20 compiler:

```text
moon run scripts/http_parser_oracle.mbtx <uWebSockets-checkout>
```

It writes temporary C++ code under `_build`, preserves logs, and regenerates
checked MoonBit fixtures. No C++ code is shipped or linked into the library.
See [BENCHMARK.md](BENCHMARK.md) for the bounded 24-case benchmark design and
the distinction between body-framing latency and bytes actually scanned.

## License and references

Original MoonBit contributions/modifications are MIT-licensed in [LICENSE](LICENSE).
The adapted uWebSockets work remains Apache-2.0, with its full license in
[LICENSE-APACHE](LICENSE-APACHE) and author/provenance/change notices in
[NOTICE](NOTICE). Retain all three files when redistributing; the MIT metadata
does not remove the upstream Apache obligations. Upstream is authored by
Alex Hultman, with the original attribution and years preserved.

- [HttpParser.h](https://github.com/uNetworking/uWebSockets/blob/05e6c8b55b4d28293cf23570f0f61318f8600560/src/HttpParser.h),
  [ChunkedEncoding.h](https://github.com/uNetworking/uWebSockets/blob/05e6c8b55b4d28293cf23570f0f61318f8600560/src/ChunkedEncoding.h),
  [QueryParser.h](https://github.com/uNetworking/uWebSockets/blob/05e6c8b55b4d28293cf23570f0f61318f8600560/src/QueryParser.h)
- [RFC 9112](https://www.rfc-editor.org/rfc/rfc9112.html): HTTP/1.1 message framing
- [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html): HTTP semantics and field syntax
- [MoonBit SIMD API](https://mooncakes.io/docs/moonbitlang/core/simd)
