# HTTP & Client Overview

For routed synchronous HTTP/1-only services, `App<{HTTP_V1}>.new()` selects a
compile-time capability profile. `App` and its `Group` values retain one exact
const-generic mask while H2, WebSocket, async-route and streaming execution
engines are excluded from the emitted program. Capabilities can be composed,
for example `App<{HTTP_V1 | WEBSOCKET}>`; unsupported registrations fail at
compile time. The specialized listener applies to `HTTP_V1`;
other valid masks use the full worker kernel. Plain `App.new()` remains the
`HTTP_FULL` compatibility default. The choice adds no per-request runtime
feature branch. See
[Fiber Framework](fiber.md#compile-time-http-1-profile).

The `http` package provides Vex-native HTTP parsers, client/server foundations,
and the `http/fiber` application framework. Its API direction takes inspiration
from modern Go/Rust libraries and Fiber v3, while ownership, arenas, scheduling,
and hardware acceleration remain native Vex mechanisms.

Fiber serves HTTP/1 routes and WebSocket upgrades with bounded connection
queues and explicit lifecycle hooks. Its HTTP/2 transport uses cleartext
prior knowledge for synchronous buffered routes, async buffered routes and
bounded response streams. TLS ALPN, HTTP/2 request-body streaming and
WebSocket-over-H2 are separate capabilities and are not exposed by those lanes.
HTTP/3/QUIC is outside this package's serving surface.

<a id="development-capability-map"></a>

## Serving capability map

| Feature | HTTP/1 | Cleartext prior-knowledge HTTP/2 |
| --- | --- | --- |
| Synchronous buffered route | Routed application handlers | Routed application handlers |
| Async buffered request route | Async route lane | Async route lane |
| Bounded streaming response | Response-stream lane | Response-stream lane |
| Streaming request body | Separate body-stream lane | Not exposed through the live route lane |
| Static files / `sendFile` | Descriptor-based bounded streaming | No dedicated file-send contract in this overview; use the documented response lane |
| WebSocket | HTTP/1 upgrade path | WebSocket-over-H2 is not exposed |

Use [Fiber](fiber.md) for application registration,
[HTTP/2](h2.md) for connection/stream ownership, and
[Middleware](middleware.md) for request composition.

## Key Capabilities

1. **Fiber Framework Layer**: `App`, `Ctx`, and `Router` provide routing, including `:param` and `*wildcard` patterns.
2. **Borrowed parser fields**: Request paths, queries and header fields use `str` views into retained input bytes. The input owner must remain live while those views are used; they are not direct socket-backed spans. Fragmented input and owning application state can require retained storage or copies.
3. **WebSockets (`http/ws`)**: Fiber-integrated HTTP/1 RFC 6455 upgrade with
   worker-owned bounded queues, strict framing, lifecycle hooks, non-blocking
   partial I/O, bounded route-level subprotocol selection and idle timeout
   ownership. Upgrade/frame handoff preserves the connection's input and
   request-arena lifetime through protocol callbacks and close drain.
4. **HTTP/2 (`http/parser`, `http/fiber`)**: Cleartext prior-knowledge serving
   has synchronous buffered, async buffered and bounded response-stream paths
   through the shared application boundary. See [HTTP/2](h2.md) for the
   protocol owner, flow control and limits.
5. **Middlewares**: Composable request handlers for logging and CORS. Static
   serving is a first-class `App.static` / `Group.static` route, not a duplicate
   middleware path.

<a id="http-1-implementation-and-test-coverage"></a>

## HTTP/1 framing and resource ownership

The server coordinates parser, connection and worker state through these
boundaries:

- strict request framing rejects ambiguous length/transfer-encoding forms;
- bounded incremental fixed-length and chunked bodies;
- fragmented chunks and trailers with exact consumed/decoded progress;
- preserved HTTP/1 pipelining suffixes and keep-alive ordering;
- frozen immutable routing with worker-local request scratch;
- route-local middleware is held once in a startup-owned flat router pool;
  frozen radix nodes retain route identity only, avoiding per-route middleware
  allocation/copy and duplicate handler ownership;
- explicit native-handle ownership transfer in multi-worker servers;
- request arenas reset handler temporaries without owning persistent connection
  state;
- monotonic absolute HTTP/1 read deadlines resist slowloris drip-feeding;
- idle peers are retired by bounded worker maintenance ticks;
- response drains are bounded across partial writes and socket backpressure;
- one shared `AppConfig.maxConnections` budget sheds excess accepted peers before
  parser/state allocation and reclaims capacity on exact descriptor ownership;
- response serialization uses reusable one-pass storage with zero allocations
  after warmup on the verified common path.
- fixed-width `Mask<16>` SIMD delimiter scans avoid dynamic-mask allocation in
  the HTTP/1 parser hot path; request/response correctness does not depend on
  a C or Rust parser implementation.
- the live Fiber and canonical request parsers agree on exact HTTP version,
  request-target, framing, and `Connection` token rules; those shared security
  boundaries are regression-tested rather than inferred from one parser alone.
- Fragmented `Content-Length` and chunked request bodies share one incremental
  body state, so slow uploads retain their header once rather than repeatedly
  copying the complete partial request.
- Fiber appends responses directly into connection-owned reusable storage;
  `Response.appendEncodedTo(out)` exposes the same caller-owned batching
  contract for advanced servers without raw socket manipulation. Its
  `AppConfig.responseBatchBytes` high-water mark drains long pipelined bursts
  before aggregate response storage can grow with the peer's request queue;
  exceptional response buffers are released after drain rather than retained
  for the entire keep-alive connection.
- `App.listenWithContext` provides context-native cancellation, descriptor
  cleanup, worker joining, and same-port restart safety.
- `App.static` and `Group.static` check traversal and canonicalize the root and
  candidate before a separate open. Candidates outside the root are rejected
  at check time; concurrent path changes can invalidate that check. Keep the
  served tree writable only by trusted actors.
- Known-length static and `Ctx.sendFile` responses are framed in order and
  streamed from their opened descriptor through Fiber's reusable 64 KiB worker
  scratch buffer, rather than being materialized as response-sized strings.
- Dynamic HTTP/1 responses use `App.getStream` / `postStream` and a bounded
  `ResponseStreamWriter`: canonical chunk framing, terminal signaling and a
  single full-response deadline remain Fiber-owned. Stream routes preserve the
  normal frozen router and middleware chain, while prior pipelined replies
  drain before a producer starts.
- Response framing has one authority: `HEAD` reports the equivalent `GET`
  length without sending bytes, while `1xx`, `204`, `205`, and `304` never
  carry content. Application headers cannot inject a competing
  `Content-Length`, `Transfer-Encoding`, or `Connection` field.

See [Fiber Framework](fiber.md) for route registration, application
configuration and the live server model.

---

## HTTP Client

The outbound HTTP/1 client is a bounded async exchange over an already-resolved
`SocketAddr`. A request carries its HTTP authority; the endpoint carries its
TCP peer. This prevents a blocking DNS operation from being accidentally hidden
inside a scheduler task.

```vex
import { ClientRequest } from "http";
import { Context } from "context";
import { IpAddr, Ipv4Addr, SocketAddr } from "net";
import { Duration } from "time";

let endpoint = SocketAddr(IpAddr.V4(Ipv4Addr.loopback()), 8080);
let context = Context.background().withTimeout(Duration.seconds(2));
let request = ClientRequest.new("GET", "service.example", "/health");
let response = await request.send(endpoint, &context)?;
```

The encoder owns `Host`, `Content-Length`, and `Connection`. Stateless client
calls use `Connection: close`; an explicit caller-owned `HttpSession` uses
`keep-alive` only after a proven response boundary. The client uses one
canonical framing decision shared with the parser: a single
`Content-Length`, exact `Transfer-Encoding: chunked`, or close-delimited body.
Ambiguous framing and configured-size violations are errors. There is no
implicit shared pool.

Redirects are equally explicit. `sendFollowing` accepts a finite
`HttpRedirectPolicy` and reuses the caller-resolved endpoint only for
same-origin hops. `sendFollowingResolved` requires an async
`HttpRedirectResolver` before any cross-origin connection and strips
authorization/cookie credentials at that boundary. RFC 3986 relative
resolution, method/body replay rules, unsupported schemes and limit failures
are documented and tested; ordinary `send` still means exactly one exchange.

Owning responses can opt into pure-Vex `br`, `zstd`, `gzip`, and `deflate`
decoding with `acceptCompressed` plus `decodeContent`. Transferred and decoded
byte ceilings are independent, coding chains are bounded and reversed
strictly, and failure leaves the raw response unchanged. Streamed decoding is
not emulated with hidden whole-body buffering.

Interim responses have an explicit count bound. Upgrade and successful
`CONNECT` responses are rejected until a public API can transfer sole stream
ownership. `HEAD`, `204`, `205`, and `304` follow their bodyless response
semantics; `205` may consume only a provably empty framed body.

Chunked responses are safe across arbitrary TCP read boundaries: an incomplete
chunk-size line, data CRLF, or trailer is retained in a small bounded framing
buffer, while already-decoded payload goes directly to the selected response
destination. This applies equally to buffered `send` and `sendInto`.

The client already routes its request/response I/O through the shared,
context-required `io::AsyncReader` / `AsyncWriter` boundary. This preserves
cancellation and backpressure semantics today while reserving one adapter seam
for TLS and streaming bodies; it is not a claim of pooling or upgrade support.

See [HTTP Client](client.md) for limits, cancellation behavior, supported
surface, and deliberate current boundaries.
