mttp

    HTTP for MoonBit apps that outgrow the built-in client: the module an app starts with, holding a ready client (retries with a budget, deadlines, redirects, cookies, decompression) and a server, on moonbitlang/core/async for native, wasm and js. Typed endpoints and OpenAPI come from gaato/mttp_core, which libraries depend on instead.

    http
    client
    server
    retry
    sse
    async
    Download zip
    Author
    Version
    0.5.2
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    1K

    #gaato/mttp

    An HTTP client and server for MoonBit apps on native, wasm (under moonrun) and JavaScript hosts.

    • Client. client() retries transient failures within a budget, enforces a deadline per attempt and per call, follows redirects without downgrading to HTTP, decodes gzip, deflate, Brotli and Zstandard, and keeps cookies when given a jar. A 404 is a value in the reply; a network failure is a typed error that says in which phase it happened and whether the request was sent.
    • Server. Any async (Request) -> Response function is a handler. The server bounds connections, heads and bodies and shuts down gracefully. Static files, response compression, WebSockets, and a fetch export for Cloudflare Workers, Deno, Bun, Node and other JavaScript hosts come in the same module.
    • Tests. Swap the network for a stub and the clock for a virtual one; the client keeps every default.

    Writing a library, such as an SDK for some API, rather than an app? Depend on gaato/mttp_core instead: it has the same types and client without any I/O. Typed endpoints, the router and OpenAPI documents also live there.

    The HTTP/1 codec is checked against llhttp's tests, WebSockets against Autobahn, and the client and server against other implementations such as nginx, curl, Go and Node: how it is checked.

    #Install

    moon add gaato/mttp

    Then import "gaato/mttp" in the moon.pkg of the package that uses it.

    #Call an API

    ///|
    #derive(FromJson)
    struct User {
    name : String
    }

    ///|
    /// Prints a user's name, the HTTP failure, or the network failure.
    pub async fn show_user(id : Int32) -> Unit {
    let api = @mttp.client(base_url="https://api.example.com")
    defer api.close()
    let request = @mttp.get("/users/\{id}").response(@mttp.as_json())
    let reply = api.send(request) catch {
    error => {
    println("network: \{error}")
    return
    }
    }
    let user : Result[User, _] = reply.body
    match user {
    Ok(user) => println(user.name)
    Err(failure) => println("HTTP \{reply.status}: \{failure}")
    }
    }

    An executable starts it with run, which needs no import of moonbitlang/core/async and no experimental opt-in in moon.pkg:

    ///|
    fn main {
    @mttp.run(async fn() { show_user(1) })
    }

    Reuse one Client for many calls: it pools connections and shares the retry budget. Close it when done.

    get, post and request build a request; .header, .bearer, .body_json and .body_bytes add to it. For other methods, pass a Request to request:

    ///|
    /// Renames a user with PATCH; true when the server answered 2xx.
    pub async fn rename_user(
    api : @mttp.Client,
    id : Int32,
    name : String,
    token : String,
    ) -> Bool {
    let request = @mttp.request(@mttp.Request::patch("/users/\{id}"))
    .bearer(token)
    .body_json({ "name": name })
    api.send(request).body is Ok(_)
    }

    .response chooses how the reply is read: as_string (the default), as_bytes, as_json, as_json_value, or, without buffering, as_lines for each line and as_sse for server-sent events. With every one of them, a final status outside 2xx is Err(UnexpectedStatus(..)) in reply.body, and JSON that does not decode is Err(Deserialization(..)); both carry the response head and an excerpt of the body. Network failures, expired deadlines, refused redirects and bodies over the limit are raised by send as a TransportError(kind~, phase~, detail~); its is_unsent() is true only when the request provably never reached the server.

    api.sse_reconnecting(@mttp.Request::get(url), on_event) reconnects an event stream when it drops and resumes from its last event ID. To read a large body in chunks, as_stream comes from gaato/mttp_core/client.

    #What client() does by default

    DefaultChange it with
    RetriesUp to two. For GET, PUT, DELETE and other idempotent requests: on 408, 409, 429, 500, 502, 503 and 504 and on network failures. For any request, POST included: when it was never sent. Retry-After is honoured, and a server that asks to wait more than 60 s is not retried. Otherwise the wait starts at 500 ms and doubles, with jitterretry=@mttp.RetryPolicy::none(), or a policy of your own
    Retry budgetRetries stay within 20 % of the requests of the last 10 s, plus 10 per second, so a failing server is not floodedretry_budget=@mttp.RetryBudget::new(..) or @mttp.RetryBudget::unlimited()
    Deadlines30 s for each attempt, 120 s for the whole call, retries and their waits includedtimeout_ms=, total_ms=, or .timeout_ms(..) on one request
    RedirectsUp to 10 hops, never from HTTPS to HTTP. Authorization, Proxy-Authorization and Cookie are dropped when the origin changes, except from http on port 80 to https on port 443 of the same hostredirect=@mttp.RedirectConfig::none(), or .follow_redirects(false) on one request
    CookiesNone keptcookies=@mttp.CookieJar::new(@mttp.clock()); the jar belongs to the caller and can be shared between Clients
    Decompressiongzip, deflate, br and zstd on native and wasmOn native and wasm, a request that sets Accept-Encoding gets its body as sent
    Body sizeBuffered bodies up to 64 MiB after decodingmax_body_bytes=, or .max_body_bytes(..) on one request
    Proxieshttp_proxy, https_proxy, all_proxy and no_proxy from the environment, on native and wasm; http://, https:// and socks5h:// proxiesconfig= a ClientConfig from gaato/mttp_core/h1client
    TLS rootsThe system'strust=PemFile("roots.pem")
    AdmissionEvery request at oncelimiter= a RateLimiter from gaato/mttp_core/client
    ObservationNoneobserver= gets one Attempt per attempt; events= gets every ClientEvent: attempts, connection phases, redirects and retries
    Network and timeThe real network, clock and timersbackend=, clock=, timer= (see Tests)

    A type from a gaato/mttp_core/... package needs moon add gaato/mttp_core as well.

    On JavaScript the client sends through the host's fetch, which chooses the protocol, pooling, proxies, decompression and TLS roots itself. The Client still applies its retries, deadlines, redirects and cookie jar, but a browser's fetch hides redirect responses, which the Client then raises as an error, and may hide Set-Cookie.

    Client::new, which builds a Client over a backend you supply, starts with no retries and no deadlines; redirects, the retry budget and the 64 MiB limit still apply.

    #Serve

    A handler is an async (Request) -> Response noraise function. The request carries meth, url and headers as fields. Its body arrives as a stream; read_all(max~) returns the bytes exactly as sent and refuses more than max. Import "gaato/mttp/server" to listen on native or wasm:

    ///|
    /// Echoes a request body of up to 64 KiB with its content type; a larger
    /// body gets 413.
    pub async fn echo(request : @mttp.Request) -> @mttp.Response noraise {
    let body = request.body.read_all(max=65536) catch {
    TransportError(kind=TooLarge(..), ..) => return @mttp.Response::new(413)
    _ => return @mttp.Response::new(400)
    }
    let content_type = request.headers
    .get("content-type")
    .unwrap_or("application/octet-stream")
    @mttp.Response::new(
    200,
    headers=@mttp.Headers::of([("content-type", content_type)]),
    body=Bytes(body),
    )
    }

    ///|
    pub async fn serve_echo() -> Unit {
    @server.serve(echo, addr="127.0.0.1:8080", on_listen=addr => {
    println("listening on \{addr}")
    })
    }

    The server also sets attributes on each request: request.attributes.get(@mttp.remote_addr) is the client's address, and @mttp.background schedules work that may outlive the response.

    By default the server takes 256 connections at once, request heads up to 16 KiB and bodies up to 1 MiB, and gives a client 5 s to send a head and 5 s for a body. When its task is cancelled it stops accepting, lets running responses finish for up to 10 s, then cancels them. limits= takes a ServerLimits from gaato/mttp_core/h1server (add gaato/mttp_core to use it).

    The other packages of the module serve and connect in more ways:

    PackageTargetsWhat it adds
    gaato/mttp/filesnative, wasmstatic_files(dir): a directory as a handler, with ETags and 304s; hidden files and paths outside the directory are 404s; ranges=true answers single byte ranges
    gaato/mttp/codingsnative, wasm, jscompress(handler) negotiates zstd, br, gzip or deflate for responses; CompressRequests compresses request bodies; RFC 9842 compression dictionaries for both ends
    gaato/mttp/wsnative, wasm, jsWebSocket connect and upgrade, with opt-in permessage-deflate on native and wasm
    gaato/mttp/fetchjsfetch_handler(handler): the same handler as a fetch export for Cloudflare Workers, Deno, Bun, Node, Fastly, Vercel and AWS Lambda
    gaato/mttp/runtimenative, wasm, jsVirtualClock for tests, and the clocks and timers behind clock() and timer()
    gaato/mttp/backendnative, wasm, jsAsyncBackend: the network alone, for a Client built by hand
    gaato/mttp/trustnative, wasm, jsTrust: which TLS roots a socket connection accepts
    gaato/mttp/connnative, wasmTcpDialer: TCP connections, and TLS over any connection, such as one through a CONNECT tunnel

    The JavaScript files that connect a fetch export to each host ship in the module's hosts/ directory; the host guide shows how to use them and which hosts accept WebSocket upgrades.

    #Typed endpoints

    An endpoint from gaato/mttp_core validates its input, serves requests and describes itself for OpenAPI; a Router serves a set of them as one handler. Add the second module with moon add gaato/mttp_core and import what the package uses:

    import { "gaato/mttp", "gaato/mttp/server", "gaato/mttp_core/endpoint", "gaato/mttp_core/router", "gaato/mttp_core/schema", }

    ///|
    /// GET /hello/{name} answers with a greeting.
    let hello : @endpoint.ServerEndpoint = @endpoint.endpoint
    .get("/hello/{name}")
    .input(@endpoint.path("name", @schema.string))
    .output(@endpoint.text_out())
    .serve_public(name => Ok("hello, \{name}"))

    ///|
    /// The app's endpoints, with the clock and timer a Client's deadlines need
    /// when it calls the Router in memory.
    fn hello_app() -> @router.Router {
    @router.Router::must([hello], clock=@mttp.clock(), timer=@mttp.timer())
    }

    ///|
    pub async fn serve_hello(addr : String) -> Unit {
    @server.serve(hello_app().handler(), addr~)
    }

    A Router is also a backend: @mttp.client(backend=hello_app()) calls the endpoints in memory, without a port, which suits tests. A Router built without clock and timer refuses calls that carry a deadline, as every call from client() does.

    #Tests

    Code that takes its Client as a parameter can be tested without the network. Give it a client() over BackendStub from gaato/mttp_core/testing, which answers with canned responses and records what was sent. backend= replaces only the network, so the Client keeps every default above. A plain test block runs the async code with run:

    ///|
    /// Reads a user's name; the Client is a parameter, so a test can pass a stub.
    pub async fn user_name(api : @mttp.Client, id : Int32) -> String? {
    let user = @mttp.get("/users/\{id}").response(@mttp.as_json_value())
    match api.send(user).body {
    Ok({ "name": String(name), .. }) => Some(name)
    _ => None
    }
    }

    ///|
    test "user_name reads the name from the reply" {
    let stub = @testing.BackendStub::new().when(
    request => request.url == "https://api.example/users/1",
    @testing.Canned::bytes(200, body=b"{\"name\":\"Ada\"}"),
    )
    let api = @mttp.client(base_url="https://api.example", backend=stub)
    let name : Ref[String?] = Ref(None)
    @mttp.run(async fn() { name.val = user_name(api, 1) })
    assert_eq(name.val, Some("Ada"))
    assert_eq(stub.sent().length(), 1)
    }

    Check results after run, as above: a failing assert_eq inside run ends the whole test executable, so the package's remaining tests do not run. To test retries and deadlines without waiting, also pass clock= a VirtualClock from gaato/mttp/runtime; the Client's timers then run on it. To test a handler, call it with a Request.

    #With a library built on mttp_core

    A library that takes a backend, a clock and a timer gets the real ones from @mttp.backend(), @mttp.clock() and @mttp.timer(). The library keeps its own base URL, authentication and retry rules; the backend supplies only the network.

    NeedModule
    HTTP Digest authenticationgaato/mttp_digest
    JSON codecs and schemas generated from annotated typesgaato/mttp_schemagen
    An httpx/requests-style calling surface over mttpgaato/requesto
    The compressors behind decompression and codings, for use on their owngaato/deflate, gaato/brotli, gaato/zstd

    #When something else fits better

    • One request in a script. moonbitlang/core/async/http's @http.get(url) needs no dependency. mttp is for what grows around that call; a side-by-side table and a migration guide compare the two.
    • HTTP/2 or HTTP/3. On native and wasm mttp speaks HTTP/1.1. On JavaScript the host's fetch and server choose the version.
    • 1xx responses or trailers. The client skips informational responses and does not expose trailers.
    • wasm-gc. This module has no runtime there; gaato/mttp_core builds on wasm-gc, and you supply its I/O.

    Before 1.0, a minor release may change the API; the changelog says how to update.

    #License

    Attempt

    A settled attempt, reported after releasing admission. Attempt zero is the initial send; status zero means no response head arrived.

    AttributeKey

    sttp-shared AttributeMap without Any: per-key slot plus closures.

    Attributes

    Immutable associations of typed keys to local metadata.

    Backend

    using @gaato/mttp_core { trait Backend }

    A transport for one exchange: it sends the request and returns the response head with a body the caller owns, reads to EOF or closes. HTTP statuses are responses, not errors; a failure to get one is a TransportError carrying the phase it happened in.

    A backend refuses an invalid request before any I/O (Request::validate, SendOptions::validate), moves raw bytes (no redirects, retries, cookies or content decoding), and propagates cancellation unchanged. After close, new sends fail with TransportError(Closed, Pool).

    Body

    using @gaato/mttp_core { type Body }

    A request body: bytes in memory, or a stream read as the request is sent.

    test {
    let request = @mttp_core.Request::post("/upload").body_bytes(b"abc")
    assert_eq(request.body, Bytes(b"abc"))
    assert_eq(request.body.length(), Some(3L))
    assert_true(request.body.is_replayable())
    }

    BodyStream

    A stream with nonempty chunks, sticky EOF and idempotent close.

    Client

    A backend plus shared request defaults, policies and injected timing services. Client::send is the only sending path: it applies the defaults, admission, deadlines, decoded-body limits, redirects, cookies and retries, and maps each plan onto the SendOptions the backend receives.

    ClientEvent

    What a Client built with events reports while it sends, in the order it happens. For each attempt: AttemptStart, then the backend's Phase events and a Redirect for each hop followed inside the attempt, then AttemptEnd with the same Attempt the observer gets; a Retry comes between one attempt's AttemptEnd and the next one's AttemptStart. Nothing about an attempt is reported after its AttemptEnd, including after a cancellation. The client README maps the fields onto OpenTelemetry's HTTP semantic conventions. Every event carries send_id, unique within its Client and unchanged across all retries and redirects of one logical send.

    CookieJar

    An RFC 6265bis-22 cookie store for an HTTP client: store takes the Set-Cookie headers of a response, header_for builds the Cookie header of a request.

    It is a client's jar, not a browser's: HttpOnly cookies are sent like any other, and SameSite is kept but not enforced, since a client has no notion of a cross-site request. Without the Public Suffix List it rejects only a Domain of a single label (com, localhost); pass is_public_suffix to reject more. An IP-address host only gets host-only cookies. Hosts must arrive in ASCII form, so a Domain with other characters is ignored.

    A host written with the root dot (example.com.) is a different host from example.com, as in browsers: neither sets nor receives the other's cookies. The public-suffix checks read a Domain without its root dot, so Domain=com. is refused as a single label, and a Domain with an empty label (a..b, com..) is ignored.

    test {
    let jar = @cookie.CookieJar::new(@sim.FakeClock::new())
    jar.store(
    @mttp_core.Headers::of([("Set-Cookie", "sid=1; Path=/; Secure")]),
    "https://example.com/login",
    )
    assert_eq(jar.header_for("https://example.com/"), Some("sid=1"))
    assert_eq(jar.header_for("http://example.com/"), None)
    }

    Handler

    A server-side handler. Adapters (mttp-net serve, fetch_handler) and the Router all speak this type. WebSocket Upgrade is not in v0.x; a later 101 response can carry the upgrade callback in an attribute.

    Headers

    using @gaato/mttp_core { type Headers }

    Immutable, ordered header pairs with ASCII lowercase names. Equality compares normalized pairs, including their order.

    test {
    let headers = @mttp_core.Headers::of([("Accept", "text/plain")])
    assert_eq(headers.get("ACCEPT"), Some("text/plain"))
    }

    Method

    using @gaato/mttp_core { type Method }

    Standard HTTP methods and extension tokens.

    PhaseEvent

    A point one attempt's exchange reached in its backend, for observation only (CONTRACT.md, Backend rule 13). A backend reports the points it can see, in the order below, each at most once per attempt, and never after the send returned or raised; JS fetch sees none of them and reports nothing. The cases are declared in the order they happen.

    test {
    let seen = []
    let request = @mttp_core.Request::get("http://example.test/")
    let request = {
    ..request,
    attributes: request.attributes.put(@mttp_core.on_phase, event => {
    seen.push(event)
    }),
    }
    // A backend looks the callback up and reports what it reached.
    if request.attributes.get(@mttp_core.on_phase) is Some(report) {
    report(Dialed(addr="example.test:80"))
    report(Pooled(reused=false))
    }
    assert_eq(seen, [Dialed(addr="example.test:80"), Pooled(reused=false)])
    }

    RedirectConfig

    How a Client (its redirect argument) or a FollowRedirects wrapper follows redirects. Build it from RedirectConfig::default() with a record update, or take RedirectConfig::none(); the field set is frozen.

    Reply

    A decoded response, preserving the actual HTTP and request metadata.

    Request

    using @gaato/mttp_core { type Request }

    url is the request target as given: an absolute URL or a relative reference ("/users/1?x=2"). Backends parse it once at send time (Kind::Invalid, phase Pool, so it is unsent); Client joins a relative target onto its base URL by prefix (sdk-runtime semantics, not RFC 3986).

    RequestPlan

    A wire request, response description and per-request options.

    Response

    using @gaato/mttp_core { type Response }

    One response type for both directions. A server closes the connection after a response carrying Connection: close (413 does). attributes is the response-side channel: FollowRedirects records the final URL and history there, and the router records the matched route template.

    ResponseFailure

    A received response that is not the value the description asked for. It is a value: readers return it as Err, and transport failures stay raised TransportErrors.

    ResponsePlan

    An immutable response description. Selection after the head arrives decides the actual lifetime; the marker describes possible streaming.

    RetryBudget

    A cap on retries as a share of recent requests, shared by every send of a Client. When a server fails, every caller's retries would otherwise multiply its load just as it tries to recover.

    Each request deposits one token; each retry withdraws one. A retry goes ahead while the withdrawals of the last window_ms stay below min_per_second times the window in seconds plus percent of the deposits in the window. Time comes from the Client's clock. Pass the same budget to several Clients to share it.

    RetryPolicy

    A retry policy for Client: a RetryRule of gaato/mttp_core/client/retry applied to HTTP outcome snapshots.

    Start from a preset — conservative() (the default), none() — or from any rule with from_rule, and adjust it with with_max_retries, allow_non_idempotent or a struct update of rule.

    SendOptions

    The per-send settings a caller hands a Backend. Build them from SendOptions::default() with a record update; the field set is frozen.

    StreamBody

    A request body read once from a BodyStream, with its length when known.

    A transport sends a known length as Content-Length and an unknown one, on HTTP/1.1, as Transfer-Encoding: chunked. The transport that sends the body takes it (take) and closes the stream when it is done with it, sent or failed; a stream that is never taken stays open and is its creator's to close. Two stream bodies are equal only when they are the same one.

    TransportError

    A failure with its category, phase and diagnostic description.

    Trust

    using @gaato/mttp/trust { type Trust }

    TLS peer verification for socket backends. JavaScript fetch uses the host's trust store and ignores this setting. PemFile replaces system roots; supply a combined PEM bundle to trust private and system roots.

    Url

    using @gaato/mttp_core { type Url }

    A URI reference (RFC 3986 §4.1), held normalised and percent-encoded.

    Url::parse lower-cases the scheme and host, writes an IPv6 address in RFC 5952's canonical hex form (a dotted-quad tail too, as WHATWG URL does), drops a scheme's default port (http 80, https 443, ws 80, wss 443, ftp 21), percent-encodes what the WHATWG URL Standard's sets encode (non-ASCII as UTF-8), and removes dot segments from the path of a reference with a scheme. Existing escapes are kept as written. No scheme makes the reference relative; no host means no authority, which is not an empty host. A host is ASCII only: internationalised domain names (IDNA) are refused, so pass their xn-- form.

    test {
    let base = @mttp_core.Url::parse("HTTPS://Example.COM:443/a/b?x=1")
    assert_eq(base.to_string(), "https://example.com/a/b?x=1")
    let next = base.resolve(@mttp_core.Url::parse("../c d"))
    assert_eq(next.to_string(), "https://example.com/c%20d")
    }

    UrlError

    using @gaato/mttp_core { type UrlError }

    Why a string is not a URI reference this package accepts.

    abandon_request_body

    let abandon_request_body :
    AttributeKey
    [Bool]

    Set on a response by its handler: the server will not read the rest of the request body, so the engine need not wait for it, as when a body exceeded the handler's bound. An HTTP/1.1 server ends the connection after the response (it sends Connection: close and does not drain); an HTTP/2 or HTTP/3 server would reset only the request's stream (RFC 9113, section 8.1). It replaces a handler-written Connection header, which only HTTP/1.1 has.

    as_bytes

    Buffers successful bodies; non-2xx responses are bounded failure values.

    as_lines

    Streams LF-separated UTF-8 lines, stripping CR in CRLF and replacing malformed UTF-8. A final nonempty unterminated line is delivered; a lone CR is data. Limits content bytes per line (default one MiB), retaining at most that limit plus a pending CR. Callback errors close the body and never retry an already-delivered stream.

    as_sse

    Reads bounded SSE events until EOF or a protocol stop predicate matches. An event over max_event_bytes raises TooLarge(limit) in phase Body as soon as the chunk holding it is read, after the events before it in that chunk were delivered.

    as_string

    Decodes UTF-8 lossily while preserving HTTP failures as values.

    backend

    The real network as a Backend: HTTP/1.1 over TCP and TLS with connection reuse and decompressed responses. It is only the I/O: the Client built over it follows redirects, and keeps cookies when given a jar, as Client::new does over any backend. Pass it, with clock and timer, to a library that builds its own Client, such as an API SDK:

    let claude = @anthropic.Anthropic::new(
    api_key~,
    @mttp.backend(),
    @mttp.clock(),
    timer=@mttp.timer(),
    )

    The libraries keep their own defaults (base URL, authentication, retries) and follow redirects through Client::new; this only supplies the I/O. Closing the library's Client closes the connections.

    background

    let background :
    AttributeKey
    [(async () -> Unit) -> Unit]

    Adapter-owned scheduling for work that may outlive the response. Invoke during request handling; the adapter owns completion and shutdown policy.

    client

    A Client over the real network with the defaults an API client wants:

    • retry (default RetryPolicy::conservative()): up to two retries of an idempotent request on 408, 409, 429, 500, 502, 503 or 504 or a network failure, and of any request that was never sent, honouring Retry-After (a server that asks to wait more than 60 s is not retried); set it to RetryPolicy::none() to turn retries off.
    • retry_budget (default RetryBudget::new()): retries stay within 20 % of the last 10 s of requests plus 10 per second.
    • timeout_ms (default 30 s) for each attempt, and total_ms (default 120 s) for the whole call, retries and their waits included.
    • redirect (default RedirectConfig::default()): up to 10 hops, no HTTPS-to-HTTP downgrade, credentials dropped across origins; RedirectConfig::none() turns redirects off, and a request opts out with RequestPlan::follow_redirects(false).
    • Responses are decompressed (gzip, deflate, br, zstd) and buffered bodies are limited to 64 MiB after decoding (max_body_bytes).
    • cookies (no jar by default): a CookieJar that stores every response's Set-Cookie and sends matching cookies, on each redirect hop too. The jar belongs to the caller, so several Clients may share it and it outlives them:

    let jar = @mttp.CookieJar::new(@mttp.clock())

    let site = @mttp.client(cookies=jar)

    base_url is joined to each relative request target, headers are sent with every request, limiter admits requests (no limit by default), trust chooses the TLS roots and config tunes the connection pool. observer gets one Attempt per attempt and events every ClientEvent (attempts, connection phases, redirects, retries), as Client::new describes; random is the source of retry jitter. Close the Client when done; that closes its connections.

    backend, clock and timer replace the real network, the system clock and the event loop's timers, so a test gets the same Client, with all the defaults above, over a stub such as @testing.BackendStub and a virtual clock. timer defaults to a timer on clock, so a virtual clock drives the deadlines too; without backend, the network backend runs its connection deadlines and pool expiry on the same clock and timer. A given backend is used as it is: trust and config configure only the network backend this builds when backend is omitted, and are ignored otherwise.

    clock

    The system's wall and monotonic clock, for a Client built by hand.

    close_on_shutdown

    let close_on_shutdown :
    AttributeKey
    [Bool]

    Set on a response by its handler: a streamed response with this attribute set to true is closed when the server starts to shut down, instead of being drained; for endless streams such as server-sent events, whose clients reconnect. The server stops pulling the body, closes it and ends the response at the point the stream had reached (a chunked body with its last chunk, otherwise by closing the connection), so shutdown does not wait out its drain time for a stream that never ends by itself.

    test {
    let response = @mttp_core.Response::new(200)
    let response = {
    ..response,
    attributes: response.attributes.put(@mttp_core.close_on_shutdown, true),
    }
    assert_eq(response.attributes.get(@mttp_core.close_on_shutdown), Some(true))
    }

    connection_scheme

    let connection_scheme :
    AttributeKey
    [String]

    The scheme the connection was accepted under, http or https, never taken from the request target: a client can write an https target over a cleartext connection, so only this says whether TLS carried the request. Set by server adapters that know it (h1server from its scheme, the Router in process from the request's own scheme); unset when unknown, as on the JS fetch hosts, whose request URL may keep a client-written scheme.

    coordination

    Signals on core/async's event loop, for the parts of gaato/mttp_core that wait without doing I/O themselves, such as @endpoint.EventStream::channel.

    get

    Creates a GET request with the default Result-valued string reader.

    on_phase

    Set on a request by the caller that wants its backend's PhaseEvents: the backend calls it as the exchange reaches each point. A Client built with events sets it on every attempt, calling a callback the request already carries first, so both are told. Wrappers pass request attributes on, so it reaches the engine underneath.

    post

    Creates a POST request with the default Result-valued string reader.

    protocol

    The protocol that carried a message, as its ALPN identifier (http/1.0, http/1.1, h2, h3): set by a backend on a response and by a server engine on a request, when it knows (CONTRACT.md, Backend rule 11). JS fetch cannot tell, so its responses leave it unset.

    read_bounded

    async fn read_bounded(stream : &
    BodyStream
    , limit : Int) -> Bytes raise
    TransportError

    Reads and closes a stream, refusing the first chunk that crosses limit. Subtraction before comparison prevents accumulated-length overflow.

    remote_addr

    Set by server adapters.

    replay_safe

    A caller's statement that resending this request is safe even after it was written (discord's REPLAY_SAFE_HEADER, without a wire header).

    request

    Pairs a wire request with a UTF-8 string reader accepting successful statuses.

    run

    fn run(main : async () -> Unit) -> Unit

    Runs main on moonbitlang/core/async's event loop and returns when it and every task it started have finished. An app calls it from a plain fn main, so it needs neither an import of core/async nor its experimental opt-in:

    fn main {
    @mttp.run(async fn() { ... })
    }

    timer

    Timers on core/async's event loop, which let a Client enforce its per-attempt and total deadlines.