openapi_client_runtime

    Sans-IO runtime for generated OpenAPI clients: Transport, middleware & retries, SSE/NDJSON/binary streaming, WebSockets, OAuth2 PKCE, JSON codecs, and HTTP encodings.

    http
    openapi
    transport
    streaming
    websocket
    oauth2
    client
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    8 hours ago
    Downloads
    14

    #vigoo/openapi_client_runtime

    Transport-agnostic, sans-IO runtime library for generated MoonBit OpenAPI clients. Compiles cleanly across native, js, wasm, and wasm-gc.

    #Install

    moon add vigoo/openapi_client_runtime

    Import the subpackages you need in moon.pkg:

    import { "vigoo/openapi_client_runtime" @runtime, "vigoo/openapi_client_runtime/json" @rjson, "vigoo/openapi_client_runtime/stream", "vigoo/openapi_client_runtime/transport/core_async", }

    #Packages & Target Matrix

    PackageTargetsPurpose
    vigoo/openapi_client_runtimenative, js, wasm, wasm-gcRequest, Response, Headers (with redacted Debug for sensitive headers), TransportError, Transport, Middleware, MiddlewareTransport[T], RetryPolicy, RetryMiddleware, RetryTransport[T].
    vigoo/openapi_client_runtime/jsonnative, js, wasm, wasm-gcStrict JsonReader, ObjectBuilder, DateTime (RFC 3339 UTC wrapper with Eq, Compare, Debug, FromJson, ToJson), Base64, lossless 64-bit integer codecs.
    vigoo/openapi_client_runtime/encodingnative, js, wasm, wasm-gcRFC 6570 path expansion (with dot-segment traversal protection), OpenAPI QueryBuilder, FormUrlEncodedBuilder, MultipartBuilder, header/cookie formatters.
    vigoo/openapi_client_runtime/streamnative, js, wasm, wasm-gcByteStream, StreamingResponse, StreamingTransport, StreamingMiddleware, StreamingMiddlewareTransport[T], BufferedStreamingTransport[T], bounded O(N) SseStream, NdjsonStream[T], BinaryStream.
    vigoo/openapi_client_runtime/oauth2native, js, wasm, wasm-gcOAuth 2.0 Authorization Code + PKCE (S256), Client Credentials, and Refresh Token flows (with redacted Debug on secrets).
    vigoo/openapi_client_runtime/wsnative, js, wasm, wasm-gcWebSocketDialer, WsConn, WsMessage, WsError.
    vigoo/openapi_client_runtime/ws/core_asyncnative, wasmCoreAsyncWsDialer backed by moonbitlang/core/async/websocket.
    vigoo/openapi_client_runtime/ws/js_wsjsJsWsDialer backed by standard browser/Node/Deno/Bun WebSocket.
    vigoo/openapi_client_runtime/transport/core_asyncnative, js, wasmCoreAsyncTransport (implements both Transport and StreamingTransport).
    vigoo/openapi_client_runtime/transport/js_fetchjsJsFetchTransport (implements both Transport and StreamingTransport).
    vigoo/openapi_client_runtime/transport/wasi_httpnative, js, wasm, wasm-gcWasiHttpTransport over WASI Preview 2 (wasi:http@0.2).
    vigoo/openapi_client_runtime/transport/wasi_http_p3native, js, wasm, wasm-gcWasiHttpP3Transport over WASI Preview 3 (wasi:http@0.3).
    vigoo/openapi_client_runtime/testingnative, js, wasm, wasm-gcMockTransport, MockWsDialer, and MockWsConn for deterministic tests.

    #Quick Examples

    Working with Headers, Request, and RetryPolicy:

    ///|
    test "headers redaction and retry policy defaults" {
    let hdrs = @openapi_client_runtime.Headers::of([
    ("Authorization", "Bearer top-secret"),
    ("X-Request-Id", "req-42"),
    ])
    assert_eq(hdrs.get("x-request-id"), Some("req-42"))
    let policy = @openapi_client_runtime.RetryPolicy::default()
    assert_eq(policy.max_retries, 3)
    assert_eq(@openapi_client_runtime.is_idempotent_method("GET"), true)
    assert_eq(@openapi_client_runtime.is_idempotent_method("POST"), false)
    assert_eq(@openapi_client_runtime.parse_retry_after_ms("5"), Some(5000))
    }

    #Middleware & Automatic Retries

    Wrap any Transport (or StreamingTransport) with RetryTransport or composable MiddlewareTransport:

    ///|
    async fn example_retrying_client() -> Unit {
    let base = @core_async.CoreAsyncTransport::new()
    let retrying = @runtime.RetryTransport::new(
    base,
    policy=@runtime.RetryPolicy::default(),
    sleep_ms=ms => @async.sleep(ms),
    )
    let cfg = @client.ClientConfig::new(base_url="https://api.example.com")
    let _client = @client.Client::new(retrying, cfg)
    }

    • RetryPolicy::default() retries only RFC 9110 idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS, TRACE) on transient TransportError::Network(_) and TransportError::Timeout errors plus status codes [408, 429, 500, 502, 503, 504], honoring numeric Retry-After headers clamped to max_delay_ms.
    • When the inner transport also implements @stream.StreamingTransport, RetryTransport[T] automatically implements StreamingTransport as well—retrying only before returning a response stream and closing discarded retryable responses.
    • For custom request/response interceptors (logging, tracing, auth refresh, custom headers), implement Middleware with MiddlewareTransport[T] (or @stream.StreamingMiddleware with @stream.StreamingMiddlewareTransport[T]).

    #Streaming (SSE, NDJSON, Binary)

    CoreAsyncTransport and JsFetchTransport implement @stream.StreamingTransport, enabling incremental decoding via SseStream, NdjsonStream[T], and BinaryStream:

    ///|
    async fn example_sse(
    sse : @stream.SseStream,
    ) -> Unit raise @runtime.TransportError {
    defer sse.close()
    while true {
    match sse.next() {
    Some(ev) => println("\{ev.event}: \{ev.data}")
    None => break
    }
    }
    }

    #Custom Transports & WebSockets

    Transport, StreamingTransport, ByteStream, Middleware, StreamingMiddleware, WebSocketDialer, and WsConn are all pub(open) traits, so platform-specific runtimes (such as custom Wasm host functions or embedded HTTP/WebSocket stacks) can plug in their own implementations directly.

    Middleware

    pub(open) trait Middleware {
    async fn handle(Self, Request, async (Request) -> Response raise TransportError) -> Response raise TransportError
    }

    A composable HTTP middleware interceptor.

    Implementations inspect or transform the outgoing Request, invoke next(req) (zero, one, or multiple times — e.g. for retries, caching, auth refresh, or request tracing), and return or transform the Response.

    Transport

    pub(open) trait Transport {
    async fn send(Self, Request) -> Response raise TransportError
    }

    The sans-IO HTTP transport contract. Implementations perform one exchange per call: send the request, buffer the response body, and return it. Non-2xx HTTP statuses MUST be returned as Response, not raised.

    TransportError

    pub(all) suberror TransportError {
    Network(String)
    InvalidUrl(String)
    Protocol(String)
    Timeout
    Cancelled
    } derive(Eq,
    Debug
    )

    Why a transport exchange failed. A non-2xx HTTP status is NOT a transport error — responses are returned normally; status handling belongs to the client error layer.

    Headers

    pub struct Headers {
    // private fields
    }

    Case-insensitive multi-value header collection. Insertion order is preserved; get returns the first matching value, get_all all of them. Equality compares entries in order with ASCII case-insensitive header names. Debug redacts sensitive headers (Authorization, Proxy-Authorization, Cookie, Set-Cookie, X-Api-Key).
    impl Eq for Headers

    Headers::append

    fn Headers::append(self : Headers, name : String, value : String) -> Unit

    Append a value without replacing existing ones (multi-value headers such as Set-Cookie).

    Headers::contains

    fn Headers::contains(self : Headers, name : String) -> Bool

    Whether name is present (case-insensitive).

    Headers::copy

    fn Headers::copy(self : Headers) -> Headers

    Return a shallow copy of this Headers collection.

    Headers::entries

    fn Headers::entries(self : Headers) -> Array[(String, String)]

    Copy of entries in insertion order.

    Headers::get

    fn Headers::get(self : Headers, name : String) -> String?

    First value for name (ASCII case-insensitive).

    Headers::get_all

    fn Headers::get_all(self : Headers, name : String) -> Array[String]

    All values for name (ASCII case-insensitive), in insertion order.

    Headers::is_empty

    fn Headers::is_empty(self : Headers) -> Bool

    True when no headers are present.

    Headers::length

    fn Headers::length(self : Headers) -> Int

    Number of header entries (including duplicate names).

    Headers::new

    fn Headers::new() -> Headers

    Create an empty Headers collection.

    Headers::of

    fn Headers::of(pairs : Array[(String, String)]) -> Headers

    Build headers from (name, value) pairs (names are stored as written).

    Headers::remove

    fn Headers::remove(self : Headers, name : String) -> Unit

    Remove all values for name (case-insensitive).

    Headers::set

    fn Headers::set(self : Headers, name : String, value : String) -> Unit

    Set (replace all existing values for name case-insensitively with one).

    MiddlewareTransport

    pub struct MiddlewareTransport[T] {
    // private fields
    }

    Wraps any Transport with an ordered chain of Middleware interceptors. Middlewares run in list order on the way out (middlewares[0] is outermost) and reverse order on the way back.

    MiddlewareTransport::inner

    fn[T] MiddlewareTransport::inner(self : MiddlewareTransport[T]) -> T

    Return the underlying wrapped transport.

    MiddlewareTransport::middlewares

    fn[T] MiddlewareTransport::middlewares(self : MiddlewareTransport[T]) -> Array[&Middleware]

    Return a defensive copy of the configured middleware chain.

    MiddlewareTransport::new

    fn[T] MiddlewareTransport::new(inner : T, middlewares : Array[&Middleware]) -> MiddlewareTransport[T]

    Wrap inner with an ordered list of middleware interceptors (middlewares[0] is outermost).

    MiddlewareTransport::send

    async fn[T : Transport] MiddlewareTransport::send(self : MiddlewareTransport[T], req : Request) -> Response raise TransportError

    MiddlewareTransport::with_middleware

    fn[T] MiddlewareTransport::with_middleware(self : MiddlewareTransport[T], mw : &Middleware) -> MiddlewareTransport[T]

    Return a new MiddlewareTransport with mw appended to the end of the chain.

    Request

    pub struct Request {
    http_method : String
    url : String
    headers : Headers
    body : Bytes?
    } derive(Eq,
    Debug
    )

    HTTP request ready for a Transport. The URL is fully assembled by the client/encoding layer.

    Request::body

    fn Request::body(self : Request) -> Bytes?

    Optional request body bytes.

    Request::clone

    fn Request::clone(self : Request) -> Request

    Return a shallow-body, deep-headers snapshot of this request.

    Request::headers

    fn Request::headers(self : Request) -> Headers

    Mutable header map attached to this request.

    Request::http_method

    fn Request::http_method(self : Request) -> String

    HTTP method verb (e.g. "GET", "POST").

    Request::new

    fn Request::new(http_method~ : String, url~ : String) -> Request

    Create a new HTTP request with empty headers and no body.

    Request::url

    fn Request::url(self : Request) -> String

    Fully assembled request URL.

    Request::with_body

    fn Request::with_body(self : Request, content_type~ : String, body~ : Bytes) -> Request

    Attach a body with an explicit Content-Type header.

    Request::with_header

    fn Request::with_header(self : Request, name : String, value : String) -> Request

    Set (replace) a request header and return self for chaining.

    Request::with_json_body

    fn Request::with_json_body(self : Request, json :
    Json
    ) -> Request

    Attach a UTF-8 JSON body (Content-Type: application/json).

    Request::with_raw_body

    fn Request::with_raw_body(self : Request, body : Bytes) -> Request

    Attach raw bytes as the request body without modifying Content-Type.

    Response

    pub struct Response {
    // private fields
    } derive(Eq,
    Debug
    )

    HTTP response with a fully buffered body.

    Response::body

    fn Response::body(self : Response) -> Bytes

    Raw buffered response body bytes.

    Response::headers

    fn Response::headers(self : Response) -> Headers

    Defensive copy of the response headers.

    Response::json

    Body decoded strictly as UTF-8 and parsed as JSON with preserve_number_repr=true so 64-bit integers preserve their exact wire text for generated codecs. Raises @utf8.Malformed on invalid UTF-8 or @json.ParseError on invalid JSON.

    Response::new

    fn Response::new(status~ : Int, headers~ : Headers, body~ : Bytes) -> Response

    Construct a buffered HTTP Response (defensively copying headers).

    Response::status

    fn Response::status(self : Response) -> Int

    HTTP status code (e.g. 200, 404).

    Response::text

    fn Response::text(self : Response) -> String

    Body decoded as UTF-8 text (lossy replacement on invalid bytes).

    Response::text_strict

    Body decoded as strict UTF-8 text (raises on invalid UTF-8).

    RetryMiddleware

    pub struct RetryMiddleware {
    // private fields
    }

    Sans-IO retry middleware using a caller-supplied async sleep_ms function (e.g. @async.sleep on native/JS, or a deterministic no-op/recorder in tests) and an optional jitter function (base_delay_ms) -> actual_delay_ms.

    RetryMiddleware::handle

    async fn RetryMiddleware::handle(self : RetryMiddleware, req : Request, next : async (Request) -> Response raise TransportError) -> Response raise TransportError

    RetryMiddleware::new

    fn RetryMiddleware::new(policy? : RetryPolicy, sleep_ms~ : async (Int) -> Unit, jitter? : (Int) -> Int) -> RetryMiddleware

    Create a RetryMiddleware with the given policy, async sleep_ms timer, and optional jitter transform (base_delay_ms) -> actual_delay_ms.

    RetryPolicy

    pub(all) struct RetryPolicy {
    max_retries : Int
    base_delay_ms : Int
    max_delay_ms : Int
    retry_statuses : Array[Int]
    retry_network_errors : Bool
    retry_timeouts : Bool
    retry_non_idempotent : Bool
    respect_retry_after : Bool
    } derive(Eq,
    Debug
    )

    Policy controlling automatic HTTP retries in RetryMiddleware / RetryTransport.

    Safe by default:
    • Retries only RFC 9110 idempotent methods (GET, HEAD, OPTIONS, PUT, DELETE, TRACE) unless retry_non_idempotent = true.
    • Retries status codes [408, 429, 500, 502, 503, 504] plus Network and Timeout transport errors (never Cancelled, InvalidUrl, or Protocol).
    • Honors Retry-After delay-seconds headers (clamped to max_delay_ms).

    RetryPolicy::compute_delay_ms

    fn RetryPolicy::compute_delay_ms(self : RetryPolicy, attempt : Int, retry_after_hdr : String?, jitter : (Int) -> Int?) -> Int

    Compute the retry delay in milliseconds for zero-based attempt, honoring an optional Retry-After header and optional jitter function.

    RetryPolicy::default

    fn RetryPolicy::default() -> RetryPolicy

    Default safe retry policy: up to 3 retries on idempotent methods with exponential backoff (200ms base, 10s cap) and Retry-After support.

    RetryTransport

    pub struct RetryTransport[T] {
    // private fields
    }

    Convenience Transport wrapper that applies RetryMiddleware directly around any underlying T : Transport.

    When T also implements @stream.StreamingTransport, RetryTransport[T] implements @stream.StreamingTransport as well (retrying only before returning a response stream and closing discarded retryable responses).

    RetryTransport::inner

    fn[T] RetryTransport::inner(self : RetryTransport[T]) -> T

    Return the underlying wrapped transport.

    RetryTransport::jitter

    fn[T] RetryTransport::jitter(self : RetryTransport[T]) -> (Int) -> Int?

    Return the optional jitter function, if configured.

    RetryTransport::new

    fn[T] RetryTransport::new(inner : T, policy? : RetryPolicy, sleep_ms~ : async (Int) -> Unit, jitter? : (Int) -> Int) -> RetryTransport[T]

    Wrap inner with automatic retries controlled by policy, sleep_ms, and optional jitter.

    RetryTransport::policy

    fn[T] RetryTransport::policy(self : RetryTransport[T]) -> RetryPolicy

    Return the configured RetryPolicy.

    RetryTransport::send

    async fn[T : Transport] RetryTransport::send(self : RetryTransport[T], req : Request) -> Response raise TransportError

    RetryTransport::sleep_ms

    fn[T] RetryTransport::sleep_ms(self : RetryTransport[T]) -> (async (Int) -> Unit)

    Return the configured async sleep callback.

    eq_ascii_ignore_case

    fn eq_ascii_ignore_case(a : String, b : String) -> Bool

    Allocation-free ASCII case-insensitive string equality (for HTTP header names).

    is_hop_by_hop_or_framing_header

    fn is_hop_by_hop_or_framing_header(name : String) -> Bool

    True for RFC 9110 hop-by-hop or transport-managed framing headers that callers must not smuggle through an HTTP transport.

    is_idempotent_method

    fn is_idempotent_method(http_method : String) -> Bool

    Whether http_method is an RFC 9110 §9.2.2 idempotent method.

    is_valid_authority

    fn is_valid_authority(authority : String, allow_userinfo? : Bool) -> Bool

    Validate an HTTP/WS URL authority (host[:port] or [ipv6][:port]). Rejects empty hosts, unclosed/nested brackets, bogus IPv6 literals, backslashes, non-ASCII hosts, port 0 or > 65535 (preventing Int32 wraparound), control characters, and userinfo @ (unless allow_userinfo=true).

    is_valid_header_value

    fn is_valid_header_value(value : String) -> Bool

    Whether value is safe as an outbound HTTP header field value per RFC 9110 §5.5 (printable ASCII 0x20..=0x7E plus horizontal tab 0x09; rejects \r, \n, \0, DEL, and non-ASCII > 0x7E that would crash JS Headers or emit raw UTF-8 into HTTP/1.1 headers).

    is_valid_http_token

    fn is_valid_http_token(token : String) -> Bool

    Whether token is a non-empty RFC 9110 HTTP token (1*tchar), valid for HTTP methods and header field names.

    parse_retry_after_ms

    fn parse_retry_after_ms(header_value : String) -> Int?

    Parse an RFC 9110 §10.2.3 numeric Retry-After delay-seconds header into milliseconds (saturating at Int32::MAX). Returns None for empty, negative, or non-integer values.

    split_absolute_url

    fn split_absolute_url(url : String) -> (String, String, String, Bool)?

    Split an absolute scheme://authority[path][?query][#fragment] URL with strict authority, port, and character validation.

    Returns Some((lowercase_scheme, authority, path_with_query, has_fragment)) where:
    • authority has been validated with is_valid_authority(allow_userinfo=false)
    • path_with_query has any #fragment stripped, defaults to "/" if absent, and prefixes "/" if only ?query was present
    • has_fragment is true if a # delimiter was present.

    Returns None if url is empty, contains whitespace, control characters, or backslashes, lacks ://, or has an invalid scheme or authority.

    utf8_decode

    fn utf8_decode(bytes : Bytes) -> String

    UTF-8 decode bytes with replacement characters for invalid sequences.

    utf8_decode_strict

    fn utf8_decode_strict(bytes : Bytes) -> String raise
    Malformed

    Strict UTF-8 decode raising @utf8.Malformed on invalid byte sequences.

    utf8_encode

    fn utf8_encode(text : String) -> Bytes

    UTF-8 encode a string into bytes.