flare -- a Mojo full networking stack in one library.

HTTP/1.1 + HTTP/2 server and client, WebSocket server and client (RFC 6455), TLS 1.2/1.3 (OpenSSL with ALPN), TCP, UDP, DNS. The HTTP server and client are version-aware: HttpServer.serve(handler) peeks the first 24 bytes of every accepted connection and dispatches HTTP/1.1 or HTTP/2 to the same handler. HttpClient.get("https://...") advertises ALPN ["h2", "http/1.1"] and switches wires from what the server picks. The application surface (Router, App[S], middleware, typed extractors, Auth, Session[T]) doesn't know which wire is talking to it.

Small FFI footprint: libc syscalls, OpenSSL for TLS, zlib + brotli for content encoding. No HTTP framework dependency.

from flare import HttpServer, Router, Request, Response, ok, SocketAddr

def hello(req: Request) raises -> Response:
    return ok("hello")

def main() raises:
    var r = Router()
    r.get("/", hello)
    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve(r^, num_workers=4)

What flare is

One reactor per worker (kqueue on macOS, epoll on Linux, opt-in io_uring on Linux >= 6.0 via FLARE_BUFRING_HANDLER=1), a Handler trait that takes plain def functions or compiled-down structs, an RFC 7230 parser exercised by 35 fuzz harnesses (8M+ runs combined, zero known crashes), and a Cancel token plumbed to handlers via CancelHandler. num_workers=1 is a single-threaded reactor; num_workers=N with N >= 2 runs N pthread workers behind per-worker SO_REUSEPORT listeners by default (matches actix_web's listener strategy and gives the highest steady-state throughput). Set FLARE_REUSEPORT_WORKERS=0 to opt into the single shared listener with EPOLLEXCLUSIVE -- trades 7-22 % req/s (handler vs static fast path) for a uniformly tighter p99.99 tail under sustained load. See docs/benchmark.md for the head-to-head numbers. Static endpoints can skip the parser entirely with serve_static(resp).

The operational core: per-request / handler / body-read deadlines, HttpServer.drain(timeout_ms) for graceful shutdown, sanitised error responses, Request.peer threaded from the accept path, zero-copy reads (RequestView[origin] + ViewHandler), streaming response primitives (Body / ChunkSource / StreamingResponse[B]), and server-side TLS (TlsAcceptor over OpenSSL).

The application layer: Router with path params, App[S] for shared state, typed extractors (PathInt / QueryInt / HeaderStr / Form / Multipart / Cookies / ...), generic middleware (Logger / RequestId / Compress / CatchPanic), Cors, FileServer with HEAD + Range, gzip + brotli content negotiation, RFC 6265 cookie jars, HMAC-SHA256 signed cookies, and typed Session[T] stores.

Architecture

flare.io       - BufReader
flare.ws       - WebSocket client + server (RFC 6455, permessage-deflate
                 with context-takeover, WS-over-h2 via RFC 8441
                 Extended CONNECT)
flare.http2    - HTTP/2 frame codec + HPACK (with table-driven Huffman
                 fast decoder) + h2c upgrade (RFC 9113 / 7541)
flare.http     - HTTP/1.1 client + reactor server + Router / App /
                 extractors + middleware (Logger / RequestId / Compress /
                 Cors / Retry / Timeout / Conditional) + FileServer +
                 forms + cookies + sessions + content-encoding + SSE
                 + template engine with {% block %} / {% extends %}
                 inheritance + sans-I/O parser sublayer under
                 flare.http.proto.*
flare.http.cache - RFC 9111 cache primitives (CacheControl directive
                 parser, CacheKey, InMemoryCacheStore)
flare.grpc     - gRPC primitives on flare.http2: LPM message framing,
                 canonical Status codes, Metadata carrier
flare.openapi  - OpenAPI 3.1 spec model + deterministic JSON emitter
flare.quic     - Sans-I/O QUIC v1 codec primitives (varint + long /
                 short packet headers); reactor + TLS + CC drive
                 ship later alongside the QUIC server
flare.h3       - Sans-I/O HTTP/3 frame codec + SETTINGS payload
flare.crypto   - HMAC-SHA256, base64url
flare.tls      - TLS 1.2/1.3 (OpenSSL, client + server, ALPN, session resumption)
flare.tcp      - TcpStream + TcpListener (IPv4 + IPv6)
flare.udp      - UdpSocket (IPv4 + IPv6)
flare.uds      - UnixListener + UnixStream (AF_UNIX sidecar IPC)
flare.dns      - getaddrinfo (dual-stack)
flare.net      - IpAddr, SocketAddr, RawSocket
flare.runtime  - Reactor (kqueue / epoll, opt-in io_uring on Linux),
                 TimerWheel, Scheduler, HandoffQueue +
                 WorkerHandoffPool, BufferPool, vectored I/O
flare.testing  - TestClient[H] (in-process handler exerciser) +
                 fork_server / kill_forked_server for integration tests
flare.utils    - POSIX FFI thunks (fork / waitpid / kill / usleep /
                 exit / getpid) the Mojo stdlib doesn't expose yet

Each layer only imports from layers below it. No circular dependencies.

HTTP requests

from flare.http import get, post

def main() raises:
    var resp = get("https://httpbin.org/get")
    print(resp.status, resp.ok()) # 200 True

    var r = post("https://httpbin.org/post", '{"hello": "flare"}')
    r.raise_for_status()
    var data = r.json()
    print(data["json"]["hello"].string_value())

post with a String body sets Content-Type: application/json automatically.

The server-side sections below build gradually: each one adds one new concept on top of the previous example.

Routing: Router

One event loop (kqueue on macOS, epoll on Linux), non-blocking sockets, a per-connection state machine, a hashed timing wheel for idle timeouts. Routes carry path parameters (:name) and methods; unknown paths return 404, known paths with the wrong method return 405 with an auto-generated Allow: header.

from flare.http import Router, Request, Response, ok, HttpServer
from flare.net import SocketAddr

def home(req: Request) raises -> Response:
    return ok("home")

def get_user(req: Request) raises -> Response:
    return ok("user " + req.param("id"))

def create_user(req: Request) raises -> Response:
    return ok("created")

def main() raises:
    var r = Router()
    r.get("/", home)
    r.get("/users/:id", get_user)
    r.post("/users", create_user)

    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve(r^)

Typed inputs: Extracted[H]

Declare the handler's extractors as the fields of a Handler struct and wrap it in Extracted[H]. The adapter reflects on the struct's field types at compile time to pull each one from the request before calling the inner serve. Parse failures become automatic 400 responses; serve is only reached when every field has a value of the right type.

from flare.http import (
    Router, Handler, Request, Response, ok, HttpServer,
    Extracted, PathInt, OptionalQueryInt, HeaderStr,
)
from flare.net import SocketAddr

@fieldwise_init
struct GetUser(Copyable, Defaultable, Handler, Movable):
    var id: PathInt["id"]
    var page: OptionalQueryInt["page"]
    var auth: HeaderStr["Authorization"]

    def __init__(out self):
        self.id = PathInt["id"]()
        self.page = OptionalQueryInt["page"]()
        self.auth = HeaderStr["Authorization"]()

    def serve(self, req: Request) raises -> Response:
        return ok("user=" + String(self.id.value))

def main() raises:
    var r = Router()
    r.get[Extracted[GetUser]]("/users/:id", Extracted[GetUser]())
    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve(r^)

The concrete PathInt / PathStr / QueryInt / HeaderStr / etc. extractors expose .value directly as the parsed primitive. The parametric Path[T: ParamParser, name] form is still public for users who want to plug in a custom ParamParser; concrete forms cover the common case. Value-constructor extractors (```PathInt["id"]`.extract(req)) are also available for use inside plain def`` handlers when the struct shape is overkill.

Static route tables: ComptimeRouter

Same routing surface as Router, but the route list is a compile-time value. Segment parsing happens at build time and the dispatch loop unrolls per route, so the runtime does zero string-compares on unknown paths.

from flare.http import (
    ComptimeRoute, ComptimeRouter, Request, Response, Method, ok, HttpServer,
)
from flare.net import SocketAddr

def home(req: Request) raises -> Response:
    return ok("home")

def get_user(req: Request) raises -> Response:
    return ok("user=" + req.param("id"))

def create_user(req: Request) raises -> Response:
    return ok("created")

comptime ROUTES: List[ComptimeRoute] = [
    ComptimeRoute(Method.GET, "/", home),
    ComptimeRoute(Method.GET, "/users/:id", get_user),
    ComptimeRoute(Method.POST, "/users", create_user),
]

def main() raises:
    var r = ComptimeRouter[ROUTES]()
    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve(r^)

Shared state and middleware: App[S]

App[S, H] bundles application-scoped state onto a handler. A wrapping middleware holds the state snapshot and decorates every response. Middleware is itself a Handler that holds another Handler, so you stack layers by nesting constructors, no callback chain to thread through.

from flare.http import App, Router, Request, Response, Handler, State, ok, HttpServer
from flare.net import SocketAddr

@fieldwise_init
struct Counters(Copyable, Movable):
    var hits: Int

def home(req: Request) raises -> Response:
    return ok("home")

@fieldwise_init
struct WithHits[Inner: Handler](Handler):
    var inner: Self.Inner
    var snapshot: State[Counters]

    def serve(self, req: Request) raises -> Response:
        var resp = self.inner.serve(req)
        resp.headers.set("X-Hits", String(self.snapshot.get().hits))
        return resp^

def main() raises:
    var router = Router()
    router.get("/", home)
    var app = App(state=Counters(hits=37), handler=router^)
    var view = app.state_view()

    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve(WithHits(inner=app^, snapshot=view^))

Scale knob: num_workers

Every server example above takes an optional num_workers. At 1 (the default) it's the single-threaded reactor. Set it to default_worker_count() and flare runs N pthread workers, each with its own reactor + timer wheel, with per-core pinning on Linux. The handler type is unchanged.

By default each worker binds its own SO_REUSEPORT listener (the kernel hashes new 4-tuples to one of N listeners; matches actix_web's listener strategy and gives the highest steady-state throughput on dev-box workloads). Export FLARE_REUSEPORT_WORKERS=0 before launch to opt back into the single shared listener with EPOLLEXCLUSIVE -- 7-22 % less req/s (handler vs static fast path) for a uniformly tighter p99.99 σ under sustained load (the kernel offers each accept event to whichever worker is currently parked in epoll_wait, so idle workers absorb spikes). See docs/benchmark.md for the head-to-head numbers and the rationale.

from flare.http import HttpServer, Router, Request, Response, ok
from flare.net import SocketAddr
from flare.runtime import default_worker_count

def hello(req: Request) raises -> Response:
    return ok("hello")

def main() raises:
    var r = Router()
    r.get("/", hello)
    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve(r^, num_workers=default_worker_count())

pin_cores=True (default) pins worker N to core N % num_cpus() on Linux and is a no-op on macOS. Upper bound on num_workers is 256.

Fixed-body endpoints: serve_static

For endpoints that always return the same bytes (health checks, TFB plaintext, single-URL microservices), precompute_response builds the full HTTP wire form at startup and HttpServer.serve_static runs a specialised reactor that skips the parser's Request-construction and handler-dispatch step entirely.

from flare.http import HttpServer, precompute_response
from flare.net import SocketAddr

def main() raises:
    var resp = precompute_response(
        status=200,
        content_type="text/plain; charset=utf-8",
        body="Hello, World!",
    )
    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve_static(resp)

Keep-alive and Connection: close wire forms are both pre-encoded; the reactor picks the right one per request from the parsed Connection header.

Comptime handler + config

For single-handler servers, serve_comptime[handler, config] specialises the reactor loop at compile time and enforces configuration invariants via Mojo comptime assert so misconfigured servers fail the build rather than the first request:

from flare.http import HttpServer, FnHandler, Request, Response, ok
from flare.http.server import ServerConfig
from flare.net import SocketAddr

def hello(req: Request) raises -> Response:
    return ok("hello")

comptime HELLO: FnHandler = FnHandler(hello)
comptime CONFIG: ServerConfig = ServerConfig(
    max_header_size=4096,
    max_body_size=64 * 1024, # must be >= max_header_size (compile time)
    max_keepalive_requests=1000,
    idle_timeout_ms=30_000,
)

def main() raises:
    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    srv.serve_comptime[HELLO, CONFIG]()

Break any invariant (e.g. max_body_size < max_header_size) and Mojo rejects the build with a pointed error. The impossible state doesn't compile, so no runtime guard is needed.

HTTP client with auth

from flare.http import HttpClient, BasicAuth, BearerAuth

def main() raises:
    var client = HttpClient("https://api.example.com", BearerAuth("tok_abc"))
    var items = client.get("/items").json()
    client.post("/items", '{"name": "new"}').raise_for_status()

HTTP/2: same client, same server, version-aware

There is no separate Http2Client / Http2Server to learn: the same :class:flare.http.HttpClient and :class:flare.http.HttpServer are HTTP-version-aware internally.

from flare.http import HttpClient

def main() raises:
    # https:// auto-negotiates via TLS+ALPN. If the server picks
    # h2 the request is driven through HTTP/2 internally; if it
    # picks http/1.1 (or doesn't speak ALPN at all) the
    # existing HTTP/1.1 wire is used. Either way you get a
    # flare.http.Response back.
    with HttpClient() as c:
        var r = c.get("https://nghttp2.org/")
        print(r.status, r.text())

    # http:// is HTTP/1.1 by default; opt into HTTP/2 cleartext
    # via prior knowledge with prefer_h2c=True:
    with HttpClient(prefer_h2c=True, base_url="http://localhost:8080") as c:
        var r = c.get("/api/users")
        r.raise_for_status()

The server side is symmetric -- one accept loop dispatches both wires per connection (preface peek for cleartext, ALPN h2 for TLS):

from flare.http import HttpServer, Request, Response, ok
from flare.net import SocketAddr

def hello(req: Request) raises -> Response:
    return ok("hi")

def main() raises:
    var srv = HttpServer.bind(SocketAddr.localhost(8080))
    # The same handler is dispatched whether the client speaks
    # HTTP/1.1 or HTTP/2 over the same port.
    srv.serve(hello, num_workers=4)

WebSocket

from flare.ws import WsClient

def main() raises:
    with WsClient.connect("ws://echo.websocket.events") as ws:
        ws.send_text("hello")
        var msg = ws.recv_message()
        if msg.is_text:
            print(msg.as_text())

Cookies

from flare.http import Cookie, CookieJar, parse_set_cookie_header

def main() raises:
    var jar = CookieJar()
    jar.set(Cookie("session", "abc123", secure=True, http_only=True))
    print(jar.to_request_header()) # session=abc123

    var c = parse_set_cookie_header("id=42; Path=/; Max-Age=3600")
    print(c.name, c.value, c.max_age) # id 42 3600

Low-level API

IP addresses and DNS

from flare.net import IpAddr, SocketAddr
from flare.dns import resolve

def main() raises:
    var ip = IpAddr.parse("192.168.1.100")
    print(ip.is_private()) # True

    var addr = SocketAddr.parse("[::1]:8080")
    print(addr.ip.is_v6(), addr.port) # True 8080

    var addrs = resolve("example.com") # returns both IPv4 and IPv6
    print(addrs[0])

TCP

from flare.tcp import TcpStream

def main() raises:
    var conn = TcpStream.connect("localhost", 8080)
    _ = conn.write("Hello\\n".as_bytes())

    var buf = List[UInt8](capacity=4096)
    buf.resize(4096, 0)
    var n = conn.read(buf.unsafe_ptr(), len(buf))
    conn.close()

TLS

from flare.tls import TlsStream, TlsConfig

def main() raises:
    var tls = TlsStream.connect("example.com", 443, TlsConfig())
    _ = tls.write("GET / HTTP/1.0\\r\\nHost: example.com\\r\\n\\r\\n".as_bytes())
    tls.close()

WebSocket frames

from flare.ws import WsClient, WsFrame

def main() raises:
    var ws = WsClient.connect("ws://echo.websocket.events")
    ws.send_text("ping")
    var frame = ws.recv()
    print(frame.text_payload())
    ws.close()

Reactor (advanced)

from flare.runtime import Reactor, Event, INTEREST_READ

def main() raises:
    var r = Reactor()
    # Register a non-blocking fd; see ``Reactor`` docs for a full example.

Public API

struct IoError Generic I/O failure not covered by the more specific :class:`flare.net.NetworkError` family.
struct ValidationError Generic input / argument-validation failure.
struct AuthError Typed error raised by the ``Authorization`` header parsers in this module (``parse_bearer_token``, ``parse_basic_credentials``, ``_b64_decode``).
struct ProxyParseError Typed parse error raised by :func:`parse_proxy_v1` / :func:`parse_proxy_v2` / :func:`parse_proxy_protocol`.
struct Template Compiled template ready to render against a :class:`TemplateContext`.
struct TemplateContext Variable bag for :func:`Template.render`.
struct TemplateError Typed error raised by :func:`Template.compile` / :func:`Template.render`.
struct SseChannel An in-memory FIFO of :class:`SseEvent` values + a closed flag.
struct SseEvent A single Server-Sent Event.
struct SseStreamingResponse A streaming-body :class:`Response` analogue for an open-ended SSE channel.
fn format_sse_event Serialise ``event`` to its on-wire byte representation.
fn sse_response Build a :class:`Response` whose body is a one-shot snapshot of every event currently buffered in ``channel``.
struct IpAddr An IP address: either IPv4 or IPv6.
struct SocketAddr A socket address: an IP address combined with a port number.
struct HttpServer A blocking HTTP/1.1 server with buffered reads and keep-alive support.
struct ServerConfig Configuration for the HTTP server.
struct ShutdownReport Result of a graceful shutdown via ``HttpServer.drain`` or ``Scheduler.drain``.
fn ok Create a 200 OK response with optional text body.
fn ok_json Create a 200 OK response with a JSON body.
fn ok_json_value Create a 200 OK response from a typed :class:`json.Value`.
fn bad_request Create a 400 Bad Request response.
fn not_found Create a 404 Not Found response.
fn internal_error Create a 500 Internal Server Error response.
fn redirect Create a redirect response (302 Found by default).
struct Request An HTTP/1.1 request.
struct Method HTTP request method string constants (RFC 7231 §4).
struct Response An HTTP/1.1 response.
struct Status Common HTTP status code constants (RFC 7231 §6).
struct ResponsePool Stack of recycled ``Response`` objects for keep-alive reuse.
struct MethodIntern Interned ``StaticString`` constants for the 9 RFC 7231 method names.
struct ValueIntern Interned ``StaticString`` constants for header values that show up on virtually every HTTP response.
fn intern_method_bytes Return the interned method name as ``Optional[String]`` if ``slice`` exactly matches one of the 9 RFC 7231 methods, otherwise ``None``.
fn intern_method_string ``String``-typed convenience wrapper around :func:`intern_method_bytes`.
fn intern_common_value Return the interned header value as ``Optional[String]`` if ``slice`` matches one of the well-known content-type / content-encoding / connection / version values, otherwise ``None``.
fn intern_common_value_string ``String``-typed convenience wrapper around :func:`intern_common_value`.
struct StandardHeader Stable comptime indices for the 70 standard HTTP header names.
fn standard_header_count Return the number of standard headers in the lookup table.
fn standard_header_name Return the canonical lowercase name for a standard header index, or an empty ``StaticString`` for out-of-range.
fn lookup_standard_header_bytes Return the standard-header index (0..N-1) if ``slice`` case-insensitively matches a known RFC 7230 / 7231 / 7232 / 7233 / 7234 / 7235 / 9110 / 6265 / CORS / WebSocket header name; -1 otherwise.
fn lookup_standard_header_string ``String``-typed convenience wrapper around :func:`lookup_standard_header_bytes`.
fn is_standard_header Boolean shorthand: ``True`` iff the slice case-insensitively matches a standard header name.
struct HuffmanError RFC 7541 §5.2 / §C-conformant decode failures.
fn huffman_encode Append the Huffman-encoded form of ``input`` to ``output``.
fn huffman_decode Append the Huffman-decoded form of ``input`` to ``output``.
fn huffman_encoded_length Return the byte length of the Huffman-encoded form of ``input``.
fn huffman_decoded_length Return an upper bound on the decoded byte length.
struct HttpParseError Typed error for byte-level parser primitives in this module.
fn simd_memmem Return the byte-offset of the first occurrence of ``needle`` in ``haystack``, or -1 on no match.
fn simd_percent_decode Append the RFC 3986 §2.1 percent-decoded form of ``input`` to ``output``.
fn simd_cookie_scan Append the byte offsets of every ``;`` in ``input`` to ``offsets``.
trait Handler The request-to-response contract every flare endpoint satisfies.
trait HandlerInfallible A :trait:`Handler` whose ``serve`` is provably infallible.
struct WithRaises Adapt a :trait:`HandlerInfallible` so it fits the regular :trait:`Handler` constraint.
struct FnHandler Adapts a plain ``def(Request) raises -> Response`` into a ``Handler``.
struct FnHandlerCT Comptime-parametric adapter: the wrapped function is a type parameter, not a runtime field.
trait CancelHandler A request-to-response contract that takes a ``Cancel`` token.
struct WithCancel Adapter that lets a plain ``Handler`` plug into the cancel-aware reactor path.
trait ViewHandler Borrowed-input request-to-response contract.
struct WithViewCancel Adapter that lets a plain ``Handler`` plug into the view-aware reactor path.
struct Router HTTP router with method dispatch, path parameters, and nesting.
struct App An application: a handler plus application-scoped state.
struct State A read-only view onto application state of type ``T``.
struct HttpClient A blocking HTTP/1.1 client.
fn get Perform a one-shot HTTP GET request.
fn post Perform a one-shot HTTP POST with a JSON string body.
fn put Perform a one-shot HTTP PUT with a JSON string body.
fn patch Perform a one-shot HTTP PATCH with a JSON string body.
fn delete Perform a one-shot HTTP DELETE request.
fn head Perform a one-shot HTTP HEAD request.
trait Auth Authentication strategy that sets one or more request headers.
struct BasicAuth HTTP Basic authentication (RFC 7617).
struct BearerAuth HTTP Bearer token authentication (RFC 6750).
fn default_worker_count Sensible default worker count: ``num_cpus()``.
struct TlsAcceptor Server-side TLS acceptor.
struct TlsServerConfig Server-side TLS policy.
struct TlsInfo Per-request TLS metadata threaded onto ``Request`` via ``Request.tls_info``.
struct TlsServerError Generic server-side TLS failure (handshake, cert load, etc.).
struct TlsServerNotImplemented Marker raised by the API-surface scaffolding to signal that the reactor-side handshake state machine has not landed yet. Distinct type so callers can match on it for graceful degradation while the implementation is in flight.
const TLS_PROTOCOL_TLS12
const TLS_PROTOCOL_TLS13
struct Cancel A handle to a per-request cancel cell owned by the reactor.
struct CancelCell Heap-allocated per-connection cancel cell.
struct CancelReason Reason the cancel cell was flipped.
struct HeaderMap An ordered, case-insensitive HTTP header collection.
struct HeaderInjectionError Raised when a header key or value contains CR or LF bytes.
struct HeaderMapView Borrowed header collection.
fn parse_header_view Parse CRLF-separated header lines into a ``HeaderMapView``.
struct RequestView Borrowed HTTP request.
fn parse_request_view Parse an HTTP/1.1 request from a byte buffer into a ``RequestView`` borrowing into the buffer.
trait Body An HTTP response body.
trait ChunkSource A source of byte chunks.
struct InlineBody Single-shot body — the prior ``List[UInt8]`` shape packaged as a ``Body`` impl.
struct ChunkedBody Adapts a ``ChunkSource`` to the ``Body`` trait.
fn drain_body Pull every chunk from ``body`` and concatenate into a single ``List[UInt8]``.
struct StreamingResponse An HTTP/1.1 response whose body is produced incrementally.
fn serialize_streaming_response Render ``resp`` to wire bytes — status line + headers + body (Content-Length or chunked framing).
struct Url A parsed HTTP/HTTPS URL.
struct UrlParseError Raised when a URL string cannot be parsed.
struct ComptimeRoute A comptime-known ``(method, pattern, handler)`` triple.
struct ComptimeRouter A ``Handler`` whose route table is comptime-parametric.
trait ParamParser Parse a URL / header string into a concrete value.
struct ParamInt ``Int`` parameter parser. Accepts optional leading ``-``.
struct ParamFloat64 ``Float64`` parameter parser. Accepts decimal and exponent forms.
struct ParamBool ``Bool`` parameter parser. Accepts ``true`` / ``false`` / ``1`` / ``0`` / ``yes`` / ``no`` (case-insensitive).
struct ParamString ``String`` parameter parser. Always succeeds on UTF-8 input.
trait Extractor Anything that can extract itself from a ``Request`` in place.
struct Path Required path parameter named ``name``, parsed into ``T``.
struct Query Required query-string parameter named ``name``, parsed into ``T``.
struct OptionalQuery Optional query-string parameter. ``value`` is ``None`` when absent.
struct Header Required header named ``name``, parsed into ``T``.
struct OptionalHeader Optional header. ``value`` is ``None`` when absent.
struct PathInt Required path parameter named ``name``, parsed as ``Int``.
struct PathStr Required path parameter named ``name``, exposed as ``String``.
struct PathFloat Required path parameter named ``name``, parsed as ``Float64``.
struct PathBool Required path parameter named ``name``, parsed as ``Bool``.
struct QueryInt Required query-string parameter named ``name``, parsed as ``Int``.
struct QueryStr Required query-string parameter named ``name``, exposed as ``String``.
struct QueryFloat Required query parameter named ``name``, parsed as ``Float64``.
struct QueryBool Required query parameter named ``name``, parsed as ``Bool``.
struct OptionalQueryInt Optional query parameter as ``Optional[Int]``. ``value`` is ``None`` when absent.
struct OptionalQueryStr Optional query parameter as ``Optional[String]``.
struct OptionalQueryFloat Optional query parameter as ``Optional[Float64]``.
struct OptionalQueryBool Optional query parameter as ``Optional[Bool]``.
struct HeaderInt Required header named ``name``, parsed as ``Int``.
struct HeaderStr Required header named ``name``, exposed as ``String``.
struct HeaderFloat Required header named ``name``, parsed as ``Float64``.
struct HeaderBool Required header named ``name``, parsed as ``Bool``.
struct OptionalHeaderInt Optional header as ``Optional[Int]``.
struct OptionalHeaderStr Optional header as ``Optional[String]``.
struct OptionalHeaderFloat Optional header as ``Optional[Float64]``.
struct OptionalHeaderBool Optional header as ``Optional[Bool]``.
struct Peer Kernel-reported peer ``SocketAddr`` of the connection.
struct BodyBytes Extracts the raw request body as ``List[UInt8]``.
struct BodyText Extracts the request body decoded as a UTF-8 ``String``.
struct Json Extracts the request body as a parsed ``json.Value``.
struct Cookies Extracts the request cookies as a ``CookieJar``.
struct Form Extracts the request body as ``application/x-www-form-urlencoded``.
struct Multipart Extracts the request body as ``multipart/form-data`` (RFC 7578).
struct Extracted Reflective auto-injection adapter: ``H``'s fields are its extractor set.
struct FormData A name → value(s) multimap, in insertion order.
fn parse_form_urlencoded Parse ``application/x-www-form-urlencoded`` bytes into a ``FormData``.
fn urldecode Percent-decode ``s`` and convert ``+`` to space.
fn urlencode Percent-encode ``s`` for use in form bodies / query strings.
struct MultipartPart A single part inside a ``multipart/form-data`` body.
struct MultipartForm All parts of a parsed ``multipart/form-data`` body in receive order.
fn parse_multipart_form_data Parse a buffered multipart/form-data body.
struct CookieSessionStore Stateless store: the entire session is encoded into the signed cookie. Suitable for small payloads (< 4 KiB).
struct InMemorySessionStore Server-side session table keyed by signed session id.
struct Session A typed session payload, carried in either a signed cookie or an in-memory store.
trait SessionCodec Encode / decode a typed payload to/from raw bytes.
struct StringSessionCodec The default codec: payload is just a UTF-8 string.
fn signed_cookie_decode Decode + verify a signed cookie under one key.
fn signed_cookie_decode_keys Decode a signed cookie under any of ``keys`` (key rotation).
fn signed_cookie_encode Encode ``payload`` into a ``"<b64>.<b64>"`` signed cookie value.
struct Encoding HTTP ``Content-Encoding`` / ``Accept-Encoding`` token constants.
fn compress_gzip Compress bytes using gzip via zlib.
fn compress_brotli Compress bytes using brotli via ``libflare_brotli``.
fn decompress_gzip Decompress a gzip-encoded buffer using zlib.
fn decompress_deflate Decompress a deflate-encoded buffer using zlib.
fn decompress_brotli Decompress brotli-encoded bytes.
fn decode_content Decode ``data`` according to the ``Content-Encoding`` header value.
struct CatchPanic Convert any ``raise`` from the inner handler into a 500.
struct Compress Negotiate ``Content-Encoding`` per RFC 9110 paragraph 12.5.3.
struct Logger Log method, url, status, and latency around the inner handler.
struct RequestId Echo the inbound ``X-Request-Id`` header back on the response.
fn negotiate_encoding Pick the best ``Content-Encoding`` for an ``Accept-Encoding``.
struct Cors CORS middleware. Wraps ``Inner`` with the spec'd preflight + response-header machinery.
struct CorsConfig Configuration knobs for ``Cors[Inner]``.
struct ByteRange One ``Range: bytes=start-end`` request.
struct FileServer Serve files from ``root`` under the request URL path.
fn parse_range Parse a single-range ``Range`` header value.
struct HttpError Raised by ``Response.raise_for_status()`` on non-2xx responses.
struct TooManyRedirects Raised when a redirect chain exceeds the configured maximum.
struct StaticResponse A pair of pre-encoded HTTP/1.1 response buffers.
fn precompute_response Build a pre-encoded static response for a known ``(status, body)``.
struct Cookie An HTTP cookie (RFC 6265).
struct CookieJar A collection of cookies for request/response management.
struct SameSite SameSite attribute values for cookies.
fn parse_cookie_header Parse a ``Cookie`` request header value into individual cookies.
fn parse_set_cookie_header Parse a ``Set-Cookie`` response header value.
struct ExtensionOffer One comma-separated extension offer + its parameters.
struct ExtensionParameter One ``;``-separated parameter inside an :class:`ExtensionOffer`.
fn parse_extensions Parse one ``Sec-WebSocket-Extensions`` header value into its constituent offers.
fn build_permessage_deflate_offer Build the client-side ``Sec-WebSocket-Extensions`` value for a ``permessage-deflate`` offer.
fn negotiate_permessage_deflate Server-side negotiation: pick the first acceptable ``permessage-deflate`` offer.
struct HandoffPolicy Knobs for the work-stealing strategy.
struct HandoffQueue Bounded MPSC FIFO of opaque ``Int`` tokens.
struct WorkerHandoffPool One :class:`HandoffQueue` per worker, addressable by worker id.
struct DateCache Per-worker IMF-fixdate cache.
struct BufferHandle An owned byte buffer with a size-class tag.
struct BufferPool Per-worker bucketed buffer pool over four size classes.
struct IoVecBuf A heap-allocated ``struct iovec[n]`` array.
fn writev_buf Single ``writev(2)`` call with EINTR retry.
fn writev_buf_all Write every byte across every cell, advancing through the iovec array on partial writes.
struct IoUringRing Owning wrapper over an io_uring kernel ring.
struct IoUringParams Mojo mirror of the kernel ``struct io_uring_params``.
fn is_io_uring_available Runtime check: does the host kernel expose io_uring?

Networking primitives.

struct RawSocket A thin, owning wrapper around a POSIX socket file descriptor.
struct NetworkError Generic network error — a catch-all for OS errors without a more specific typed variant.
struct ConnectionRefused Raised when a TCP ``connect()`` fails with ``ECONNREFUSED``.
struct ConnectionTimeout Raised when a TCP ``connect()`` times out (``ETIMEDOUT``).
struct ConnectionReset Raised when the peer forcibly closes a connection (``ECONNRESET``).
struct AddressInUse Raised when ``bind()`` fails because the port is in use (``EADDRINUSE``).
struct AddressParseError Raised when an address string cannot be parsed.
struct BrokenPipe Raised on write to a connection whose read end is closed (``EPIPE``).
struct DnsError Raised when DNS resolution fails.
struct Timeout Raised when a blocking I/O operation exceeds its timeout.

flare.dns

fn resolve Resolve a hostname to a list of IP addresses.
fn resolve_v4 Resolve a hostname, returning only IPv4 results.
fn resolve_v6 Resolve a hostname, returning only IPv6 results.

flare.tcp

struct TcpStream A connected TCP socket.
struct TcpListener A TCP socket in the listening state.

flare.udp

struct UdpSocket A UDP socket for sending and receiving datagrams.
struct DatagramTooLarge Raised when a UDP datagram exceeds the maximum allowed payload size.

flare.uds — Unix-domain sockets

struct UnixListener A bound + listening AF_UNIX socket.
fn accept_uds_fd Accept one connection on a borrowed listener fd.
struct UnixStream A connected AF_UNIX byte stream.

flare.tls

struct TlsConfig Configuration for a TLS connection.
struct TlsVerify Peer certificate verification mode constants.
struct TlsStream An encrypted TCP stream using TLS (via OpenSSL FFI).
struct TlsHandshakeError The TLS handshake failed (generic failure not covered by cert errors).
struct CertificateExpired The server certificate has passed its ``notAfter`` date.
struct CertificateHostnameMismatch The server certificate's CN/SAN does not match the target hostname.
struct CertificateUntrusted The server certificate is not trusted by any CA in the bundle.

higher up in this file).

struct Retry Retry the inner handler on transient failure.
struct RetryPolicy Tunable retry policy.
struct Timeout Bound the inner handler's wall-clock time.

flare.ws

struct WsClient A WebSocket client connection established via HTTP Upgrade.
struct WsHandshakeError Raised when the WebSocket opening handshake fails.
struct WsMessage A high-level WebSocket message (Text or Binary).
struct WsServer A WebSocket server that upgrades incoming HTTP connections.
struct WsFrame A single WebSocket frame.
struct WsOpcode WebSocket opcode byte constants (RFC 6455 §5.2).
struct WsCloseCode WebSocket close status code constants (RFC 6455 §7.4.1).
struct WsProtocolError Raised when an incoming frame violates RFC 6455.
struct WsOverH2Stream Stream-keyed adapter that turns an h2 stream into a WS tunnel.
fn bootstrap_ws_over_h2 Open an Extended CONNECT stream for a WebSocket tunnel.
struct PermessageDeflateConfig Per-side knobs for the permessage-deflate extension.
struct PermessageDeflateContext Persistent compressor + decompressor for permessage-deflate with **context-takeover** (RFC 7692 §7.1).
fn compress_message Compress one WebSocket message per RFC 7692 §7.2.1.
fn decompress_message Decompress one WebSocket message per RFC 7692 §7.2.2.

flare.io

trait Readable A byte stream that can be read into a mutable buffer.
struct BufReader A buffered byte reader wrapping any ``Readable`` stream.

flare.runtime (advanced / custom protocols)

struct Reactor An OS-event-loop handle with a uniform API over epoll and kqueue.
struct TimerWheel Fixed-size hashed timing wheel with an overflow list.
struct Event A readiness event for a single registered fd.
const INTEREST_READ
const INTEREST_WRITE
const EVENT_READABLE
const EVENT_WRITABLE
const EVENT_ERROR
const EVENT_HUP
const WAKEUP_TOKEN