From 8e98c0a3d613f77a126545915158cf23ad58b828 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 2 Nov 2026 23:00:08 -0500 Subject: [PATCH 1/5] docs: select Wasmtime 50.0.1 across WASI workflows [skip ci] --- AGENTS.md | 4 ++-- README.md | 10 +++++----- doc/boost.adoc | 2 +- doc/build.adoc | 2 +- doc/guarantees.adoc | 2 +- doc/introduction.adoc | 2 +- doc/main.adoc | 2 +- doc/response.adoc | 2 +- doc/testing.adoc | 2 +- doc/wasip3.adoc | 2 +- include/webcpp/wasi/http/entrypoint.hpp | 2 +- include/webcpp/wasi/http/response.hpp | 2 +- test/http_content_type_of_target.cpp | 2 +- test/http_long_body.cpp | 2 +- 14 files changed, 19 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f42d33a..d83f389 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,7 +43,7 @@ holds only what is specific to wasi. built with exceptions on wasip2 and wasip3, as the superproject's Jamroot builds any; wasmtime serves both with no flag beyond those of `webcpp.serve`. An exception that escapes the main on either traps the - instance, and wasmtime 47 answers its own HTML 500 and keeps serving: the + instance, and wasmtime 50.0.1 answers its own HTML 500 and keeps serving: the page and the main's Doc Comment say so. The handler catches nothing, by the owner's decision; the host answers. - **`config.hpp` comes first.** Every public header includes @@ -60,7 +60,7 @@ holds only what is specific to wasi. else `PATH`); the `wasi:http` WIT of WASI 0.2.12 and 0.3.0, the `wit/deps` directories of the Rust crates `wasip2` 1.0.4 and `wasip3` 0.9.0 (`-sWASI_WIT_P2=` and `-sWASI_WIT_P3=`, else - `.local/wasi-wit/p2` and `.local/wasi-wit/p3`); wasmtime 47.0.3 + `.local/wasi-wit/p2` and `.local/wasi-wit/p3`); wasmtime 50.0.1 (`-sWASMTIME=`, else `PATH`), looked for only when a served test runs. A native build needs none of them. - **Served tests.** A program that answers HTTP is tested with diff --git a/README.md b/README.md index 5ce17ca..cbdcfb8 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ request, calls your main and writes the answer back. It covers WASI 0.2 Requirements: C++20, wasi-sdk 34, wit-bindgen's C generator (0.62.0 measured), the `wasi:http` WIT of your target, and a host such as wasmtime -(47.0.3 measured). The headers include only the standard library and the +(50.0.1 measured). The headers include only the standard library and the bindings wit-bindgen writes. The helper needs neither exceptions nor RTTI and imposes neither: webcpp builds it with exceptions on wasip2 and wasip3, where an exception that escapes your main traps the instance (see @@ -43,7 +43,7 @@ where an exception that escapes your main traps the instance (see A component that greets whoever calls it, built by hand with wasi-sdk. These are the exact files and commands, which webcpp's test `by_hand` runs in the lane `http` of `example/`, on wasip2 and on wasip3, with wasi-sdk 34, -wit-bindgen 0.62.0 and wasmtime 47.0.3 +wit-bindgen 0.62.0 and wasmtime 50.0.1 ([example/by_hand/build.sh](example/by_hand/build.sh)). `wit/world.wit`, the world your component exports (name it as you like): @@ -176,7 +176,7 @@ library, Boost.URL's `parse_origin_form` for example. The handler catches nothing. On wasip2 and wasip3, where webcpp builds a program with exceptions, an exception that escapes your main traps the -instance: wasmtime 47 prints the trap on its standard error, `thrown Wasm +instance: wasmtime 50.0.1 prints the trap on its standard error, `thrown Wasm exception`, and answers the client with its own `500 Internal Server Error`, an HTML page, then serves the requests after it. @@ -199,7 +199,7 @@ struct of three members: | Member | Type | What it holds | | --- | --- | --- | -| `status` | `unsigned`, 200 by default | the status, sent as it is within 100 to 599; outside them the handler answers an internal error instead, which wasmtime 47 sends as its own `500 Internal Server Error` | +| `status` | `unsigned`, 200 by default | the status, sent as it is within 100 to 599; outside them the handler answers an internal error instead, which wasmtime 50.0.1 sends as its own `500 Internal Server Error` | | `content_type` | `std::string_view`, empty by default | the `content-type` header, sent only when not empty; read after your main returns, so it views a literal, like `"application/json"`, or the method or the target, never a string of your main's own; one the host refuses, with a CR, an LF or a NUL for example, answers an internal error instead | | `body` | `std::string`, empty by default | the body, sent whole, however long | @@ -220,7 +220,7 @@ itself: | the bindings generated with `--rename-world webcpp_wasi_http` | the header includes `webcpp_wasi_http.h` and uses the names wit-bindgen gives the world, `webcpp_wasi_http_string_t` and the like; renaming makes them the same in every project, whatever its world is called | | `webcpp_wasi_http.c` compiled as C for the target, and `webcpp_wasi_http_component_type.o`, linked | the glue that calls your handler, and the world's type information for the component linker | | the directory of the bindings on the include path | for `webcpp_wasi_http.h` | -| `-mexec-model=reactor` on the link | the program is a reactor: it exports a handler and has no C `main`; wasmtime 47 also serves it linked as a command, but webcpp builds and tests reactors | +| `-mexec-model=reactor` on the link | the program is a reactor: it exports a handler and has no C `main`; wasmtime 50.0.1 also serves it linked as a command, but webcpp builds and tests reactors | The host has its part too: `wasmtime serve` runs a component of wasi with `-S cli`, since wasi-libc imports parts of `wasi:cli`, and on wasip3 with diff --git a/doc/boost.adoc b/doc/boost.adoc index a0e7d96..8039a12 100644 --- a/doc/boost.adoc +++ b/doc/boost.adoc @@ -93,7 +93,7 @@ given `-W exceptions=y`; jco, whose `jco transpile` is given `--bindgen-enable-wasm-exnref`; or another engine of WebAssembly 3.0. wasi's handler catches nothing: an exception that escapes the main traps the -instance, and wasmtime 47 answers the client with its own +instance, and wasmtime 50.0.1 answers the client with its own `500 Internal Server Error` (<>). A main that may throw catches what it can answer itself. diff --git a/doc/build.adoc b/doc/build.adoc index 3673fbd..07348b8 100644 --- a/doc/build.adoc +++ b/doc/build.adoc @@ -34,7 +34,7 @@ version of WASI it is built for. A build provides it with these: | `-mexec-model=reactor` on the link | The program is a reactor: it exports a handler and has no C `main`. - wasmtime 47 also serves the same program linked without it, as a + wasmtime 50.0.1 also serves the same program linked without it, as a command, but webcpp builds and tests reactors. |=== diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index 8cc675e..cb00f15 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -43,7 +43,7 @@ is read; and by `response`, which checks that the body is a copy. chunks of at most 4096 bytes, the most `blocking-write-and-flush` takes; on wasip3 by writing until the stream has taken every byte. _Held by_ `http_long_body`, whose body of three chunks and some bytes more arrives -whole, on wasip2 and on wasip3. wasmtime 47 takes the whole body in one write +whole, on wasip2 and on wasip3. wasmtime 50.0.1 takes the whole body in one write on wasip3, a body of 1{nbsp}MiB too, so it never makes the loop of wasip3 take a second turn: the test fails there when a write is cut short, and the loop stands for a host that takes less per write. diff --git a/doc/introduction.adoc b/doc/introduction.adoc index 01a4be8..90e20cf 100644 --- a/doc/introduction.adoc +++ b/doc/introduction.adoc @@ -73,7 +73,7 @@ bindings are generated: <> shows the commands. * *wit-bindgen's C generator,* 0.62.0 measured, and the `wasi:http` WIT of the target: the `wit/deps` directory of the Rust crate `wasip2` 1.0.4 for WASI 0.2.12, or of `wasip3` 0.9.0 for WASI 0.3.0. -* *A host of `wasi:http`,* such as wasmtime, 47.0.3 measured. +* *A host of `wasi:http`,* such as wasmtime, 50.0.1 measured. * *Nothing else.* The headers include only the standard library and the bindings wit-bindgen writes, and need no Boost. They throw, try and catch nothing, and use no RTTI: wasi needs neither exceptions nor RTTI, and diff --git a/doc/main.adoc b/doc/main.adoc index 29ef0d3..bc12148 100644 --- a/doc/main.adoc +++ b/doc/main.adoc @@ -53,7 +53,7 @@ each request, and sends what it returns. * *An exception that escapes it is not caught.* The handler catches nothing, so on wasip2 and wasip3, where webcpp builds a program with exceptions, an exception that escapes the main traps the instance, and the - response is never sent. wasmtime 47 then prints the trap and its backtrace + response is never sent. wasmtime 50.0.1 then prints the trap and its backtrace on its standard error, `thrown Wasm exception` among them, and answers the client with its own `500 Internal Server Error`, the HTML page it answers an internal error with; it serves the requests after it. diff --git a/doc/response.adoc b/doc/response.adoc index 6d48d0b..746808f 100644 --- a/doc/response.adoc +++ b/doc/response.adoc @@ -41,7 +41,7 @@ The handler sends no other header (<>). A response the handler cannot send as the main wrote it, with a status outside 100 to 599 or a content type the host refuses, is not sent at all: the handler answers an internal error, before it has committed anything, and -wasmtime 47 sends that as its own `500 Internal Server Error`, an HTML page +wasmtime 50.0.1 sends that as its own `500 Internal Server Error`, an HTML page that names it. Without the check, wasmtime would send some of those statuses as `200 OK`, and the status of `wasi:http`, 16 bits wide, would read 65736 as 200, so a main's bug would reach the client as a success; and a content type diff --git a/doc/testing.adoc b/doc/testing.adoc index 7fdd8ab..590c5b0 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -200,7 +200,7 @@ A WASI build needs, besides b2 and Boost 1.92: | The `wit/deps` directories of the Rust crates `wasip2` 1.0.4 and `wasip3` 0.9.0, which the bindings are generated from. -| wasmtime 47.0.3 +| wasmtime 50.0.1 | Runs every test and example, and serves each component. |=== diff --git a/doc/wasip3.adoc b/doc/wasip3.adoc index 3d10d04..4719a35 100644 --- a/doc/wasip3.adoc +++ b/doc/wasip3.adoc @@ -38,7 +38,7 @@ include::{examples}/by_hand/build.sh[tag=p3] The test `by_hand` runs them in its lane on wasip3, and wasmtime serves what they build with the flags above and no other. With exceptions on, an exception that escapes the main traps the instance: the handler catches -nothing, and wasmtime 47 answers the client with its own +nothing, and wasmtime 50.0.1 answers the client with its own `500 Internal Server Error` (<>). Built with `-fno-exceptions` in place of the exception flags, on the compile and on the link, the component answers the same; webcpp measured that once, by diff --git a/include/webcpp/wasi/http/entrypoint.hpp b/include/webcpp/wasi/http/entrypoint.hpp index 7522749..1631d7a 100644 --- a/include/webcpp/wasi/http/entrypoint.hpp +++ b/include/webcpp/wasi/http/entrypoint.hpp @@ -57,7 +57,7 @@ namespace webcpp::wasi::http { the main copies what it keeps beyond the request. @note The handler catches nothing. On wasip2 and wasip3, where webcpp builds a program with exceptions, an exception that escapes the main traps the - instance: wasmtime 47 prints the trap and answers the client with its own + instance: wasmtime 50.0.1 prints the trap and answers the client with its own `500 Internal Server Error`. @see "Your main", in the guide. */ diff --git a/include/webcpp/wasi/http/response.hpp b/include/webcpp/wasi/http/response.hpp index 1ec741f..0358bf4 100644 --- a/include/webcpp/wasi/http/response.hpp +++ b/include/webcpp/wasi/http/response.hpp @@ -39,7 +39,7 @@ struct response { It is sent as it is when it lies within 100 to 599, the five classes of HTTP. Outside them the handler sends no response of the main's and - answers an internal error instead, which wasmtime 47 sends as its own + answers an internal error instead, which wasmtime 50.0.1 sends as its own `500 Internal Server Error`. */ unsigned status = 200; diff --git a/test/http_content_type_of_target.cpp b/test/http_content_type_of_target.cpp index f176cd9..62d9070 100644 --- a/test/http_content_type_of_target.cpp +++ b/test/http_content_type_of_target.cpp @@ -11,7 +11,7 @@ // // It fails, every time, on a handler that frees the target before it reads // the content type, because the free itself overwrites the target. Each -// request meets the heap the same: wasmtime 47 gives each request of wasip2 a +// request meets the heap the same: wasmtime 50.0.1 gives each request of wasip2 a // fresh instance, and on wasip3, where it reuses one, every earlier request // gave back all it took. The bindings allocate the target as the request is // read, and the main the body after it, so the target's chunk lies between diff --git a/test/http_long_body.cpp b/test/http_long_body.cpp index 6e7cc9d..4c29ba0 100644 --- a/test/http_long_body.cpp +++ b/test/http_long_body.cpp @@ -8,7 +8,7 @@ // three times the most that one blocking-write-and-flush of wasip2 takes, and // a rest. The body is 192 numbered lines of 64 bytes, so a chunk of 4096 ends // at a line's end and a missing one shows as lines that are not there, and -// then a last line of 17 bytes. On wasip3, wasmtime 47 takes the whole body in +// then a last line of 17 bytes. On wasip3, wasmtime 50.0.1 takes the whole body in // one write, so the writer's loop never takes a second turn there: the test // holds that the body arrives whole, not that the loop goes on. From 27aafae0a7693b80bd69ff0052cb4f9eebd6aa4b Mon Sep 17 00:00:00 2001 From: R Date: Mon, 2 Nov 2026 23:03:51 -0500 Subject: [PATCH 2/5] wasi: preserve historical runtime measurements [skip ci] --- doc/build.adoc | 4 ++-- doc/changelog.adoc | 1 + doc/guarantees.adoc | 9 +++++---- test/http_long_body.cpp | 6 +++--- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/doc/build.adoc b/doc/build.adoc index 07348b8..75ee96e 100644 --- a/doc/build.adoc +++ b/doc/build.adoc @@ -34,8 +34,8 @@ version of WASI it is built for. A build provides it with these: | `-mexec-model=reactor` on the link | The program is a reactor: it exports a handler and has no C `main`. - wasmtime 50.0.1 also serves the same program linked without it, as a - command, but webcpp builds and tests reactors. + Historical tests with wasmtime 47 also served the same program linked + without it, as a command. Current webcpp builds and tests reactors. |=== The host has its part too: `wasmtime serve` runs a component of wasi with diff --git a/doc/changelog.adoc b/doc/changelog.adoc index c6b0782..c71d0ac 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,6 +16,7 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* Updated Wasmtime instructions to 50.0.1, preserving historical measurements. // end::unreleased[] [#wasi-changelog-0-1-0] diff --git a/doc/guarantees.adoc b/doc/guarantees.adoc index cb00f15..0f59b46 100644 --- a/doc/guarantees.adoc +++ b/doc/guarantees.adoc @@ -43,10 +43,11 @@ is read; and by `response`, which checks that the body is a copy. chunks of at most 4096 bytes, the most `blocking-write-and-flush` takes; on wasip3 by writing until the stream has taken every byte. _Held by_ `http_long_body`, whose body of three chunks and some bytes more arrives -whole, on wasip2 and on wasip3. wasmtime 50.0.1 takes the whole body in one write -on wasip3, a body of 1{nbsp}MiB too, so it never makes the loop of wasip3 take -a second turn: the test fails there when a write is cut short, and the loop -stands for a host that takes less per write. +whole, on wasip2 and on wasip3. Historical tests with wasmtime 47 took the +whole body in one write on wasip3, a body of 1{nbsp}MiB too. The regression +with wasmtime 50.0.1 verifies complete delivery, not the number of writes. +The loop stands for a host that takes less per write; the test fails when +a write is cut short and the remaining bytes are not sent. . [[wasi-invariant-5]]*On wasip3, the handler never resumes in its callback.* It waits inside the task for every write that blocks, and always ends with `EXIT`, because context slot 0 belongs to wasi-libc on wasip3: using it diff --git a/test/http_long_body.cpp b/test/http_long_body.cpp index 4c29ba0..3132728 100644 --- a/test/http_long_body.cpp +++ b/test/http_long_body.cpp @@ -8,9 +8,9 @@ // three times the most that one blocking-write-and-flush of wasip2 takes, and // a rest. The body is 192 numbered lines of 64 bytes, so a chunk of 4096 ends // at a line's end and a missing one shows as lines that are not there, and -// then a last line of 17 bytes. On wasip3, wasmtime 50.0.1 takes the whole body in -// one write, so the writer's loop never takes a second turn there: the test -// holds that the body arrives whole, not that the loop goes on. +// then a last line of 17 bytes. Historical wasip3 tests with wasmtime 47 took +// the whole body in one write. This test checks that the body arrives whole, +// not the number of iterations of the writer's loop. #include From edf8c3191f88d4c7c758a251aeb4637c5f004093 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 00:22:37 -0500 Subject: [PATCH 3/5] feat: provide complete WASI host HTTP messages and readiness operations [skip ci] --- build.jam | 10 + doc/Jamfile | 4 +- doc/limits.adoc | 7 +- doc/messages.adoc | 84 ++++ doc/wasi.adoc | 2 + include/webcpp/wasi/http/host.hpp | 461 +++++++++++++++++ include/webcpp/wasi/http/message.hpp | 721 +++++++++++++++++++++++++++ include/webcpp/wasi/http/poll.hpp | 460 +++++++++++++++++ include/webcpp/wasi/stdio.hpp | 296 +++++++++++ test/Jamfile | 5 + wit/host-http-p2.wit | 14 + wit/host-http-p3.wit | 14 + 12 files changed, 2072 insertions(+), 6 deletions(-) create mode 100644 doc/messages.adoc create mode 100644 include/webcpp/wasi/http/host.hpp create mode 100644 include/webcpp/wasi/http/message.hpp create mode 100644 include/webcpp/wasi/http/poll.hpp create mode 100644 include/webcpp/wasi/stdio.hpp create mode 100644 wit/host-http-p2.wit create mode 100644 wit/host-http-p3.wit diff --git a/build.jam b/build.jam index 77dd153..780a3c0 100644 --- a/build.jam +++ b/build.jam @@ -28,3 +28,13 @@ alias http-bindings : http-bindings-p2 http-bindings-p3 ; alias http : : : : wasi http-bindings clang-wasip2:WEBCPP_WASI_HTTP_P2 clang-wasip3:WEBCPP_WASI_HTTP_P3 ; + +# Complete host messages use the host client, never a guest socket reactor. +webcpp.wit-bindings host-http-bindings-p2 : wit/host-http-p2.wit : http : webcpp_wasi_http : p2 ; +webcpp.wit-bindings host-http-bindings-p3 : wit/host-http-p3.wit : http : webcpp_wasi_http : p3 + : --async "wasi:http/handler@0.3.0#handle" --async "wasi:http/client@0.3.0#send" + --async "wasi:clocks/monotonic-clock@0.3.0#wait-until" ; +alias host-http-bindings : host-http-bindings-p2 host-http-bindings-p3 ; +alias host-http : : : : wasi host-http-bindings + clang-wasip2:WEBCPP_WASI_HTTP_P2 + clang-wasip3:WEBCPP_WASI_HTTP_P3 ; diff --git a/doc/Jamfile b/doc/Jamfile index 4e00b4d..0f01f94 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -12,6 +12,6 @@ webcpp.doc wasi : wasi.adoc ; # with the bindings of wasip2 and the macro of that version; the Doc Comments # of its wasip3 branch are checked too, with the bindings and the macro of # wasip3. -webcpp.reference wasi : /webcpp/wasi//http-bindings-p2-headers +webcpp.reference wasi : /webcpp/wasi//host-http-bindings-p2-headers WEBCPP_WASI_HTTP_P2 - : /webcpp/wasi//http-bindings-p3-headers WEBCPP_WASI_HTTP_P3 ; + : /webcpp/wasi//host-http-bindings-p3-headers WEBCPP_WASI_HTTP_P3 ; diff --git a/doc/limits.adoc b/doc/limits.adoc index 0d4d0b4..f410b09 100644 --- a/doc/limits.adoc +++ b/doc/limits.adoc @@ -7,11 +7,10 @@ [#wasi-limits] == Limits -The handler hands the main only the method and the target. It reads no +The original main-macro handler hands the main only the method and the target. It reads no request header and no request body, and sends no response header but -`content-type`. A main that needs a request's body or its headers, or to set -other headers, waits for the handler to grow: today it cannot be written with -wasi. +`content-type`. Use the <> for a request body, +additional fields, trailers or an outgoing host request. [#wasi-limits-allocation] === What it allocates diff --git a/doc/messages.adoc b/doc/messages.adoc new file mode 100644 index 0000000..f782a5a --- /dev/null +++ b/doc/messages.adoc @@ -0,0 +1,84 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#wasi-host-messages] +== Complete host messages and streams + +Select `/webcpp/wasi//host-http` and include +`` for incoming and outgoing HTTP with exposed +fields, bodies and trailers. This profile imports `wasi:http/outgoing-handler` +on P2 and `wasi:http/client` on P3, as well as the monotonic clock used for +transfer deadlines. It does not require a guest TCP reactor or guest TLS. +The existing `/webcpp/wasi//http` profile and main macros remain available. + +`incoming_request` owns the host request. Read `method()`, `target()`, +`authority()` and `headers()` before `consume(error)`. A `body_reader` reads +into caller-owned spans, enforces `transfer_options::body_limit`, and reports +EOF separately from successful completion. After EOF, call `finish` to +check the completion result and visit the trailers. On P2 the request or +response owner must outlive its body reader. On P3 consuming the body moves +the request or response and retains its completion future in the reader. + +`commit_response` commits status and fields once and returns a +`body_writer`. Write partial spans with `write_some`, or a complete span +with `write`, then call `finish` with optional trailers. Dropping a writer +before finishing fails the remaining body. It cannot replace an already +committed response. P3 abandonment resolves the mandatory trailers future +with an error before releasing the writer; simply dropping that writer +would trap in the component ABI. + +`outgoing_exchange::start` takes the scheme, authority, method, path and +fields, starts the host operation and returns a request body writer. Finish +that writer before `receive` waits for response headers. The returned +`incoming_response` provides its status, fields and body. The host owns +connection reuse, DNS and HTTPS trust. Invalid or forbidden fields return +an error; the adapter does not silently switch transports or discard them. +`message_error` retains the pinned interface's host error discriminant. + +The operations above suspend inside the current component task. They are not an +Asio completion-token interface. A transfer can use an absolute monotonic +deadline or a cancellation predicate. Cancellation is checked between +chunks and while waiting, at intervals of at most ten milliseconds, except +when the host itself blocks inside an imported operation. The adapter does +not allocate {cpp} operation state. Canonical ABI strings and lists still use +the generated bindings' `cabi_realloc`; caller-owned bodies and fields use +their own allocator. + +[#wasi-http-readiness] +=== Nonblocking body and response operations + +`` exposes `read_task`, `write_task` and +`response_task`. Each poll performs one bounded readiness step and returns +false while the host operation remains pending. The tasks own their body +resources and, on P3, stable storage for pending stream and future results. +A pending read or write borrows its payload span until a subsequent poll +completes; the caller must keep that span unchanged and alive. Destroying +a task cancels pending host access before releasing resources or storage. + +`read_task::finish` polls body completion and incoming trailers after EOF. +`write_task::finish` polls outgoing trailers after the final content chunk. +`response_task::poll` waits for response headers without blocking on the +network. P2 future tasks retain their readiness subscriptions for the +entire pending interval. These primitives allocate no {cpp} operation +state and can be driven by a component event loop. Beast's explicit WASI +asynchronous adapter builds completion-token operations over them. + +[#wasi-cli-streams] +=== Standard CLI streams + +`` exposes `stdio_channel` over the pinned wasi-sdk +CLI stream bindings on P2 and P3. Each operation returns a partial byte +count and `ready`, `blocked`, `eof` or `failed`. The object owns the acquired +stream resources; it neither creates sockets nor interprets protocol bytes. +No caller buffer remains borrowed after a partial operation returns. + +The direct CLI adapter avoids wasi-sdk 34's stdio descriptors, which reject +`fcntl(F_SETFL)` and always request blocking I/O. Wasmtime 50.0.1 can still +block inside a standard-output host write when its OS pipe fills. Guest +cancellation is then observed after the peer resumes draining. The tests +bound that pause and resume draining concurrently; they do not claim that +the guest can interrupt a blocking host import. Diagnostics belong on +stderr, separately from the protocol on stdout. diff --git a/doc/wasi.adoc b/doc/wasi.adoc index d25ca79..e3ac174 100644 --- a/doc/wasi.adoc +++ b/doc/wasi.adoc @@ -40,6 +40,8 @@ include::wasip3.adoc[] include::flow.adoc[] +include::messages.adoc[] + include::limits.adoc[] include::guarantees.adoc[] diff --git a/include/webcpp/wasi/http/host.hpp b/include/webcpp/wasi/http/host.hpp new file mode 100644 index 0000000..c07b233 --- /dev/null +++ b/include/webcpp/wasi/http/host.hpp @@ -0,0 +1,461 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WASI_HTTP_HOST_HPP +#define WEBCPP_WASI_HTTP_HOST_HPP + +#include +#include + +namespace webcpp::wasi::http { + +#ifdef WEBCPP_WASI_HTTP_P2 +/** Owned request resource of the selected WASI ABI. */ +using request_handle = wasi_http_types_own_incoming_request_t; +/** P2 response commitment resource. */ +using response_out = wasi_http_types_own_response_outparam_t; +#else +/** Owned request resource of the selected WASI ABI. */ +using request_handle = wasi_http_types_own_request_t; + +/** P3 returns a response from the active task rather than a P2 outparam resource. */ +struct response_out {}; +#endif + +/** An incoming host request. + + Its child body must be destroyed before this owner on P2. */ +class incoming_request { +#ifdef WEBCPP_WASI_HTTP_P2 + detail::resource request_; +#else + detail::resource request_; +#endif + wasi_http_types_method_t method_{}; + webcpp_wasi_http_string_t target_{}; + webcpp_wasi_http_string_t authority_{}; + bool has_target_ = false; + bool has_authority_ = false; + +public: + /** Takes ownership of the incoming request. + @param request Request supplied by the exported handler. */ + explicit incoming_request(request_handle request) : request_(request) { +#ifdef WEBCPP_WASI_HTTP_P2 + const auto borrowed = wasi_http_types_borrow_incoming_request(request); + wasi_http_types_method_incoming_request_method(borrowed, &method_); + has_target_ = wasi_http_types_method_incoming_request_path_with_query(borrowed, &target_); + has_authority_ = wasi_http_types_method_incoming_request_authority(borrowed, &authority_); +#else + const auto borrowed = wasi_http_types_borrow_request(request); + wasi_http_types_method_request_get_method(borrowed, &method_); + has_target_ = wasi_http_types_method_request_get_path_with_query(borrowed, &target_); + has_authority_ = wasi_http_types_method_request_get_authority(borrowed, &authority_); +#endif + } + + /** Forbids copying resource ownership. */ + incoming_request(const incoming_request&) = delete; + /** Forbids copying resource ownership. */ + incoming_request& operator=(const incoming_request&) = delete; + + /** Releases metadata and any unconsumed request. */ + ~incoming_request() { + wasi_http_types_method_free(&method_); + if (has_target_) { + webcpp_wasi_http_string_free(&target_); + } + if (has_authority_) { + webcpp_wasi_http_string_free(&authority_); + } + } + + /** Borrows the method name. + @return A view valid while this request owner remains alive. */ + [[nodiscard]] std::string_view method() const { return detail::method_name(method_); } + + /** Borrows the original path and query. + @return A view valid while this request owner remains alive. */ + [[nodiscard]] std::string_view target() const { + return has_target_ ? detail::view_of(target_) : "/"; + } + + /** Borrows the request authority. + @return A view valid while this request owner remains alive. */ + [[nodiscard]] std::string_view authority() const { + return has_authority_ ? detail::view_of(authority_) : ""; + } + + /** Acquires the exposed header fields. + @return Owning fields exposing the host headers. */ + [[nodiscard]] message_fields headers() const { +#ifdef WEBCPP_WASI_HTTP_P2 + return message_fields(wasi_http_types_method_incoming_request_headers( + wasi_http_types_borrow_incoming_request(request_.get()))); +#else + return message_fields(wasi_http_types_method_request_get_headers( + wasi_http_types_borrow_request(request_.get()))); +#endif + } + + /** Consumes the content once, after reading metadata. + @param error Receives an invalid-state error on repeated consumption. + @return The body reader, or an empty reader on failure. */ + /** Consumes the response or request body once. + @param error Receives a resource-state failure. */ + body_reader consume(message_error& error) { + if (!request_) { + error = {.code = message_errc::invalid_state}; + return {}; + } +#ifdef WEBCPP_WASI_HTTP_P2 + wasi_http_types_own_incoming_body_t body{}; + if (!wasi_http_types_method_incoming_request_consume( + wasi_http_types_borrow_incoming_request(request_.get()), &body)) { + error = {.code = message_errc::invalid_state}; + return {}; + } + return body_reader(body); +#else + wasi_http_types_future_result_void_error_code_writer_t writer{}; + const auto completion = wasi_http_types_future_result_void_error_code_new(&writer); + wasi_http_types_tuple2_stream_u8_future_result_option_own_trailers_error_code_t body{}; + wasi_http_types_static_request_consume_body(request_.release(), completion, &body); + return {body, writer}; +#endif + } +}; + +/** Reports a pre-commit error. + + Never call after committing. + @param out Active response commitment resource. */ +inline void refuse_response(response_out out) { +#ifdef WEBCPP_WASI_HTTP_P2 + detail::refuse(out); +#else + static_cast(out); + detail::refuse(); +#endif +} + +/** Commits response headers once and returns its body writer. + @param out Active response commitment resource. + @param status HTTP status code. + @param headers Header fields transferred to the host. + @param error Receives any pre-commit failure. + @return The committed body writer, or an empty writer on failure. */ +inline body_writer commit_response(response_out out, std::uint16_t status, message_fields headers, + message_error& error) { + if (!detail::sendable(status)) { + error = {.code = message_errc::invalid_message}; + refuse_response(out); + return {}; + } +#ifdef WEBCPP_WASI_HTTP_P2 + auto const response = wasi_http_types_constructor_outgoing_response(headers.release()); + static_cast(wasi_http_types_method_outgoing_response_set_status_code( + wasi_http_types_borrow_outgoing_response(response), status)); + wasi_http_types_own_outgoing_body_t body{}; + if (!wasi_http_types_method_outgoing_response_body( + wasi_http_types_borrow_outgoing_response(response), &body)) { + wasi_http_types_outgoing_response_drop_own(response); + error = {.code = message_errc::invalid_state}; + refuse_response(out); + return {}; + } + wasi_http_types_result_own_outgoing_response_error_code_t result{}; + result.val.ok = response; + wasi_http_types_static_response_outparam_set(out, &result); + return body_writer(body); +#else + static_cast(out); + wasi_http_types_stream_u8_writer_t writer{}; + auto contents = wasi_http_types_stream_u8_new(&writer); + wasi_http_types_future_result_option_own_trailers_error_code_writer_t trailers_writer{}; + const auto trailers = + wasi_http_types_future_result_option_own_trailers_error_code_new(&trailers_writer); + wasi_http_types_tuple2_own_response_future_result_void_error_code_t made{}; + wasi_http_types_static_response_new(headers.release(), &contents, trailers, &made); + wasi_http_types_future_result_void_error_code_drop_readable(made.f1); + static_cast(wasi_http_types_method_response_set_status_code( + wasi_http_types_borrow_response(made.f0), status)); + exports_wasi_http_handler_result_own_response_error_code_t result{}; + result.val.ok = made.f0; + exports_wasi_http_handler_handle_return(result); + return {writer, trailers_writer}; +#endif +} + +/** A response received from the host client, including its body resource lifetime. */ +class incoming_response { +#ifdef WEBCPP_WASI_HTTP_P2 + detail::resource + response_; +#else + detail::resource response_; +#endif +public: + /** Constructs an empty response owner. */ + incoming_response() = default; + /** Transfers response ownership. */ + incoming_response(incoming_response&&) = default; + /** Replaces response ownership. + @return A reference to this object. */ + incoming_response& operator=(incoming_response&&) = default; +#ifdef WEBCPP_WASI_HTTP_P2 + /** Takes ownership of a P2 response. + @param value Incoming host response. */ + explicit incoming_response(wasi_http_types_own_incoming_response_t value) : response_(value) {} + + /** Returns the host response status code. + @return The HTTP status code. */ + [[nodiscard]] std::uint16_t status() const { + return wasi_http_types_method_incoming_response_status( + wasi_http_types_borrow_incoming_response(response_.get())); + } + + /** Acquires the exposed header fields. + @return Owning fields exposing the host headers. */ + [[nodiscard]] message_fields headers() const { + return message_fields(wasi_http_types_method_incoming_response_headers( + wasi_http_types_borrow_incoming_response(response_.get()))); + } + + /** Consumes the response or request body once. + @param error Receives a resource-state failure. + @return The body reader, or an empty reader on failure. */ + body_reader consume(message_error& error) { + wasi_http_types_own_incoming_body_t body{}; + if (!response_ || !wasi_http_types_method_incoming_response_consume( + wasi_http_types_borrow_incoming_response(response_.get()), &body)) { + error = {.code = message_errc::invalid_state}; + return {}; + } + return body_reader(body); + } +#else + /** Takes ownership of a P3 response. + @param value Incoming host response. */ + explicit incoming_response(wasi_http_types_own_response_t value) : response_(value) {} + + /** Returns the host response status code. + @return The HTTP status code. */ + [[nodiscard]] std::uint16_t status() const { + return wasi_http_types_method_response_get_status_code( + wasi_http_types_borrow_response(response_.get())); + } + + /** Acquires the exposed header fields. + @return Owning fields exposing the host headers. */ + [[nodiscard]] message_fields headers() const { + return message_fields(wasi_http_types_method_response_get_headers( + wasi_http_types_borrow_response(response_.get()))); + } + + /** Consumes the response or request body once. + @param error Receives a resource-state failure. + @return The body reader, or an empty reader on failure. */ + body_reader consume(message_error& error) { + if (!response_) { + error = {.code = message_errc::invalid_state}; + return {}; + } + wasi_http_types_future_result_void_error_code_writer_t writer{}; + auto const completion = wasi_http_types_future_result_void_error_code_new(&writer); + wasi_http_types_tuple2_stream_u8_future_result_option_own_trailers_error_code_t body{}; + wasi_http_types_static_response_consume_body(response_.release(), completion, &body); + return {body, writer}; + } +#endif +}; + +/** An outgoing exchange. + + Destroying it cancels a pending response; send the body before receive. */ +class outgoing_exchange { + friend class response_task; +#ifdef WEBCPP_WASI_HTTP_P2 + detail::resource + future_; +#else + std::uint32_t subtask_ = 0; + wasi_http_client_result_own_response_error_code_t result_{}; + bool started_ = false; + bool returned_ = false; +#endif +public: + /** Constructs an idle exchange. */ + outgoing_exchange() = default; + /** Forbids duplicate exchange ownership. */ + outgoing_exchange(const outgoing_exchange&) = delete; + /** Forbids duplicate exchange ownership. */ + outgoing_exchange& operator=(const outgoing_exchange&) = delete; +#ifdef WEBCPP_WASI_HTTP_P3 + /** Cancels any pending response and releases its resources. */ + ~outgoing_exchange() { + if (subtask_ != 0) { + auto status = webcpp_wasi_http_subtask_cancel(subtask_); + if ((status & 15U) != WEBCPP_WASI_HTTP_SUBTASK_RETURNED && + (status & 15U) != WEBCPP_WASI_HTTP_SUBTASK_RETURNED_CANCELLED) { + status = detail::wait_for(subtask_); + } + returned_ = returned_ || (status & 15U) == WEBCPP_WASI_HTTP_SUBTASK_RETURNED; + webcpp_wasi_http_subtask_drop(subtask_); + } + if (returned_) { + wasi_http_client_result_own_response_error_code_free(&result_); + } + } +#endif + /** Starts an outgoing host request without guest DNS, TCP or TLS. + @param scheme HTTP or HTTPS. + @param authority Host and optional port. + @param method HTTP method name. + @param target Path and query. + @param headers Fields transferred to the host. + @param error Receives any request construction or host failure. + @return The committed body writer, or an empty writer on failure. */ + body_writer start(std::string_view scheme, std::string_view authority, std::string_view method, + std::string_view target, message_fields headers, message_error& error) { + if (scheme != "http" && scheme != "https") { + error = {.code = message_errc::invalid_message}; + return {}; + } + auto path = detail::abi_string(target); + auto host = detail::abi_string(authority); + wasi_http_types_method_t verb{}; + verb.tag = WASI_HTTP_TYPES_METHOD_OTHER; + verb.val.other = detail::abi_string(method); + wasi_http_types_scheme_t protocol{}; + protocol.tag = + scheme == "https" ? WASI_HTTP_TYPES_SCHEME_HTTPS : WASI_HTTP_TYPES_SCHEME_HTTP; +#ifdef WEBCPP_WASI_HTTP_P2 + if (future_) { + error = {.code = message_errc::invalid_state}; + return {}; + } + detail::resource + request(wasi_http_types_constructor_outgoing_request(headers.release())); + const auto borrowed = wasi_http_types_borrow_outgoing_request(request.get()); + if (!wasi_http_types_method_outgoing_request_set_method(borrowed, &verb) || + !wasi_http_types_method_outgoing_request_set_path_with_query(borrowed, &path) || + !wasi_http_types_method_outgoing_request_set_scheme(borrowed, &protocol) || + !wasi_http_types_method_outgoing_request_set_authority(borrowed, &host)) { + error = {.code = message_errc::invalid_message}; + return {}; + } + wasi_http_types_own_outgoing_body_t body{}; + if (!wasi_http_types_method_outgoing_request_body(borrowed, &body)) { + error = {.code = message_errc::invalid_state}; + return {}; + } + body_writer writer(body); + wasi_http_types_own_future_incoming_response_t future{}; + wasi_http_types_error_code_t failure{}; + if (!wasi_http_outgoing_handler_handle(request.release(), nullptr, &future, &failure)) { + error = detail::host_failure(failure); + return {}; + } + future_.reset(future); + return writer; +#else + if (started_) { + error = {.code = message_errc::invalid_state}; + return {}; + } + wasi_http_types_stream_u8_writer_t writer_handle{}; + auto contents = wasi_http_types_stream_u8_new(&writer_handle); + wasi_http_types_future_result_option_own_trailers_error_code_writer_t trailers_writer{}; + auto const trailers = + wasi_http_types_future_result_option_own_trailers_error_code_new(&trailers_writer); + body_writer writer(writer_handle, trailers_writer); + wasi_http_types_tuple2_own_request_future_result_void_error_code_t made{}; + wasi_http_types_static_request_new(headers.release(), &contents, trailers, nullptr, &made); + wasi_http_types_future_result_void_error_code_drop_readable(made.f1); + detail::resource request( + made.f0); + auto const borrowed = wasi_http_types_borrow_request(request.get()); + if (!wasi_http_types_method_request_set_method(borrowed, &verb) || + !wasi_http_types_method_request_set_path_with_query(borrowed, &path) || + !wasi_http_types_method_request_set_scheme(borrowed, &protocol) || + !wasi_http_types_method_request_set_authority(borrowed, &host)) { + error = {.code = message_errc::invalid_message}; + return {}; + } + auto const status = wasi_http_client_send(request.release(), &result_); + started_ = true; + returned_ = (status & 15U) == WEBCPP_WASI_HTTP_SUBTASK_RETURNED; + subtask_ = status >> 4U; + return writer; +#endif + } + + /** Waits for response headers independently of its body. + @param options Cancellation and deadline. + @param error Receives any host or cancellation failure. + @return The response owner, or an empty owner on failure. */ + incoming_response receive(const transfer_options& options, message_error& error) { +#ifdef WEBCPP_WASI_HTTP_P2 + if (!future_) { + error = {.code = message_errc::invalid_state}; + return {}; + } + detail::pollable const ready(wasi_http_types_method_future_incoming_response_subscribe( + wasi_http_types_borrow_future_incoming_response(future_.get()))); + error = detail::wait_ready(ready.get(), options); + if (error) { + return {}; + } + wasi_http_types_result_result_own_incoming_response_error_code_void_t result{}; + if (!wasi_http_types_method_future_incoming_response_get( + wasi_http_types_borrow_future_incoming_response(future_.get()), &result) || + result.is_err) { + error = {.code = message_errc::invalid_state}; + return {}; + } + if (result.val.ok.is_err) { + error = detail::host_failure(result.val.ok.val.err); + return {}; + } + return incoming_response(result.val.ok.val.ok); +#else + if (!started_) { + error = {.code = message_errc::invalid_state}; + return {}; + } + while (!returned_) { + const auto status = detail::wait_operation(subtask_, options, error); + if (error) { + return {}; + } + returned_ = status == WEBCPP_WASI_HTTP_SUBTASK_RETURNED; + if (status == WEBCPP_WASI_HTTP_SUBTASK_RETURNED_CANCELLED) { + error = {.code = message_errc::cancelled}; + return {}; + } + } + if (subtask_ != 0) { + webcpp_wasi_http_subtask_drop(subtask_); + subtask_ = 0; + } + returned_ = false; + started_ = false; + if (result_.is_err) { + error = detail::host_failure(result_.val.err); + return {}; + } + return incoming_response(result_.val.ok); +#endif + } +}; + +} // namespace webcpp::wasi::http + +#endif diff --git a/include/webcpp/wasi/http/message.hpp b/include/webcpp/wasi/http/message.hpp new file mode 100644 index 0000000..eeb85dc --- /dev/null +++ b/include/webcpp/wasi/http/message.hpp @@ -0,0 +1,721 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WASI_HTTP_MESSAGE_HPP +#define WEBCPP_WASI_HTTP_MESSAGE_HPP + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::wasi::http { + +/** Errors of a host message operation, independent of a C++ exception runtime. */ +enum class message_errc : std::uint8_t { + /** No failure. */ + success = 0, + /** Invalid HTTP metadata. */ + invalid_message = 1, + /** A field forbidden by the host. */ + forbidden_header = 2, + /** The incoming body exceeded its configured limit. */ + body_limit = 3, + /** The caller cancelled the transfer. */ + cancelled = 4, + /** The transfer deadline expired. */ + timed_out = 5, + /** A stream closed before the operation completed. */ + closed = 6, + /** A pinned wasi:http error-code. */ + host_error = 7, + /** The resource has already been consumed or finished. */ + invalid_state = 8, +}; + +/** An operation failure, retaining the pinned wasi:http error-code discriminant. */ +struct message_error { + /** Portable failure classification. */ + message_errc code = message_errc::success; + /** Host error-code discriminant when code is host_error. */ + std::uint8_t host_code = 0; + + /** Whether this value represents failure. + @return Whether the object holds a resource or failure, as documented. */ + explicit operator bool() const noexcept { return code != message_errc::success; } +}; + +/** Limits shared by a transfer. + + Cancellation is checked while waiting and between chunks. */ +struct transfer_options { + /** Maximum incoming payload size in bytes. */ + std::uint64_t body_limit = static_cast(static_cast(1024) * 1024); + /** Absolute host monotonic deadline, or the maximum value for none. */ + std::uint64_t deadline = std::numeric_limits::max(); + /** Optional cancellation predicate, called on the component task. */ + bool (*cancelled)(void*) = nullptr; + /** Opaque state supplied to the cancellation predicate. */ + void* cancellation_context = nullptr; + + /** Sets an absolute monotonic deadline. + @param nanoseconds Duration from the current host monotonic time. */ + void expires_after(std::uint64_t nanoseconds) { + const auto now = wasi_clocks_monotonic_clock_now(); + deadline = nanoseconds > std::numeric_limits::max() - now + ? std::numeric_limits::max() + : now + nanoseconds; + } + + /** Checks the cancellation source and the absolute deadline. + @return An empty error value on success, otherwise the failure. */ + [[nodiscard]] message_error check() const { + if ((cancelled != nullptr) && cancelled(cancellation_context)) { + return {.code = message_errc::cancelled}; + } + if (deadline != std::numeric_limits::max() && + wasi_clocks_monotonic_clock_now() >= deadline) { + return {.code = message_errc::timed_out}; + } + return {}; + } +}; + +namespace detail { + +/** Owns one component resource, including handle zero, with move-only lifetime. */ +template +class resource { + std::optional value_; + +public: + /** Constructs an empty owner. */ + resource() = default; + + /** Takes ownership of one handle. */ + explicit resource(Handle value) : value_(value) {} + + /** Forbids duplicated resource ownership. */ + resource(const resource&) = delete; + /** Forbids duplicated resource ownership. */ + resource& operator=(const resource&) = delete; + + /** Transfers resource ownership. */ + resource(resource&& other) noexcept : value_(std::exchange(other.value_, {})) {} + + /** Replaces ownership with another resource. + @return A reference to this object. */ + resource& operator=(resource&& other) noexcept { + if (this != &other) { + reset(); + value_ = std::exchange(other.value_, {}); + } + return *this; + } + + /** Drops a remaining handle. */ + ~resource() { reset(); } + + /** Whether this object owns a handle. + @return Whether the object holds a resource or failure, as documented. */ + explicit operator bool() const noexcept { return value_.has_value(); } + + /** Borrows the owned handle. + @return The borrowed resource handle. */ + [[nodiscard]] Handle get() const { + assert(value_.has_value()); + return *value_; + } + + /** Transfers the handle to the caller. + @return The resource handle, whose ownership passes to the caller. */ + Handle release() { + assert(value_.has_value()); + auto value = *value_; + value_.reset(); + return value; + } + + /** Releases the owned handle. */ + void reset() { + if (value_) { + Drop(*value_); + value_.reset(); + } + } + + /** Replaces the owned handle. */ + void reset(Handle value) { + reset(); + value_ = value; + } +}; + +/** Borrows an ABI string without allocating. */ +inline webcpp_wasi_http_string_t abi_string(std::string_view value) { + return { + .ptr = reinterpret_cast(const_cast(value.data())), + .len = value.size(), + }; +} + +/** Captures a host error discriminant and frees its ABI payload. */ +inline message_error host_failure(wasi_http_types_error_code_t& error) { + const auto code = error.tag; + wasi_http_types_error_code_free(&error); + return {.code = message_errc::host_error, .host_code = code}; +} + +#ifdef WEBCPP_WASI_HTTP_P2 +/** Scoped ownership of a P2 pollable. */ +using pollable = resource; + +/** Waits for P2 readiness while checking cancellation and deadline. */ +inline message_error wait_ready(wasi_io_poll_own_pollable_t source, + const transfer_options& options) { + while (!wasi_io_poll_method_pollable_ready(wasi_io_poll_borrow_pollable(source))) { + if (auto error = options.check()) { + return error; + } + const auto now = wasi_clocks_monotonic_clock_now(); + const auto until = std::min(options.deadline, now + 10000000); + pollable const timer(wasi_clocks_monotonic_clock_subscribe_instant(until)); + std::array values{ + wasi_io_poll_borrow_pollable(source), + wasi_io_poll_borrow_pollable(timer.get()), + }; + wasi_io_poll_list_borrow_pollable_t pending{.ptr = values.data(), .len = values.size()}; + webcpp_wasi_http_list_u32_t ready{}; + wasi_io_poll_poll(&pending, &ready); + webcpp_wasi_http_list_u32_free(&ready); + } + return options.check(); +} +#else +/** Waits without using wasi-libc's task context slots. */ +inline std::uint32_t wait_operation(std::uint32_t waitable, const transfer_options& options, + message_error& error) { + const auto set = webcpp_wasi_http_waitable_set_new(); + webcpp_wasi_http_waitable_join(waitable, set); + std::uint32_t answer = 0; + for (;;) { + error = options.check(); + if (error) { + break; + } + const auto now = wasi_clocks_monotonic_clock_now(); + const auto timer_status = + wasi_clocks_monotonic_clock_wait_until(std::min(options.deadline, now + 10000000)); + const auto timer = timer_status >> 4U; + if (timer == 0) { + continue; + } + webcpp_wasi_http_waitable_join(timer, set); + webcpp_wasi_http_event_t event{}; + webcpp_wasi_http_waitable_set_wait(set, &event); + if (timer != 0) { + webcpp_wasi_http_waitable_join(timer, 0); + if (event.waitable != timer) { + const auto cancelled = webcpp_wasi_http_subtask_cancel(timer); + if ((cancelled & 15U) != WEBCPP_WASI_HTTP_SUBTASK_RETURNED && + (cancelled & 15U) != WEBCPP_WASI_HTTP_SUBTASK_RETURNED_CANCELLED) { + static_cast(wait_for(timer)); + } + } + webcpp_wasi_http_subtask_drop(timer); + } + if (event.waitable == waitable) { + answer = event.code; + break; + } + } + webcpp_wasi_http_waitable_join(waitable, 0); + webcpp_wasi_http_waitable_set_drop(set); + return answer; +} +#endif +} // namespace detail + +/** Owning HTTP fields. + + Duplicate values retain their order. */ +class message_fields { + detail::resource fields_; + +public: + /** Constructs empty mutable fields in the host. */ + message_fields() : fields_(wasi_http_types_constructor_fields()) {} + + /** Takes ownership of host fields. + @param fields The host resource to consume. */ + explicit message_fields(wasi_http_types_own_fields_t fields) : fields_(fields) {} + + /** Transfers the field resource. */ + message_fields(message_fields&&) = default; + /** Replaces the field resource. + @return A reference to this object. */ + message_fields& operator=(message_fields&&) = default; + + /** Transfers the resource to the component ABI. + @return The resource handle, whose ownership passes to the caller. */ + auto release() { return fields_.release(); } + + /** Appends a field without silently dropping forbidden values. + @param name Field name. + @param value Field value. + @return An empty error value on success, otherwise the failure. */ + message_error append(std::string_view name, std::string_view value) { + auto key = detail::abi_string(name); + wasi_http_types_field_value_t bytes{ + .ptr = reinterpret_cast(const_cast(value.data())), + .len = value.size(), + }; + wasi_http_types_header_error_t error{}; + if (wasi_http_types_method_fields_append(wasi_http_types_borrow_fields(fields_.get()), &key, + &bytes, &error)) { + return {}; + } + const auto code = error.tag; + wasi_http_types_header_error_free(&error); + return { + .code = code == WASI_HTTP_TYPES_HEADER_ERROR_FORBIDDEN ? message_errc::forbidden_header + : message_errc::invalid_message, + }; + } + + /** Visits borrowed field strings, valid only during the call. + @tparam Visitor Callable accepting name and value string views. + @param visitor Callback invoked for each field. */ + template + void for_each(Visitor&& visitor) const { + wasi_http_types_list_tuple2_field_name_field_value_t list{}; +#ifdef WEBCPP_WASI_HTTP_P2 + wasi_http_types_method_fields_entries(wasi_http_types_borrow_fields(fields_.get()), &list); +#else + wasi_http_types_method_fields_copy_all(wasi_http_types_borrow_fields(fields_.get()), &list); +#endif + struct cleanup { + wasi_http_types_list_tuple2_field_name_field_value_t* list; + + ~cleanup() { wasi_http_types_list_tuple2_field_name_field_value_free(list); } + } const guard{&list}; + + for (std::size_t i = 0; i != list.len; ++i) { + visitor(detail::view_of(list.ptr[i].f0), + std::string_view(reinterpret_cast(list.ptr[i].f1.ptr), + list.ptr[i].f1.len)); + } + } +}; + +/** A host body reader, with bounded partial I/O and explicit trailers completion. */ +class body_reader { + friend class read_task; +#ifdef WEBCPP_WASI_HTTP_P2 + detail::resource + body_; + detail::resource + stream_; +#else + detail::resource stream_; + detail::resource + trailers_; + detail::resource + completion_; +#endif + std::uint64_t received_ = 0; + bool eof_ = false; + +public: + /** Constructs an empty reader. */ + body_reader() = default; + + /** Fails and releases any unfinished body. */ + ~body_reader() { +#ifdef WEBCPP_WASI_HTTP_P3 + // A P3 future writer must publish a value even when the body was abandoned. + if (completion_) { + stream_.reset(); + trailers_.reset(); + wasi_http_types_result_void_error_code_t result{}; + result.is_err = true; + result.val.err.tag = WASI_HTTP_TYPES_ERROR_CODE_INTERNAL_ERROR; + const auto status = + wasi_http_types_future_result_void_error_code_write(completion_.get(), &result); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + detail::wait_for(completion_.get()); + } + completion_.reset(); + } +#endif + } + + /** Transfers body ownership. */ + body_reader(body_reader&&) = default; + /** Forbids replacing a potentially unfinished body. */ + body_reader& operator=(body_reader&&) = delete; +#ifdef WEBCPP_WASI_HTTP_P2 + /** Takes ownership of a P2 incoming body. + @param body Incoming body resource. */ + explicit body_reader(wasi_http_types_own_incoming_body_t body) : body_(body) { + wasi_io_streams_own_input_stream_t stream{}; + if (wasi_http_types_method_incoming_body_stream(wasi_http_types_borrow_incoming_body(body), + &stream)) { + stream_.reset(stream); + } + } +#else + /** Takes ownership of P3 body and completion resources. + @param body Content reader and trailer future. + @param completion Completion writer resolved after consuming the body. */ + body_reader( + wasi_http_types_tuple2_stream_u8_future_result_option_own_trailers_error_code_t body, + wasi_http_types_future_result_void_error_code_writer_t completion) + : stream_(body.f0), trailers_(body.f1), completion_(completion) {} +#endif + /** Whether the content stream has reached its end; finish still checks body failure. + @return Whether the body content stream has ended. */ + [[nodiscard]] bool eof() const noexcept { return eof_; } + + /** Reads at most the supplied span. + @param output Destination bytes. + @param options Body limit, cancellation and deadline. + @param error Receives any failure. + @return The number of bytes transferred before completion or failure. */ + std::size_t read_some(std::span output, const transfer_options& options, + message_error& error) { + error = options.check(); + if (error || eof_ || output.empty()) { + return 0; + } + if (!stream_) { + error = {.code = message_errc::invalid_state}; + return 0; + } + std::size_t count = 0; +#ifdef WEBCPP_WASI_HTTP_P2 + for (;;) { + webcpp_wasi_http_list_u8_t bytes{}; + wasi_io_streams_stream_error_t stream_error{}; + if (!wasi_io_streams_method_input_stream_read( + wasi_io_streams_borrow_input_stream(stream_.get()), output.size(), &bytes, + &stream_error)) { + if (stream_error.tag == WASI_IO_STREAMS_STREAM_ERROR_CLOSED) { + eof_ = true; + } else { + error = {.code = message_errc::closed}; + } + wasi_io_streams_stream_error_free(&stream_error); + break; + } + count = bytes.len; + std::copy_n(reinterpret_cast(bytes.ptr), count, output.data()); + webcpp_wasi_http_list_u8_free(&bytes); + if (count != 0) { + break; + } + detail::pollable const ready(wasi_io_streams_method_input_stream_subscribe( + wasi_io_streams_borrow_input_stream(stream_.get()))); + error = detail::wait_ready(ready.get(), options); + if (error) { + break; + } + } +#else + auto status = wasi_http_types_stream_u8_read( + stream_.get(), reinterpret_cast(output.data()), output.size()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_operation(stream_.get(), options, error); + if (error) { + status = wasi_http_types_stream_u8_cancel_read(stream_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_for(stream_.get()); + } + } + } + count = status >> 4U; + eof_ = (status & 15U) == WEBCPP_WASI_HTTP_WAITABLE_DROPPED; +#endif + if (count > options.body_limit - std::min(received_, options.body_limit)) { + error = {.code = message_errc::body_limit}; + return 0; + } + received_ += count; + return count; + } + + /** Resolves body completion, then visits trailers. + + Call after EOF. + @tparam Visitor Callable accepting trailer name and value views. + @param visitor Callback for the received trailers. + @param options Cancellation and deadline while waiting for trailers. + @return An empty error value on success, otherwise the failure. */ + template + message_error finish(Visitor&& visitor, const transfer_options& options) { + if (!eof_) { + return {.code = message_errc::invalid_state}; + } + stream_.reset(); + wasi_http_types_result_option_own_trailers_error_code_t result{}; +#ifdef WEBCPP_WASI_HTTP_P2 + if (!body_) { + return {.code = message_errc::invalid_state}; + } + detail::resource const + future(wasi_http_types_static_incoming_body_finish(body_.release())); + detail::pollable const ready(wasi_http_types_method_future_trailers_subscribe( + wasi_http_types_borrow_future_trailers(future.get()))); + if (auto error = detail::wait_ready(ready.get(), options)) { + return error; + } + wasi_http_types_result_result_option_own_trailers_error_code_void_t outer{}; + if (!wasi_http_types_method_future_trailers_get( + wasi_http_types_borrow_future_trailers(future.get()), &outer) || + outer.is_err) { + return {.code = message_errc::invalid_state}; + } + result = outer.val.ok; +#else + if (!trailers_) { + return {.code = message_errc::invalid_state}; + } + message_error error; + auto status = wasi_http_types_future_result_option_own_trailers_error_code_read( + trailers_.get(), &result); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_operation(trailers_.get(), options, error); + if (error) { + status = wasi_http_types_future_result_option_own_trailers_error_code_cancel_read( + trailers_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + detail::wait_for(trailers_.get()); + } + return error; + } + } + trailers_.reset(); + if ((status & 15U) != WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + return {.code = message_errc::closed}; + } + const wasi_http_types_result_void_error_code_t completed{}; + auto const written = + wasi_http_types_future_result_void_error_code_write(completion_.get(), &completed); + if (written == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + detail::wait_for(completion_.get()); + } + completion_.reset(); +#endif + if (result.is_err) { + return detail::host_failure(result.val.err); + } + if (result.val.ok.is_some) { + message_fields const trailers(result.val.ok.val); + trailers.for_each(std::forward(visitor)); + } + return {}; + } +}; + +/** A committed body writer. + + Destruction without finish fails the body, never commits again. */ +class body_writer { + friend class write_task; +#ifdef WEBCPP_WASI_HTTP_P2 + detail::resource + body_; + detail::resource + stream_; +#else + detail::resource + stream_; + detail::resource + trailers_; +#endif +public: + /** Constructs an empty writer. */ + body_writer() = default; + + /** Fails and releases any unfinished outgoing body. */ + ~body_writer() { +#ifdef WEBCPP_WASI_HTTP_P3 + // A failed body closes its content stream and resolves trailers as an error. + if (trailers_) { + stream_.reset(); + wasi_http_types_result_option_own_trailers_error_code_t result{}; + result.is_err = true; + result.val.err.tag = WASI_HTTP_TYPES_ERROR_CODE_INTERNAL_ERROR; + auto const status = wasi_http_types_future_result_option_own_trailers_error_code_write( + trailers_.get(), &result); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + detail::wait_for(trailers_.get()); + } + trailers_.reset(); + } +#endif + } + + /** Transfers outgoing body ownership. */ + body_writer(body_writer&&) = default; + /** Forbids replacing a potentially unfinished body. */ + body_writer& operator=(body_writer&&) = delete; +#ifdef WEBCPP_WASI_HTTP_P2 + /** Takes ownership of a P2 outgoing body. + @param body The outgoing body resource. */ + explicit body_writer(wasi_http_types_own_outgoing_body_t body) : body_(body) { + wasi_io_streams_own_output_stream_t stream{}; + if (wasi_http_types_method_outgoing_body_write(wasi_http_types_borrow_outgoing_body(body), + &stream)) { + stream_.reset(stream); + } + } +#else + /** Takes ownership of P3 body writers. + @param stream Content writer. + @param trailers Completion and trailers writer. */ + body_writer(wasi_http_types_stream_u8_writer_t stream, + wasi_http_types_future_result_option_own_trailers_error_code_writer_t trailers) + : stream_(stream), trailers_(trailers) {} +#endif + /** Writes a partial span, waiting only for host readiness and honouring transfer cancellation. + @param bytes Source payload bytes. + @param options Cancellation and deadline. + @param error Receives any transfer failure. + @return The number of bytes transferred before completion or failure. */ + std::size_t write_some(std::string_view bytes, const transfer_options& options, + message_error& error) { + error = options.check(); + if (error || bytes.empty()) { + return 0; + } + if (!stream_) { + error = {.code = message_errc::invalid_state}; + return 0; + } +#ifdef WEBCPP_WASI_HTTP_P2 + std::uint64_t available = 0; + wasi_io_streams_stream_error_t failed{}; + while (available == 0) { + if (!wasi_io_streams_method_output_stream_check_write( + wasi_io_streams_borrow_output_stream(stream_.get()), &available, &failed)) { + wasi_io_streams_stream_error_free(&failed); + error = {.code = message_errc::closed}; + return 0; + } + if (available != 0) { + break; + } + detail::pollable const ready(wasi_io_streams_method_output_stream_subscribe( + wasi_io_streams_borrow_output_stream(stream_.get()))); + error = detail::wait_ready(ready.get(), options); + if (error) { + return 0; + } + } + const auto count = + std::min({bytes.size(), static_cast(available), 4096}); + webcpp_wasi_http_list_u8_t buffer{ + .ptr = reinterpret_cast(const_cast(bytes.data())), + .len = count, + }; + if (!wasi_io_streams_method_output_stream_write( + wasi_io_streams_borrow_output_stream(stream_.get()), &buffer, &failed)) { + wasi_io_streams_stream_error_free(&failed); + error = {.code = message_errc::closed}; + return 0; + } + return count; +#else + auto status = wasi_http_types_stream_u8_write( + stream_.get(), reinterpret_cast(bytes.data()), bytes.size()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_operation(stream_.get(), options, error); + if (error) { + status = wasi_http_types_stream_u8_cancel_write(stream_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_for(stream_.get()); + } + } + } + if (!error && (status & 15U) != WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + error = {.code = message_errc::closed}; + } + return status >> 4U; +#endif + } + + /** Writes all supplied bytes, with bounded host buffering. + @param bytes Source payload. + @param options Cancellation and deadline. + @return An empty error value on success, otherwise the failure. */ + message_error write(std::string_view bytes, const transfer_options& options = {}) { + message_error error; + while (!bytes.empty()) { + const auto written = write_some(bytes, options, error); + if (error) { + return error; + } + bytes.remove_prefix(written); + } + return {}; + } + + /** Finishes the only committed body. + @param trailers Optional fields whose resource is transferred to the host. + @return An empty error value on success, otherwise the failure. */ + message_error finish(message_fields* trailers = nullptr) { + stream_.reset(); +#ifdef WEBCPP_WASI_HTTP_P2 + if (!body_) { + return {.code = message_errc::invalid_state}; + } + wasi_http_types_own_fields_t fields{}; + if (trailers != nullptr) { + fields = trailers->release(); + } + wasi_http_types_error_code_t error{}; + if (!wasi_http_types_static_outgoing_body_finish( + body_.release(), (trailers != nullptr) ? &fields : nullptr, &error)) { + return detail::host_failure(error); + } +#else + if (!trailers_) { + return {.code = message_errc::invalid_state}; + } + wasi_http_types_result_option_own_trailers_error_code_t result{}; + result.val.ok.is_some = trailers != nullptr; + if (trailers != nullptr) { + result.val.ok.val = trailers->release(); + } + auto status = wasi_http_types_future_result_option_own_trailers_error_code_write( + trailers_.get(), &result); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_for(trailers_.get()); + } + trailers_.reset(); + if ((status & 15U) != WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + wasi_http_types_result_option_own_trailers_error_code_free(&result); + return {.code = message_errc::closed}; + } +#endif + return {}; + } +}; + +} // namespace webcpp::wasi::http + +#endif diff --git a/include/webcpp/wasi/http/poll.hpp b/include/webcpp/wasi/http/poll.hpp new file mode 100644 index 0000000..17c93dd --- /dev/null +++ b/include/webcpp/wasi/http/poll.hpp @@ -0,0 +1,460 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WASI_HTTP_POLL_HPP +#define WEBCPP_WASI_HTTP_POLL_HPP +#include + +namespace webcpp::wasi::http { +namespace detail { +#ifdef WEBCPP_WASI_HTTP_P3 +/** Checks one pending operation without waiting for host readiness. */ +inline std::uint32_t poll_operation(std::uint32_t handle) { + auto const set = webcpp_wasi_http_waitable_set_new(); + webcpp_wasi_http_waitable_join(handle, set); + webcpp_wasi_http_event_t event{}; + webcpp_wasi_http_waitable_set_poll(set, &event); + webcpp_wasi_http_waitable_join(handle, 0); + webcpp_wasi_http_waitable_set_drop(set); + return event.event == WEBCPP_WASI_HTTP_EVENT_NONE ? WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED + : event.code; +} +#endif +/** Yields the current component task for one millisecond between readiness scans. */ +inline void yield_polling_task() { +#ifdef WEBCPP_WASI_HTTP_P2 + pollable const timer(wasi_clocks_monotonic_clock_subscribe_duration(1000000)); + wasi_io_poll_method_pollable_block(wasi_io_poll_borrow_pollable(timer.get())); +#else + auto status = + wasi_clocks_monotonic_clock_wait_until(wasi_clocks_monotonic_clock_now() + 1000000); + auto const task = status >> 4U; + if (task != 0u) { + while ((status & 15U) != WEBCPP_WASI_HTTP_SUBTASK_RETURNED && + (status & 15U) != WEBCPP_WASI_HTTP_SUBTASK_RETURNED_CANCELLED) { + status = wait_for(task); + } + webcpp_wasi_http_subtask_drop(task); + } +#endif +} +} // namespace detail + +/** Owns a nonblocking body read and its pending completion resources. + + A pending read borrows the same destination span until a later poll completes. + Destroying this object cancels pending host access before releasing resources. */ +class read_task { + body_reader body_; +#ifdef WEBCPP_WASI_HTTP_P2 + detail::resource + trailers_; + detail::pollable ready_; +#else + bool reading_ = false; + bool finishing_ = false; + bool completing_ = false; + bool result_ready_ = false; + wasi_http_types_result_option_own_trailers_error_code_t result_{}; + wasi_http_types_result_void_error_code_t completed_{}; +#endif + bool finished_ = false; + +public: + /** Takes ownership of an incoming body. + @param body Incoming body owner. */ + explicit read_task(body_reader body) : body_(std::move(body)) {} + + /** Forbids moving a task with host-borrowed result storage. */ + read_task(read_task&&) = delete; + + /** Cancels pending host operations before releasing their borrowed memory. */ + ~read_task() { +#ifdef WEBCPP_WASI_HTTP_P3 + if (reading_) { + auto const status = wasi_http_types_stream_u8_cancel_read(body_.stream_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + detail::wait_for(body_.stream_.get()); + } + } + if (finishing_) { + auto status = wasi_http_types_future_result_option_own_trailers_error_code_cancel_read( + body_.trailers_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_for(body_.trailers_.get()); + } + result_ready_ = (status & 15U) == WEBCPP_WASI_HTTP_WAITABLE_COMPLETED; + } + if (completing_) { + auto status = + wasi_http_types_future_result_void_error_code_cancel_write(body_.completion_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_for(body_.completion_.get()); + } + if ((status & 15U) == WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + body_.completion_.reset(); + } + } + if (result_ready_) { + wasi_http_types_result_option_own_trailers_error_code_free(&result_); + } +#endif + } + + /** Reports whether body content ended; finish still resolves trailers. + @return Whether input reached EOF. */ + [[nodiscard]] bool eof() const noexcept { return body_.eof_; } + + /** Polls one partial read without blocking for data. + @param buffer Stable destination while a read is pending. + @param count Receives the completed byte count. + @param options Incoming limit, cancellation and deadline. + @param error Receives any completed failure. + @return False while pending, true when bytes, EOF or failure are available. */ + bool read(std::span buffer, std::size_t& count, const transfer_options& options, + message_error& error) { + count = 0; + error = options.check(); + if (error || eof() || buffer.empty()) { + return true; + } + if (!body_.stream_) { + error = {.code = message_errc::invalid_state}; + return true; + } +#ifdef WEBCPP_WASI_HTTP_P2 + webcpp_wasi_http_list_u8_t bytes{}; + wasi_io_streams_stream_error_t failure{}; + if (!wasi_io_streams_method_input_stream_read( + wasi_io_streams_borrow_input_stream(body_.stream_.get()), buffer.size(), &bytes, + &failure)) { + if (failure.tag == WASI_IO_STREAMS_STREAM_ERROR_CLOSED) { + body_.eof_ = true; + } else { + error = {.code = message_errc::closed}; + } + wasi_io_streams_stream_error_free(&failure); + return true; + } + count = bytes.len; + std::copy_n(reinterpret_cast(bytes.ptr), count, buffer.data()); + webcpp_wasi_http_list_u8_free(&bytes); + if (count == 0u) { + return false; + } +#else + auto const status = + reading_ ? detail::poll_operation(body_.stream_.get()) + : wasi_http_types_stream_u8_read( + body_.stream_.get(), reinterpret_cast(buffer.data()), + buffer.size()); + reading_ = status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED; + if (reading_) { + return false; + } + count = status >> 4U; + body_.eof_ = (status & 15U) == WEBCPP_WASI_HTTP_WAITABLE_DROPPED; +#endif + if (count > options.body_limit - std::min(body_.received_, options.body_limit)) { + count = 0; + error = {.code = message_errc::body_limit}; + } else { + body_.received_ += count; + } + return true; + } + + /** Polls trailers and consumption completion after EOF. + @tparam Visitor Callable accepting trailer name and value views. + @param visitor Callback for complete trailer fields. + @param options Cancellation and deadline. + @param error Receives any completed failure. + @return False while pending, true on completion or failure. */ + template + bool finish(Visitor&& visitor, const transfer_options& options, message_error& error) { + error = options.check(); + if (error) { + return true; + } + if (!eof() || finished_) { + error = {.code = message_errc::invalid_state}; + return true; + } + body_.stream_.reset(); +#ifdef WEBCPP_WASI_HTTP_P2 + if (!trailers_) { + trailers_.reset(wasi_http_types_static_incoming_body_finish(body_.body_.release())); + } + if (!ready_) { + ready_.reset(wasi_http_types_method_future_trailers_subscribe( + wasi_http_types_borrow_future_trailers(trailers_.get()))); + } + if (!wasi_io_poll_method_pollable_ready(wasi_io_poll_borrow_pollable(ready_.get()))) { + return false; + } + wasi_http_types_result_result_option_own_trailers_error_code_void_t outer{}; + if (!wasi_http_types_method_future_trailers_get( + wasi_http_types_borrow_future_trailers(trailers_.get()), &outer)) { + return false; + } + ready_.reset(); + trailers_.reset(); + if (outer.is_err) { + error = {.code = message_errc::invalid_state}; + return true; + } + auto result = outer.val.ok; +#else + if (!result_ready_) { + auto const status = + finishing_ ? detail::poll_operation(body_.trailers_.get()) + : wasi_http_types_future_result_option_own_trailers_error_code_read( + body_.trailers_.get(), &result_); + finishing_ = status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED; + if (finishing_) { + return false; + } + body_.trailers_.reset(); + if ((status & 15U) != WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + error = {.code = message_errc::closed}; + return true; + } + result_ready_ = true; + } + auto const status = completing_ ? detail::poll_operation(body_.completion_.get()) + : wasi_http_types_future_result_void_error_code_write( + body_.completion_.get(), &completed_); + completing_ = status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED; + if (completing_) { + return false; + } + body_.completion_.reset(); + auto result = result_; + result_ready_ = false; +#endif + finished_ = true; + if (result.is_err) { + error = detail::host_failure(result.val.err); + } else if (result.val.ok.is_some) { + message_fields const fields(result.val.ok.val); + fields.for_each(std::forward(visitor)); + } + return true; + } +}; + +/** Owns a nonblocking body write and stable pending trailer storage. */ +class write_task { + body_writer body_; +#ifdef WEBCPP_WASI_HTTP_P3 + bool writing_ = false; + bool finishing_ = false; + wasi_http_types_result_option_own_trailers_error_code_t result_{}; +#endif +public: + /** Takes ownership of the only outgoing body. + @param body Outgoing body owner. */ + explicit write_task(body_writer body) : body_(std::move(body)) {} + + /** Forbids moving a task with host-borrowed result storage. */ + write_task(write_task&&) = delete; + + /** Cancels pending writes before releasing borrowed payload storage. */ + ~write_task() { +#ifdef WEBCPP_WASI_HTTP_P3 + if (writing_) { + auto const status = wasi_http_types_stream_u8_cancel_write(body_.stream_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + detail::wait_for(body_.stream_.get()); + } + } + if (finishing_) { + auto status = wasi_http_types_future_result_option_own_trailers_error_code_cancel_write( + body_.trailers_.get()); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + status = detail::wait_for(body_.trailers_.get()); + } + if ((status & 15U) == WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + body_.trailers_.reset(); + } else { + wasi_http_types_result_option_own_trailers_error_code_free(&result_); + } + } +#endif + } + + /** Polls a bounded partial write without waiting for readiness. + @param bytes Stable source until the pending write completes. + @param count Receives the completed byte count. + @param options Cancellation and deadline. + @param error Receives any completed failure. + @return False while pending, true when bytes or failure are available. */ + bool write(std::string_view bytes, std::size_t& count, const transfer_options& options, + message_error& error) { + count = 0; + error = options.check(); + if (error || bytes.empty()) { + return true; + } + if (!body_.stream_) { + error = {.code = message_errc::invalid_state}; + return true; + } +#ifdef WEBCPP_WASI_HTTP_P2 + std::uint64_t available = 0; + wasi_io_streams_stream_error_t failure{}; + if (!wasi_io_streams_method_output_stream_check_write( + wasi_io_streams_borrow_output_stream(body_.stream_.get()), &available, &failure)) { + wasi_io_streams_stream_error_free(&failure); + error = {.code = message_errc::closed}; + return true; + } + if (available == 0u) { + return false; + } + count = std::min({bytes.size(), static_cast(available), 4096}); + webcpp_wasi_http_list_u8_t buffer{ + .ptr = reinterpret_cast(const_cast(bytes.data())), + .len = count, + }; + if (!wasi_io_streams_method_output_stream_write( + wasi_io_streams_borrow_output_stream(body_.stream_.get()), &buffer, &failure)) { + wasi_io_streams_stream_error_free(&failure); + count = 0; + error = {.code = message_errc::closed}; + } +#else + auto const status = + writing_ ? detail::poll_operation(body_.stream_.get()) + : wasi_http_types_stream_u8_write( + body_.stream_.get(), reinterpret_cast(bytes.data()), + std::min(bytes.size(), 4096)); + writing_ = status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED; + if (writing_) { + return false; + } + count = status >> 4U; + if ((status & 15U) != WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + error = {.code = message_errc::closed}; + } +#endif + return true; + } + + /** Polls the final trailer write without committing another response. + @param trailers Optional fields consumed when finishing begins. + @param error Receives any completed failure. + @return False while pending, true on completion or failure. */ + bool finish(message_fields* trailers, message_error& error) { +#ifdef WEBCPP_WASI_HTTP_P2 + error = body_.finish(trailers); + return true; +#else + if (!body_.trailers_) { + error = {.code = message_errc::invalid_state}; + return true; + } + if (!finishing_) { + body_.stream_.reset(); + result_.val.ok.is_some = trailers != nullptr; + if (trailers != nullptr) { + result_.val.ok.val = trailers->release(); + } + } + auto const status = + finishing_ ? detail::poll_operation(body_.trailers_.get()) + : wasi_http_types_future_result_option_own_trailers_error_code_write( + body_.trailers_.get(), &result_); + finishing_ = status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED; + if (finishing_) { + return false; + } + body_.trailers_.reset(); + if ((status & 15U) != WEBCPP_WASI_HTTP_WAITABLE_COMPLETED) { + wasi_http_types_result_option_own_trailers_error_code_free(&result_); + error = {.code = message_errc::closed}; + } + return true; +#endif + } +}; + +/** Polls an outgoing exchange's response without waiting for network readiness. */ +class response_task { + outgoing_exchange& exchange_; +#ifdef WEBCPP_WASI_HTTP_P2 + detail::pollable ready_; +#endif + +public: + /** Borrows a started exchange until response completion. + @param exchange Started outgoing host exchange. */ + explicit response_task(outgoing_exchange& exchange) : exchange_(exchange) {} + + /** Polls response headers once. + @param response Receives ownership of the completed response. + @param options Cancellation and deadline. + @param error Receives any completed failure. + @return False while pending, true on response or failure. */ + bool poll(incoming_response& response, const transfer_options& options, message_error& error) { + error = options.check(); + if (error) { + return true; + } +#ifdef WEBCPP_WASI_HTTP_P2 + if (!exchange_.future_) { + error = {.code = message_errc::invalid_state}; + return true; + } + if (!ready_) { + ready_.reset(wasi_http_types_method_future_incoming_response_subscribe( + wasi_http_types_borrow_future_incoming_response(exchange_.future_.get()))); + } + if (!wasi_io_poll_method_pollable_ready(wasi_io_poll_borrow_pollable(ready_.get()))) { + return false; + } + wasi_http_types_result_result_own_incoming_response_error_code_void_t result{}; + if (!wasi_http_types_method_future_incoming_response_get( + wasi_http_types_borrow_future_incoming_response(exchange_.future_.get()), + &result)) { + return false; + } + ready_.reset(); + exchange_.future_.reset(); + if (result.is_err) { + error = {.code = message_errc::invalid_state}; + } else if (result.val.ok.is_err) { + error = detail::host_failure(result.val.ok.val.err); + } else { + response = incoming_response(result.val.ok.val.ok); + } +#else + if (!exchange_.started_) { + error = {.code = message_errc::invalid_state}; + return true; + } + if (!exchange_.returned_) { + auto status = detail::poll_operation(exchange_.subtask_); + if (status == WEBCPP_WASI_HTTP_WAITABLE_STATUS_BLOCKED) { + return false; + } + if (status == WEBCPP_WASI_HTTP_SUBTASK_RETURNED_CANCELLED) { + error = {.code = message_errc::cancelled}; + return true; + } + exchange_.returned_ = status == WEBCPP_WASI_HTTP_SUBTASK_RETURNED; + if (!exchange_.returned_) { + return false; + } + } + response = exchange_.receive(options, error); +#endif + return true; + } +}; +} // namespace webcpp::wasi::http +#endif diff --git a/include/webcpp/wasi/stdio.hpp b/include/webcpp/wasi/stdio.hpp new file mode 100644 index 0000000..e5c79ec --- /dev/null +++ b/include/webcpp/wasi/stdio.hpp @@ -0,0 +1,296 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_WASI_STDIO_HPP +#define WEBCPP_WASI_STDIO_HPP + +#include + +#include +#include +#include +#include +#include + +#ifdef __wasip3__ +#include // lint-world: wasi-sdk's standard CLI stream bindings +#elif defined(__wasip2__) +#include // lint-world: wasi-sdk's standard CLI stream bindings +#elif !defined(__MRDOCS__) && !defined(WEBCPP_WASI_HTTP_P2) && !defined(WEBCPP_WASI_HTTP_P3) +#error "webcpp::wasi::stdio_channel requires WASIp2 or WASIp3" +#endif + +namespace webcpp::wasi { + +/** The observable result of a partial host stream operation. */ +enum class stream_status { + /** Bytes transferred successfully. */ ready, + /** No progress before the bounded wait ended. */ blocked, + /** Input ended. */ eof, + /** The host reported an I/O failure. */ failed, +}; + +/** Bytes copied by a partial stream operation, independent of any wire protocol. */ +struct stream_result { + /** Bytes copied during this operation. */ + std::size_t count = 0; + /** Transfer status, distinct from the byte count. */ + stream_status status = stream_status::ready; +}; + +#if !defined(__wasip2__) && !defined(__wasip3__) +/** Owns standard WASI CLI streams. + + Readiness polling waits are bounded to ten milliseconds. */ +class stdio_channel { +public: + /** Acquires the standard input and output streams. */ + stdio_channel(); + /** Releases all owned CLI stream resources. */ + ~stdio_channel(); + /** Reads a partial byte span. + @param buffer Destination bytes. + @return The partial byte count and readiness or failure status. */ + stream_result read(std::span buffer); + /** Writes a partial byte span. + @param buffer Source bytes. + @return The partial byte count and readiness or failure status. */ + [[nodiscard]] stream_result write(std::span buffer) const; +}; +#else +/** Owns standard CLI stream resources directly, independently of libc's blocking descriptors. + + Readiness polling waits are bounded to ten milliseconds. Synchronous host imports + still follow the host blocking behavior. The caller checks cancellation/deadline + between operations. No callback or data pointer remains + borrowed by the host after an operation returns. Diagnostics must use stderr. */ +class stdio_channel { +#ifdef __wasip2__ + streams_own_input_stream_t input_ = stdin_get_stdin(); + streams_own_output_stream_t output_ = stdout_get_stdout(); + + static void wait(poll_own_pollable_t source) { + auto const timer = monotonic_clock_subscribe_duration(10000000); + std::array items{ + poll_borrow_pollable(source), + poll_borrow_pollable(timer), + }; + poll_list_borrow_pollable_t list{.ptr = items.data(), .len = items.size()}; + wasip2_list_u32_t ready{}; + poll_poll(&list, &ready); + wasip2_list_u32_free(&ready); + poll_pollable_drop_own(timer); + poll_pollable_drop_own(source); + } +#else + stdin_tuple2_stream_u8_future_result_void_error_code_t input_{}; + stdin_stream_u8_writer_t output_{}; + stdout_future_result_void_error_code_t output_result_{}; + bool eof_ = false; + bool completed_ = false; + bool failed_ = false; + + static std::uint32_t await(std::uint32_t handle) { + const auto set = wasip3_waitable_set_new(); + wasip3_waitable_join(handle, set); + wasip3_event_t event{}; + wasip3_waitable_set_wait(set, &event); + wasip3_waitable_join(handle, 0); + wasip3_waitable_set_drop(set); + return event.code; + } + + static std::uint32_t cancel(std::uint32_t handle, bool writing, bool future) { + if (future) { + return stdin_future_result_void_error_code_cancel_read(handle); + } + return writing ? stdin_stream_u8_cancel_write(handle) : stdin_stream_u8_cancel_read(handle); + } + + static std::uint32_t wait(std::uint32_t handle, bool writing, bool future = false) { + auto const timer_status = monotonic_clock_wait_until(monotonic_clock_now() + 10000000); + auto const timer = timer_status >> 4U; + if (timer == 0) { + const auto cancelled = cancel(handle, writing, future); + return cancelled == WASIP3_WAITABLE_STATUS_BLOCKED ? await(handle) : cancelled; + } + const auto set = wasip3_waitable_set_new(); + wasip3_waitable_join(handle, set); + wasip3_waitable_join(timer, set); + wasip3_event_t event{}; + wasip3_waitable_set_wait(set, &event); + wasip3_waitable_join(handle, 0); + wasip3_waitable_join(timer, 0); + wasip3_waitable_set_drop(set); + if (event.waitable != timer) { + auto const cancelled = wasip3_subtask_cancel(timer); + if ((cancelled & 15U) != WASIP3_SUBTASK_RETURNED && + (cancelled & 15U) != WASIP3_SUBTASK_RETURNED_CANCELLED) { + await(timer); + } + } + wasip3_subtask_drop(timer); + if (event.waitable == handle) { + return event.code; + } + const auto cancelled = cancel(handle, writing, future); + return cancelled == WASIP3_WAITABLE_STATUS_BLOCKED ? await(handle) : cancelled; + } + + stream_result finish_input() { + if (!completed_) { + stdin_result_void_error_code_t result{}; + auto status = stdin_future_result_void_error_code_read(input_.f1, &result); + if (status == WASIP3_WAITABLE_STATUS_BLOCKED) { + status = wait(input_.f1, false, true); + } + if ((status & 15U) == WASIP3_WAITABLE_CANCELLED) { + return {.status = stream_status::blocked}; + } + completed_ = true; + failed_ = (status & 15U) != WASIP3_WAITABLE_COMPLETED || result.is_err; + if ((status & 15U) == WASIP3_WAITABLE_COMPLETED) { + stdin_result_void_error_code_free(&result); + } + } + return {.status = failed_ ? stream_status::failed : stream_status::eof}; + } + +#endif +public: + /** Acquires the standard input and output host streams. */ + stdio_channel() { +#ifdef __wasip3__ + stdin_read_via_stream(&input_); + const auto reader = stdin_stream_u8_new(&output_); + output_result_ = stdout_write_via_stream(reader); +#endif + } + + /** Forbids duplicated resource ownership. */ + stdio_channel(const stdio_channel&) = delete; + /** Forbids duplicated resource ownership. */ + stdio_channel& operator=(const stdio_channel&) = delete; + + /** Releases all stream resources. */ + ~stdio_channel() { +#ifdef __wasip2__ + streams_input_stream_drop_own(input_); + streams_output_stream_drop_own(output_); +#else + stdin_stream_u8_drop_readable(input_.f0); + stdin_future_result_void_error_code_drop_readable(input_.f1); + stdin_stream_u8_drop_writable(output_); + stdout_future_result_void_error_code_drop_readable(output_result_); +#endif + } + + /** Reads one bounded chunk with explicit EOF. + @param buffer Destination bytes. + @return The partial byte count and readiness or failure status. */ + stream_result read(std::span buffer) { + if (buffer.empty()) { + return {}; + } +#ifdef __wasip2__ + wasip2_list_u8_t bytes{}; + streams_stream_error_t error{}; + if (!streams_method_input_stream_read(streams_borrow_input_stream(input_), buffer.size(), + &bytes, &error)) { + const auto status = error.tag == STREAMS_STREAM_ERROR_CLOSED ? stream_status::eof + : stream_status::failed; + streams_stream_error_free(&error); + return {.count = 0, .status = status}; + } + const auto count = bytes.len; + std::copy_n(reinterpret_cast(bytes.ptr), count, buffer.data()); + wasip2_list_u8_free(&bytes); + if (count == 0) { + wait(streams_method_input_stream_subscribe(streams_borrow_input_stream(input_))); + return {.count = 0, .status = stream_status::blocked}; + } + return {.count = count}; +#else + if (eof_) { + return finish_input(); + } + auto status = stdin_stream_u8_read( + input_.f0, reinterpret_cast(buffer.data()), buffer.size()); + if (status == WASIP3_WAITABLE_STATUS_BLOCKED) { + status = wait(input_.f0, false); + } + const auto count = status >> 4U; + if ((status & 15U) == WASIP3_WAITABLE_DROPPED) { + eof_ = true; + } + if (count != 0) { + return {.count = count}; + } + return eof_ ? finish_input() : stream_result{.status = stream_status::blocked}; +#endif + } + + /** Writes one bounded chunk, reporting back-pressure explicitly. + @param buffer Source bytes. + @return The partial byte count and readiness or failure status. */ + [[nodiscard]] stream_result write(std::span buffer) const { + if (buffer.empty()) { + return {}; + } +#ifdef __wasip2__ + std::uint64_t available = 0; + streams_stream_error_t error{}; + if (!streams_method_output_stream_check_write(streams_borrow_output_stream(output_), + &available, &error)) { + streams_stream_error_free(&error); + return { + .count = 0, + .status = stream_status::failed, + }; + } + if (available == 0) { + wait(streams_method_output_stream_subscribe(streams_borrow_output_stream(output_))); + return {.count = 0, .status = stream_status::blocked}; + } + const auto count = + std::min({buffer.size(), static_cast(available), 4096}); + wasip2_list_u8_t bytes{ + .ptr = reinterpret_cast(const_cast(buffer.data())), + .len = count, + }; + if (!streams_method_output_stream_write(streams_borrow_output_stream(output_), &bytes, + &error)) { + streams_stream_error_free(&error); + return { + .count = 0, + .status = stream_status::failed, + }; + } + return {.count = count}; +#else + auto status = stdin_stream_u8_write( + output_, reinterpret_cast(buffer.data()), buffer.size()); + if (status == WASIP3_WAITABLE_STATUS_BLOCKED) { + status = wait(output_, true); + } + const auto count = status >> 4U; + if ((status & 15U) == WASIP3_WAITABLE_DROPPED) { + return { + .count = count, + .status = stream_status::failed, + }; + } + return { + .count = count, + .status = count == 0 ? stream_status::blocked : stream_status::ready, + }; +#endif + } +}; +#endif // Documentation declarations or WASI implementation. +} // namespace webcpp::wasi + +#endif diff --git a/test/Jamfile b/test/Jamfile index ec174d3..a31c189 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -69,3 +69,8 @@ webcpp.compile-diagnostic neither_target_refused : neither_target_refused.cpp : /webcpp/wasi//http-bindings ; webcpp.compile-diagnostic both_targets_refused : both_targets_refused.cpp : /webcpp/wasi//http-bindings WEBCPP_WASI_HTTP_P2 WEBCPP_WASI_HTTP_P3 ; + +# Host-only message operations and direct CLI streams are checked with their own bindings. +webcpp.headers-alone wasi : ../include : wasi/http/message.hpp wasi/http/host.hpp wasi/http/poll.hpp + : /webcpp/wasi//host-http ; +webcpp.headers-alone wasi : ../include : wasi/stdio.hpp ; diff --git a/wit/host-http-p2.wit b/wit/host-http-p2.wit new file mode 100644 index 0000000..7bded22 --- /dev/null +++ b/wit/host-http-p2.wit @@ -0,0 +1,14 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Incoming and outgoing host HTTP, independently of guest sockets. +package webcpp:wasi-http; + +world http { + import wasi:http/outgoing-handler@0.2.12; + import wasi:clocks/monotonic-clock@0.2.12; + export wasi:http/incoming-handler@0.2.12; +} diff --git a/wit/host-http-p3.wit b/wit/host-http-p3.wit new file mode 100644 index 0000000..1b86730 --- /dev/null +++ b/wit/host-http-p3.wit @@ -0,0 +1,14 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Incoming and outgoing host HTTP, independently of guest sockets. +package webcpp:wasi-http; + +world http { + import wasi:http/client@0.3.0; + import wasi:clocks/monotonic-clock@0.3.0; + export wasi:http/handler@0.3.0; +} From fb551ae6dc31e0ee9f3b9b90243c08fb673b4ef4 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 01:16:02 -0500 Subject: [PATCH 4/5] style: wrap the host-binding test comment [skip ci] --- test/Jamfile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/Jamfile b/test/Jamfile index a31c189..932bd9f 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -70,7 +70,8 @@ webcpp.compile-diagnostic neither_target_refused : neither_target_refused.cpp webcpp.compile-diagnostic both_targets_refused : both_targets_refused.cpp : /webcpp/wasi//http-bindings WEBCPP_WASI_HTTP_P2 WEBCPP_WASI_HTTP_P3 ; -# Host-only message operations and direct CLI streams are checked with their own bindings. +# Host-only message operations and direct CLI streams are checked with their +# own bindings. webcpp.headers-alone wasi : ../include : wasi/http/message.hpp wasi/http/host.hpp wasi/http/poll.hpp : /webcpp/wasi//host-http ; webcpp.headers-alone wasi : ../include : wasi/stdio.hpp ; From 80f573a1a35062866efd2367e41e7cff6dad7a63 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 3 Nov 2026 04:03:05 -0500 Subject: [PATCH 5/5] wasi: include runtime update in the 0.1.0 candidate notes [skip ci] --- doc/changelog.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index c71d0ac..d971b4d 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,13 +16,13 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Updated Wasmtime instructions to 50.0.1, preserving historical measurements. // end::unreleased[] [#wasi-changelog-0-1-0] === webcpp 0.1.0 // tag::0.1.0[] +* Updated Wasmtime instructions to 50.0.1, preserving historical measurements. * Fixed a status outside 100-599 answering 200 OK; it now answers an internal error. * Fixed a content type viewing the request's method or target not being