From 8fbe8498e7b634340e1562adf97e99322989d80f Mon Sep 17 00:00:00 2001 From: Jiaxiao Zhou Date: Thu, 13 Mar 2025 15:03:56 -0700 Subject: [PATCH 1/7] x/wasihttp: add wasihttp package This commit ports the wasihttp package from the [wasi-http-go](https://github.com/ydnar/wasi-http-go) repository to here under the `x/wasihttp` directory. The wasihttp package provides a WASI HTTP server and client implementation using Go net/http package. The ./x/wasihttp/internal directory is regenerated using `make go-bindings` command from the wasihttp Makefile. Examples can be found in the `x/wasihttp/examples` directory and can be run under the ./x/wasihttp working directory. This new package has its own CHANGELOG.md, README.md, and RELEASE.md files to document the changes, usage, and release notes. Signed-off-by: Jiaxiao Zhou --- x/wasihttp/CHANGELOG.md | 11 + x/wasihttp/README.md | 46 + x/wasihttp/RELEASE.md | 21 + x/wasihttp/docs.go | 11 + x/wasihttp/examples/basic/basic.go | 27 + x/wasihttp/examples/counter/counter.go | 33 + x/wasihttp/examples/proxy/proxy.go | 59 + x/wasihttp/examples/roundtrip/roundtrip.go | 80 + .../internal/go/http/proxy/proxy.wit.go | 6 + .../internal/wasi/cli/environment/empty.s | 3 + .../wasi/cli/environment/environment.wasm.go | 21 + .../wasi/cli/environment/environment.wit.go | 52 + x/wasihttp/internal/wasi/cli/exit/empty.s | 3 + .../internal/wasi/cli/exit/exit.wasm.go | 9 + x/wasihttp/internal/wasi/cli/exit/exit.wit.go | 21 + x/wasihttp/internal/wasi/cli/run/empty.s | 3 + .../internal/wasi/cli/run/run.exports.go | 17 + x/wasihttp/internal/wasi/cli/run/run.wasm.go | 17 + x/wasihttp/internal/wasi/cli/run/run.wit.go | 4 + x/wasihttp/internal/wasi/cli/stderr/empty.s | 3 + .../internal/wasi/cli/stderr/stderr.wasm.go | 9 + .../internal/wasi/cli/stderr/stderr.wit.go | 25 + x/wasihttp/internal/wasi/cli/stdin/empty.s | 3 + .../internal/wasi/cli/stdin/stdin.wasm.go | 9 + .../internal/wasi/cli/stdin/stdin.wit.go | 25 + x/wasihttp/internal/wasi/cli/stdout/empty.s | 3 + .../internal/wasi/cli/stdout/stdout.wasm.go | 9 + .../internal/wasi/cli/stdout/stdout.wit.go | 25 + .../internal/wasi/cli/terminal-input/empty.s | 3 + .../cli/terminal-input/terminal-input.wasm.go | 9 + .../cli/terminal-input/terminal-input.wit.go | 32 + .../internal/wasi/cli/terminal-output/empty.s | 3 + .../terminal-output/terminal-output.wasm.go | 9 + .../terminal-output/terminal-output.wit.go | 32 + .../internal/wasi/cli/terminal-stderr/empty.s | 3 + .../terminal-stderr/terminal-stderr.wasm.go | 13 + .../terminal-stderr/terminal-stderr.wit.go | 30 + .../internal/wasi/cli/terminal-stdin/empty.s | 3 + .../cli/terminal-stdin/terminal-stdin.wasm.go | 13 + .../cli/terminal-stdin/terminal-stdin.wit.go | 30 + .../internal/wasi/cli/terminal-stdout/empty.s | 3 + .../terminal-stdout/terminal-stdout.wasm.go | 13 + .../terminal-stdout/terminal-stdout.wit.go | 30 + .../wasi/clocks/monotonic-clock/empty.s | 3 + .../monotonic-clock/monotonic-clock.wasm.go | 21 + .../monotonic-clock/monotonic-clock.wit.go | 102 + .../internal/wasi/clocks/wall-clock/empty.s | 3 + .../wasi/clocks/wall-clock/wall-clock.wasm.go | 13 + .../wasi/clocks/wall-clock/wall-clock.wit.go | 75 + .../internal/wasi/filesystem/preopens/empty.s | 3 + .../wasi/filesystem/preopens/preopens.wasm.go | 13 + .../wasi/filesystem/preopens/preopens.wit.go | 26 + .../internal/wasi/filesystem/types/abi.go | 50 + .../internal/wasi/filesystem/types/empty.s | 3 + .../wasi/filesystem/types/types.wasm.go | 133 ++ .../wasi/filesystem/types/types.wit.go | 1305 +++++++++++ .../wasi/http/incoming-handler/empty.s | 3 + .../incoming-handler.exports.go | 22 + .../incoming-handler/incoming-handler.wasm.go | 18 + .../incoming-handler/incoming-handler.wit.go | 21 + .../wasi/http/outgoing-handler/abi.go | 24 + .../wasi/http/outgoing-handler/empty.s | 3 + .../outgoing-handler/outgoing-handler.wasm.go | 13 + .../outgoing-handler/outgoing-handler.wit.go | 56 + x/wasihttp/internal/wasi/http/types/abi.go | 264 +++ x/wasihttp/internal/wasi/http/types/empty.s | 3 + .../internal/wasi/http/types/types.wasm.go | 257 +++ .../internal/wasi/http/types/types.wit.go | 2020 +++++++++++++++++ x/wasihttp/internal/wasi/io/error/empty.s | 3 + .../internal/wasi/io/error/error.wasm.go | 13 + .../internal/wasi/io/error/error.wit.go | 63 + x/wasihttp/internal/wasi/io/poll/empty.s | 3 + x/wasihttp/internal/wasi/io/poll/poll.wasm.go | 25 + x/wasihttp/internal/wasi/io/poll/poll.wit.go | 92 + x/wasihttp/internal/wasi/io/streams/empty.s | 3 + .../internal/wasi/io/streams/streams.wasm.go | 77 + .../internal/wasi/io/streams/streams.wit.go | 471 ++++ .../wasi/random/insecure-seed/empty.s | 3 + .../insecure-seed/insecure-seed.wasm.go | 9 + .../random/insecure-seed/insecure-seed.wit.go | 37 + .../internal/wasi/random/insecure/empty.s | 3 + .../wasi/random/insecure/insecure.wasm.go | 17 + .../wasi/random/insecure/insecure.wit.go | 49 + .../internal/wasi/random/random/empty.s | 3 + .../wasi/random/random/random.wasm.go | 17 + .../internal/wasi/random/random/random.wit.go | 53 + .../wasi/sockets/instance-network/empty.s | 3 + .../instance-network/instance-network.wasm.go | 9 + .../instance-network/instance-network.wit.go | 29 + .../wasi/sockets/ip-name-lookup/abi.go | 14 + .../wasi/sockets/ip-name-lookup/empty.s | 3 + .../ip-name-lookup/ip-name-lookup.wasm.go | 25 + .../ip-name-lookup/ip-name-lookup.wit.go | 125 + .../internal/wasi/sockets/network/abi.go | 14 + .../internal/wasi/sockets/network/empty.s | 3 + .../wasi/sockets/network/network.wasm.go | 9 + .../wasi/sockets/network/network.wit.go | 359 +++ .../wasi/sockets/tcp-create-socket/empty.s | 3 + .../tcp-create-socket.wasm.go | 13 + .../tcp-create-socket.wit.go | 68 + x/wasihttp/internal/wasi/sockets/tcp/abi.go | 88 + x/wasihttp/internal/wasi/sockets/tcp/empty.s | 3 + .../internal/wasi/sockets/tcp/tcp.wasm.go | 125 + .../internal/wasi/sockets/tcp/tcp.wit.go | 785 +++++++ .../wasi/sockets/udp-create-socket/empty.s | 3 + .../udp-create-socket.wasm.go | 13 + .../udp-create-socket.wit.go | 68 + x/wasihttp/internal/wasi/sockets/udp/abi.go | 103 + x/wasihttp/internal/wasi/sockets/udp/empty.s | 3 + .../internal/wasi/sockets/udp/udp.wasm.go | 93 + .../internal/wasi/sockets/udp/udp.wit.go | 584 +++++ x/wasihttp/server.go | 131 ++ x/wasihttp/transport.go | 103 + x/wasihttp/types.go | 287 +++ x/wasihttp/wasip2-http.json | 6 + x/wasihttp/wasip2-roundtrip.json | 6 + x/wasihttp/wit/deps/cli/command.wit | 7 + x/wasihttp/wit/deps/cli/environment.wit | 18 + x/wasihttp/wit/deps/cli/exit.wit | 4 + x/wasihttp/wit/deps/cli/imports.wit | 20 + x/wasihttp/wit/deps/cli/run.wit | 4 + x/wasihttp/wit/deps/cli/stdio.wit | 17 + x/wasihttp/wit/deps/cli/terminal.wit | 49 + .../wit/deps/clocks/monotonic-clock.wit | 45 + x/wasihttp/wit/deps/clocks/wall-clock.wit | 42 + x/wasihttp/wit/deps/clocks/world.wit | 6 + x/wasihttp/wit/deps/filesystem/preopens.wit | 8 + x/wasihttp/wit/deps/filesystem/types.wit | 634 ++++++ x/wasihttp/wit/deps/filesystem/world.wit | 6 + x/wasihttp/wit/deps/http/handler.wit | 43 + x/wasihttp/wit/deps/http/proxy.wit | 32 + x/wasihttp/wit/deps/http/types.wit | 570 +++++ x/wasihttp/wit/deps/io/error.wit | 34 + x/wasihttp/wit/deps/io/poll.wit | 41 + x/wasihttp/wit/deps/io/streams.wit | 262 +++ x/wasihttp/wit/deps/io/world.wit | 6 + x/wasihttp/wit/deps/random/insecure-seed.wit | 25 + x/wasihttp/wit/deps/random/insecure.wit | 22 + x/wasihttp/wit/deps/random/random.wit | 26 + x/wasihttp/wit/deps/random/world.wit | 7 + .../wit/deps/sockets/instance-network.wit | 9 + .../wit/deps/sockets/ip-name-lookup.wit | 51 + x/wasihttp/wit/deps/sockets/network.wit | 145 ++ .../wit/deps/sockets/tcp-create-socket.wit | 27 + x/wasihttp/wit/deps/sockets/tcp.wit | 353 +++ .../wit/deps/sockets/udp-create-socket.wit | 27 + x/wasihttp/wit/deps/sockets/udp.wit | 266 +++ x/wasihttp/wit/deps/sockets/world.wit | 11 + x/wasihttp/wit/proxy.wit | 8 + 149 files changed, 12079 insertions(+) create mode 100644 x/wasihttp/CHANGELOG.md create mode 100644 x/wasihttp/README.md create mode 100644 x/wasihttp/RELEASE.md create mode 100644 x/wasihttp/docs.go create mode 100644 x/wasihttp/examples/basic/basic.go create mode 100644 x/wasihttp/examples/counter/counter.go create mode 100644 x/wasihttp/examples/proxy/proxy.go create mode 100644 x/wasihttp/examples/roundtrip/roundtrip.go create mode 100755 x/wasihttp/internal/go/http/proxy/proxy.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/environment/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/environment/environment.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/environment/environment.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/exit/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/exit/exit.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/exit/exit.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/run/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/run/run.exports.go create mode 100755 x/wasihttp/internal/wasi/cli/run/run.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/run/run.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/stderr/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/stdin/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/stdout/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-input/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-output/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go create mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go create mode 100755 x/wasihttp/internal/wasi/clocks/monotonic-clock/empty.s create mode 100755 x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wasm.go create mode 100755 x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wit.go create mode 100755 x/wasihttp/internal/wasi/clocks/wall-clock/empty.s create mode 100755 x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go create mode 100755 x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go create mode 100755 x/wasihttp/internal/wasi/filesystem/preopens/empty.s create mode 100755 x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go create mode 100755 x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go create mode 100755 x/wasihttp/internal/wasi/filesystem/types/abi.go create mode 100755 x/wasihttp/internal/wasi/filesystem/types/empty.s create mode 100755 x/wasihttp/internal/wasi/filesystem/types/types.wasm.go create mode 100755 x/wasihttp/internal/wasi/filesystem/types/types.wit.go create mode 100755 x/wasihttp/internal/wasi/http/incoming-handler/empty.s create mode 100755 x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.exports.go create mode 100755 x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wasm.go create mode 100755 x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wit.go create mode 100755 x/wasihttp/internal/wasi/http/outgoing-handler/abi.go create mode 100755 x/wasihttp/internal/wasi/http/outgoing-handler/empty.s create mode 100755 x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wasm.go create mode 100755 x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wit.go create mode 100755 x/wasihttp/internal/wasi/http/types/abi.go create mode 100755 x/wasihttp/internal/wasi/http/types/empty.s create mode 100755 x/wasihttp/internal/wasi/http/types/types.wasm.go create mode 100755 x/wasihttp/internal/wasi/http/types/types.wit.go create mode 100755 x/wasihttp/internal/wasi/io/error/empty.s create mode 100755 x/wasihttp/internal/wasi/io/error/error.wasm.go create mode 100755 x/wasihttp/internal/wasi/io/error/error.wit.go create mode 100755 x/wasihttp/internal/wasi/io/poll/empty.s create mode 100755 x/wasihttp/internal/wasi/io/poll/poll.wasm.go create mode 100755 x/wasihttp/internal/wasi/io/poll/poll.wit.go create mode 100755 x/wasihttp/internal/wasi/io/streams/empty.s create mode 100755 x/wasihttp/internal/wasi/io/streams/streams.wasm.go create mode 100755 x/wasihttp/internal/wasi/io/streams/streams.wit.go create mode 100755 x/wasihttp/internal/wasi/random/insecure-seed/empty.s create mode 100755 x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go create mode 100755 x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go create mode 100755 x/wasihttp/internal/wasi/random/insecure/empty.s create mode 100755 x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go create mode 100755 x/wasihttp/internal/wasi/random/insecure/insecure.wit.go create mode 100755 x/wasihttp/internal/wasi/random/random/empty.s create mode 100755 x/wasihttp/internal/wasi/random/random/random.wasm.go create mode 100755 x/wasihttp/internal/wasi/random/random/random.wit.go create mode 100755 x/wasihttp/internal/wasi/sockets/instance-network/empty.s create mode 100755 x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go create mode 100755 x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go create mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go create mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s create mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go create mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go create mode 100755 x/wasihttp/internal/wasi/sockets/network/abi.go create mode 100755 x/wasihttp/internal/wasi/sockets/network/empty.s create mode 100755 x/wasihttp/internal/wasi/sockets/network/network.wasm.go create mode 100755 x/wasihttp/internal/wasi/sockets/network/network.wit.go create mode 100755 x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s create mode 100755 x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go create mode 100755 x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go create mode 100755 x/wasihttp/internal/wasi/sockets/tcp/abi.go create mode 100755 x/wasihttp/internal/wasi/sockets/tcp/empty.s create mode 100755 x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go create mode 100755 x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go create mode 100755 x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s create mode 100755 x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go create mode 100755 x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go create mode 100755 x/wasihttp/internal/wasi/sockets/udp/abi.go create mode 100755 x/wasihttp/internal/wasi/sockets/udp/empty.s create mode 100755 x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go create mode 100755 x/wasihttp/internal/wasi/sockets/udp/udp.wit.go create mode 100644 x/wasihttp/server.go create mode 100644 x/wasihttp/transport.go create mode 100644 x/wasihttp/types.go create mode 100644 x/wasihttp/wasip2-http.json create mode 100644 x/wasihttp/wasip2-roundtrip.json create mode 100644 x/wasihttp/wit/deps/cli/command.wit create mode 100644 x/wasihttp/wit/deps/cli/environment.wit create mode 100644 x/wasihttp/wit/deps/cli/exit.wit create mode 100644 x/wasihttp/wit/deps/cli/imports.wit create mode 100644 x/wasihttp/wit/deps/cli/run.wit create mode 100644 x/wasihttp/wit/deps/cli/stdio.wit create mode 100644 x/wasihttp/wit/deps/cli/terminal.wit create mode 100644 x/wasihttp/wit/deps/clocks/monotonic-clock.wit create mode 100644 x/wasihttp/wit/deps/clocks/wall-clock.wit create mode 100644 x/wasihttp/wit/deps/clocks/world.wit create mode 100644 x/wasihttp/wit/deps/filesystem/preopens.wit create mode 100644 x/wasihttp/wit/deps/filesystem/types.wit create mode 100644 x/wasihttp/wit/deps/filesystem/world.wit create mode 100644 x/wasihttp/wit/deps/http/handler.wit create mode 100644 x/wasihttp/wit/deps/http/proxy.wit create mode 100644 x/wasihttp/wit/deps/http/types.wit create mode 100644 x/wasihttp/wit/deps/io/error.wit create mode 100644 x/wasihttp/wit/deps/io/poll.wit create mode 100644 x/wasihttp/wit/deps/io/streams.wit create mode 100644 x/wasihttp/wit/deps/io/world.wit create mode 100644 x/wasihttp/wit/deps/random/insecure-seed.wit create mode 100644 x/wasihttp/wit/deps/random/insecure.wit create mode 100644 x/wasihttp/wit/deps/random/random.wit create mode 100644 x/wasihttp/wit/deps/random/world.wit create mode 100644 x/wasihttp/wit/deps/sockets/instance-network.wit create mode 100644 x/wasihttp/wit/deps/sockets/ip-name-lookup.wit create mode 100644 x/wasihttp/wit/deps/sockets/network.wit create mode 100644 x/wasihttp/wit/deps/sockets/tcp-create-socket.wit create mode 100644 x/wasihttp/wit/deps/sockets/tcp.wit create mode 100644 x/wasihttp/wit/deps/sockets/udp-create-socket.wit create mode 100644 x/wasihttp/wit/deps/sockets/udp.wit create mode 100644 x/wasihttp/wit/deps/sockets/world.wit create mode 100644 x/wasihttp/wit/proxy.wit diff --git a/x/wasihttp/CHANGELOG.md b/x/wasihttp/CHANGELOG.md new file mode 100644 index 00000000..6690bdf0 --- /dev/null +++ b/x/wasihttp/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- Initial import of the WASI HTTP package from the standalone repository + +### Changed +- Package import path is now `go.bytecodealliance.org/x/wasihttp` diff --git a/x/wasihttp/README.md b/x/wasihttp/README.md new file mode 100644 index 00000000..b35f010a --- /dev/null +++ b/x/wasihttp/README.md @@ -0,0 +1,46 @@ +# `go.bytecodealliance.org/x/wasihttp` + +Package `go.bytecodealliance.org/x/wasihttp` implements [`wasi:http/proxy`](https://github.com/WebAssembly/wasi-http/blob/v0.2.0/proxy.md) for Go using standard [`net/http`](https://pkg.go.dev/net/http) interfaces. + +This package allows Go applications to use the familiar `net/http` API when building WebAssembly modules that use the WASI HTTP standard. + +## Prerequisites + +To use this package, you'll need: + +- [TinyGo](https://tinygo.org/) 0.34.0 or later. +- [Wasmtime](https://wasmtime.dev/) 26.0.0 or later. + +## Usage + +### Server + +Create a standard Go HTTP server using the familiar `net/http` API: + +```go +package main + +import ( + "net/http" + _ "go.bytecodealliance.org/x/wasihttp" // enable wasi-http +) + +func init() { + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("X-Go", "Gopher") + w.Write([]byte("Hello world!\n")) + }) +} + +func main() {} +``` + +Compile with: + +```bash +tinygo build -target=wasip2-http.json -o server.wasm ./main.go +``` + +## Examples + +For more examples, see the `examples` directory. diff --git a/x/wasihttp/RELEASE.md b/x/wasihttp/RELEASE.md new file mode 100644 index 00000000..4f0a94d1 --- /dev/null +++ b/x/wasihttp/RELEASE.md @@ -0,0 +1,21 @@ +# Release Process + +This document describes how to release a new version of the `wasihttp` package. + +## Release Steps + +1. Update the [CHANGELOG.md](CHANGELOG.md) with the changes since the last release. +2. Ensure all tests pass and examples work correctly. + +## Creating a Release + +Create a new git tag for the release: + +```bash +git tag x/wasihttp/v0.1.0 +git push origin x/wasihttp/v0.1.0 +``` + +## Version Numbering + +The `wasihttp` package follows [semantic versioning](https://semver.org/). diff --git a/x/wasihttp/docs.go b/x/wasihttp/docs.go new file mode 100644 index 00000000..04ac4106 --- /dev/null +++ b/x/wasihttp/docs.go @@ -0,0 +1,11 @@ +// Package wasihttp implements [`wasi:http/proxy`](https://github.com/WebAssembly/wasi-http/blob/v0.2.0/proxy.md) for Go using standard [`net/http`](https://pkg.go.dev/net/http) interfaces +// +// It provides an implementation of the wasi:http/proxy interface that allows Go applications +// to use the standard net/http library for both client and server operations within a WebAssembly +// module. This allows Go developers to use familiar HTTP APIs when building WebAssembly modules +// that need to make or handle HTTP requests. +// +// To use this package in your Go application, simply import it: +// +// import _ "go.bytecodealliance.org/x/wasihttp" +package wasihttp diff --git a/x/wasihttp/examples/basic/basic.go b/x/wasihttp/examples/basic/basic.go new file mode 100644 index 00000000..9d2da026 --- /dev/null +++ b/x/wasihttp/examples/basic/basic.go @@ -0,0 +1,27 @@ +// This example implements a basic web server. +// +// To run: `tinygo run -target=wasip2-http.json ./examples/basic` +// Test /: `curl -v 'http://0.0.0.0:8080/'` +// Test /error: `curl -v 'http://0.0.0.0:8080/error'` + +package main + +import ( + "net/http" + + _ "go.bytecodealliance.org/x/wasihttp" +) + +func init() { + // TODO: use "GET /" when TinyGo supports net/http from Go 1.22+ + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("X-Go", "Gopher") + w.Write([]byte("Hello world!\n")) + }) + + http.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) { + // do nothing, force default response handling + }) +} + +func main() {} diff --git a/x/wasihttp/examples/counter/counter.go b/x/wasihttp/examples/counter/counter.go new file mode 100644 index 00000000..af3f2609 --- /dev/null +++ b/x/wasihttp/examples/counter/counter.go @@ -0,0 +1,33 @@ +// This example implements a web server with a counter running in a goroutine. +// This demonstrates instance reuse by the host. +// +// To run: `tinygo run -target=wasip2-http.json ./examples/counter` +// Test /: `curl -v 'http://0.0.0.0:8080/'` + +package main + +import ( + "fmt" + "net/http" + + _ "go.bytecodealliance.org/x/wasihttp" +) + +func init() { + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + n := <-c + fmt.Fprintf(w, "%d", n) + }) + + go func() { + var n int + for { + c <- n + n++ + } + }() +} + +var c = make(chan int, 1) + +func main() {} diff --git a/x/wasihttp/examples/proxy/proxy.go b/x/wasihttp/examples/proxy/proxy.go new file mode 100644 index 00000000..69961e31 --- /dev/null +++ b/x/wasihttp/examples/proxy/proxy.go @@ -0,0 +1,59 @@ +// This example implements a reverse proxy that sends requests to postman-echo.com. +// +// To run: `tinygo run -target=wasip2-http.json ./examples/proxy` +// Test GET: `curl -v 'http://0.0.0.0:8080/get'` +// Test POST: `curl -v -d hello 'http://0.0.0.0:8080/post'` + +package main + +import ( + "context" + "fmt" + "io" + "log" + "net/http" + "time" + + _ "go.bytecodealliance.org/x/wasihttp" +) + +func init() { + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + + r2 := r.Clone(ctx) + r2.Host = "postman-echo.com" + r2.URL.Host = "postman-echo.com" + r2.URL.Scheme = "https" + + defer func() { + dur := time.Since(start) + log.Printf("proxied %s in %s\n", r2.URL.String(), dur.String()) + }() + + res, err := http.DefaultClient.Do(r2) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, "error: %v", err) + log.Printf("error: %v", err) + return + } + + for k, v := range res.Header { + for _, vv := range v { + w.Header().Add(k, vv) + } + } + + w.WriteHeader(res.StatusCode) + if res.Body != nil { + io.Copy(w, res.Body) + res.Body.Close() + } + }) +} + +func main() {} diff --git a/x/wasihttp/examples/roundtrip/roundtrip.go b/x/wasihttp/examples/roundtrip/roundtrip.go new file mode 100644 index 00000000..c4aea66b --- /dev/null +++ b/x/wasihttp/examples/roundtrip/roundtrip.go @@ -0,0 +1,80 @@ +// This example is taken from https://github.com/dev-wasm/dev-wasm-go/blob/main/http/main.go +// demonstrates how to use the wasihttp package to make HTTP requests using the `http.Client` interface. +// +// To run: `tinygo build -target=wasip2-roundtrip.json -o roundtrip.wasm ./examples/roundtrip` +// Test: `wasmtime run -Shttp -Sinherit-network -Sinherit-env roundtrip.wasm` +package main + +import ( + "bytes" + "fmt" + "io" + "net/http" + + wasihttp "go.bytecodealliance.org/x/wasihttp" +) + +func printResponse(r *http.Response) error { + fmt.Printf("Status: %d\n", r.StatusCode) + for k, v := range r.Header { + fmt.Printf("%s: %s\n", k, v[0]) + } + body, err := io.ReadAll(r.Body) + if err != nil { + return err + } + fmt.Printf("Body: \n%s\n", body) + return nil +} + +func main() { + client := &http.Client{ + Transport: &wasihttp.Transport{}, + } + req, err := http.NewRequest("GET", "https://postman-echo.com/get", nil) + if err != nil { + panic(err.Error()) + } + if req == nil { + panic("Nil request!") + } + res, err := client.Do(req) + if err != nil { + panic(err.Error()) + } + defer res.Body.Close() + + err = printResponse(res) + if err != nil { + panic(err.Error()) + } + + res, err = client.Post("https://postman-echo.com/post", "application/json", bytes.NewReader([]byte("{\"foo\": \"bar\"}"))) + if err != nil { + panic(err.Error()) + } + defer res.Body.Close() + + err = printResponse(res) + if err != nil { + panic(err.Error()) + } + + req, err = http.NewRequest("PUT", "http://postman-echo.com/put", bytes.NewReader([]byte("{\"baz\": \"blah\"}"))) + if err != nil { + panic(err.Error()) + } + if req == nil { + panic("Nil request!") + } + res, err = client.Do(req) + if err != nil { + panic(err.Error()) + } + defer res.Body.Close() + + err = printResponse(res) + if err != nil { + panic(err.Error()) + } +} diff --git a/x/wasihttp/internal/go/http/proxy/proxy.wit.go b/x/wasihttp/internal/go/http/proxy/proxy.wit.go new file mode 100755 index 00000000..0cd2e7de --- /dev/null +++ b/x/wasihttp/internal/go/http/proxy/proxy.wit.go @@ -0,0 +1,6 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package proxy represents the world "go:http/proxy@0.2.0". +// +// The `go:http/proxy` world implements a strict superset of `wasi:http/proxy`. +package proxy diff --git a/x/wasihttp/internal/wasi/cli/environment/empty.s b/x/wasihttp/internal/wasi/cli/environment/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/environment/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/environment/environment.wasm.go b/x/wasihttp/internal/wasi/cli/environment/environment.wasm.go new file mode 100755 index 00000000..89bb596b --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/environment/environment.wasm.go @@ -0,0 +1,21 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package environment + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/environment@0.2.0 get-environment +//go:noescape +func wasmimport_GetEnvironment(result *cm.List[[2]string]) + +//go:wasmimport wasi:cli/environment@0.2.0 get-arguments +//go:noescape +func wasmimport_GetArguments(result *cm.List[string]) + +//go:wasmimport wasi:cli/environment@0.2.0 initial-cwd +//go:noescape +func wasmimport_InitialCWD(result *cm.Option[string]) diff --git a/x/wasihttp/internal/wasi/cli/environment/environment.wit.go b/x/wasihttp/internal/wasi/cli/environment/environment.wit.go new file mode 100755 index 00000000..3a3b6247 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/environment/environment.wit.go @@ -0,0 +1,52 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package environment represents the imported interface "wasi:cli/environment@0.2.0". +package environment + +import ( + "go.bytecodealliance.org/cm" +) + +// GetEnvironment represents the imported function "get-environment". +// +// Get the POSIX-style environment variables. +// +// Each environment variable is provided as a pair of string variable names +// and string value. +// +// Morally, these are a value import, but until value imports are available +// in the component model, this import function should return the same +// values each time it is called. +// +// get-environment: func() -> list> +// +//go:nosplit +func GetEnvironment() (result cm.List[[2]string]) { + wasmimport_GetEnvironment(&result) + return +} + +// GetArguments represents the imported function "get-arguments". +// +// Get the POSIX-style arguments to the program. +// +// get-arguments: func() -> list +// +//go:nosplit +func GetArguments() (result cm.List[string]) { + wasmimport_GetArguments(&result) + return +} + +// InitialCWD represents the imported function "initial-cwd". +// +// Return a path that programs should use as their initial current working +// directory, interpreting `.` as shorthand for this. +// +// initial-cwd: func() -> option +// +//go:nosplit +func InitialCWD() (result cm.Option[string]) { + wasmimport_InitialCWD(&result) + return +} diff --git a/x/wasihttp/internal/wasi/cli/exit/empty.s b/x/wasihttp/internal/wasi/cli/exit/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/exit/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/exit/exit.wasm.go b/x/wasihttp/internal/wasi/cli/exit/exit.wasm.go new file mode 100755 index 00000000..849d5f50 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/exit/exit.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package exit + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/exit@0.2.0 exit +//go:noescape +func wasmimport_Exit(status0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/exit/exit.wit.go b/x/wasihttp/internal/wasi/cli/exit/exit.wit.go new file mode 100755 index 00000000..947fa253 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/exit/exit.wit.go @@ -0,0 +1,21 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package exit represents the imported interface "wasi:cli/exit@0.2.0". +package exit + +import ( + "go.bytecodealliance.org/cm" +) + +// Exit represents the imported function "exit". +// +// Exit the current instance and any linked instances. +// +// exit: func(status: result) +// +//go:nosplit +func Exit(status cm.BoolResult) { + status0 := (uint32)(cm.BoolToU32(status)) + wasmimport_Exit((uint32)(status0)) + return +} diff --git a/x/wasihttp/internal/wasi/cli/run/empty.s b/x/wasihttp/internal/wasi/cli/run/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/run/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/run/run.exports.go b/x/wasihttp/internal/wasi/cli/run/run.exports.go new file mode 100755 index 00000000..647b093c --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/run/run.exports.go @@ -0,0 +1,17 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package run + +import ( + "go.bytecodealliance.org/cm" +) + +// Exports represents the caller-defined exports from "wasi:cli/run@0.2.0". +var Exports struct { + // Run represents the caller-defined, exported function "run". + // + // Run the program. + // + // run: func() -> result + Run func() (result cm.BoolResult) +} diff --git a/x/wasihttp/internal/wasi/cli/run/run.wasm.go b/x/wasihttp/internal/wasi/cli/run/run.wasm.go new file mode 100755 index 00000000..43487234 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/run/run.wasm.go @@ -0,0 +1,17 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package run + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmexport wasi:cli/run@0.2.0#run +//export wasi:cli/run@0.2.0#run +func wasmexport_Run() (result0 uint32) { + result := Exports.Run() + result0 = (uint32)(cm.BoolToU32(result)) + return +} diff --git a/x/wasihttp/internal/wasi/cli/run/run.wit.go b/x/wasihttp/internal/wasi/cli/run/run.wit.go new file mode 100755 index 00000000..4cea75d3 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/run/run.wit.go @@ -0,0 +1,4 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package run represents the exported interface "wasi:cli/run@0.2.0". +package run diff --git a/x/wasihttp/internal/wasi/cli/stderr/empty.s b/x/wasihttp/internal/wasi/cli/stderr/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stderr/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go b/x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go new file mode 100755 index 00000000..462cf172 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package stderr + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/stderr@0.2.0 get-stderr +//go:noescape +func wasmimport_GetStderr() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go b/x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go new file mode 100755 index 00000000..9731dd7a --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package stderr represents the imported interface "wasi:cli/stderr@0.2.0". +package stderr + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" +) + +// OutputStream represents the imported type alias "wasi:cli/stderr@0.2.0#output-stream". +// +// See [streams.OutputStream] for more information. +type OutputStream = streams.OutputStream + +// GetStderr represents the imported function "get-stderr". +// +// get-stderr: func() -> output-stream +// +//go:nosplit +func GetStderr() (result OutputStream) { + result0 := wasmimport_GetStderr() + result = cm.Reinterpret[OutputStream]((uint32)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/cli/stdin/empty.s b/x/wasihttp/internal/wasi/cli/stdin/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stdin/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go b/x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go new file mode 100755 index 00000000..374eb253 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package stdin + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/stdin@0.2.0 get-stdin +//go:noescape +func wasmimport_GetStdin() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go b/x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go new file mode 100755 index 00000000..edb52a3e --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package stdin represents the imported interface "wasi:cli/stdin@0.2.0". +package stdin + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" +) + +// InputStream represents the imported type alias "wasi:cli/stdin@0.2.0#input-stream". +// +// See [streams.InputStream] for more information. +type InputStream = streams.InputStream + +// GetStdin represents the imported function "get-stdin". +// +// get-stdin: func() -> input-stream +// +//go:nosplit +func GetStdin() (result InputStream) { + result0 := wasmimport_GetStdin() + result = cm.Reinterpret[InputStream]((uint32)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/cli/stdout/empty.s b/x/wasihttp/internal/wasi/cli/stdout/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stdout/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go b/x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go new file mode 100755 index 00000000..68e4a3da --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package stdout + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/stdout@0.2.0 get-stdout +//go:noescape +func wasmimport_GetStdout() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go b/x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go new file mode 100755 index 00000000..46461fb1 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package stdout represents the imported interface "wasi:cli/stdout@0.2.0". +package stdout + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" +) + +// OutputStream represents the imported type alias "wasi:cli/stdout@0.2.0#output-stream". +// +// See [streams.OutputStream] for more information. +type OutputStream = streams.OutputStream + +// GetStdout represents the imported function "get-stdout". +// +// get-stdout: func() -> output-stream +// +//go:nosplit +func GetStdout() (result OutputStream) { + result0 := wasmimport_GetStdout() + result = cm.Reinterpret[OutputStream]((uint32)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/cli/terminal-input/empty.s b/x/wasihttp/internal/wasi/cli/terminal-input/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-input/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go new file mode 100755 index 00000000..1df3794f --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package terminalinput + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/terminal-input@0.2.0 [resource-drop]terminal-input +//go:noescape +func wasmimport_TerminalInputResourceDrop(self0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go b/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go new file mode 100755 index 00000000..fa12e90c --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go @@ -0,0 +1,32 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalinput represents the imported interface "wasi:cli/terminal-input@0.2.0". +// +// Terminal input. +// +// In the future, this may include functions for disabling echoing, +// disabling input buffering so that keyboard events are sent through +// immediately, querying supported features, and so on. +package terminalinput + +import ( + "go.bytecodealliance.org/cm" +) + +// TerminalInput represents the imported resource "wasi:cli/terminal-input@0.2.0#terminal-input". +// +// The input side of a terminal. +// +// resource terminal-input +type TerminalInput cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "terminal-input". +// +// Drops a resource handle. +// +//go:nosplit +func (self TerminalInput) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TerminalInputResourceDrop((uint32)(self0)) + return +} diff --git a/x/wasihttp/internal/wasi/cli/terminal-output/empty.s b/x/wasihttp/internal/wasi/cli/terminal-output/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-output/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go new file mode 100755 index 00000000..fb35fc41 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package terminaloutput + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/terminal-output@0.2.0 [resource-drop]terminal-output +//go:noescape +func wasmimport_TerminalOutputResourceDrop(self0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go b/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go new file mode 100755 index 00000000..199e0cc0 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go @@ -0,0 +1,32 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminaloutput represents the imported interface "wasi:cli/terminal-output@0.2.0". +// +// Terminal output. +// +// In the future, this may include functions for querying the terminal +// size, being notified of terminal size changes, querying supported +// features, and so on. +package terminaloutput + +import ( + "go.bytecodealliance.org/cm" +) + +// TerminalOutput represents the imported resource "wasi:cli/terminal-output@0.2.0#terminal-output". +// +// The output side of a terminal. +// +// resource terminal-output +type TerminalOutput cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "terminal-output". +// +// Drops a resource handle. +// +//go:nosplit +func (self TerminalOutput) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TerminalOutputResourceDrop((uint32)(self0)) + return +} diff --git a/x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s b/x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go new file mode 100755 index 00000000..be9af72f --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package terminalstderr + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/terminal-stderr@0.2.0 get-terminal-stderr +//go:noescape +func wasmimport_GetTerminalStderr(result *cm.Option[TerminalOutput]) diff --git a/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go b/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go new file mode 100755 index 00000000..219155fa --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go @@ -0,0 +1,30 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalstderr represents the imported interface "wasi:cli/terminal-stderr@0.2.0". +// +// An interface providing an optional `terminal-output` for stderr as a +// link-time authority. +package terminalstderr + +import ( + "go.bytecodealliance.org/cm" + terminaloutput "go.bytecodealliance.org/x/wasihttp/internal/wasi/cli/terminal-output" +) + +// TerminalOutput represents the imported type alias "wasi:cli/terminal-stderr@0.2.0#terminal-output". +// +// See [terminaloutput.TerminalOutput] for more information. +type TerminalOutput = terminaloutput.TerminalOutput + +// GetTerminalStderr represents the imported function "get-terminal-stderr". +// +// If stderr is connected to a terminal, return a `terminal-output` handle +// allowing further interaction with it. +// +// get-terminal-stderr: func() -> option +// +//go:nosplit +func GetTerminalStderr() (result cm.Option[TerminalOutput]) { + wasmimport_GetTerminalStderr(&result) + return +} diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s b/x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go new file mode 100755 index 00000000..e3b3ac61 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package terminalstdin + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/terminal-stdin@0.2.0 get-terminal-stdin +//go:noescape +func wasmimport_GetTerminalStdin(result *cm.Option[TerminalInput]) diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go b/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go new file mode 100755 index 00000000..335b8cb1 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go @@ -0,0 +1,30 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalstdin represents the imported interface "wasi:cli/terminal-stdin@0.2.0". +// +// An interface providing an optional `terminal-input` for stdin as a +// link-time authority. +package terminalstdin + +import ( + "go.bytecodealliance.org/cm" + terminalinput "go.bytecodealliance.org/x/wasihttp/internal/wasi/cli/terminal-input" +) + +// TerminalInput represents the imported type alias "wasi:cli/terminal-stdin@0.2.0#terminal-input". +// +// See [terminalinput.TerminalInput] for more information. +type TerminalInput = terminalinput.TerminalInput + +// GetTerminalStdin represents the imported function "get-terminal-stdin". +// +// If stdin is connected to a terminal, return a `terminal-input` handle +// allowing further interaction with it. +// +// get-terminal-stdin: func() -> option +// +//go:nosplit +func GetTerminalStdin() (result cm.Option[TerminalInput]) { + wasmimport_GetTerminalStdin(&result) + return +} diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s b/x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go new file mode 100755 index 00000000..fa750ad9 --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package terminalstdout + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". + +//go:wasmimport wasi:cli/terminal-stdout@0.2.0 get-terminal-stdout +//go:noescape +func wasmimport_GetTerminalStdout(result *cm.Option[TerminalOutput]) diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go b/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go new file mode 100755 index 00000000..26abf43c --- /dev/null +++ b/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go @@ -0,0 +1,30 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalstdout represents the imported interface "wasi:cli/terminal-stdout@0.2.0". +// +// An interface providing an optional `terminal-output` for stdout as a +// link-time authority. +package terminalstdout + +import ( + "go.bytecodealliance.org/cm" + terminaloutput "go.bytecodealliance.org/x/wasihttp/internal/wasi/cli/terminal-output" +) + +// TerminalOutput represents the imported type alias "wasi:cli/terminal-stdout@0.2.0#terminal-output". +// +// See [terminaloutput.TerminalOutput] for more information. +type TerminalOutput = terminaloutput.TerminalOutput + +// GetTerminalStdout represents the imported function "get-terminal-stdout". +// +// If stdout is connected to a terminal, return a `terminal-output` handle +// allowing further interaction with it. +// +// get-terminal-stdout: func() -> option +// +//go:nosplit +func GetTerminalStdout() (result cm.Option[TerminalOutput]) { + wasmimport_GetTerminalStdout(&result) + return +} diff --git a/x/wasihttp/internal/wasi/clocks/monotonic-clock/empty.s b/x/wasihttp/internal/wasi/clocks/monotonic-clock/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/clocks/monotonic-clock/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wasm.go b/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wasm.go new file mode 100755 index 00000000..36a1720a --- /dev/null +++ b/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wasm.go @@ -0,0 +1,21 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package monotonicclock + +// This file contains wasmimport and wasmexport declarations for "wasi:clocks@0.2.0". + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 now +//go:noescape +func wasmimport_Now() (result0 uint64) + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 resolution +//go:noescape +func wasmimport_Resolution() (result0 uint64) + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 subscribe-instant +//go:noescape +func wasmimport_SubscribeInstant(when0 uint64) (result0 uint32) + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 subscribe-duration +//go:noescape +func wasmimport_SubscribeDuration(when0 uint64) (result0 uint32) diff --git a/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wit.go b/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wit.go new file mode 100755 index 00000000..125dc528 --- /dev/null +++ b/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wit.go @@ -0,0 +1,102 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package monotonicclock represents the imported interface "wasi:clocks/monotonic-clock@0.2.0". +// +// WASI Monotonic Clock is a clock API intended to let users measure elapsed +// time. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +// +// A monotonic clock is a clock which has an unspecified initial value, and +// successive reads of the clock will produce non-decreasing values. +// +// It is intended for measuring elapsed time. +package monotonicclock + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" +) + +// Pollable represents the imported type alias "wasi:clocks/monotonic-clock@0.2.0#pollable". +// +// See [poll.Pollable] for more information. +type Pollable = poll.Pollable + +// Instant represents the u64 "wasi:clocks/monotonic-clock@0.2.0#instant". +// +// An instant in time, in nanoseconds. An instant is relative to an +// unspecified initial value, and can only be compared to instances from +// the same monotonic-clock. +// +// type instant = u64 +type Instant uint64 + +// Duration represents the u64 "wasi:clocks/monotonic-clock@0.2.0#duration". +// +// A duration of time, in nanoseconds. +// +// type duration = u64 +type Duration uint64 + +// Now represents the imported function "now". +// +// Read the current value of the clock. +// +// The clock is monotonic, therefore calling this function repeatedly will +// produce a sequence of non-decreasing values. +// +// now: func() -> instant +// +//go:nosplit +func Now() (result Instant) { + result0 := wasmimport_Now() + result = (Instant)((uint64)(result0)) + return +} + +// Resolution represents the imported function "resolution". +// +// Query the resolution of the clock. Returns the duration of time +// corresponding to a clock tick. +// +// resolution: func() -> duration +// +//go:nosplit +func Resolution() (result Duration) { + result0 := wasmimport_Resolution() + result = (Duration)((uint64)(result0)) + return +} + +// SubscribeInstant represents the imported function "subscribe-instant". +// +// Create a `pollable` which will resolve once the specified instant +// occured. +// +// subscribe-instant: func(when: instant) -> pollable +// +//go:nosplit +func SubscribeInstant(when Instant) (result Pollable) { + when0 := (uint64)(when) + result0 := wasmimport_SubscribeInstant((uint64)(when0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// SubscribeDuration represents the imported function "subscribe-duration". +// +// Create a `pollable` which will resolve once the given duration has +// elapsed, starting at the time at which this function was called. +// occured. +// +// subscribe-duration: func(when: duration) -> pollable +// +//go:nosplit +func SubscribeDuration(when Duration) (result Pollable) { + when0 := (uint64)(when) + result0 := wasmimport_SubscribeDuration((uint64)(when0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/clocks/wall-clock/empty.s b/x/wasihttp/internal/wasi/clocks/wall-clock/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/clocks/wall-clock/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go b/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go new file mode 100755 index 00000000..321ff3f1 --- /dev/null +++ b/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package wallclock + +// This file contains wasmimport and wasmexport declarations for "wasi:clocks@0.2.0". + +//go:wasmimport wasi:clocks/wall-clock@0.2.0 now +//go:noescape +func wasmimport_Now(result *DateTime) + +//go:wasmimport wasi:clocks/wall-clock@0.2.0 resolution +//go:noescape +func wasmimport_Resolution(result *DateTime) diff --git a/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go b/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go new file mode 100755 index 00000000..9c0a9684 --- /dev/null +++ b/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go @@ -0,0 +1,75 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package wallclock represents the imported interface "wasi:clocks/wall-clock@0.2.0". +// +// WASI Wall Clock is a clock API intended to let users query the current +// time. The name "wall" makes an analogy to a "clock on the wall", which +// is not necessarily monotonic as it may be reset. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +// +// A wall clock is a clock which measures the date and time according to +// some external reference. +// +// External references may be reset, so this clock is not necessarily +// monotonic, making it unsuitable for measuring elapsed time. +// +// It is intended for reporting the current date and time for humans. +package wallclock + +import ( + "go.bytecodealliance.org/cm" +) + +// DateTime represents the record "wasi:clocks/wall-clock@0.2.0#datetime". +// +// A time and date in seconds plus nanoseconds. +// +// record datetime { +// seconds: u64, +// nanoseconds: u32, +// } +type DateTime struct { + _ cm.HostLayout `json:"-"` + Seconds uint64 `json:"seconds"` + Nanoseconds uint32 `json:"nanoseconds"` +} + +// Now represents the imported function "now". +// +// Read the current value of the clock. +// +// This clock is not monotonic, therefore calling this function repeatedly +// will not necessarily produce a sequence of non-decreasing values. +// +// The returned timestamps represent the number of seconds since +// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], +// also known as [Unix Time]. +// +// The nanoseconds field of the output is always less than 1000000000. +// +// now: func() -> datetime +// +// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 +// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time +// +//go:nosplit +func Now() (result DateTime) { + wasmimport_Now(&result) + return +} + +// Resolution represents the imported function "resolution". +// +// Query the resolution of the clock. +// +// The nanoseconds field of the output is always less than 1000000000. +// +// resolution: func() -> datetime +// +//go:nosplit +func Resolution() (result DateTime) { + wasmimport_Resolution(&result) + return +} diff --git a/x/wasihttp/internal/wasi/filesystem/preopens/empty.s b/x/wasihttp/internal/wasi/filesystem/preopens/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/filesystem/preopens/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go b/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go new file mode 100755 index 00000000..1bcd416a --- /dev/null +++ b/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package preopens + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:filesystem@0.2.0". + +//go:wasmimport wasi:filesystem/preopens@0.2.0 get-directories +//go:noescape +func wasmimport_GetDirectories(result *cm.List[cm.Tuple[Descriptor, string]]) diff --git a/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go b/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go new file mode 100755 index 00000000..652323e0 --- /dev/null +++ b/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go @@ -0,0 +1,26 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package preopens represents the imported interface "wasi:filesystem/preopens@0.2.0". +package preopens + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/filesystem/types" +) + +// Descriptor represents the imported type alias "wasi:filesystem/preopens@0.2.0#descriptor". +// +// See [types.Descriptor] for more information. +type Descriptor = types.Descriptor + +// GetDirectories represents the imported function "get-directories". +// +// Return the set of preopened directories, and their path. +// +// get-directories: func() -> list> +// +//go:nosplit +func GetDirectories() (result cm.List[cm.Tuple[Descriptor, string]]) { + wasmimport_GetDirectories(&result) + return +} diff --git a/x/wasihttp/internal/wasi/filesystem/types/abi.go b/x/wasihttp/internal/wasi/filesystem/types/abi.go new file mode 100755 index 00000000..06ee48d7 --- /dev/null +++ b/x/wasihttp/internal/wasi/filesystem/types/abi.go @@ -0,0 +1,50 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package types + +import ( + "go.bytecodealliance.org/cm" + wallclock "go.bytecodealliance.org/x/wasihttp/internal/wasi/clocks/wall-clock" + "unsafe" +) + +// MetadataHashValueShape is used for storage in variant or result types. +type MetadataHashValueShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(MetadataHashValue{})]byte +} + +// TupleListU8BoolShape is used for storage in variant or result types. +type TupleListU8BoolShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(cm.Tuple[cm.List[uint8], bool]{})]byte +} + +func lower_DateTime(v wallclock.DateTime) (f0 uint64, f1 uint32) { + f0 = (uint64)(v.Seconds) + f1 = (uint32)(v.Nanoseconds) + return +} + +func lower_NewTimestamp(v NewTimestamp) (f0 uint32, f1 uint64, f2 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 2: // timestamp + v1, v2 := lower_DateTime(*cm.Case[DateTime](&v, 2)) + f1 = (uint64)(v1) + f2 = (uint32)(v2) + } + return +} + +// DescriptorStatShape is used for storage in variant or result types. +type DescriptorStatShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(DescriptorStat{})]byte +} + +// OptionDirectoryEntryShape is used for storage in variant or result types. +type OptionDirectoryEntryShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(cm.Option[DirectoryEntry]{})]byte +} diff --git a/x/wasihttp/internal/wasi/filesystem/types/empty.s b/x/wasihttp/internal/wasi/filesystem/types/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/filesystem/types/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/filesystem/types/types.wasm.go b/x/wasihttp/internal/wasi/filesystem/types/types.wasm.go new file mode 100755 index 00000000..b97dad84 --- /dev/null +++ b/x/wasihttp/internal/wasi/filesystem/types/types.wasm.go @@ -0,0 +1,133 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package types + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:filesystem@0.2.0". + +//go:wasmimport wasi:filesystem/types@0.2.0 [resource-drop]descriptor +//go:noescape +func wasmimport_DescriptorResourceDrop(self0 uint32) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.advise +//go:noescape +func wasmimport_DescriptorAdvise(self0 uint32, offset0 uint64, length0 uint64, advice0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.append-via-stream +//go:noescape +func wasmimport_DescriptorAppendViaStream(self0 uint32, result *cm.Result[OutputStream, OutputStream, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.create-directory-at +//go:noescape +func wasmimport_DescriptorCreateDirectoryAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.get-flags +//go:noescape +func wasmimport_DescriptorGetFlags(self0 uint32, result *cm.Result[DescriptorFlags, DescriptorFlags, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.get-type +//go:noescape +func wasmimport_DescriptorGetType(self0 uint32, result *cm.Result[DescriptorType, DescriptorType, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.is-same-object +//go:noescape +func wasmimport_DescriptorIsSameObject(self0 uint32, other0 uint32) (result0 uint32) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.link-at +//go:noescape +func wasmimport_DescriptorLinkAt(self0 uint32, oldPathFlags0 uint32, oldPath0 *uint8, oldPath1 uint32, newDescriptor0 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.metadata-hash +//go:noescape +func wasmimport_DescriptorMetadataHash(self0 uint32, result *cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.metadata-hash-at +//go:noescape +func wasmimport_DescriptorMetadataHashAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, result *cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.open-at +//go:noescape +func wasmimport_DescriptorOpenAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, openFlags0 uint32, flags0 uint32, result *cm.Result[Descriptor, Descriptor, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read +//go:noescape +func wasmimport_DescriptorRead(self0 uint32, length0 uint64, offset0 uint64, result *cm.Result[TupleListU8BoolShape, cm.Tuple[cm.List[uint8], bool], ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read-directory +//go:noescape +func wasmimport_DescriptorReadDirectory(self0 uint32, result *cm.Result[DirectoryEntryStream, DirectoryEntryStream, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read-via-stream +//go:noescape +func wasmimport_DescriptorReadViaStream(self0 uint32, offset0 uint64, result *cm.Result[InputStream, InputStream, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.readlink-at +//go:noescape +func wasmimport_DescriptorReadLinkAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[string, string, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.remove-directory-at +//go:noescape +func wasmimport_DescriptorRemoveDirectoryAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.rename-at +//go:noescape +func wasmimport_DescriptorRenameAt(self0 uint32, oldPath0 *uint8, oldPath1 uint32, newDescriptor0 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-size +//go:noescape +func wasmimport_DescriptorSetSize(self0 uint32, size0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-times +//go:noescape +func wasmimport_DescriptorSetTimes(self0 uint32, dataAccessTimestamp0 uint32, dataAccessTimestamp1 uint64, dataAccessTimestamp2 uint32, dataModificationTimestamp0 uint32, dataModificationTimestamp1 uint64, dataModificationTimestamp2 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-times-at +//go:noescape +func wasmimport_DescriptorSetTimesAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, dataAccessTimestamp0 uint32, dataAccessTimestamp1 uint64, dataAccessTimestamp2 uint32, dataModificationTimestamp0 uint32, dataModificationTimestamp1 uint64, dataModificationTimestamp2 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.stat +//go:noescape +func wasmimport_DescriptorStat(self0 uint32, result *cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.stat-at +//go:noescape +func wasmimport_DescriptorStatAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, result *cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.symlink-at +//go:noescape +func wasmimport_DescriptorSymlinkAt(self0 uint32, oldPath0 *uint8, oldPath1 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.sync +//go:noescape +func wasmimport_DescriptorSync(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.sync-data +//go:noescape +func wasmimport_DescriptorSyncData(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.unlink-file-at +//go:noescape +func wasmimport_DescriptorUnlinkFileAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.write +//go:noescape +func wasmimport_DescriptorWrite(self0 uint32, buffer0 *uint8, buffer1 uint32, offset0 uint64, result *cm.Result[uint64, FileSize, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.write-via-stream +//go:noescape +func wasmimport_DescriptorWriteViaStream(self0 uint32, offset0 uint64, result *cm.Result[OutputStream, OutputStream, ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 [resource-drop]directory-entry-stream +//go:noescape +func wasmimport_DirectoryEntryStreamResourceDrop(self0 uint32) + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]directory-entry-stream.read-directory-entry +//go:noescape +func wasmimport_DirectoryEntryStreamReadDirectoryEntry(self0 uint32, result *cm.Result[OptionDirectoryEntryShape, cm.Option[DirectoryEntry], ErrorCode]) + +//go:wasmimport wasi:filesystem/types@0.2.0 filesystem-error-code +//go:noescape +func wasmimport_FilesystemErrorCode(err0 uint32, result *cm.Option[ErrorCode]) diff --git a/x/wasihttp/internal/wasi/filesystem/types/types.wit.go b/x/wasihttp/internal/wasi/filesystem/types/types.wit.go new file mode 100755 index 00000000..7c4501e8 --- /dev/null +++ b/x/wasihttp/internal/wasi/filesystem/types/types.wit.go @@ -0,0 +1,1305 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package types represents the imported interface "wasi:filesystem/types@0.2.0". +// +// WASI filesystem is a filesystem API primarily intended to let users run WASI +// programs that access their files on their existing filesystems, without +// significant overhead. +// +// It is intended to be roughly portable between Unix-family platforms and +// Windows, though it does not hide many of the major differences. +// +// Paths are passed as interface-type `string`s, meaning they must consist of +// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +// paths which are not accessible by this API. +// +// The directory separator in WASI is always the forward-slash (`/`). +// +// All paths in WASI are relative paths, and are interpreted relative to a +// `descriptor` referring to a base directory. If a `path` argument to any WASI +// function starts with `/`, or if any step of resolving a `path`, including +// `..` and symbolic link steps, reaches a directory outside of the base +// directory, or reaches a symlink to an absolute or rooted path in the +// underlying filesystem, the function fails with `error-code::not-permitted`. +// +// For more information about WASI path resolution and sandboxing, see +// [WASI filesystem path resolution]. +// +// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +package types + +import ( + "go.bytecodealliance.org/cm" + wallclock "go.bytecodealliance.org/x/wasihttp/internal/wasi/clocks/wall-clock" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" +) + +// InputStream represents the imported type alias "wasi:filesystem/types@0.2.0#input-stream". +// +// See [streams.InputStream] for more information. +type InputStream = streams.InputStream + +// OutputStream represents the imported type alias "wasi:filesystem/types@0.2.0#output-stream". +// +// See [streams.OutputStream] for more information. +type OutputStream = streams.OutputStream + +// Error represents the imported type alias "wasi:filesystem/types@0.2.0#error". +// +// See [streams.Error] for more information. +type Error = streams.Error + +// DateTime represents the type alias "wasi:filesystem/types@0.2.0#datetime". +// +// See [wallclock.DateTime] for more information. +type DateTime = wallclock.DateTime + +// FileSize represents the u64 "wasi:filesystem/types@0.2.0#filesize". +// +// File size or length of a region within a file. +// +// type filesize = u64 +type FileSize uint64 + +// DescriptorType represents the enum "wasi:filesystem/types@0.2.0#descriptor-type". +// +// The type of a filesystem object referenced by a descriptor. +// +// Note: This was called `filetype` in earlier versions of WASI. +// +// enum descriptor-type { +// unknown, +// block-device, +// character-device, +// directory, +// fifo, +// symbolic-link, +// regular-file, +// socket +// } +type DescriptorType uint8 + +const ( + // The type of the descriptor or file is unknown or is different from + // any of the other types specified. + DescriptorTypeUnknown DescriptorType = iota + + // The descriptor refers to a block device inode. + DescriptorTypeBlockDevice + + // The descriptor refers to a character device inode. + DescriptorTypeCharacterDevice + + // The descriptor refers to a directory inode. + DescriptorTypeDirectory + + // The descriptor refers to a named pipe. + DescriptorTypeFIFO + + // The file refers to a symbolic link inode. + DescriptorTypeSymbolicLink + + // The descriptor refers to a regular file inode. + DescriptorTypeRegularFile + + // The descriptor refers to a socket. + DescriptorTypeSocket +) + +var _DescriptorTypeStrings = [8]string{ + "unknown", + "block-device", + "character-device", + "directory", + "fifo", + "symbolic-link", + "regular-file", + "socket", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e DescriptorType) String() string { + return _DescriptorTypeStrings[e] +} + +// MarshalText implements [encoding.TextMarshaler]. +func (e DescriptorType) MarshalText() ([]byte, error) { + return []byte(e.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum +// case. Returns an error if the supplied text is not one of the enum cases. +func (e *DescriptorType) UnmarshalText(text []byte) error { + return _DescriptorTypeUnmarshalCase(e, text) +} + +var _DescriptorTypeUnmarshalCase = cm.CaseUnmarshaler[DescriptorType](_DescriptorTypeStrings[:]) + +// DescriptorFlags represents the flags "wasi:filesystem/types@0.2.0#descriptor-flags". +// +// Descriptor flags. +// +// Note: This was called `fdflags` in earlier versions of WASI. +// +// flags descriptor-flags { +// read, +// write, +// file-integrity-sync, +// data-integrity-sync, +// requested-write-sync, +// mutate-directory, +// } +type DescriptorFlags uint8 + +const ( + // Read mode: Data can be read. + DescriptorFlagsRead DescriptorFlags = 1 << iota + + // Write mode: Data can be written to. + DescriptorFlagsWrite + + // Request that writes be performed according to synchronized I/O file + // integrity completion. The data stored in the file and the file's + // metadata are synchronized. This is similar to `O_SYNC` in POSIX. + // + // The precise semantics of this operation have not yet been defined for + // WASI. At this time, it should be interpreted as a request, and not a + // requirement. + DescriptorFlagsFileIntegritySync + + // Request that writes be performed according to synchronized I/O data + // integrity completion. Only the data stored in the file is + // synchronized. This is similar to `O_DSYNC` in POSIX. + // + // The precise semantics of this operation have not yet been defined for + // WASI. At this time, it should be interpreted as a request, and not a + // requirement. + DescriptorFlagsDataIntegritySync + + // Requests that reads be performed at the same level of integrety + // requested for writes. This is similar to `O_RSYNC` in POSIX. + // + // The precise semantics of this operation have not yet been defined for + // WASI. At this time, it should be interpreted as a request, and not a + // requirement. + DescriptorFlagsRequestedWriteSync + + // Mutating directories mode: Directory contents may be mutated. + // + // When this flag is unset on a descriptor, operations using the + // descriptor which would create, rename, delete, modify the data or + // metadata of filesystem objects, or obtain another handle which + // would permit any of those, shall fail with `error-code::read-only` if + // they would otherwise succeed. + // + // This may only be set on directories. + DescriptorFlagsMutateDirectory +) + +// PathFlags represents the flags "wasi:filesystem/types@0.2.0#path-flags". +// +// Flags determining the method of how paths are resolved. +// +// flags path-flags { +// symlink-follow, +// } +type PathFlags uint8 + +const ( + // As long as the resolved path corresponds to a symbolic link, it is + // expanded. + PathFlagsSymlinkFollow PathFlags = 1 << iota +) + +// OpenFlags represents the flags "wasi:filesystem/types@0.2.0#open-flags". +// +// Open flags used by `open-at`. +// +// flags open-flags { +// create, +// directory, +// exclusive, +// truncate, +// } +type OpenFlags uint8 + +const ( + // Create file if it does not exist, similar to `O_CREAT` in POSIX. + OpenFlagsCreate OpenFlags = 1 << iota + + // Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + OpenFlagsDirectory + + // Fail if file already exists, similar to `O_EXCL` in POSIX. + OpenFlagsExclusive + + // Truncate file to size 0, similar to `O_TRUNC` in POSIX. + OpenFlagsTruncate +) + +// LinkCount represents the u64 "wasi:filesystem/types@0.2.0#link-count". +// +// Number of hard links to an inode. +// +// type link-count = u64 +type LinkCount uint64 + +// DescriptorStat represents the record "wasi:filesystem/types@0.2.0#descriptor-stat". +// +// File attributes. +// +// Note: This was called `filestat` in earlier versions of WASI. +// +// record descriptor-stat { +// %type: descriptor-type, +// link-count: link-count, +// size: filesize, +// data-access-timestamp: option, +// data-modification-timestamp: option, +// status-change-timestamp: option, +// } +type DescriptorStat struct { + _ cm.HostLayout `json:"-"` + // File type. + Type DescriptorType `json:"type"` + + // Number of hard links to the file. + LinkCount LinkCount `json:"link-count"` + + // For regular files, the file size in bytes. For symbolic links, the + // length in bytes of the pathname contained in the symbolic link. + Size FileSize `json:"size"` + + // Last data access timestamp. + // + // If the `option` is none, the platform doesn't maintain an access + // timestamp for this file. + DataAccessTimestamp cm.Option[DateTime] `json:"data-access-timestamp"` + + // Last data modification timestamp. + // + // If the `option` is none, the platform doesn't maintain a + // modification timestamp for this file. + DataModificationTimestamp cm.Option[DateTime] `json:"data-modification-timestamp"` + + // Last file status-change timestamp. + // + // If the `option` is none, the platform doesn't maintain a + // status-change timestamp for this file. + StatusChangeTimestamp cm.Option[DateTime] `json:"status-change-timestamp"` +} + +// NewTimestamp represents the variant "wasi:filesystem/types@0.2.0#new-timestamp". +// +// When setting a timestamp, this gives the value to set it to. +// +// variant new-timestamp { +// no-change, +// now, +// timestamp(datetime), +// } +type NewTimestamp cm.Variant[uint8, DateTime, DateTime] + +// NewTimestampNoChange returns a [NewTimestamp] of case "no-change". +// +// Leave the timestamp set to its previous value. +func NewTimestampNoChange() NewTimestamp { + var data struct{} + return cm.New[NewTimestamp](0, data) +} + +// NoChange returns true if [NewTimestamp] represents the variant case "no-change". +func (self *NewTimestamp) NoChange() bool { + return self.Tag() == 0 +} + +// NewTimestampNow returns a [NewTimestamp] of case "now". +// +// Set the timestamp to the current time of the system clock associated +// with the filesystem. +func NewTimestampNow() NewTimestamp { + var data struct{} + return cm.New[NewTimestamp](1, data) +} + +// Now returns true if [NewTimestamp] represents the variant case "now". +func (self *NewTimestamp) Now() bool { + return self.Tag() == 1 +} + +// NewTimestampTimestamp returns a [NewTimestamp] of case "timestamp". +// +// Set the timestamp to the given value. +func NewTimestampTimestamp(data DateTime) NewTimestamp { + return cm.New[NewTimestamp](2, data) +} + +// Timestamp returns a non-nil *[DateTime] if [NewTimestamp] represents the variant case "timestamp". +func (self *NewTimestamp) Timestamp() *DateTime { + return cm.Case[DateTime](self, 2) +} + +var _NewTimestampStrings = [3]string{ + "no-change", + "now", + "timestamp", +} + +// String implements [fmt.Stringer], returning the variant case name of v. +func (v NewTimestamp) String() string { + return _NewTimestampStrings[v.Tag()] +} + +// DirectoryEntry represents the record "wasi:filesystem/types@0.2.0#directory-entry". +// +// A directory entry. +// +// record directory-entry { +// %type: descriptor-type, +// name: string, +// } +type DirectoryEntry struct { + _ cm.HostLayout `json:"-"` + // The type of the file referred to by this directory entry. + Type DescriptorType `json:"type"` + + // The name of the object. + Name string `json:"name"` +} + +// ErrorCode represents the enum "wasi:filesystem/types@0.2.0#error-code". +// +// Error codes returned by functions, similar to `errno` in POSIX. +// Not all of these error codes are returned by the functions provided by this +// API; some are used in higher-level library layers, and others are provided +// merely for alignment with POSIX. +// +// enum error-code { +// access, +// would-block, +// already, +// bad-descriptor, +// busy, +// deadlock, +// quota, +// exist, +// file-too-large, +// illegal-byte-sequence, +// in-progress, +// interrupted, +// invalid, +// io, +// is-directory, +// loop, +// too-many-links, +// message-size, +// name-too-long, +// no-device, +// no-entry, +// no-lock, +// insufficient-memory, +// insufficient-space, +// not-directory, +// not-empty, +// not-recoverable, +// unsupported, +// no-tty, +// no-such-device, +// overflow, +// not-permitted, +// pipe, +// read-only, +// invalid-seek, +// text-file-busy, +// cross-device +// } +type ErrorCode uint8 + +const ( + // Permission denied, similar to `EACCES` in POSIX. + ErrorCodeAccess ErrorCode = iota + + // Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` + // in POSIX. + ErrorCodeWouldBlock + + // Connection already in progress, similar to `EALREADY` in POSIX. + ErrorCodeAlready + + // Bad descriptor, similar to `EBADF` in POSIX. + ErrorCodeBadDescriptor + + // Device or resource busy, similar to `EBUSY` in POSIX. + ErrorCodeBusy + + // Resource deadlock would occur, similar to `EDEADLK` in POSIX. + ErrorCodeDeadlock + + // Storage quota exceeded, similar to `EDQUOT` in POSIX. + ErrorCodeQuota + + // File exists, similar to `EEXIST` in POSIX. + ErrorCodeExist + + // File too large, similar to `EFBIG` in POSIX. + ErrorCodeFileTooLarge + + // Illegal byte sequence, similar to `EILSEQ` in POSIX. + ErrorCodeIllegalByteSequence + + // Operation in progress, similar to `EINPROGRESS` in POSIX. + ErrorCodeInProgress + + // Interrupted function, similar to `EINTR` in POSIX. + ErrorCodeInterrupted + + // Invalid argument, similar to `EINVAL` in POSIX. + ErrorCodeInvalid + + // I/O error, similar to `EIO` in POSIX. + ErrorCodeIO + + // Is a directory, similar to `EISDIR` in POSIX. + ErrorCodeIsDirectory + + // Too many levels of symbolic links, similar to `ELOOP` in POSIX. + ErrorCodeLoop + + // Too many links, similar to `EMLINK` in POSIX. + ErrorCodeTooManyLinks + + // Message too large, similar to `EMSGSIZE` in POSIX. + ErrorCodeMessageSize + + // Filename too long, similar to `ENAMETOOLONG` in POSIX. + ErrorCodeNameTooLong + + // No such device, similar to `ENODEV` in POSIX. + ErrorCodeNoDevice + + // No such file or directory, similar to `ENOENT` in POSIX. + ErrorCodeNoEntry + + // No locks available, similar to `ENOLCK` in POSIX. + ErrorCodeNoLock + + // Not enough space, similar to `ENOMEM` in POSIX. + ErrorCodeInsufficientMemory + + // No space left on device, similar to `ENOSPC` in POSIX. + ErrorCodeInsufficientSpace + + // Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + ErrorCodeNotDirectory + + // Directory not empty, similar to `ENOTEMPTY` in POSIX. + ErrorCodeNotEmpty + + // State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + ErrorCodeNotRecoverable + + // Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + ErrorCodeUnsupported + + // Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + ErrorCodeNoTTY + + // No such device or address, similar to `ENXIO` in POSIX. + ErrorCodeNoSuchDevice + + // Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + ErrorCodeOverflow + + // Operation not permitted, similar to `EPERM` in POSIX. + ErrorCodeNotPermitted + + // Broken pipe, similar to `EPIPE` in POSIX. + ErrorCodePipe + + // Read-only file system, similar to `EROFS` in POSIX. + ErrorCodeReadOnly + + // Invalid seek, similar to `ESPIPE` in POSIX. + ErrorCodeInvalidSeek + + // Text file busy, similar to `ETXTBSY` in POSIX. + ErrorCodeTextFileBusy + + // Cross-device link, similar to `EXDEV` in POSIX. + ErrorCodeCrossDevice +) + +var _ErrorCodeStrings = [37]string{ + "access", + "would-block", + "already", + "bad-descriptor", + "busy", + "deadlock", + "quota", + "exist", + "file-too-large", + "illegal-byte-sequence", + "in-progress", + "interrupted", + "invalid", + "io", + "is-directory", + "loop", + "too-many-links", + "message-size", + "name-too-long", + "no-device", + "no-entry", + "no-lock", + "insufficient-memory", + "insufficient-space", + "not-directory", + "not-empty", + "not-recoverable", + "unsupported", + "no-tty", + "no-such-device", + "overflow", + "not-permitted", + "pipe", + "read-only", + "invalid-seek", + "text-file-busy", + "cross-device", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e ErrorCode) String() string { + return _ErrorCodeStrings[e] +} + +// MarshalText implements [encoding.TextMarshaler]. +func (e ErrorCode) MarshalText() ([]byte, error) { + return []byte(e.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum +// case. Returns an error if the supplied text is not one of the enum cases. +func (e *ErrorCode) UnmarshalText(text []byte) error { + return _ErrorCodeUnmarshalCase(e, text) +} + +var _ErrorCodeUnmarshalCase = cm.CaseUnmarshaler[ErrorCode](_ErrorCodeStrings[:]) + +// Advice represents the enum "wasi:filesystem/types@0.2.0#advice". +// +// File or memory access pattern advisory information. +// +// enum advice { +// normal, +// sequential, +// random, +// will-need, +// dont-need, +// no-reuse +// } +type Advice uint8 + +const ( + // The application has no advice to give on its behavior with respect + // to the specified data. + AdviceNormal Advice = iota + + // The application expects to access the specified data sequentially + // from lower offsets to higher offsets. + AdviceSequential + + // The application expects to access the specified data in a random + // order. + AdviceRandom + + // The application expects to access the specified data in the near + // future. + AdviceWillNeed + + // The application expects that it will not access the specified data + // in the near future. + AdviceDontNeed + + // The application expects to access the specified data once and then + // not reuse it thereafter. + AdviceNoReuse +) + +var _AdviceStrings = [6]string{ + "normal", + "sequential", + "random", + "will-need", + "dont-need", + "no-reuse", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e Advice) String() string { + return _AdviceStrings[e] +} + +// MarshalText implements [encoding.TextMarshaler]. +func (e Advice) MarshalText() ([]byte, error) { + return []byte(e.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum +// case. Returns an error if the supplied text is not one of the enum cases. +func (e *Advice) UnmarshalText(text []byte) error { + return _AdviceUnmarshalCase(e, text) +} + +var _AdviceUnmarshalCase = cm.CaseUnmarshaler[Advice](_AdviceStrings[:]) + +// MetadataHashValue represents the record "wasi:filesystem/types@0.2.0#metadata-hash-value". +// +// A 128-bit hash value, split into parts because wasm doesn't have a +// 128-bit integer type. +// +// record metadata-hash-value { +// lower: u64, +// upper: u64, +// } +type MetadataHashValue struct { + _ cm.HostLayout `json:"-"` + // 64 bits of a 128-bit hash value. + Lower uint64 `json:"lower"` + + // Another 64 bits of a 128-bit hash value. + Upper uint64 `json:"upper"` +} + +// Descriptor represents the imported resource "wasi:filesystem/types@0.2.0#descriptor". +// +// A descriptor is a reference to a filesystem object, which may be a file, +// directory, named pipe, special file, or other object on which filesystem +// calls may be made. +// +// resource descriptor +type Descriptor cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "descriptor". +// +// Drops a resource handle. +// +//go:nosplit +func (self Descriptor) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorResourceDrop((uint32)(self0)) + return +} + +// Advise represents the imported method "advise". +// +// Provide file advisory information on a descriptor. +// +// This is similar to `posix_fadvise` in POSIX. +// +// advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) Advise(offset FileSize, length FileSize, advice Advice) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + offset0 := (uint64)(offset) + length0 := (uint64)(length) + advice0 := (uint32)(advice) + wasmimport_DescriptorAdvise((uint32)(self0), (uint64)(offset0), (uint64)(length0), (uint32)(advice0), &result) + return +} + +// AppendViaStream represents the imported method "append-via-stream". +// +// Return a stream for appending to a file, if available. +// +// May fail with an error-code describing why the file cannot be appended. +// +// Note: This allows using `write-stream`, which is similar to `write` with +// `O_APPEND` in in POSIX. +// +// append-via-stream: func() -> result +// +//go:nosplit +func (self Descriptor) AppendViaStream() (result cm.Result[OutputStream, OutputStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorAppendViaStream((uint32)(self0), &result) + return +} + +// CreateDirectoryAt represents the imported method "create-directory-at". +// +// Create a directory. +// +// Note: This is similar to `mkdirat` in POSIX. +// +// create-directory-at: func(path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) CreateDirectoryAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorCreateDirectoryAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +// GetFlags represents the imported method "get-flags". +// +// Get flags associated with a descriptor. +// +// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. +// +// Note: This returns the value that was the `fs_flags` value returned +// from `fdstat_get` in earlier versions of WASI. +// +// get-flags: func() -> result +// +//go:nosplit +func (self Descriptor) GetFlags() (result cm.Result[DescriptorFlags, DescriptorFlags, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorGetFlags((uint32)(self0), &result) + return +} + +// GetType represents the imported method "get-type". +// +// Get the dynamic type of a descriptor. +// +// Note: This returns the same value as the `type` field of the `fd-stat` +// returned by `stat`, `stat-at` and similar. +// +// Note: This returns similar flags to the `st_mode & S_IFMT` value provided +// by `fstat` in POSIX. +// +// Note: This returns the value that was the `fs_filetype` value returned +// from `fdstat_get` in earlier versions of WASI. +// +// get-type: func() -> result +// +//go:nosplit +func (self Descriptor) GetType() (result cm.Result[DescriptorType, DescriptorType, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorGetType((uint32)(self0), &result) + return +} + +// IsSameObject represents the imported method "is-same-object". +// +// Test whether two descriptors refer to the same filesystem object. +// +// In POSIX, this corresponds to testing whether the two descriptors have the +// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. +// wasi-filesystem does not expose device and inode numbers, so this function +// may be used instead. +// +// is-same-object: func(other: borrow) -> bool +// +//go:nosplit +func (self Descriptor) IsSameObject(other Descriptor) (result bool) { + self0 := cm.Reinterpret[uint32](self) + other0 := cm.Reinterpret[uint32](other) + result0 := wasmimport_DescriptorIsSameObject((uint32)(self0), (uint32)(other0)) + result = (bool)(cm.U32ToBool((uint32)(result0))) + return +} + +// LinkAt represents the imported method "link-at". +// +// Create a hard link. +// +// Note: This is similar to `linkat` in POSIX. +// +// link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, +// new-path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) LinkAt(oldPathFlags PathFlags, oldPath string, newDescriptor Descriptor, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + oldPathFlags0 := (uint32)(oldPathFlags) + oldPath0, oldPath1 := cm.LowerString(oldPath) + newDescriptor0 := cm.Reinterpret[uint32](newDescriptor) + newPath0, newPath1 := cm.LowerString(newPath) + wasmimport_DescriptorLinkAt((uint32)(self0), (uint32)(oldPathFlags0), (*uint8)(oldPath0), (uint32)(oldPath1), (uint32)(newDescriptor0), (*uint8)(newPath0), (uint32)(newPath1), &result) + return +} + +// MetadataHash represents the imported method "metadata-hash". +// +// Return a hash of the metadata associated with a filesystem object referred +// to by a descriptor. +// +// This returns a hash of the last-modification timestamp and file size, and +// may also include the inode number, device number, birth timestamp, and +// other metadata fields that may change when the file is modified or +// replaced. It may also include a secret value chosen by the +// implementation and not otherwise exposed. +// +// Implementations are encourated to provide the following properties: +// +// - If the file is not modified or replaced, the computed hash value should +// usually not change. +// - If the object is modified or replaced, the computed hash value should +// usually change. +// - The inputs to the hash should not be easily computable from the +// computed hash. +// +// However, none of these is required. +// +// metadata-hash: func() -> result +// +//go:nosplit +func (self Descriptor) MetadataHash() (result cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorMetadataHash((uint32)(self0), &result) + return +} + +// MetadataHashAt represents the imported method "metadata-hash-at". +// +// Return a hash of the metadata associated with a filesystem object referred +// to by a directory descriptor and a relative path. +// +// This performs the same hash computation as `metadata-hash`. +// +// metadata-hash-at: func(path-flags: path-flags, path: string) -> result +// +//go:nosplit +func (self Descriptor) MetadataHashAt(pathFlags PathFlags, path string) (result cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorMetadataHashAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +// OpenAt represents the imported method "open-at". +// +// Open a file or directory. +// +// The returned descriptor is not guaranteed to be the lowest-numbered +// descriptor not currently open/ it is randomized to prevent applications +// from depending on making assumptions about indexes, since this is +// error-prone in multi-threaded contexts. The returned descriptor is +// guaranteed to be less than 2**31. +// +// If `flags` contains `descriptor-flags::mutate-directory`, and the base +// descriptor doesn't have `descriptor-flags::mutate-directory` set, +// `open-at` fails with `error-code::read-only`. +// +// If `flags` contains `write` or `mutate-directory`, or `open-flags` +// contains `truncate` or `create`, and the base descriptor doesn't have +// `descriptor-flags::mutate-directory` set, `open-at` fails with +// `error-code::read-only`. +// +// Note: This is similar to `openat` in POSIX. +// +// open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: +// descriptor-flags) -> result +// +//go:nosplit +func (self Descriptor) OpenAt(pathFlags PathFlags, path string, openFlags OpenFlags, flags DescriptorFlags) (result cm.Result[Descriptor, Descriptor, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + openFlags0 := (uint32)(openFlags) + flags0 := (uint32)(flags) + wasmimport_DescriptorOpenAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), (uint32)(openFlags0), (uint32)(flags0), &result) + return +} + +// Read represents the imported method "read". +// +// Read from a descriptor, without using and updating the descriptor's offset. +// +// This function returns a list of bytes containing the data that was +// read, along with a bool which, when true, indicates that the end of the +// file was reached. The returned list will contain up to `length` bytes; it +// may return fewer than requested, if the end of the file is reached or +// if the I/O operation is interrupted. +// +// In the future, this may change to return a `stream`. +// +// Note: This is similar to `pread` in POSIX. +// +// read: func(length: filesize, offset: filesize) -> result, bool>, +// error-code> +// +//go:nosplit +func (self Descriptor) Read(length FileSize, offset FileSize) (result cm.Result[TupleListU8BoolShape, cm.Tuple[cm.List[uint8], bool], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + length0 := (uint64)(length) + offset0 := (uint64)(offset) + wasmimport_DescriptorRead((uint32)(self0), (uint64)(length0), (uint64)(offset0), &result) + return +} + +// ReadDirectory represents the imported method "read-directory". +// +// Read directory entries from a directory. +// +// On filesystems where directories contain entries referring to themselves +// and their parents, often named `.` and `..` respectively, these entries +// are omitted. +// +// This always returns a new stream which starts at the beginning of the +// directory. Multiple streams may be active on the same directory, and they +// do not interfere with each other. +// +// read-directory: func() -> result +// +//go:nosplit +func (self Descriptor) ReadDirectory() (result cm.Result[DirectoryEntryStream, DirectoryEntryStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorReadDirectory((uint32)(self0), &result) + return +} + +// ReadViaStream represents the imported method "read-via-stream". +// +// Return a stream for reading from a file, if available. +// +// May fail with an error-code describing why the file cannot be read. +// +// Multiple read, write, and append streams may be active on the same open +// file and they do not interfere with each other. +// +// Note: This allows using `read-stream`, which is similar to `read` in POSIX. +// +// read-via-stream: func(offset: filesize) -> result +// +//go:nosplit +func (self Descriptor) ReadViaStream(offset FileSize) (result cm.Result[InputStream, InputStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + offset0 := (uint64)(offset) + wasmimport_DescriptorReadViaStream((uint32)(self0), (uint64)(offset0), &result) + return +} + +// ReadLinkAt represents the imported method "readlink-at". +// +// Read the contents of a symbolic link. +// +// If the contents contain an absolute or rooted path in the underlying +// filesystem, this function fails with `error-code::not-permitted`. +// +// Note: This is similar to `readlinkat` in POSIX. +// +// readlink-at: func(path: string) -> result +// +//go:nosplit +func (self Descriptor) ReadLinkAt(path string) (result cm.Result[string, string, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorReadLinkAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +// RemoveDirectoryAt represents the imported method "remove-directory-at". +// +// Remove a directory. +// +// Return `error-code::not-empty` if the directory is not empty. +// +// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. +// +// remove-directory-at: func(path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) RemoveDirectoryAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorRemoveDirectoryAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +// RenameAt represents the imported method "rename-at". +// +// Rename a filesystem object. +// +// Note: This is similar to `renameat` in POSIX. +// +// rename-at: func(old-path: string, new-descriptor: borrow, new-path: +// string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) RenameAt(oldPath string, newDescriptor Descriptor, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + oldPath0, oldPath1 := cm.LowerString(oldPath) + newDescriptor0 := cm.Reinterpret[uint32](newDescriptor) + newPath0, newPath1 := cm.LowerString(newPath) + wasmimport_DescriptorRenameAt((uint32)(self0), (*uint8)(oldPath0), (uint32)(oldPath1), (uint32)(newDescriptor0), (*uint8)(newPath0), (uint32)(newPath1), &result) + return +} + +// SetSize represents the imported method "set-size". +// +// Adjust the size of an open file. If this increases the file's size, the +// extra bytes are filled with zeros. +// +// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. +// +// set-size: func(size: filesize) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SetSize(size FileSize) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + size0 := (uint64)(size) + wasmimport_DescriptorSetSize((uint32)(self0), (uint64)(size0), &result) + return +} + +// SetTimes represents the imported method "set-times". +// +// Adjust the timestamps of an open file or directory. +// +// Note: This is similar to `futimens` in POSIX. +// +// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. +// +// set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: +// new-timestamp) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SetTimes(dataAccessTimestamp NewTimestamp, dataModificationTimestamp NewTimestamp) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + dataAccessTimestamp0, dataAccessTimestamp1, dataAccessTimestamp2 := lower_NewTimestamp(dataAccessTimestamp) + dataModificationTimestamp0, dataModificationTimestamp1, dataModificationTimestamp2 := lower_NewTimestamp(dataModificationTimestamp) + wasmimport_DescriptorSetTimes((uint32)(self0), (uint32)(dataAccessTimestamp0), (uint64)(dataAccessTimestamp1), (uint32)(dataAccessTimestamp2), (uint32)(dataModificationTimestamp0), (uint64)(dataModificationTimestamp1), (uint32)(dataModificationTimestamp2), &result) + return +} + +// SetTimesAt represents the imported method "set-times-at". +// +// Adjust the timestamps of a file or directory. +// +// Note: This is similar to `utimensat` in POSIX. +// +// Note: This was called `path_filestat_set_times` in earlier versions of +// WASI. +// +// set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: +// new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SetTimesAt(pathFlags PathFlags, path string, dataAccessTimestamp NewTimestamp, dataModificationTimestamp NewTimestamp) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + dataAccessTimestamp0, dataAccessTimestamp1, dataAccessTimestamp2 := lower_NewTimestamp(dataAccessTimestamp) + dataModificationTimestamp0, dataModificationTimestamp1, dataModificationTimestamp2 := lower_NewTimestamp(dataModificationTimestamp) + wasmimport_DescriptorSetTimesAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), (uint32)(dataAccessTimestamp0), (uint64)(dataAccessTimestamp1), (uint32)(dataAccessTimestamp2), (uint32)(dataModificationTimestamp0), (uint64)(dataModificationTimestamp1), (uint32)(dataModificationTimestamp2), &result) + return +} + +// Stat represents the imported method "stat". +// +// Return the attributes of an open file or directory. +// +// Note: This is similar to `fstat` in POSIX, except that it does not return +// device and inode information. For testing whether two descriptors refer to +// the same underlying filesystem object, use `is-same-object`. To obtain +// additional data that can be used do determine whether a file has been +// modified, use `metadata-hash`. +// +// Note: This was called `fd_filestat_get` in earlier versions of WASI. +// +// stat: func() -> result +// +//go:nosplit +func (self Descriptor) Stat() (result cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorStat((uint32)(self0), &result) + return +} + +// StatAt represents the imported method "stat-at". +// +// Return the attributes of a file or directory. +// +// Note: This is similar to `fstatat` in POSIX, except that it does not +// return device and inode information. See the `stat` description for a +// discussion of alternatives. +// +// Note: This was called `path_filestat_get` in earlier versions of WASI. +// +// stat-at: func(path-flags: path-flags, path: string) -> result +// +//go:nosplit +func (self Descriptor) StatAt(pathFlags PathFlags, path string) (result cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorStatAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +// SymlinkAt represents the imported method "symlink-at". +// +// Create a symbolic link (also known as a "symlink"). +// +// If `old-path` starts with `/`, the function fails with +// `error-code::not-permitted`. +// +// Note: This is similar to `symlinkat` in POSIX. +// +// symlink-at: func(old-path: string, new-path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SymlinkAt(oldPath string, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + oldPath0, oldPath1 := cm.LowerString(oldPath) + newPath0, newPath1 := cm.LowerString(newPath) + wasmimport_DescriptorSymlinkAt((uint32)(self0), (*uint8)(oldPath0), (uint32)(oldPath1), (*uint8)(newPath0), (uint32)(newPath1), &result) + return +} + +// Sync represents the imported method "sync". +// +// Synchronize the data and metadata of a file to disk. +// +// This function succeeds with no effect if the file descriptor is not +// opened for writing. +// +// Note: This is similar to `fsync` in POSIX. +// +// sync: func() -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) Sync() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorSync((uint32)(self0), &result) + return +} + +// SyncData represents the imported method "sync-data". +// +// Synchronize the data of a file to disk. +// +// This function succeeds with no effect if the file descriptor is not +// opened for writing. +// +// Note: This is similar to `fdatasync` in POSIX. +// +// sync-data: func() -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SyncData() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorSyncData((uint32)(self0), &result) + return +} + +// UnlinkFileAt represents the imported method "unlink-file-at". +// +// Unlink a filesystem object that is not a directory. +// +// Return `error-code::is-directory` if the path refers to a directory. +// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. +// +// unlink-file-at: func(path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) UnlinkFileAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorUnlinkFileAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +// Write represents the imported method "write". +// +// Write to a descriptor, without using and updating the descriptor's offset. +// +// It is valid to write past the end of a file; the file is extended to the +// extent of the write, with bytes between the previous end and the start of +// the write set to zero. +// +// In the future, this may change to take a `stream`. +// +// Note: This is similar to `pwrite` in POSIX. +// +// write: func(buffer: list, offset: filesize) -> result +// +//go:nosplit +func (self Descriptor) Write(buffer cm.List[uint8], offset FileSize) (result cm.Result[uint64, FileSize, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + buffer0, buffer1 := cm.LowerList(buffer) + offset0 := (uint64)(offset) + wasmimport_DescriptorWrite((uint32)(self0), (*uint8)(buffer0), (uint32)(buffer1), (uint64)(offset0), &result) + return +} + +// WriteViaStream represents the imported method "write-via-stream". +// +// Return a stream for writing to a file, if available. +// +// May fail with an error-code describing why the file cannot be written. +// +// Note: This allows using `write-stream`, which is similar to `write` in +// POSIX. +// +// write-via-stream: func(offset: filesize) -> result +// +//go:nosplit +func (self Descriptor) WriteViaStream(offset FileSize) (result cm.Result[OutputStream, OutputStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + offset0 := (uint64)(offset) + wasmimport_DescriptorWriteViaStream((uint32)(self0), (uint64)(offset0), &result) + return +} + +// DirectoryEntryStream represents the imported resource "wasi:filesystem/types@0.2.0#directory-entry-stream". +// +// A stream of directory entries. +// +// resource directory-entry-stream +type DirectoryEntryStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "directory-entry-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self DirectoryEntryStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DirectoryEntryStreamResourceDrop((uint32)(self0)) + return +} + +// ReadDirectoryEntry represents the imported method "read-directory-entry". +// +// Read a single directory entry from a `directory-entry-stream`. +// +// read-directory-entry: func() -> result, error-code> +// +//go:nosplit +func (self DirectoryEntryStream) ReadDirectoryEntry() (result cm.Result[OptionDirectoryEntryShape, cm.Option[DirectoryEntry], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DirectoryEntryStreamReadDirectoryEntry((uint32)(self0), &result) + return +} + +// FilesystemErrorCode represents the imported function "filesystem-error-code". +// +// Attempts to extract a filesystem-related `error-code` from the stream +// `error` provided. +// +// Stream operations which return `stream-error::last-operation-failed` +// have a payload with more information about the operation that failed. +// This payload can be passed through to this function to see if there's +// filesystem-related information about the error to return. +// +// Note that this function is fallible because not all stream-related +// errors are filesystem-related errors. +// +// filesystem-error-code: func(err: borrow) -> option +// +//go:nosplit +func FilesystemErrorCode(err Error) (result cm.Option[ErrorCode]) { + err0 := cm.Reinterpret[uint32](err) + wasmimport_FilesystemErrorCode((uint32)(err0), &result) + return +} diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/empty.s b/x/wasihttp/internal/wasi/http/incoming-handler/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/incoming-handler/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.exports.go b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.exports.go new file mode 100755 index 00000000..673ccb48 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.exports.go @@ -0,0 +1,22 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package incominghandler + +// Exports represents the caller-defined exports from "wasi:http/incoming-handler@0.2.0". +var Exports struct { + // Handle represents the caller-defined, exported function "handle". + // + // This function is invoked with an incoming HTTP Request, and a resource + // `response-outparam` which provides the capability to reply with an HTTP + // Response. The response is sent by calling the `response-outparam.set` + // method, which allows execution to continue after the response has been + // sent. This enables both streaming to the response body, and performing other + // work. + // + // The implementor of this function must write a response to the + // `response-outparam` before returning, or else the caller will respond + // with an error on its behalf. + // + // handle: func(request: incoming-request, response-out: response-outparam) + Handle func(request IncomingRequest, responseOut ResponseOutparam) +} diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wasm.go b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wasm.go new file mode 100755 index 00000000..eae429f3 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wasm.go @@ -0,0 +1,18 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package incominghandler + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:http@0.2.0". + +//go:wasmexport wasi:http/incoming-handler@0.2.0#handle +//export wasi:http/incoming-handler@0.2.0#handle +func wasmexport_Handle(request0 uint32, responseOut0 uint32) { + request := cm.Reinterpret[IncomingRequest]((uint32)(request0)) + responseOut := cm.Reinterpret[ResponseOutparam]((uint32)(responseOut0)) + Exports.Handle(request, responseOut) + return +} diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wit.go b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wit.go new file mode 100755 index 00000000..63ce2382 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wit.go @@ -0,0 +1,21 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package incominghandler represents the exported interface "wasi:http/incoming-handler@0.2.0". +// +// This interface defines a handler of incoming HTTP Requests. It should +// be exported by components which can respond to HTTP Requests. +package incominghandler + +import ( + "go.bytecodealliance.org/x/wasihttp/internal/wasi/http/types" +) + +// IncomingRequest represents the exported type alias "wasi:http/incoming-handler@0.2.0#incoming-request". +// +// See [types.IncomingRequest] for more information. +type IncomingRequest = types.IncomingRequest + +// ResponseOutparam represents the exported type alias "wasi:http/incoming-handler@0.2.0#response-outparam". +// +// See [types.ResponseOutparam] for more information. +type ResponseOutparam = types.ResponseOutparam diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/abi.go b/x/wasihttp/internal/wasi/http/outgoing-handler/abi.go new file mode 100755 index 00000000..cdc17d0d --- /dev/null +++ b/x/wasihttp/internal/wasi/http/outgoing-handler/abi.go @@ -0,0 +1,24 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package outgoinghandler + +import ( + "go.bytecodealliance.org/cm" + "unsafe" +) + +// ErrorCodeShape is used for storage in variant or result types. +type ErrorCodeShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(ErrorCode{})]byte +} + +func lower_OptionRequestOptions(v cm.Option[RequestOptions]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := cm.Reinterpret[uint32](*some) + f1 = (uint32)(v1) + } + return +} diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/empty.s b/x/wasihttp/internal/wasi/http/outgoing-handler/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/outgoing-handler/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wasm.go b/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wasm.go new file mode 100755 index 00000000..6b3f3828 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package outgoinghandler + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:http@0.2.0". + +//go:wasmimport wasi:http/outgoing-handler@0.2.0 handle +//go:noescape +func wasmimport_Handle(request0 uint32, options0 uint32, options1 uint32, result *cm.Result[ErrorCodeShape, FutureIncomingResponse, ErrorCode]) diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wit.go b/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wit.go new file mode 100755 index 00000000..d413ec98 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wit.go @@ -0,0 +1,56 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package outgoinghandler represents the imported interface "wasi:http/outgoing-handler@0.2.0". +// +// This interface defines a handler of outgoing HTTP Requests. It should be +// imported by components which wish to make HTTP Requests. +package outgoinghandler + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/http/types" +) + +// OutgoingRequest represents the imported type alias "wasi:http/outgoing-handler@0.2.0#outgoing-request". +// +// See [types.OutgoingRequest] for more information. +type OutgoingRequest = types.OutgoingRequest + +// RequestOptions represents the imported type alias "wasi:http/outgoing-handler@0.2.0#request-options". +// +// See [types.RequestOptions] for more information. +type RequestOptions = types.RequestOptions + +// FutureIncomingResponse represents the imported type alias "wasi:http/outgoing-handler@0.2.0#future-incoming-response". +// +// See [types.FutureIncomingResponse] for more information. +type FutureIncomingResponse = types.FutureIncomingResponse + +// ErrorCode represents the type alias "wasi:http/outgoing-handler@0.2.0#error-code". +// +// See [types.ErrorCode] for more information. +type ErrorCode = types.ErrorCode + +// Handle represents the imported function "handle". +// +// This function is invoked with an outgoing HTTP Request, and it returns +// a resource `future-incoming-response` which represents an HTTP Response +// which may arrive in the future. +// +// The `options` argument accepts optional parameters for the HTTP +// protocol's transport layer. +// +// This function may return an error if the `outgoing-request` is invalid +// or not allowed to be made. Otherwise, protocol errors are reported +// through the `future-incoming-response`. +// +// handle: func(request: outgoing-request, options: option) -> result +// +//go:nosplit +func Handle(request OutgoingRequest, options cm.Option[RequestOptions]) (result cm.Result[ErrorCodeShape, FutureIncomingResponse, ErrorCode]) { + request0 := cm.Reinterpret[uint32](request) + options0, options1 := lower_OptionRequestOptions(options) + wasmimport_Handle((uint32)(request0), (uint32)(options0), (uint32)(options1), &result) + return +} diff --git a/x/wasihttp/internal/wasi/http/types/abi.go b/x/wasihttp/internal/wasi/http/types/abi.go new file mode 100755 index 00000000..6ffb1fdd --- /dev/null +++ b/x/wasihttp/internal/wasi/http/types/abi.go @@ -0,0 +1,264 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package types + +import ( + "go.bytecodealliance.org/cm" + "unsafe" +) + +// OptionFieldSizePayloadShape is used for storage in variant or result types. +type OptionFieldSizePayloadShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(cm.Option[FieldSizePayload]{})]byte +} + +func lower_OptionString(v cm.Option[string]) (f0 uint32, f1 *uint8, f2 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2 := cm.LowerString(*some) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_Method(v Method) (f0 uint32, f1 *uint8, f2 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 9: // other + v1, v2 := cm.LowerString(*cm.Case[string](&v, 9)) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_Scheme(v Scheme) (f0 uint32, f1 *uint8, f2 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 2: // other + v1, v2 := cm.LowerString(*cm.Case[string](&v, 2)) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_OptionScheme(v cm.Option[Scheme]) (f0 uint32, f1 uint32, f2 *uint8, f3 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2, v3 := lower_Scheme(*some) + f1 = (uint32)(v1) + f2 = (*uint8)(v2) + f3 = (uint32)(v3) + } + return +} + +func lower_OptionDuration(v cm.Option[Duration]) (f0 uint32, f1 uint64) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint64)(*some) + f1 = (uint64)(v1) + } + return +} + +// ErrorCodeShape is used for storage in variant or result types. +type ErrorCodeShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(ErrorCode{})]byte +} + +func lower_OptionU16(v cm.Option[uint16]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint32)(*some) + f1 = (uint32)(v1) + } + return +} + +func lower_DNSErrorPayload(v DNSErrorPayload) (f0 uint32, f1 *uint8, f2 uint32, f3 uint32, f4 uint32) { + f0, f1, f2 = lower_OptionString(v.Rcode) + f3, f4 = lower_OptionU16(v.InfoCode) + return +} + +func lower_OptionU8(v cm.Option[uint8]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint32)(*some) + f1 = (uint32)(v1) + } + return +} + +func lower_TLSAlertReceivedPayload(v TLSAlertReceivedPayload) (f0 uint32, f1 uint32, f2 uint32, f3 *uint8, f4 uint32) { + f0, f1 = lower_OptionU8(v.AlertID) + f2, f3, f4 = lower_OptionString(v.AlertMessage) + return +} + +func lower_OptionU64(v cm.Option[uint64]) (f0 uint32, f1 uint64) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint64)(*some) + f1 = (uint64)(v1) + } + return +} + +func lower_OptionU32(v cm.Option[uint32]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint32)(*some) + f1 = (uint32)(v1) + } + return +} + +func lower_FieldSizePayload(v FieldSizePayload) (f0 uint32, f1 *uint8, f2 uint32, f3 uint32, f4 uint32) { + f0, f1, f2 = lower_OptionString(v.FieldName) + f3, f4 = lower_OptionU32(v.FieldSize) + return +} + +func lower_OptionFieldSizePayload(v cm.Option[FieldSizePayload]) (f0 uint32, f1 uint32, f2 *uint8, f3 uint32, f4 uint32, f5 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*some) + f1 = (uint32)(v1) + f2 = (*uint8)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + } + return +} + +func lower_ErrorCode(v ErrorCode) (f0 uint32, f1 uint32, f2 uint64, f3 uint32, f4 uint32, f5 uint32, f6 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 1: // DNS-error + v1, v2, v3, v4, v5 := lower_DNSErrorPayload(*cm.Case[DNSErrorPayload](&v, 1)) + f1 = (uint32)(v1) + f2 = (uint64)(cm.PointerToU64(v2)) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 14: // TLS-alert-received + v1, v2, v3, v4, v5 := lower_TLSAlertReceivedPayload(*cm.Case[TLSAlertReceivedPayload](&v, 14)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(cm.PointerToU32(v4)) + f5 = (uint32)(v5) + case 17: // HTTP-request-body-size + v1, v2 := lower_OptionU64(*cm.Case[cm.Option[uint64]](&v, 17)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 21: // HTTP-request-header-section-size + v1, v2 := lower_OptionU32(*cm.Case[cm.Option[uint32]](&v, 21)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 22: // HTTP-request-header-size + v1, v2, v3, v4, v5, v6 := lower_OptionFieldSizePayload(*cm.Case[cm.Option[FieldSizePayload]](&v, 22)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + f3 = (uint32)(cm.PointerToU32(v3)) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + case 23: // HTTP-request-trailer-section-size + v1, v2 := lower_OptionU32(*cm.Case[cm.Option[uint32]](&v, 23)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 24: // HTTP-request-trailer-size + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*cm.Case[FieldSizePayload](&v, 24)) + f1 = (uint32)(v1) + f2 = (uint64)(cm.PointerToU64(v2)) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 26: // HTTP-response-header-section-size + v1, v2 := lower_OptionU32(*cm.Case[cm.Option[uint32]](&v, 26)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 27: // HTTP-response-header-size + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*cm.Case[FieldSizePayload](&v, 27)) + f1 = (uint32)(v1) + f2 = (uint64)(cm.PointerToU64(v2)) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 28: // HTTP-response-body-size + v1, v2 := lower_OptionU64(*cm.Case[cm.Option[uint64]](&v, 28)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 29: // HTTP-response-trailer-section-size + v1, v2 := lower_OptionU32(*cm.Case[cm.Option[uint32]](&v, 29)) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 30: // HTTP-response-trailer-size + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*cm.Case[FieldSizePayload](&v, 30)) + f1 = (uint32)(v1) + f2 = (uint64)(cm.PointerToU64(v2)) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 31: // HTTP-response-transfer-coding + v1, v2, v3 := lower_OptionString(*cm.Case[cm.Option[string]](&v, 31)) + f1 = (uint32)(v1) + f2 = (uint64)(cm.PointerToU64(v2)) + f3 = (uint32)(v3) + case 32: // HTTP-response-content-coding + v1, v2, v3 := lower_OptionString(*cm.Case[cm.Option[string]](&v, 32)) + f1 = (uint32)(v1) + f2 = (uint64)(cm.PointerToU64(v2)) + f3 = (uint32)(v3) + case 38: // internal-error + v1, v2, v3 := lower_OptionString(*cm.Case[cm.Option[string]](&v, 38)) + f1 = (uint32)(v1) + f2 = (uint64)(cm.PointerToU64(v2)) + f3 = (uint32)(v3) + } + return +} + +func lower_ResultOutgoingResponseErrorCode(v cm.Result[ErrorCodeShape, OutgoingResponse, ErrorCode]) (f0 uint32, f1 uint32, f2 uint32, f3 uint64, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { + if v.IsOK() { + v1 := cm.Reinterpret[uint32](*v.OK()) + f1 = (uint32)(v1) + } else { + f0 = 1 + v1, v2, v3, v4, v5, v6, v7 := lower_ErrorCode(*v.Err()) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint64)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + } + return +} + +func lower_OptionTrailers(v cm.Option[Trailers]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := cm.Reinterpret[uint32](*some) + f1 = (uint32)(v1) + } + return +} diff --git a/x/wasihttp/internal/wasi/http/types/empty.s b/x/wasihttp/internal/wasi/http/types/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/types/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/http/types/types.wasm.go b/x/wasihttp/internal/wasi/http/types/types.wasm.go new file mode 100755 index 00000000..b025b2af --- /dev/null +++ b/x/wasihttp/internal/wasi/http/types/types.wasm.go @@ -0,0 +1,257 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package types + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:http@0.2.0". + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]fields +//go:noescape +func wasmimport_FieldsResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [constructor]fields +//go:noescape +func wasmimport_NewFields() (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [static]fields.from-list +//go:noescape +func wasmimport_FieldsFromList(entries0 *cm.Tuple[FieldKey, FieldValue], entries1 uint32, result *cm.Result[Fields, Fields, HeaderError]) + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.append +//go:noescape +func wasmimport_FieldsAppend(self0 uint32, name0 *uint8, name1 uint32, value0 *uint8, value1 uint32, result *cm.Result[HeaderError, struct{}, HeaderError]) + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.clone +//go:noescape +func wasmimport_FieldsClone(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.delete +//go:noescape +func wasmimport_FieldsDelete(self0 uint32, name0 *uint8, name1 uint32, result *cm.Result[HeaderError, struct{}, HeaderError]) + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.entries +//go:noescape +func wasmimport_FieldsEntries(self0 uint32, result *cm.List[cm.Tuple[FieldKey, FieldValue]]) + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.get +//go:noescape +func wasmimport_FieldsGet(self0 uint32, name0 *uint8, name1 uint32, result *cm.List[FieldValue]) + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.has +//go:noescape +func wasmimport_FieldsHas(self0 uint32, name0 *uint8, name1 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.set +//go:noescape +func wasmimport_FieldsSet(self0 uint32, name0 *uint8, name1 uint32, value0 *FieldValue, value1 uint32, result *cm.Result[HeaderError, struct{}, HeaderError]) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]incoming-request +//go:noescape +func wasmimport_IncomingRequestResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.authority +//go:noescape +func wasmimport_IncomingRequestAuthority(self0 uint32, result *cm.Option[string]) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.consume +//go:noescape +func wasmimport_IncomingRequestConsume(self0 uint32, result *cm.Result[IncomingBody, IncomingBody, struct{}]) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.headers +//go:noescape +func wasmimport_IncomingRequestHeaders(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.method +//go:noescape +func wasmimport_IncomingRequestMethod(self0 uint32, result *Method) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.path-with-query +//go:noescape +func wasmimport_IncomingRequestPathWithQuery(self0 uint32, result *cm.Option[string]) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.scheme +//go:noescape +func wasmimport_IncomingRequestScheme(self0 uint32, result *cm.Option[Scheme]) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]outgoing-request +//go:noescape +func wasmimport_OutgoingRequestResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [constructor]outgoing-request +//go:noescape +func wasmimport_NewOutgoingRequest(headers0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.authority +//go:noescape +func wasmimport_OutgoingRequestAuthority(self0 uint32, result *cm.Option[string]) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.body +//go:noescape +func wasmimport_OutgoingRequestBody(self0 uint32, result *cm.Result[OutgoingBody, OutgoingBody, struct{}]) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.headers +//go:noescape +func wasmimport_OutgoingRequestHeaders(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.method +//go:noescape +func wasmimport_OutgoingRequestMethod(self0 uint32, result *Method) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.path-with-query +//go:noescape +func wasmimport_OutgoingRequestPathWithQuery(self0 uint32, result *cm.Option[string]) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.scheme +//go:noescape +func wasmimport_OutgoingRequestScheme(self0 uint32, result *cm.Option[Scheme]) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-authority +//go:noescape +func wasmimport_OutgoingRequestSetAuthority(self0 uint32, authority0 uint32, authority1 *uint8, authority2 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-method +//go:noescape +func wasmimport_OutgoingRequestSetMethod(self0 uint32, method0 uint32, method1 *uint8, method2 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-path-with-query +//go:noescape +func wasmimport_OutgoingRequestSetPathWithQuery(self0 uint32, pathWithQuery0 uint32, pathWithQuery1 *uint8, pathWithQuery2 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-scheme +//go:noescape +func wasmimport_OutgoingRequestSetScheme(self0 uint32, scheme0 uint32, scheme1 uint32, scheme2 *uint8, scheme3 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]request-options +//go:noescape +func wasmimport_RequestOptionsResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [constructor]request-options +//go:noescape +func wasmimport_NewRequestOptions() (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.between-bytes-timeout +//go:noescape +func wasmimport_RequestOptionsBetweenBytesTimeout(self0 uint32, result *cm.Option[Duration]) + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.connect-timeout +//go:noescape +func wasmimport_RequestOptionsConnectTimeout(self0 uint32, result *cm.Option[Duration]) + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.first-byte-timeout +//go:noescape +func wasmimport_RequestOptionsFirstByteTimeout(self0 uint32, result *cm.Option[Duration]) + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.set-between-bytes-timeout +//go:noescape +func wasmimport_RequestOptionsSetBetweenBytesTimeout(self0 uint32, duration0 uint32, duration1 uint64) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.set-connect-timeout +//go:noescape +func wasmimport_RequestOptionsSetConnectTimeout(self0 uint32, duration0 uint32, duration1 uint64) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.set-first-byte-timeout +//go:noescape +func wasmimport_RequestOptionsSetFirstByteTimeout(self0 uint32, duration0 uint32, duration1 uint64) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]response-outparam +//go:noescape +func wasmimport_ResponseOutparamResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [static]response-outparam.set +//go:noescape +func wasmimport_ResponseOutparamSet(param0 uint32, response0 uint32, response1 uint32, response2 uint32, response3 uint64, response4 uint32, response5 uint32, response6 uint32, response7 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]incoming-response +//go:noescape +func wasmimport_IncomingResponseResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-response.consume +//go:noescape +func wasmimport_IncomingResponseConsume(self0 uint32, result *cm.Result[IncomingBody, IncomingBody, struct{}]) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-response.headers +//go:noescape +func wasmimport_IncomingResponseHeaders(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-response.status +//go:noescape +func wasmimport_IncomingResponseStatus(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]incoming-body +//go:noescape +func wasmimport_IncomingBodyResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [static]incoming-body.finish +//go:noescape +func wasmimport_IncomingBodyFinish(this0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-body.stream +//go:noescape +func wasmimport_IncomingBodyStream(self0 uint32, result *cm.Result[InputStream, InputStream, struct{}]) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]future-trailers +//go:noescape +func wasmimport_FutureTrailersResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]future-trailers.get +//go:noescape +func wasmimport_FutureTrailersGet(self0 uint32, result *cm.Option[cm.Result[cm.Result[ErrorCodeShape, cm.Option[Trailers], ErrorCode], cm.Result[ErrorCodeShape, cm.Option[Trailers], ErrorCode], struct{}]]) + +//go:wasmimport wasi:http/types@0.2.0 [method]future-trailers.subscribe +//go:noescape +func wasmimport_FutureTrailersSubscribe(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]outgoing-response +//go:noescape +func wasmimport_OutgoingResponseResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [constructor]outgoing-response +//go:noescape +func wasmimport_NewOutgoingResponse(headers0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.body +//go:noescape +func wasmimport_OutgoingResponseBody(self0 uint32, result *cm.Result[OutgoingBody, OutgoingBody, struct{}]) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.headers +//go:noescape +func wasmimport_OutgoingResponseHeaders(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.set-status-code +//go:noescape +func wasmimport_OutgoingResponseSetStatusCode(self0 uint32, statusCode0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.status-code +//go:noescape +func wasmimport_OutgoingResponseStatusCode(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]outgoing-body +//go:noescape +func wasmimport_OutgoingBodyResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [static]outgoing-body.finish +//go:noescape +func wasmimport_OutgoingBodyFinish(this0 uint32, trailers0 uint32, trailers1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-body.write +//go:noescape +func wasmimport_OutgoingBodyWrite(self0 uint32, result *cm.Result[OutputStream, OutputStream, struct{}]) + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]future-incoming-response +//go:noescape +func wasmimport_FutureIncomingResponseResourceDrop(self0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 [method]future-incoming-response.get +//go:noescape +func wasmimport_FutureIncomingResponseGet(self0 uint32, result *cm.Option[cm.Result[cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], struct{}]]) + +//go:wasmimport wasi:http/types@0.2.0 [method]future-incoming-response.subscribe +//go:noescape +func wasmimport_FutureIncomingResponseSubscribe(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:http/types@0.2.0 http-error-code +//go:noescape +func wasmimport_HTTPErrorCode(err0 uint32, result *cm.Option[ErrorCode]) diff --git a/x/wasihttp/internal/wasi/http/types/types.wit.go b/x/wasihttp/internal/wasi/http/types/types.wit.go new file mode 100755 index 00000000..4998f413 --- /dev/null +++ b/x/wasihttp/internal/wasi/http/types/types.wit.go @@ -0,0 +1,2020 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package types represents the imported interface "wasi:http/types@0.2.0". +// +// This interface defines all of the types and methods for implementing +// HTTP Requests and Responses, both incoming and outgoing, as well as +// their headers, trailers, and bodies. +package types + +import ( + "go.bytecodealliance.org/cm" + monotonicclock "go.bytecodealliance.org/x/wasihttp/internal/wasi/clocks/monotonic-clock" + ioerror "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/error" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" +) + +// Duration represents the type alias "wasi:http/types@0.2.0#duration". +// +// See [monotonicclock.Duration] for more information. +type Duration = monotonicclock.Duration + +// InputStream represents the imported type alias "wasi:http/types@0.2.0#input-stream". +// +// See [streams.InputStream] for more information. +type InputStream = streams.InputStream + +// OutputStream represents the imported type alias "wasi:http/types@0.2.0#output-stream". +// +// See [streams.OutputStream] for more information. +type OutputStream = streams.OutputStream + +// IOError represents the imported type alias "wasi:http/types@0.2.0#io-error". +// +// See [ioerror.Error] for more information. +type IOError = ioerror.Error + +// Pollable represents the imported type alias "wasi:http/types@0.2.0#pollable". +// +// See [poll.Pollable] for more information. +type Pollable = poll.Pollable + +// Method represents the variant "wasi:http/types@0.2.0#method". +// +// This type corresponds to HTTP standard Methods. +// +// variant method { +// get, +// head, +// post, +// put, +// delete, +// connect, +// options, +// trace, +// patch, +// other(string), +// } +type Method cm.Variant[uint8, string, string] + +// MethodGet returns a [Method] of case "get". +func MethodGet() Method { + var data struct{} + return cm.New[Method](0, data) +} + +// Get returns true if [Method] represents the variant case "get". +func (self *Method) Get() bool { + return self.Tag() == 0 +} + +// MethodHead returns a [Method] of case "head". +func MethodHead() Method { + var data struct{} + return cm.New[Method](1, data) +} + +// Head returns true if [Method] represents the variant case "head". +func (self *Method) Head() bool { + return self.Tag() == 1 +} + +// MethodPost returns a [Method] of case "post". +func MethodPost() Method { + var data struct{} + return cm.New[Method](2, data) +} + +// Post returns true if [Method] represents the variant case "post". +func (self *Method) Post() bool { + return self.Tag() == 2 +} + +// MethodPut returns a [Method] of case "put". +func MethodPut() Method { + var data struct{} + return cm.New[Method](3, data) +} + +// Put returns true if [Method] represents the variant case "put". +func (self *Method) Put() bool { + return self.Tag() == 3 +} + +// MethodDelete returns a [Method] of case "delete". +func MethodDelete() Method { + var data struct{} + return cm.New[Method](4, data) +} + +// Delete returns true if [Method] represents the variant case "delete". +func (self *Method) Delete() bool { + return self.Tag() == 4 +} + +// MethodConnect returns a [Method] of case "connect". +func MethodConnect() Method { + var data struct{} + return cm.New[Method](5, data) +} + +// Connect returns true if [Method] represents the variant case "connect". +func (self *Method) Connect() bool { + return self.Tag() == 5 +} + +// MethodOptions returns a [Method] of case "options". +func MethodOptions() Method { + var data struct{} + return cm.New[Method](6, data) +} + +// Options returns true if [Method] represents the variant case "options". +func (self *Method) Options() bool { + return self.Tag() == 6 +} + +// MethodTrace returns a [Method] of case "trace". +func MethodTrace() Method { + var data struct{} + return cm.New[Method](7, data) +} + +// Trace returns true if [Method] represents the variant case "trace". +func (self *Method) Trace() bool { + return self.Tag() == 7 +} + +// MethodPatch returns a [Method] of case "patch". +func MethodPatch() Method { + var data struct{} + return cm.New[Method](8, data) +} + +// Patch returns true if [Method] represents the variant case "patch". +func (self *Method) Patch() bool { + return self.Tag() == 8 +} + +// MethodOther returns a [Method] of case "other". +func MethodOther(data string) Method { + return cm.New[Method](9, data) +} + +// Other returns a non-nil *[string] if [Method] represents the variant case "other". +func (self *Method) Other() *string { + return cm.Case[string](self, 9) +} + +var _MethodStrings = [10]string{ + "get", + "head", + "post", + "put", + "delete", + "connect", + "options", + "trace", + "patch", + "other", +} + +// String implements [fmt.Stringer], returning the variant case name of v. +func (v Method) String() string { + return _MethodStrings[v.Tag()] +} + +// Scheme represents the variant "wasi:http/types@0.2.0#scheme". +// +// This type corresponds to HTTP standard Related Schemes. +// +// variant scheme { +// HTTP, +// HTTPS, +// other(string), +// } +type Scheme cm.Variant[uint8, string, string] + +// SchemeHTTP returns a [Scheme] of case "HTTP". +func SchemeHTTP() Scheme { + var data struct{} + return cm.New[Scheme](0, data) +} + +// HTTP returns true if [Scheme] represents the variant case "HTTP". +func (self *Scheme) HTTP() bool { + return self.Tag() == 0 +} + +// SchemeHTTPS returns a [Scheme] of case "HTTPS". +func SchemeHTTPS() Scheme { + var data struct{} + return cm.New[Scheme](1, data) +} + +// HTTPS returns true if [Scheme] represents the variant case "HTTPS". +func (self *Scheme) HTTPS() bool { + return self.Tag() == 1 +} + +// SchemeOther returns a [Scheme] of case "other". +func SchemeOther(data string) Scheme { + return cm.New[Scheme](2, data) +} + +// Other returns a non-nil *[string] if [Scheme] represents the variant case "other". +func (self *Scheme) Other() *string { + return cm.Case[string](self, 2) +} + +var _SchemeStrings = [3]string{ + "HTTP", + "HTTPS", + "other", +} + +// String implements [fmt.Stringer], returning the variant case name of v. +func (v Scheme) String() string { + return _SchemeStrings[v.Tag()] +} + +// DNSErrorPayload represents the record "wasi:http/types@0.2.0#DNS-error-payload". +// +// Defines the case payload type for `DNS-error` above: +// +// record DNS-error-payload { +// rcode: option, +// info-code: option, +// } +type DNSErrorPayload struct { + _ cm.HostLayout `json:"-"` + Rcode cm.Option[string] `json:"rcode"` + InfoCode cm.Option[uint16] `json:"info-code"` +} + +// TLSAlertReceivedPayload represents the record "wasi:http/types@0.2.0#TLS-alert-received-payload". +// +// Defines the case payload type for `TLS-alert-received` above: +// +// record TLS-alert-received-payload { +// alert-id: option, +// alert-message: option, +// } +type TLSAlertReceivedPayload struct { + _ cm.HostLayout `json:"-"` + AlertID cm.Option[uint8] `json:"alert-id"` + AlertMessage cm.Option[string] `json:"alert-message"` +} + +// FieldSizePayload represents the record "wasi:http/types@0.2.0#field-size-payload". +// +// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: +// +// record field-size-payload { +// field-name: option, +// field-size: option, +// } +type FieldSizePayload struct { + _ cm.HostLayout `json:"-"` + FieldName cm.Option[string] `json:"field-name"` + FieldSize cm.Option[uint32] `json:"field-size"` +} + +// ErrorCode represents the variant "wasi:http/types@0.2.0#error-code". +// +// These cases are inspired by the IANA HTTP Proxy Error Types: +// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types +// +// variant error-code { +// DNS-timeout, +// DNS-error(DNS-error-payload), +// destination-not-found, +// destination-unavailable, +// destination-IP-prohibited, +// destination-IP-unroutable, +// connection-refused, +// connection-terminated, +// connection-timeout, +// connection-read-timeout, +// connection-write-timeout, +// connection-limit-reached, +// TLS-protocol-error, +// TLS-certificate-error, +// TLS-alert-received(TLS-alert-received-payload), +// HTTP-request-denied, +// HTTP-request-length-required, +// HTTP-request-body-size(option), +// HTTP-request-method-invalid, +// HTTP-request-URI-invalid, +// HTTP-request-URI-too-long, +// HTTP-request-header-section-size(option), +// HTTP-request-header-size(option), +// HTTP-request-trailer-section-size(option), +// HTTP-request-trailer-size(field-size-payload), +// HTTP-response-incomplete, +// HTTP-response-header-section-size(option), +// HTTP-response-header-size(field-size-payload), +// HTTP-response-body-size(option), +// HTTP-response-trailer-section-size(option), +// HTTP-response-trailer-size(field-size-payload), +// HTTP-response-transfer-coding(option), +// HTTP-response-content-coding(option), +// HTTP-response-timeout, +// HTTP-upgrade-failed, +// HTTP-protocol-error, +// loop-detected, +// configuration-error, +// internal-error(option), +// } +type ErrorCode cm.Variant[uint8, OptionFieldSizePayloadShape, cm.Option[uint64]] + +// ErrorCodeDNSTimeout returns a [ErrorCode] of case "DNS-timeout". +func ErrorCodeDNSTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](0, data) +} + +// DNSTimeout returns true if [ErrorCode] represents the variant case "DNS-timeout". +func (self *ErrorCode) DNSTimeout() bool { + return self.Tag() == 0 +} + +// ErrorCodeDNSError returns a [ErrorCode] of case "DNS-error". +func ErrorCodeDNSError(data DNSErrorPayload) ErrorCode { + return cm.New[ErrorCode](1, data) +} + +// DNSError returns a non-nil *[DNSErrorPayload] if [ErrorCode] represents the variant case "DNS-error". +func (self *ErrorCode) DNSError() *DNSErrorPayload { + return cm.Case[DNSErrorPayload](self, 1) +} + +// ErrorCodeDestinationNotFound returns a [ErrorCode] of case "destination-not-found". +func ErrorCodeDestinationNotFound() ErrorCode { + var data struct{} + return cm.New[ErrorCode](2, data) +} + +// DestinationNotFound returns true if [ErrorCode] represents the variant case "destination-not-found". +func (self *ErrorCode) DestinationNotFound() bool { + return self.Tag() == 2 +} + +// ErrorCodeDestinationUnavailable returns a [ErrorCode] of case "destination-unavailable". +func ErrorCodeDestinationUnavailable() ErrorCode { + var data struct{} + return cm.New[ErrorCode](3, data) +} + +// DestinationUnavailable returns true if [ErrorCode] represents the variant case "destination-unavailable". +func (self *ErrorCode) DestinationUnavailable() bool { + return self.Tag() == 3 +} + +// ErrorCodeDestinationIPProhibited returns a [ErrorCode] of case "destination-IP-prohibited". +func ErrorCodeDestinationIPProhibited() ErrorCode { + var data struct{} + return cm.New[ErrorCode](4, data) +} + +// DestinationIPProhibited returns true if [ErrorCode] represents the variant case "destination-IP-prohibited". +func (self *ErrorCode) DestinationIPProhibited() bool { + return self.Tag() == 4 +} + +// ErrorCodeDestinationIPUnroutable returns a [ErrorCode] of case "destination-IP-unroutable". +func ErrorCodeDestinationIPUnroutable() ErrorCode { + var data struct{} + return cm.New[ErrorCode](5, data) +} + +// DestinationIPUnroutable returns true if [ErrorCode] represents the variant case "destination-IP-unroutable". +func (self *ErrorCode) DestinationIPUnroutable() bool { + return self.Tag() == 5 +} + +// ErrorCodeConnectionRefused returns a [ErrorCode] of case "connection-refused". +func ErrorCodeConnectionRefused() ErrorCode { + var data struct{} + return cm.New[ErrorCode](6, data) +} + +// ConnectionRefused returns true if [ErrorCode] represents the variant case "connection-refused". +func (self *ErrorCode) ConnectionRefused() bool { + return self.Tag() == 6 +} + +// ErrorCodeConnectionTerminated returns a [ErrorCode] of case "connection-terminated". +func ErrorCodeConnectionTerminated() ErrorCode { + var data struct{} + return cm.New[ErrorCode](7, data) +} + +// ConnectionTerminated returns true if [ErrorCode] represents the variant case "connection-terminated". +func (self *ErrorCode) ConnectionTerminated() bool { + return self.Tag() == 7 +} + +// ErrorCodeConnectionTimeout returns a [ErrorCode] of case "connection-timeout". +func ErrorCodeConnectionTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](8, data) +} + +// ConnectionTimeout returns true if [ErrorCode] represents the variant case "connection-timeout". +func (self *ErrorCode) ConnectionTimeout() bool { + return self.Tag() == 8 +} + +// ErrorCodeConnectionReadTimeout returns a [ErrorCode] of case "connection-read-timeout". +func ErrorCodeConnectionReadTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](9, data) +} + +// ConnectionReadTimeout returns true if [ErrorCode] represents the variant case "connection-read-timeout". +func (self *ErrorCode) ConnectionReadTimeout() bool { + return self.Tag() == 9 +} + +// ErrorCodeConnectionWriteTimeout returns a [ErrorCode] of case "connection-write-timeout". +func ErrorCodeConnectionWriteTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](10, data) +} + +// ConnectionWriteTimeout returns true if [ErrorCode] represents the variant case "connection-write-timeout". +func (self *ErrorCode) ConnectionWriteTimeout() bool { + return self.Tag() == 10 +} + +// ErrorCodeConnectionLimitReached returns a [ErrorCode] of case "connection-limit-reached". +func ErrorCodeConnectionLimitReached() ErrorCode { + var data struct{} + return cm.New[ErrorCode](11, data) +} + +// ConnectionLimitReached returns true if [ErrorCode] represents the variant case "connection-limit-reached". +func (self *ErrorCode) ConnectionLimitReached() bool { + return self.Tag() == 11 +} + +// ErrorCodeTLSProtocolError returns a [ErrorCode] of case "TLS-protocol-error". +func ErrorCodeTLSProtocolError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](12, data) +} + +// TLSProtocolError returns true if [ErrorCode] represents the variant case "TLS-protocol-error". +func (self *ErrorCode) TLSProtocolError() bool { + return self.Tag() == 12 +} + +// ErrorCodeTLSCertificateError returns a [ErrorCode] of case "TLS-certificate-error". +func ErrorCodeTLSCertificateError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](13, data) +} + +// TLSCertificateError returns true if [ErrorCode] represents the variant case "TLS-certificate-error". +func (self *ErrorCode) TLSCertificateError() bool { + return self.Tag() == 13 +} + +// ErrorCodeTLSAlertReceived returns a [ErrorCode] of case "TLS-alert-received". +func ErrorCodeTLSAlertReceived(data TLSAlertReceivedPayload) ErrorCode { + return cm.New[ErrorCode](14, data) +} + +// TLSAlertReceived returns a non-nil *[TLSAlertReceivedPayload] if [ErrorCode] represents the variant case "TLS-alert-received". +func (self *ErrorCode) TLSAlertReceived() *TLSAlertReceivedPayload { + return cm.Case[TLSAlertReceivedPayload](self, 14) +} + +// ErrorCodeHTTPRequestDenied returns a [ErrorCode] of case "HTTP-request-denied". +func ErrorCodeHTTPRequestDenied() ErrorCode { + var data struct{} + return cm.New[ErrorCode](15, data) +} + +// HTTPRequestDenied returns true if [ErrorCode] represents the variant case "HTTP-request-denied". +func (self *ErrorCode) HTTPRequestDenied() bool { + return self.Tag() == 15 +} + +// ErrorCodeHTTPRequestLengthRequired returns a [ErrorCode] of case "HTTP-request-length-required". +func ErrorCodeHTTPRequestLengthRequired() ErrorCode { + var data struct{} + return cm.New[ErrorCode](16, data) +} + +// HTTPRequestLengthRequired returns true if [ErrorCode] represents the variant case "HTTP-request-length-required". +func (self *ErrorCode) HTTPRequestLengthRequired() bool { + return self.Tag() == 16 +} + +// ErrorCodeHTTPRequestBodySize returns a [ErrorCode] of case "HTTP-request-body-size". +func ErrorCodeHTTPRequestBodySize(data cm.Option[uint64]) ErrorCode { + return cm.New[ErrorCode](17, data) +} + +// HTTPRequestBodySize returns a non-nil *[cm.Option[uint64]] if [ErrorCode] represents the variant case "HTTP-request-body-size". +func (self *ErrorCode) HTTPRequestBodySize() *cm.Option[uint64] { + return cm.Case[cm.Option[uint64]](self, 17) +} + +// ErrorCodeHTTPRequestMethodInvalid returns a [ErrorCode] of case "HTTP-request-method-invalid". +func ErrorCodeHTTPRequestMethodInvalid() ErrorCode { + var data struct{} + return cm.New[ErrorCode](18, data) +} + +// HTTPRequestMethodInvalid returns true if [ErrorCode] represents the variant case "HTTP-request-method-invalid". +func (self *ErrorCode) HTTPRequestMethodInvalid() bool { + return self.Tag() == 18 +} + +// ErrorCodeHTTPRequestURIInvalid returns a [ErrorCode] of case "HTTP-request-URI-invalid". +func ErrorCodeHTTPRequestURIInvalid() ErrorCode { + var data struct{} + return cm.New[ErrorCode](19, data) +} + +// HTTPRequestURIInvalid returns true if [ErrorCode] represents the variant case "HTTP-request-URI-invalid". +func (self *ErrorCode) HTTPRequestURIInvalid() bool { + return self.Tag() == 19 +} + +// ErrorCodeHTTPRequestURITooLong returns a [ErrorCode] of case "HTTP-request-URI-too-long". +func ErrorCodeHTTPRequestURITooLong() ErrorCode { + var data struct{} + return cm.New[ErrorCode](20, data) +} + +// HTTPRequestURITooLong returns true if [ErrorCode] represents the variant case "HTTP-request-URI-too-long". +func (self *ErrorCode) HTTPRequestURITooLong() bool { + return self.Tag() == 20 +} + +// ErrorCodeHTTPRequestHeaderSectionSize returns a [ErrorCode] of case "HTTP-request-header-section-size". +func ErrorCodeHTTPRequestHeaderSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](21, data) +} + +// HTTPRequestHeaderSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-request-header-section-size". +func (self *ErrorCode) HTTPRequestHeaderSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 21) +} + +// ErrorCodeHTTPRequestHeaderSize returns a [ErrorCode] of case "HTTP-request-header-size". +func ErrorCodeHTTPRequestHeaderSize(data cm.Option[FieldSizePayload]) ErrorCode { + return cm.New[ErrorCode](22, data) +} + +// HTTPRequestHeaderSize returns a non-nil *[cm.Option[FieldSizePayload]] if [ErrorCode] represents the variant case "HTTP-request-header-size". +func (self *ErrorCode) HTTPRequestHeaderSize() *cm.Option[FieldSizePayload] { + return cm.Case[cm.Option[FieldSizePayload]](self, 22) +} + +// ErrorCodeHTTPRequestTrailerSectionSize returns a [ErrorCode] of case "HTTP-request-trailer-section-size". +func ErrorCodeHTTPRequestTrailerSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](23, data) +} + +// HTTPRequestTrailerSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-request-trailer-section-size". +func (self *ErrorCode) HTTPRequestTrailerSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 23) +} + +// ErrorCodeHTTPRequestTrailerSize returns a [ErrorCode] of case "HTTP-request-trailer-size". +func ErrorCodeHTTPRequestTrailerSize(data FieldSizePayload) ErrorCode { + return cm.New[ErrorCode](24, data) +} + +// HTTPRequestTrailerSize returns a non-nil *[FieldSizePayload] if [ErrorCode] represents the variant case "HTTP-request-trailer-size". +func (self *ErrorCode) HTTPRequestTrailerSize() *FieldSizePayload { + return cm.Case[FieldSizePayload](self, 24) +} + +// ErrorCodeHTTPResponseIncomplete returns a [ErrorCode] of case "HTTP-response-incomplete". +func ErrorCodeHTTPResponseIncomplete() ErrorCode { + var data struct{} + return cm.New[ErrorCode](25, data) +} + +// HTTPResponseIncomplete returns true if [ErrorCode] represents the variant case "HTTP-response-incomplete". +func (self *ErrorCode) HTTPResponseIncomplete() bool { + return self.Tag() == 25 +} + +// ErrorCodeHTTPResponseHeaderSectionSize returns a [ErrorCode] of case "HTTP-response-header-section-size". +func ErrorCodeHTTPResponseHeaderSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](26, data) +} + +// HTTPResponseHeaderSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-response-header-section-size". +func (self *ErrorCode) HTTPResponseHeaderSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 26) +} + +// ErrorCodeHTTPResponseHeaderSize returns a [ErrorCode] of case "HTTP-response-header-size". +func ErrorCodeHTTPResponseHeaderSize(data FieldSizePayload) ErrorCode { + return cm.New[ErrorCode](27, data) +} + +// HTTPResponseHeaderSize returns a non-nil *[FieldSizePayload] if [ErrorCode] represents the variant case "HTTP-response-header-size". +func (self *ErrorCode) HTTPResponseHeaderSize() *FieldSizePayload { + return cm.Case[FieldSizePayload](self, 27) +} + +// ErrorCodeHTTPResponseBodySize returns a [ErrorCode] of case "HTTP-response-body-size". +func ErrorCodeHTTPResponseBodySize(data cm.Option[uint64]) ErrorCode { + return cm.New[ErrorCode](28, data) +} + +// HTTPResponseBodySize returns a non-nil *[cm.Option[uint64]] if [ErrorCode] represents the variant case "HTTP-response-body-size". +func (self *ErrorCode) HTTPResponseBodySize() *cm.Option[uint64] { + return cm.Case[cm.Option[uint64]](self, 28) +} + +// ErrorCodeHTTPResponseTrailerSectionSize returns a [ErrorCode] of case "HTTP-response-trailer-section-size". +func ErrorCodeHTTPResponseTrailerSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](29, data) +} + +// HTTPResponseTrailerSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-response-trailer-section-size". +func (self *ErrorCode) HTTPResponseTrailerSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 29) +} + +// ErrorCodeHTTPResponseTrailerSize returns a [ErrorCode] of case "HTTP-response-trailer-size". +func ErrorCodeHTTPResponseTrailerSize(data FieldSizePayload) ErrorCode { + return cm.New[ErrorCode](30, data) +} + +// HTTPResponseTrailerSize returns a non-nil *[FieldSizePayload] if [ErrorCode] represents the variant case "HTTP-response-trailer-size". +func (self *ErrorCode) HTTPResponseTrailerSize() *FieldSizePayload { + return cm.Case[FieldSizePayload](self, 30) +} + +// ErrorCodeHTTPResponseTransferCoding returns a [ErrorCode] of case "HTTP-response-transfer-coding". +func ErrorCodeHTTPResponseTransferCoding(data cm.Option[string]) ErrorCode { + return cm.New[ErrorCode](31, data) +} + +// HTTPResponseTransferCoding returns a non-nil *[cm.Option[string]] if [ErrorCode] represents the variant case "HTTP-response-transfer-coding". +func (self *ErrorCode) HTTPResponseTransferCoding() *cm.Option[string] { + return cm.Case[cm.Option[string]](self, 31) +} + +// ErrorCodeHTTPResponseContentCoding returns a [ErrorCode] of case "HTTP-response-content-coding". +func ErrorCodeHTTPResponseContentCoding(data cm.Option[string]) ErrorCode { + return cm.New[ErrorCode](32, data) +} + +// HTTPResponseContentCoding returns a non-nil *[cm.Option[string]] if [ErrorCode] represents the variant case "HTTP-response-content-coding". +func (self *ErrorCode) HTTPResponseContentCoding() *cm.Option[string] { + return cm.Case[cm.Option[string]](self, 32) +} + +// ErrorCodeHTTPResponseTimeout returns a [ErrorCode] of case "HTTP-response-timeout". +func ErrorCodeHTTPResponseTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](33, data) +} + +// HTTPResponseTimeout returns true if [ErrorCode] represents the variant case "HTTP-response-timeout". +func (self *ErrorCode) HTTPResponseTimeout() bool { + return self.Tag() == 33 +} + +// ErrorCodeHTTPUpgradeFailed returns a [ErrorCode] of case "HTTP-upgrade-failed". +func ErrorCodeHTTPUpgradeFailed() ErrorCode { + var data struct{} + return cm.New[ErrorCode](34, data) +} + +// HTTPUpgradeFailed returns true if [ErrorCode] represents the variant case "HTTP-upgrade-failed". +func (self *ErrorCode) HTTPUpgradeFailed() bool { + return self.Tag() == 34 +} + +// ErrorCodeHTTPProtocolError returns a [ErrorCode] of case "HTTP-protocol-error". +func ErrorCodeHTTPProtocolError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](35, data) +} + +// HTTPProtocolError returns true if [ErrorCode] represents the variant case "HTTP-protocol-error". +func (self *ErrorCode) HTTPProtocolError() bool { + return self.Tag() == 35 +} + +// ErrorCodeLoopDetected returns a [ErrorCode] of case "loop-detected". +func ErrorCodeLoopDetected() ErrorCode { + var data struct{} + return cm.New[ErrorCode](36, data) +} + +// LoopDetected returns true if [ErrorCode] represents the variant case "loop-detected". +func (self *ErrorCode) LoopDetected() bool { + return self.Tag() == 36 +} + +// ErrorCodeConfigurationError returns a [ErrorCode] of case "configuration-error". +func ErrorCodeConfigurationError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](37, data) +} + +// ConfigurationError returns true if [ErrorCode] represents the variant case "configuration-error". +func (self *ErrorCode) ConfigurationError() bool { + return self.Tag() == 37 +} + +// ErrorCodeInternalError returns a [ErrorCode] of case "internal-error". +// +// This is a catch-all error for anything that doesn't fit cleanly into a +// more specific case. It also includes an optional string for an +// unstructured description of the error. Users should not depend on the +// string for diagnosing errors, as it's not required to be consistent +// between implementations. +func ErrorCodeInternalError(data cm.Option[string]) ErrorCode { + return cm.New[ErrorCode](38, data) +} + +// InternalError returns a non-nil *[cm.Option[string]] if [ErrorCode] represents the variant case "internal-error". +func (self *ErrorCode) InternalError() *cm.Option[string] { + return cm.Case[cm.Option[string]](self, 38) +} + +var _ErrorCodeStrings = [39]string{ + "DNS-timeout", + "DNS-error", + "destination-not-found", + "destination-unavailable", + "destination-IP-prohibited", + "destination-IP-unroutable", + "connection-refused", + "connection-terminated", + "connection-timeout", + "connection-read-timeout", + "connection-write-timeout", + "connection-limit-reached", + "TLS-protocol-error", + "TLS-certificate-error", + "TLS-alert-received", + "HTTP-request-denied", + "HTTP-request-length-required", + "HTTP-request-body-size", + "HTTP-request-method-invalid", + "HTTP-request-URI-invalid", + "HTTP-request-URI-too-long", + "HTTP-request-header-section-size", + "HTTP-request-header-size", + "HTTP-request-trailer-section-size", + "HTTP-request-trailer-size", + "HTTP-response-incomplete", + "HTTP-response-header-section-size", + "HTTP-response-header-size", + "HTTP-response-body-size", + "HTTP-response-trailer-section-size", + "HTTP-response-trailer-size", + "HTTP-response-transfer-coding", + "HTTP-response-content-coding", + "HTTP-response-timeout", + "HTTP-upgrade-failed", + "HTTP-protocol-error", + "loop-detected", + "configuration-error", + "internal-error", +} + +// String implements [fmt.Stringer], returning the variant case name of v. +func (v ErrorCode) String() string { + return _ErrorCodeStrings[v.Tag()] +} + +// HeaderError represents the variant "wasi:http/types@0.2.0#header-error". +// +// This type enumerates the different kinds of errors that may occur when +// setting or appending to a `fields` resource. +// +// variant header-error { +// invalid-syntax, +// forbidden, +// immutable, +// } +type HeaderError uint8 + +const ( + // This error indicates that a `field-key` or `field-value` was + // syntactically invalid when used with an operation that sets headers in a + // `fields`. + HeaderErrorInvalidSyntax HeaderError = iota + + // This error indicates that a forbidden `field-key` was used when trying + // to set a header in a `fields`. + HeaderErrorForbidden + + // This error indicates that the operation on the `fields` was not + // permitted because the fields are immutable. + HeaderErrorImmutable +) + +var _HeaderErrorStrings = [3]string{ + "invalid-syntax", + "forbidden", + "immutable", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e HeaderError) String() string { + return _HeaderErrorStrings[e] +} + +// MarshalText implements [encoding.TextMarshaler]. +func (e HeaderError) MarshalText() ([]byte, error) { + return []byte(e.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum +// case. Returns an error if the supplied text is not one of the enum cases. +func (e *HeaderError) UnmarshalText(text []byte) error { + return _HeaderErrorUnmarshalCase(e, text) +} + +var _HeaderErrorUnmarshalCase = cm.CaseUnmarshaler[HeaderError](_HeaderErrorStrings[:]) + +// FieldKey represents the string "wasi:http/types@0.2.0#field-key". +// +// Field keys are always strings. +// +// type field-key = string +type FieldKey string + +// FieldValue represents the list "wasi:http/types@0.2.0#field-value". +// +// Field values should always be ASCII strings. However, in +// reality, HTTP implementations often have to interpret malformed values, +// so they are provided as a list of bytes. +// +// type field-value = list +type FieldValue cm.List[uint8] + +// Fields represents the imported resource "wasi:http/types@0.2.0#fields". +// +// This following block defines the `fields` resource which corresponds to +// HTTP standard Fields. Fields are a common representation used for both +// Headers and Trailers. +// +// A `fields` may be mutable or immutable. A `fields` created using the +// constructor, `from-list`, or `clone` will be mutable, but a `fields` +// resource given by other means (including, but not limited to, +// `incoming-request.headers`, `outgoing-request.headers`) might be be +// immutable. In an immutable fields, the `set`, `append`, and `delete` +// operations will fail with `header-error.immutable`. +// +// resource fields +type Fields cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "fields". +// +// Drops a resource handle. +// +//go:nosplit +func (self Fields) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FieldsResourceDrop((uint32)(self0)) + return +} + +// NewFields represents the imported constructor for resource "fields". +// +// Construct an empty HTTP Fields. +// +// The resulting `fields` is mutable. +// +// constructor() +// +//go:nosplit +func NewFields() (result Fields) { + result0 := wasmimport_NewFields() + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +// FieldsFromList represents the imported static function "from-list". +// +// Construct an HTTP Fields. +// +// The resulting `fields` is mutable. +// +// The list represents each key-value pair in the Fields. Keys +// which have multiple values are represented by multiple entries in this +// list with the same key. +// +// The tuple is a pair of the field key, represented as a string, and +// Value, represented as a list of bytes. In a valid Fields, all keys +// and values are valid UTF-8 strings. However, values are not always +// well-formed, so they are represented as a raw list of bytes. +// +// An error result will be returned if any header or value was +// syntactically invalid, or if a header was forbidden. +// +// from-list: static func(entries: list>) -> result +// +//go:nosplit +func FieldsFromList(entries cm.List[cm.Tuple[FieldKey, FieldValue]]) (result cm.Result[Fields, Fields, HeaderError]) { + entries0, entries1 := cm.LowerList(entries) + wasmimport_FieldsFromList((*cm.Tuple[FieldKey, FieldValue])(entries0), (uint32)(entries1), &result) + return +} + +// Append represents the imported method "append". +// +// Append a value for a key. Does not change or delete any existing +// values for that key. +// +// Fails with `header-error.immutable` if the `fields` are immutable. +// +// append: func(name: field-key, value: field-value) -> result<_, header-error> +// +//go:nosplit +func (self Fields) Append(name FieldKey, value FieldValue) (result cm.Result[HeaderError, struct{}, HeaderError]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + value0, value1 := cm.LowerList(value) + wasmimport_FieldsAppend((uint32)(self0), (*uint8)(name0), (uint32)(name1), (*uint8)(value0), (uint32)(value1), &result) + return +} + +// Clone represents the imported method "clone". +// +// Make a deep copy of the Fields. Equivelant in behavior to calling the +// `fields` constructor on the return value of `entries`. The resulting +// `fields` is mutable. +// +// clone: func() -> fields +// +//go:nosplit +func (self Fields) Clone() (result Fields) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_FieldsClone((uint32)(self0)) + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +// Delete represents the imported method "delete". +// +// Delete all values for a key. Does nothing if no values for the key +// exist. +// +// Fails with `header-error.immutable` if the `fields` are immutable. +// +// delete: func(name: field-key) -> result<_, header-error> +// +//go:nosplit +func (self Fields) Delete(name FieldKey) (result cm.Result[HeaderError, struct{}, HeaderError]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + wasmimport_FieldsDelete((uint32)(self0), (*uint8)(name0), (uint32)(name1), &result) + return +} + +// Entries represents the imported method "entries". +// +// Retrieve the full set of keys and values in the Fields. Like the +// constructor, the list represents each key-value pair. +// +// The outer list represents each key-value pair in the Fields. Keys +// which have multiple values are represented by multiple entries in this +// list with the same key. +// +// entries: func() -> list> +// +//go:nosplit +func (self Fields) Entries() (result cm.List[cm.Tuple[FieldKey, FieldValue]]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FieldsEntries((uint32)(self0), &result) + return +} + +// Get represents the imported method "get". +// +// Get all of the values corresponding to a key. If the key is not present +// in this `fields`, an empty list is returned. However, if the key is +// present but empty, this is represented by a list with one or more +// empty field-values present. +// +// get: func(name: field-key) -> list +// +//go:nosplit +func (self Fields) Get(name FieldKey) (result cm.List[FieldValue]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + wasmimport_FieldsGet((uint32)(self0), (*uint8)(name0), (uint32)(name1), &result) + return +} + +// Has represents the imported method "has". +// +// Returns `true` when the key is present in this `fields`. If the key is +// syntactically invalid, `false` is returned. +// +// has: func(name: field-key) -> bool +// +//go:nosplit +func (self Fields) Has(name FieldKey) (result bool) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + result0 := wasmimport_FieldsHas((uint32)(self0), (*uint8)(name0), (uint32)(name1)) + result = (bool)(cm.U32ToBool((uint32)(result0))) + return +} + +// Set represents the imported method "set". +// +// Set all of the values for a key. Clears any existing values for that +// key, if they have been set. +// +// Fails with `header-error.immutable` if the `fields` are immutable. +// +// set: func(name: field-key, value: list) -> result<_, header-error> +// +//go:nosplit +func (self Fields) Set(name FieldKey, value cm.List[FieldValue]) (result cm.Result[HeaderError, struct{}, HeaderError]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + value0, value1 := cm.LowerList(value) + wasmimport_FieldsSet((uint32)(self0), (*uint8)(name0), (uint32)(name1), (*FieldValue)(value0), (uint32)(value1), &result) + return +} + +// Headers represents the imported type alias "wasi:http/types@0.2.0#headers". +// +// See [Fields] for more information. +type Headers = Fields + +// Trailers represents the imported type alias "wasi:http/types@0.2.0#trailers". +// +// See [Fields] for more information. +type Trailers = Fields + +// IncomingRequest represents the imported resource "wasi:http/types@0.2.0#incoming-request". +// +// Represents an incoming HTTP Request. +// +// resource incoming-request +type IncomingRequest cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-request". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingRequest) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestResourceDrop((uint32)(self0)) + return +} + +// Authority represents the imported method "authority". +// +// Returns the authority from the request, if it was present. +// +// authority: func() -> option +// +//go:nosplit +func (self IncomingRequest) Authority() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestAuthority((uint32)(self0), &result) + return +} + +// Consume represents the imported method "consume". +// +// Gives the `incoming-body` associated with this request. Will only +// return success at most once, and subsequent calls will return error. +// +// consume: func() -> result +// +//go:nosplit +func (self IncomingRequest) Consume() (result cm.Result[IncomingBody, IncomingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestConsume((uint32)(self0), &result) + return +} + +// Headers represents the imported method "headers". +// +// Get the `headers` associated with the request. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// The `headers` returned are a child resource: it must be dropped before +// the parent `incoming-request` is dropped. Dropping this +// `incoming-request` before all children are dropped will trap. +// +// headers: func() -> headers +// +//go:nosplit +func (self IncomingRequest) Headers() (result Headers) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingRequestHeaders((uint32)(self0)) + result = cm.Reinterpret[Headers]((uint32)(result0)) + return +} + +// Method represents the imported method "method". +// +// Returns the method of the incoming request. +// +// method: func() -> method +// +//go:nosplit +func (self IncomingRequest) Method() (result Method) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestMethod((uint32)(self0), &result) + return +} + +// PathWithQuery represents the imported method "path-with-query". +// +// Returns the path with query parameters from the request, as a string. +// +// path-with-query: func() -> option +// +//go:nosplit +func (self IncomingRequest) PathWithQuery() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestPathWithQuery((uint32)(self0), &result) + return +} + +// Scheme represents the imported method "scheme". +// +// Returns the protocol scheme from the request. +// +// scheme: func() -> option +// +//go:nosplit +func (self IncomingRequest) Scheme() (result cm.Option[Scheme]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestScheme((uint32)(self0), &result) + return +} + +// OutgoingRequest represents the imported resource "wasi:http/types@0.2.0#outgoing-request". +// +// Represents an outgoing HTTP Request. +// +// resource outgoing-request +type OutgoingRequest cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-request". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingRequest) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestResourceDrop((uint32)(self0)) + return +} + +// NewOutgoingRequest represents the imported constructor for resource "outgoing-request". +// +// Construct a new `outgoing-request` with a default `method` of `GET`, and +// `none` values for `path-with-query`, `scheme`, and `authority`. +// +// * `headers` is the HTTP Headers for the Request. +// +// It is possible to construct, or manipulate with the accessor functions +// below, an `outgoing-request` with an invalid combination of `scheme` +// and `authority`, or `headers` which are not permitted to be sent. +// It is the obligation of the `outgoing-handler.handle` implementation +// to reject invalid constructions of `outgoing-request`. +// +// constructor(headers: headers) +// +//go:nosplit +func NewOutgoingRequest(headers Headers) (result OutgoingRequest) { + headers0 := cm.Reinterpret[uint32](headers) + result0 := wasmimport_NewOutgoingRequest((uint32)(headers0)) + result = cm.Reinterpret[OutgoingRequest]((uint32)(result0)) + return +} + +// Authority represents the imported method "authority". +// +// Get the HTTP Authority for the Request. A value of `none` may be used +// with Related Schemes which do not require an Authority. The HTTP and +// HTTPS schemes always require an authority. +// +// authority: func() -> option +// +//go:nosplit +func (self OutgoingRequest) Authority() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestAuthority((uint32)(self0), &result) + return +} + +// Body represents the imported method "body". +// +// Returns the resource corresponding to the outgoing Body for this +// Request. +// +// Returns success on the first call: the `outgoing-body` resource for +// this `outgoing-request` can be retrieved at most once. Subsequent +// calls will return error. +// +// body: func() -> result +// +//go:nosplit +func (self OutgoingRequest) Body() (result cm.Result[OutgoingBody, OutgoingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestBody((uint32)(self0), &result) + return +} + +// Headers represents the imported method "headers". +// +// Get the headers associated with the Request. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// This headers resource is a child: it must be dropped before the parent +// `outgoing-request` is dropped, or its ownership is transfered to +// another component by e.g. `outgoing-handler.handle`. +// +// headers: func() -> headers +// +//go:nosplit +func (self OutgoingRequest) Headers() (result Headers) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingRequestHeaders((uint32)(self0)) + result = cm.Reinterpret[Headers]((uint32)(result0)) + return +} + +// Method represents the imported method "method". +// +// Get the Method for the Request. +// +// method: func() -> method +// +//go:nosplit +func (self OutgoingRequest) Method() (result Method) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestMethod((uint32)(self0), &result) + return +} + +// PathWithQuery represents the imported method "path-with-query". +// +// Get the combination of the HTTP Path and Query for the Request. +// When `none`, this represents an empty Path and empty Query. +// +// path-with-query: func() -> option +// +//go:nosplit +func (self OutgoingRequest) PathWithQuery() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestPathWithQuery((uint32)(self0), &result) + return +} + +// Scheme represents the imported method "scheme". +// +// Get the HTTP Related Scheme for the Request. When `none`, the +// implementation may choose an appropriate default scheme. +// +// scheme: func() -> option +// +//go:nosplit +func (self OutgoingRequest) Scheme() (result cm.Option[Scheme]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestScheme((uint32)(self0), &result) + return +} + +// SetAuthority represents the imported method "set-authority". +// +// Set the HTTP Authority for the Request. A value of `none` may be used +// with Related Schemes which do not require an Authority. The HTTP and +// HTTPS schemes always require an authority. Fails if the string given is +// not a syntactically valid uri authority. +// +// set-authority: func(authority: option) -> result +// +//go:nosplit +func (self OutgoingRequest) SetAuthority(authority cm.Option[string]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + authority0, authority1, authority2 := lower_OptionString(authority) + result0 := wasmimport_OutgoingRequestSetAuthority((uint32)(self0), (uint32)(authority0), (*uint8)(authority1), (uint32)(authority2)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// SetMethod represents the imported method "set-method". +// +// Set the Method for the Request. Fails if the string present in a +// `method.other` argument is not a syntactically valid method. +// +// set-method: func(method: method) -> result +// +//go:nosplit +func (self OutgoingRequest) SetMethod(method Method) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + method0, method1, method2 := lower_Method(method) + result0 := wasmimport_OutgoingRequestSetMethod((uint32)(self0), (uint32)(method0), (*uint8)(method1), (uint32)(method2)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// SetPathWithQuery represents the imported method "set-path-with-query". +// +// Set the combination of the HTTP Path and Query for the Request. +// When `none`, this represents an empty Path and empty Query. Fails is the +// string given is not a syntactically valid path and query uri component. +// +// set-path-with-query: func(path-with-query: option) -> result +// +//go:nosplit +func (self OutgoingRequest) SetPathWithQuery(pathWithQuery cm.Option[string]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + pathWithQuery0, pathWithQuery1, pathWithQuery2 := lower_OptionString(pathWithQuery) + result0 := wasmimport_OutgoingRequestSetPathWithQuery((uint32)(self0), (uint32)(pathWithQuery0), (*uint8)(pathWithQuery1), (uint32)(pathWithQuery2)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// SetScheme represents the imported method "set-scheme". +// +// Set the HTTP Related Scheme for the Request. When `none`, the +// implementation may choose an appropriate default scheme. Fails if the +// string given is not a syntactically valid uri scheme. +// +// set-scheme: func(scheme: option) -> result +// +//go:nosplit +func (self OutgoingRequest) SetScheme(scheme cm.Option[Scheme]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + scheme0, scheme1, scheme2, scheme3 := lower_OptionScheme(scheme) + result0 := wasmimport_OutgoingRequestSetScheme((uint32)(self0), (uint32)(scheme0), (uint32)(scheme1), (*uint8)(scheme2), (uint32)(scheme3)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// RequestOptions represents the imported resource "wasi:http/types@0.2.0#request-options". +// +// Parameters for making an HTTP Request. Each of these parameters is +// currently an optional timeout applicable to the transport layer of the +// HTTP protocol. +// +// These timeouts are separate from any the user may use to bound a +// blocking call to `wasi:io/poll.poll`. +// +// resource request-options +type RequestOptions cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "request-options". +// +// Drops a resource handle. +// +//go:nosplit +func (self RequestOptions) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsResourceDrop((uint32)(self0)) + return +} + +// NewRequestOptions represents the imported constructor for resource "request-options". +// +// Construct a default `request-options` value. +// +// constructor() +// +//go:nosplit +func NewRequestOptions() (result RequestOptions) { + result0 := wasmimport_NewRequestOptions() + result = cm.Reinterpret[RequestOptions]((uint32)(result0)) + return +} + +// BetweenBytesTimeout represents the imported method "between-bytes-timeout". +// +// The timeout for receiving subsequent chunks of bytes in the Response +// body stream. +// +// between-bytes-timeout: func() -> option +// +//go:nosplit +func (self RequestOptions) BetweenBytesTimeout() (result cm.Option[Duration]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsBetweenBytesTimeout((uint32)(self0), &result) + return +} + +// ConnectTimeout represents the imported method "connect-timeout". +// +// The timeout for the initial connect to the HTTP Server. +// +// connect-timeout: func() -> option +// +//go:nosplit +func (self RequestOptions) ConnectTimeout() (result cm.Option[Duration]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsConnectTimeout((uint32)(self0), &result) + return +} + +// FirstByteTimeout represents the imported method "first-byte-timeout". +// +// The timeout for receiving the first byte of the Response body. +// +// first-byte-timeout: func() -> option +// +//go:nosplit +func (self RequestOptions) FirstByteTimeout() (result cm.Option[Duration]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsFirstByteTimeout((uint32)(self0), &result) + return +} + +// SetBetweenBytesTimeout represents the imported method "set-between-bytes-timeout". +// +// Set the timeout for receiving subsequent chunks of bytes in the Response +// body stream. An error return value indicates that this timeout is not +// supported. +// +// set-between-bytes-timeout: func(duration: option) -> result +// +//go:nosplit +func (self RequestOptions) SetBetweenBytesTimeout(duration cm.Option[Duration]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + duration0, duration1 := lower_OptionDuration(duration) + result0 := wasmimport_RequestOptionsSetBetweenBytesTimeout((uint32)(self0), (uint32)(duration0), (uint64)(duration1)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// SetConnectTimeout represents the imported method "set-connect-timeout". +// +// Set the timeout for the initial connect to the HTTP Server. An error +// return value indicates that this timeout is not supported. +// +// set-connect-timeout: func(duration: option) -> result +// +//go:nosplit +func (self RequestOptions) SetConnectTimeout(duration cm.Option[Duration]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + duration0, duration1 := lower_OptionDuration(duration) + result0 := wasmimport_RequestOptionsSetConnectTimeout((uint32)(self0), (uint32)(duration0), (uint64)(duration1)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// SetFirstByteTimeout represents the imported method "set-first-byte-timeout". +// +// Set the timeout for receiving the first byte of the Response body. An +// error return value indicates that this timeout is not supported. +// +// set-first-byte-timeout: func(duration: option) -> result +// +//go:nosplit +func (self RequestOptions) SetFirstByteTimeout(duration cm.Option[Duration]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + duration0, duration1 := lower_OptionDuration(duration) + result0 := wasmimport_RequestOptionsSetFirstByteTimeout((uint32)(self0), (uint32)(duration0), (uint64)(duration1)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// ResponseOutparam represents the imported resource "wasi:http/types@0.2.0#response-outparam". +// +// Represents the ability to send an HTTP Response. +// +// This resource is used by the `wasi:http/incoming-handler` interface to +// allow a Response to be sent corresponding to the Request provided as the +// other argument to `incoming-handler.handle`. +// +// resource response-outparam +type ResponseOutparam cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "response-outparam". +// +// Drops a resource handle. +// +//go:nosplit +func (self ResponseOutparam) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ResponseOutparamResourceDrop((uint32)(self0)) + return +} + +// ResponseOutparamSet represents the imported static function "set". +// +// Set the value of the `response-outparam` to either send a response, +// or indicate an error. +// +// This method consumes the `response-outparam` to ensure that it is +// called at most once. If it is never called, the implementation +// will respond with an error. +// +// The user may provide an `error` to `response` to allow the +// implementation determine how to respond with an HTTP error response. +// +// set: static func(param: response-outparam, response: result) +// +//go:nosplit +func ResponseOutparamSet(param ResponseOutparam, response cm.Result[ErrorCodeShape, OutgoingResponse, ErrorCode]) { + param0 := cm.Reinterpret[uint32](param) + response0, response1, response2, response3, response4, response5, response6, response7 := lower_ResultOutgoingResponseErrorCode(response) + wasmimport_ResponseOutparamSet((uint32)(param0), (uint32)(response0), (uint32)(response1), (uint32)(response2), (uint64)(response3), (uint32)(response4), (uint32)(response5), (uint32)(response6), (uint32)(response7)) + return +} + +// StatusCode represents the u16 "wasi:http/types@0.2.0#status-code". +// +// This type corresponds to the HTTP standard Status Code. +// +// type status-code = u16 +type StatusCode uint16 + +// IncomingResponse represents the imported resource "wasi:http/types@0.2.0#incoming-response". +// +// Represents an incoming HTTP Response. +// +// resource incoming-response +type IncomingResponse cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-response". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingResponse) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingResponseResourceDrop((uint32)(self0)) + return +} + +// Consume represents the imported method "consume". +// +// Returns the incoming body. May be called at most once. Returns error +// if called additional times. +// +// consume: func() -> result +// +//go:nosplit +func (self IncomingResponse) Consume() (result cm.Result[IncomingBody, IncomingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingResponseConsume((uint32)(self0), &result) + return +} + +// Headers represents the imported method "headers". +// +// Returns the headers from the incoming response. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// This headers resource is a child: it must be dropped before the parent +// `incoming-response` is dropped. +// +// headers: func() -> headers +// +//go:nosplit +func (self IncomingResponse) Headers() (result Headers) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingResponseHeaders((uint32)(self0)) + result = cm.Reinterpret[Headers]((uint32)(result0)) + return +} + +// Status represents the imported method "status". +// +// Returns the status code from the incoming response. +// +// status: func() -> status-code +// +//go:nosplit +func (self IncomingResponse) Status() (result StatusCode) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingResponseStatus((uint32)(self0)) + result = (StatusCode)((uint32)(result0)) + return +} + +// IncomingBody represents the imported resource "wasi:http/types@0.2.0#incoming-body". +// +// Represents an incoming HTTP Request or Response's Body. +// +// A body has both its contents - a stream of bytes - and a (possibly +// empty) set of trailers, indicating that the full contents of the +// body have been received. This resource represents the contents as +// an `input-stream` and the delivery of trailers as a `future-trailers`, +// and ensures that the user of this interface may only be consuming either +// the body contents or waiting on trailers at any given time. +// +// resource incoming-body +type IncomingBody cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-body". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingBody) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingBodyResourceDrop((uint32)(self0)) + return +} + +// IncomingBodyFinish represents the imported static function "finish". +// +// Takes ownership of `incoming-body`, and returns a `future-trailers`. +// This function will trap if the `input-stream` child is still alive. +// +// finish: static func(this: incoming-body) -> future-trailers +// +//go:nosplit +func IncomingBodyFinish(this IncomingBody) (result FutureTrailers) { + this0 := cm.Reinterpret[uint32](this) + result0 := wasmimport_IncomingBodyFinish((uint32)(this0)) + result = cm.Reinterpret[FutureTrailers]((uint32)(result0)) + return +} + +// Stream represents the imported method "stream". +// +// Returns the contents of the body, as a stream of bytes. +// +// Returns success on first call: the stream representing the contents +// can be retrieved at most once. Subsequent calls will return error. +// +// The returned `input-stream` resource is a child: it must be dropped +// before the parent `incoming-body` is dropped, or consumed by +// `incoming-body.finish`. +// +// This invariant ensures that the implementation can determine whether +// the user is consuming the contents of the body, waiting on the +// `future-trailers` to be ready, or neither. This allows for network +// backpressure is to be applied when the user is consuming the body, +// and for that backpressure to not inhibit delivery of the trailers if +// the user does not read the entire body. +// +// %stream: func() -> result +// +//go:nosplit +func (self IncomingBody) Stream() (result cm.Result[InputStream, InputStream, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingBodyStream((uint32)(self0), &result) + return +} + +// FutureTrailers represents the imported resource "wasi:http/types@0.2.0#future-trailers". +// +// Represents a future which may eventaully return trailers, or an error. +// +// In the case that the incoming HTTP Request or Response did not have any +// trailers, this future will resolve to the empty set of trailers once the +// complete Request or Response body has been received. +// +// resource future-trailers +type FutureTrailers cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "future-trailers". +// +// Drops a resource handle. +// +//go:nosplit +func (self FutureTrailers) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureTrailersResourceDrop((uint32)(self0)) + return +} + +// Get represents the imported method "get". +// +// Returns the contents of the trailers, or an error which occured, +// once the future is ready. +// +// The outer `option` represents future readiness. Users can wait on this +// `option` to become `some` using the `subscribe` method. +// +// The outer `result` is used to retrieve the trailers or error at most +// once. It will be success on the first call in which the outer option +// is `some`, and error on subsequent calls. +// +// The inner `result` represents that either the HTTP Request or Response +// body, as well as any trailers, were received successfully, or that an +// error occured receiving them. The optional `trailers` indicates whether +// or not trailers were present in the body. +// +// When some `trailers` are returned by this method, the `trailers` +// resource is immutable, and a child. Use of the `set`, `append`, or +// `delete` methods will return an error, and the resource must be +// dropped before the parent `future-trailers` is dropped. +// +// get: func() -> option, error-code>>> +// +//go:nosplit +func (self FutureTrailers) Get() (result cm.Option[cm.Result[cm.Result[ErrorCodeShape, cm.Option[Trailers], ErrorCode], cm.Result[ErrorCodeShape, cm.Option[Trailers], ErrorCode], struct{}]]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureTrailersGet((uint32)(self0), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Returns a pollable which becomes ready when either the trailers have +// been received, or an error has occured. When this pollable is ready, +// the `get` method will return `some`. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self FutureTrailers) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_FutureTrailersSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// OutgoingResponse represents the imported resource "wasi:http/types@0.2.0#outgoing-response". +// +// Represents an outgoing HTTP Response. +// +// resource outgoing-response +type OutgoingResponse cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-response". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingResponse) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingResponseResourceDrop((uint32)(self0)) + return +} + +// NewOutgoingResponse represents the imported constructor for resource "outgoing-response". +// +// Construct an `outgoing-response`, with a default `status-code` of `200`. +// If a different `status-code` is needed, it must be set via the +// `set-status-code` method. +// +// * `headers` is the HTTP Headers for the Response. +// +// constructor(headers: headers) +// +//go:nosplit +func NewOutgoingResponse(headers Headers) (result OutgoingResponse) { + headers0 := cm.Reinterpret[uint32](headers) + result0 := wasmimport_NewOutgoingResponse((uint32)(headers0)) + result = cm.Reinterpret[OutgoingResponse]((uint32)(result0)) + return +} + +// Body represents the imported method "body". +// +// Returns the resource corresponding to the outgoing Body for this Response. +// +// Returns success on the first call: the `outgoing-body` resource for +// this `outgoing-response` can be retrieved at most once. Subsequent +// calls will return error. +// +// body: func() -> result +// +//go:nosplit +func (self OutgoingResponse) Body() (result cm.Result[OutgoingBody, OutgoingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingResponseBody((uint32)(self0), &result) + return +} + +// Headers represents the imported method "headers". +// +// Get the headers associated with the Request. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// This headers resource is a child: it must be dropped before the parent +// `outgoing-request` is dropped, or its ownership is transfered to +// another component by e.g. `outgoing-handler.handle`. +// +// headers: func() -> headers +// +//go:nosplit +func (self OutgoingResponse) Headers() (result Headers) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingResponseHeaders((uint32)(self0)) + result = cm.Reinterpret[Headers]((uint32)(result0)) + return +} + +// SetStatusCode represents the imported method "set-status-code". +// +// Set the HTTP Status Code for the Response. Fails if the status-code +// given is not a valid http status code. +// +// set-status-code: func(status-code: status-code) -> result +// +//go:nosplit +func (self OutgoingResponse) SetStatusCode(statusCode StatusCode) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + statusCode0 := (uint32)(statusCode) + result0 := wasmimport_OutgoingResponseSetStatusCode((uint32)(self0), (uint32)(statusCode0)) + result = (cm.BoolResult)((bool)(cm.U32ToBool((uint32)(result0)))) + return +} + +// StatusCode represents the imported method "status-code". +// +// Get the HTTP Status Code for the Response. +// +// status-code: func() -> status-code +// +//go:nosplit +func (self OutgoingResponse) StatusCode() (result StatusCode) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingResponseStatusCode((uint32)(self0)) + result = (StatusCode)((uint32)(result0)) + return +} + +// OutgoingBody represents the imported resource "wasi:http/types@0.2.0#outgoing-body". +// +// Represents an outgoing HTTP Request or Response's Body. +// +// A body has both its contents - a stream of bytes - and a (possibly +// empty) set of trailers, inducating the full contents of the body +// have been sent. This resource represents the contents as an +// `output-stream` child resource, and the completion of the body (with +// optional trailers) with a static function that consumes the +// `outgoing-body` resource, and ensures that the user of this interface +// may not write to the body contents after the body has been finished. +// +// If the user code drops this resource, as opposed to calling the static +// method `finish`, the implementation should treat the body as incomplete, +// and that an error has occured. The implementation should propogate this +// error to the HTTP protocol by whatever means it has available, +// including: corrupting the body on the wire, aborting the associated +// Request, or sending a late status code for the Response. +// +// resource outgoing-body +type OutgoingBody cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-body". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingBody) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingBodyResourceDrop((uint32)(self0)) + return +} + +// OutgoingBodyFinish represents the imported static function "finish". +// +// Finalize an outgoing body, optionally providing trailers. This must be +// called to signal that the response is complete. If the `outgoing-body` +// is dropped without calling `outgoing-body.finalize`, the implementation +// should treat the body as corrupted. +// +// Fails if the body's `outgoing-request` or `outgoing-response` was +// constructed with a Content-Length header, and the contents written +// to the body (via `write`) does not match the value given in the +// Content-Length. +// +// finish: static func(this: outgoing-body, trailers: option) -> result<_, +// error-code> +// +//go:nosplit +func OutgoingBodyFinish(this OutgoingBody, trailers cm.Option[Trailers]) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + this0 := cm.Reinterpret[uint32](this) + trailers0, trailers1 := lower_OptionTrailers(trailers) + wasmimport_OutgoingBodyFinish((uint32)(this0), (uint32)(trailers0), (uint32)(trailers1), &result) + return +} + +// Write represents the imported method "write". +// +// Returns a stream for writing the body contents. +// +// The returned `output-stream` is a child resource: it must be dropped +// before the parent `outgoing-body` resource is dropped (or finished), +// otherwise the `outgoing-body` drop or `finish` will trap. +// +// Returns success on the first call: the `output-stream` resource for +// this `outgoing-body` may be retrieved at most once. Subsequent calls +// will return error. +// +// write: func() -> result +// +//go:nosplit +func (self OutgoingBody) Write() (result cm.Result[OutputStream, OutputStream, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingBodyWrite((uint32)(self0), &result) + return +} + +// FutureIncomingResponse represents the imported resource "wasi:http/types@0.2.0#future-incoming-response". +// +// Represents a future which may eventaully return an incoming HTTP +// Response, or an error. +// +// This resource is returned by the `wasi:http/outgoing-handler` interface to +// provide the HTTP Response corresponding to the sent Request. +// +// resource future-incoming-response +type FutureIncomingResponse cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "future-incoming-response". +// +// Drops a resource handle. +// +//go:nosplit +func (self FutureIncomingResponse) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureIncomingResponseResourceDrop((uint32)(self0)) + return +} + +// Get represents the imported method "get". +// +// Returns the incoming HTTP Response, or an error, once one is ready. +// +// The outer `option` represents future readiness. Users can wait on this +// `option` to become `some` using the `subscribe` method. +// +// The outer `result` is used to retrieve the response or error at most +// once. It will be success on the first call in which the outer option +// is `some`, and error on subsequent calls. +// +// The inner `result` represents that either the incoming HTTP Response +// status and headers have recieved successfully, or that an error +// occured. Errors may also occur while consuming the response body, +// but those will be reported by the `incoming-body` and its +// `output-stream` child. +// +// get: func() -> option>> +// +//go:nosplit +func (self FutureIncomingResponse) Get() (result cm.Option[cm.Result[cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], struct{}]]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureIncomingResponseGet((uint32)(self0), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Returns a pollable which becomes ready when either the Response has +// been received, or an error has occured. When this pollable is ready, +// the `get` method will return `some`. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self FutureIncomingResponse) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_FutureIncomingResponseSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// HTTPErrorCode represents the imported function "http-error-code". +// +// Attempts to extract a http-related `error` from the wasi:io `error` +// provided. +// +// Stream operations which return +// `wasi:io/stream/stream-error::last-operation-failed` have a payload of +// type `wasi:io/error/error` with more information about the operation +// that failed. This payload can be passed through to this function to see +// if there's http-related information about the error to return. +// +// Note that this function is fallible because not all io-errors are +// http-related errors. +// +// http-error-code: func(err: borrow) -> option +// +//go:nosplit +func HTTPErrorCode(err IOError) (result cm.Option[ErrorCode]) { + err0 := cm.Reinterpret[uint32](err) + wasmimport_HTTPErrorCode((uint32)(err0), &result) + return +} diff --git a/x/wasihttp/internal/wasi/io/error/empty.s b/x/wasihttp/internal/wasi/io/error/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/io/error/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/io/error/error.wasm.go b/x/wasihttp/internal/wasi/io/error/error.wasm.go new file mode 100755 index 00000000..e254b5d8 --- /dev/null +++ b/x/wasihttp/internal/wasi/io/error/error.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package ioerror + +// This file contains wasmimport and wasmexport declarations for "wasi:io@0.2.0". + +//go:wasmimport wasi:io/error@0.2.0 [resource-drop]error +//go:noescape +func wasmimport_ErrorResourceDrop(self0 uint32) + +//go:wasmimport wasi:io/error@0.2.0 [method]error.to-debug-string +//go:noescape +func wasmimport_ErrorToDebugString(self0 uint32, result *string) diff --git a/x/wasihttp/internal/wasi/io/error/error.wit.go b/x/wasihttp/internal/wasi/io/error/error.wit.go new file mode 100755 index 00000000..24bad438 --- /dev/null +++ b/x/wasihttp/internal/wasi/io/error/error.wit.go @@ -0,0 +1,63 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package ioerror represents the imported interface "wasi:io/error@0.2.0". +package ioerror + +import ( + "go.bytecodealliance.org/cm" +) + +// Error represents the imported resource "wasi:io/error@0.2.0#error". +// +// A resource which represents some error information. +// +// The only method provided by this resource is `to-debug-string`, +// which provides some human-readable information about the error. +// +// In the `wasi:io` package, this resource is returned through the +// `wasi:io/streams/stream-error` type. +// +// To provide more specific error information, other interfaces may +// provide functions to further "downcast" this error into more specific +// error information. For example, `error`s returned in streams derived +// from filesystem types to be described using the filesystem's own +// error-code type, using the function +// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter +// `borrow` and returns +// `option`. +// +// The set of functions which can "downcast" an `error` into a more +// concrete type is open. +// +// resource error +type Error cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "error". +// +// Drops a resource handle. +// +//go:nosplit +func (self Error) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ErrorResourceDrop((uint32)(self0)) + return +} + +// ToDebugString represents the imported method "to-debug-string". +// +// Returns a string that is suitable to assist humans in debugging +// this error. +// +// WARNING: The returned string should not be consumed mechanically! +// It may change across platforms, hosts, or other implementation +// details. Parsing this string is a major platform-compatibility +// hazard. +// +// to-debug-string: func() -> string +// +//go:nosplit +func (self Error) ToDebugString() (result string) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ErrorToDebugString((uint32)(self0), &result) + return +} diff --git a/x/wasihttp/internal/wasi/io/poll/empty.s b/x/wasihttp/internal/wasi/io/poll/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/io/poll/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/io/poll/poll.wasm.go b/x/wasihttp/internal/wasi/io/poll/poll.wasm.go new file mode 100755 index 00000000..f7c55c3d --- /dev/null +++ b/x/wasihttp/internal/wasi/io/poll/poll.wasm.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package poll + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:io@0.2.0". + +//go:wasmimport wasi:io/poll@0.2.0 [resource-drop]pollable +//go:noescape +func wasmimport_PollableResourceDrop(self0 uint32) + +//go:wasmimport wasi:io/poll@0.2.0 [method]pollable.block +//go:noescape +func wasmimport_PollableBlock(self0 uint32) + +//go:wasmimport wasi:io/poll@0.2.0 [method]pollable.ready +//go:noescape +func wasmimport_PollableReady(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:io/poll@0.2.0 poll +//go:noescape +func wasmimport_Poll(in0 *Pollable, in1 uint32, result *cm.List[uint32]) diff --git a/x/wasihttp/internal/wasi/io/poll/poll.wit.go b/x/wasihttp/internal/wasi/io/poll/poll.wit.go new file mode 100755 index 00000000..10c0033b --- /dev/null +++ b/x/wasihttp/internal/wasi/io/poll/poll.wit.go @@ -0,0 +1,92 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package poll represents the imported interface "wasi:io/poll@0.2.0". +// +// A poll API intended to let users wait for I/O events on multiple handles +// at once. +package poll + +import ( + "go.bytecodealliance.org/cm" +) + +// Pollable represents the imported resource "wasi:io/poll@0.2.0#pollable". +// +// `pollable` represents a single I/O event which may be ready, or not. +// +// resource pollable +type Pollable cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "pollable". +// +// Drops a resource handle. +// +//go:nosplit +func (self Pollable) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_PollableResourceDrop((uint32)(self0)) + return +} + +// Block represents the imported method "block". +// +// `block` returns immediately if the pollable is ready, and otherwise +// blocks until ready. +// +// This function is equivalent to calling `poll.poll` on a list +// containing only this pollable. +// +// block: func() +// +//go:nosplit +func (self Pollable) Block() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_PollableBlock((uint32)(self0)) + return +} + +// Ready represents the imported method "ready". +// +// Return the readiness of a pollable. This function never blocks. +// +// Returns `true` when the pollable is ready, and `false` otherwise. +// +// ready: func() -> bool +// +//go:nosplit +func (self Pollable) Ready() (result bool) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_PollableReady((uint32)(self0)) + result = (bool)(cm.U32ToBool((uint32)(result0))) + return +} + +// Poll represents the imported function "poll". +// +// Poll for completion on a set of pollables. +// +// This function takes a list of pollables, which identify I/O sources of +// interest, and waits until one or more of the events is ready for I/O. +// +// The result `list` contains one or more indices of handles in the +// argument list that is ready for I/O. +// +// If the list contains more elements than can be indexed with a `u32` +// value, this function traps. +// +// A timeout can be implemented by adding a pollable from the +// wasi-clocks API to the list. +// +// This function does not return a `result`; polling in itself does not +// do any I/O so it doesn't fail. If any of the I/O sources identified by +// the pollables has an error, it is indicated by marking the source as +// being reaedy for I/O. +// +// poll: func(in: list>) -> list +// +//go:nosplit +func Poll(in cm.List[Pollable]) (result cm.List[uint32]) { + in0, in1 := cm.LowerList(in) + wasmimport_Poll((*Pollable)(in0), (uint32)(in1), &result) + return +} diff --git a/x/wasihttp/internal/wasi/io/streams/empty.s b/x/wasihttp/internal/wasi/io/streams/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/io/streams/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/io/streams/streams.wasm.go b/x/wasihttp/internal/wasi/io/streams/streams.wasm.go new file mode 100755 index 00000000..eec56645 --- /dev/null +++ b/x/wasihttp/internal/wasi/io/streams/streams.wasm.go @@ -0,0 +1,77 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package streams + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:io@0.2.0". + +//go:wasmimport wasi:io/streams@0.2.0 [resource-drop]input-stream +//go:noescape +func wasmimport_InputStreamResourceDrop(self0 uint32) + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.blocking-read +//go:noescape +func wasmimport_InputStreamBlockingRead(self0 uint32, len0 uint64, result *cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.blocking-skip +//go:noescape +func wasmimport_InputStreamBlockingSkip(self0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.read +//go:noescape +func wasmimport_InputStreamRead(self0 uint32, len0 uint64, result *cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.skip +//go:noescape +func wasmimport_InputStreamSkip(self0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.subscribe +//go:noescape +func wasmimport_InputStreamSubscribe(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:io/streams@0.2.0 [resource-drop]output-stream +//go:noescape +func wasmimport_OutputStreamResourceDrop(self0 uint32) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-flush +//go:noescape +func wasmimport_OutputStreamBlockingFlush(self0 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-splice +//go:noescape +func wasmimport_OutputStreamBlockingSplice(self0 uint32, src0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-write-and-flush +//go:noescape +func wasmimport_OutputStreamBlockingWriteAndFlush(self0 uint32, contents0 *uint8, contents1 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-write-zeroes-and-flush +//go:noescape +func wasmimport_OutputStreamBlockingWriteZeroesAndFlush(self0 uint32, len0 uint64, result *cm.Result[StreamError, struct{}, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.check-write +//go:noescape +func wasmimport_OutputStreamCheckWrite(self0 uint32, result *cm.Result[uint64, uint64, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.flush +//go:noescape +func wasmimport_OutputStreamFlush(self0 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.splice +//go:noescape +func wasmimport_OutputStreamSplice(self0 uint32, src0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.subscribe +//go:noescape +func wasmimport_OutputStreamSubscribe(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.write +//go:noescape +func wasmimport_OutputStreamWrite(self0 uint32, contents0 *uint8, contents1 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.write-zeroes +//go:noescape +func wasmimport_OutputStreamWriteZeroes(self0 uint32, len0 uint64, result *cm.Result[StreamError, struct{}, StreamError]) diff --git a/x/wasihttp/internal/wasi/io/streams/streams.wit.go b/x/wasihttp/internal/wasi/io/streams/streams.wit.go new file mode 100755 index 00000000..f146ae8e --- /dev/null +++ b/x/wasihttp/internal/wasi/io/streams/streams.wit.go @@ -0,0 +1,471 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package streams represents the imported interface "wasi:io/streams@0.2.0". +// +// WASI I/O is an I/O abstraction API which is currently focused on providing +// stream types. +// +// In the future, the component model is expected to add built-in stream types; +// when it does, they are expected to subsume this API. +package streams + +import ( + "go.bytecodealliance.org/cm" + ioerror "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/error" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" +) + +// Error represents the imported type alias "wasi:io/streams@0.2.0#error". +// +// See [ioerror.Error] for more information. +type Error = ioerror.Error + +// Pollable represents the imported type alias "wasi:io/streams@0.2.0#pollable". +// +// See [poll.Pollable] for more information. +type Pollable = poll.Pollable + +// StreamError represents the imported variant "wasi:io/streams@0.2.0#stream-error". +// +// An error for input-stream and output-stream operations. +// +// variant stream-error { +// last-operation-failed(error), +// closed, +// } +type StreamError cm.Variant[uint8, Error, Error] + +// StreamErrorLastOperationFailed returns a [StreamError] of case "last-operation-failed". +// +// The last operation (a write or flush) failed before completion. +// +// More information is available in the `error` payload. +func StreamErrorLastOperationFailed(data Error) StreamError { + return cm.New[StreamError](0, data) +} + +// LastOperationFailed returns a non-nil *[Error] if [StreamError] represents the variant case "last-operation-failed". +func (self *StreamError) LastOperationFailed() *Error { + return cm.Case[Error](self, 0) +} + +// StreamErrorClosed returns a [StreamError] of case "closed". +// +// The stream is closed: no more input will be accepted by the +// stream. A closed output-stream will return this error on all +// future operations. +func StreamErrorClosed() StreamError { + var data struct{} + return cm.New[StreamError](1, data) +} + +// Closed returns true if [StreamError] represents the variant case "closed". +func (self *StreamError) Closed() bool { + return self.Tag() == 1 +} + +var _StreamErrorStrings = [2]string{ + "last-operation-failed", + "closed", +} + +// String implements [fmt.Stringer], returning the variant case name of v. +func (v StreamError) String() string { + return _StreamErrorStrings[v.Tag()] +} + +// InputStream represents the imported resource "wasi:io/streams@0.2.0#input-stream". +// +// An input bytestream. +// +// `input-stream`s are *non-blocking* to the extent practical on underlying +// platforms. I/O operations always return promptly; if fewer bytes are +// promptly available than requested, they return the number of bytes promptly +// available, which could even be zero. To wait for data to be available, +// use the `subscribe` function to obtain a `pollable` which can be polled +// for using `wasi:io/poll`. +// +// resource input-stream +type InputStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "input-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self InputStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_InputStreamResourceDrop((uint32)(self0)) + return +} + +// BlockingRead represents the imported method "blocking-read". +// +// Read bytes from a stream, after blocking until at least one byte can +// be read. Except for blocking, behavior is identical to `read`. +// +// blocking-read: func(len: u64) -> result, stream-error> +// +//go:nosplit +func (self InputStream) BlockingRead(len_ uint64) (result cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamBlockingRead((uint32)(self0), (uint64)(len0), &result) + return +} + +// BlockingSkip represents the imported method "blocking-skip". +// +// Skip bytes from a stream, after blocking until at least one byte +// can be skipped. Except for blocking behavior, identical to `skip`. +// +// blocking-skip: func(len: u64) -> result +// +//go:nosplit +func (self InputStream) BlockingSkip(len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamBlockingSkip((uint32)(self0), (uint64)(len0), &result) + return +} + +// Read represents the imported method "read". +// +// Perform a non-blocking read from the stream. +// +// When the source of a `read` is binary data, the bytes from the source +// are returned verbatim. When the source of a `read` is known to the +// implementation to be text, bytes containing the UTF-8 encoding of the +// text are returned. +// +// This function returns a list of bytes containing the read data, +// when successful. The returned list will contain up to `len` bytes; +// it may return fewer than requested, but not more. The list is +// empty when no bytes are available for reading at this time. The +// pollable given by `subscribe` will be ready when more bytes are +// available. +// +// This function fails with a `stream-error` when the operation +// encounters an error, giving `last-operation-failed`, or when the +// stream is closed, giving `closed`. +// +// When the caller gives a `len` of 0, it represents a request to +// read 0 bytes. If the stream is still open, this call should +// succeed and return an empty list, or otherwise fail with `closed`. +// +// The `len` parameter is a `u64`, which could represent a list of u8 which +// is not possible to allocate in wasm32, or not desirable to allocate as +// as a return value by the callee. The callee may return a list of bytes +// less than `len` in size while more bytes are available for reading. +// +// read: func(len: u64) -> result, stream-error> +// +//go:nosplit +func (self InputStream) Read(len_ uint64) (result cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamRead((uint32)(self0), (uint64)(len0), &result) + return +} + +// Skip represents the imported method "skip". +// +// Skip bytes from a stream. Returns number of bytes skipped. +// +// Behaves identical to `read`, except instead of returning a list +// of bytes, returns the number of bytes consumed from the stream. +// +// skip: func(len: u64) -> result +// +//go:nosplit +func (self InputStream) Skip(len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamSkip((uint32)(self0), (uint64)(len0), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once either the specified stream +// has bytes available to read or the other end of the stream has been +// closed. +// The created `pollable` is a child resource of the `input-stream`. +// Implementations may trap if the `input-stream` is dropped before +// all derived `pollable`s created with this function are dropped. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self InputStream) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_InputStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// OutputStream represents the imported resource "wasi:io/streams@0.2.0#output-stream". +// +// An output bytestream. +// +// `output-stream`s are *non-blocking* to the extent practical on +// underlying platforms. Except where specified otherwise, I/O operations also +// always return promptly, after the number of bytes that can be written +// promptly, which could even be zero. To wait for the stream to be ready to +// accept data, the `subscribe` function to obtain a `pollable` which can be +// polled for using `wasi:io/poll`. +// +// resource output-stream +type OutputStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "output-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutputStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamResourceDrop((uint32)(self0)) + return +} + +// BlockingFlush represents the imported method "blocking-flush". +// +// Request to flush buffered output, and block until flush completes +// and stream is ready for writing again. +// +// blocking-flush: func() -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) BlockingFlush() (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamBlockingFlush((uint32)(self0), &result) + return +} + +// BlockingSplice represents the imported method "blocking-splice". +// +// Read from one stream and write to another, with blocking. +// +// This is similar to `splice`, except that it blocks until the +// `output-stream` is ready for writing, and the `input-stream` +// is ready for reading, before performing the `splice`. +// +// blocking-splice: func(src: borrow, len: u64) -> result +// +//go:nosplit +func (self OutputStream) BlockingSplice(src InputStream, len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + src0 := cm.Reinterpret[uint32](src) + len0 := (uint64)(len_) + wasmimport_OutputStreamBlockingSplice((uint32)(self0), (uint32)(src0), (uint64)(len0), &result) + return +} + +// BlockingWriteAndFlush represents the imported method "blocking-write-and-flush". +// +// Perform a write of up to 4096 bytes, and then flush the stream. Block +// until all of these operations are complete, or an error occurs. +// +// This is a convenience wrapper around the use of `check-write`, +// `subscribe`, `write`, and `flush`, and is implemented with the +// following pseudo-code: +// +// let pollable = this.subscribe(); +// while !contents.is_empty() { +// // Wait for the stream to become writable +// pollable.block(); +// let Ok(n) = this.check-write(); // eliding error handling +// let len = min(n, contents.len()); +// let (chunk, rest) = contents.split_at(len); +// this.write(chunk ); // eliding error handling +// contents = rest; +// } +// this.flush(); +// // Wait for completion of `flush` +// pollable.block(); +// // Check for any errors that arose during `flush` +// let _ = this.check-write(); // eliding error handling +// +// blocking-write-and-flush: func(contents: list) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) BlockingWriteAndFlush(contents cm.List[uint8]) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + contents0, contents1 := cm.LowerList(contents) + wasmimport_OutputStreamBlockingWriteAndFlush((uint32)(self0), (*uint8)(contents0), (uint32)(contents1), &result) + return +} + +// BlockingWriteZeroesAndFlush represents the imported method "blocking-write-zeroes-and-flush". +// +// Perform a write of up to 4096 zeroes, and then flush the stream. +// Block until all of these operations are complete, or an error +// occurs. +// +// This is a convenience wrapper around the use of `check-write`, +// `subscribe`, `write-zeroes`, and `flush`, and is implemented with +// the following pseudo-code: +// +// let pollable = this.subscribe(); +// while num_zeroes != 0 { +// // Wait for the stream to become writable +// pollable.block(); +// let Ok(n) = this.check-write(); // eliding error handling +// let len = min(n, num_zeroes); +// this.write-zeroes(len); // eliding error handling +// num_zeroes -= len; +// } +// this.flush(); +// // Wait for completion of `flush` +// pollable.block(); +// // Check for any errors that arose during `flush` +// let _ = this.check-write(); // eliding error handling +// +// blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) BlockingWriteZeroesAndFlush(len_ uint64) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_OutputStreamBlockingWriteZeroesAndFlush((uint32)(self0), (uint64)(len0), &result) + return +} + +// CheckWrite represents the imported method "check-write". +// +// Check readiness for writing. This function never blocks. +// +// Returns the number of bytes permitted for the next call to `write`, +// or an error. Calling `write` with more bytes than this function has +// permitted will trap. +// +// When this function returns 0 bytes, the `subscribe` pollable will +// become ready when this function will report at least 1 byte, or an +// error. +// +// check-write: func() -> result +// +//go:nosplit +func (self OutputStream) CheckWrite() (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamCheckWrite((uint32)(self0), &result) + return +} + +// Flush represents the imported method "flush". +// +// Request to flush buffered output. This function never blocks. +// +// This tells the output-stream that the caller intends any buffered +// output to be flushed. the output which is expected to be flushed +// is all that has been passed to `write` prior to this call. +// +// Upon calling this function, the `output-stream` will not accept any +// writes (`check-write` will return `ok(0)`) until the flush has +// completed. The `subscribe` pollable will become ready when the +// flush has completed and the stream can accept more writes. +// +// flush: func() -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) Flush() (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamFlush((uint32)(self0), &result) + return +} + +// Splice represents the imported method "splice". +// +// Read from one stream and write to another. +// +// The behavior of splice is equivelant to: +// 1. calling `check-write` on the `output-stream` +// 2. calling `read` on the `input-stream` with the smaller of the +// `check-write` permitted length and the `len` provided to `splice` +// 3. calling `write` on the `output-stream` with that read data. +// +// Any error reported by the call to `check-write`, `read`, or +// `write` ends the splice and reports that error. +// +// This function returns the number of bytes transferred; it may be less +// than `len`. +// +// splice: func(src: borrow, len: u64) -> result +// +//go:nosplit +func (self OutputStream) Splice(src InputStream, len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + src0 := cm.Reinterpret[uint32](src) + len0 := (uint64)(len_) + wasmimport_OutputStreamSplice((uint32)(self0), (uint32)(src0), (uint64)(len0), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the output-stream +// is ready for more writing, or an error has occured. When this +// pollable is ready, `check-write` will return `ok(n)` with n>0, or an +// error. +// +// If the stream is closed, this pollable is always ready immediately. +// +// The created `pollable` is a child resource of the `output-stream`. +// Implementations may trap if the `output-stream` is dropped before +// all derived `pollable`s created with this function are dropped. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self OutputStream) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutputStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// Write represents the imported method "write". +// +// Perform a write. This function never blocks. +// +// When the destination of a `write` is binary data, the bytes from +// `contents` are written verbatim. When the destination of a `write` is +// known to the implementation to be text, the bytes of `contents` are +// transcoded from UTF-8 into the encoding of the destination and then +// written. +// +// Precondition: check-write gave permit of Ok(n) and contents has a +// length of less than or equal to n. Otherwise, this function will trap. +// +// returns Err(closed) without writing if the stream has closed since +// the last call to check-write provided a permit. +// +// write: func(contents: list) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) Write(contents cm.List[uint8]) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + contents0, contents1 := cm.LowerList(contents) + wasmimport_OutputStreamWrite((uint32)(self0), (*uint8)(contents0), (uint32)(contents1), &result) + return +} + +// WriteZeroes represents the imported method "write-zeroes". +// +// Write zeroes to a stream. +// +// This should be used precisely like `write` with the exact same +// preconditions (must use check-write first), but instead of +// passing a list of bytes, you simply pass the number of zero-bytes +// that should be written. +// +// write-zeroes: func(len: u64) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) WriteZeroes(len_ uint64) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_OutputStreamWriteZeroes((uint32)(self0), (uint64)(len0), &result) + return +} diff --git a/x/wasihttp/internal/wasi/random/insecure-seed/empty.s b/x/wasihttp/internal/wasi/random/insecure-seed/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/random/insecure-seed/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go b/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go new file mode 100755 index 00000000..e94356df --- /dev/null +++ b/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package insecureseed + +// This file contains wasmimport and wasmexport declarations for "wasi:random@0.2.0". + +//go:wasmimport wasi:random/insecure-seed@0.2.0 insecure-seed +//go:noescape +func wasmimport_InsecureSeed(result *[2]uint64) diff --git a/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go b/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go new file mode 100755 index 00000000..6f363673 --- /dev/null +++ b/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go @@ -0,0 +1,37 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package insecureseed represents the imported interface "wasi:random/insecure-seed@0.2.0". +// +// The insecure-seed interface for seeding hash-map DoS resistance. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +package insecureseed + +// InsecureSeed represents the imported function "insecure-seed". +// +// Return a 128-bit value that may contain a pseudo-random value. +// +// The returned value is not required to be computed from a CSPRNG, and may +// even be entirely deterministic. Host implementations are encouraged to +// provide pseudo-random values to any program exposed to +// attacker-controlled content, to enable DoS protection built into many +// languages' hash-map implementations. +// +// This function is intended to only be called once, by a source language +// to initialize Denial Of Service (DoS) protection in its hash-map +// implementation. +// +// # Expected future evolution +// +// This will likely be changed to a value import, to prevent it from being +// called multiple times and potentially used for purposes other than DoS +// protection. +// +// insecure-seed: func() -> tuple +// +//go:nosplit +func InsecureSeed() (result [2]uint64) { + wasmimport_InsecureSeed(&result) + return +} diff --git a/x/wasihttp/internal/wasi/random/insecure/empty.s b/x/wasihttp/internal/wasi/random/insecure/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/random/insecure/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go b/x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go new file mode 100755 index 00000000..498bfe4a --- /dev/null +++ b/x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go @@ -0,0 +1,17 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package insecure + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:random@0.2.0". + +//go:wasmimport wasi:random/insecure@0.2.0 get-insecure-random-bytes +//go:noescape +func wasmimport_GetInsecureRandomBytes(len0 uint64, result *cm.List[uint8]) + +//go:wasmimport wasi:random/insecure@0.2.0 get-insecure-random-u64 +//go:noescape +func wasmimport_GetInsecureRandomU64() (result0 uint64) diff --git a/x/wasihttp/internal/wasi/random/insecure/insecure.wit.go b/x/wasihttp/internal/wasi/random/insecure/insecure.wit.go new file mode 100755 index 00000000..295a1ada --- /dev/null +++ b/x/wasihttp/internal/wasi/random/insecure/insecure.wit.go @@ -0,0 +1,49 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package insecure represents the imported interface "wasi:random/insecure@0.2.0". +// +// The insecure interface for insecure pseudo-random numbers. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +package insecure + +import ( + "go.bytecodealliance.org/cm" +) + +// GetInsecureRandomBytes represents the imported function "get-insecure-random-bytes". +// +// Return `len` insecure pseudo-random bytes. +// +// This function is not cryptographically secure. Do not use it for +// anything related to security. +// +// There are no requirements on the values of the returned bytes, however +// implementations are encouraged to return evenly distributed values with +// a long period. +// +// get-insecure-random-bytes: func(len: u64) -> list +// +//go:nosplit +func GetInsecureRandomBytes(len_ uint64) (result cm.List[uint8]) { + len0 := (uint64)(len_) + wasmimport_GetInsecureRandomBytes((uint64)(len0), &result) + return +} + +// GetInsecureRandomU64 represents the imported function "get-insecure-random-u64". +// +// Return an insecure pseudo-random `u64` value. +// +// This function returns the same type of pseudo-random data as +// `get-insecure-random-bytes`, represented as a `u64`. +// +// get-insecure-random-u64: func() -> u64 +// +//go:nosplit +func GetInsecureRandomU64() (result uint64) { + result0 := wasmimport_GetInsecureRandomU64() + result = (uint64)((uint64)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/random/random/empty.s b/x/wasihttp/internal/wasi/random/random/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/random/random/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/random/random/random.wasm.go b/x/wasihttp/internal/wasi/random/random/random.wasm.go new file mode 100755 index 00000000..9096457b --- /dev/null +++ b/x/wasihttp/internal/wasi/random/random/random.wasm.go @@ -0,0 +1,17 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package random + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:random@0.2.0". + +//go:wasmimport wasi:random/random@0.2.0 get-random-bytes +//go:noescape +func wasmimport_GetRandomBytes(len0 uint64, result *cm.List[uint8]) + +//go:wasmimport wasi:random/random@0.2.0 get-random-u64 +//go:noescape +func wasmimport_GetRandomU64() (result0 uint64) diff --git a/x/wasihttp/internal/wasi/random/random/random.wit.go b/x/wasihttp/internal/wasi/random/random/random.wit.go new file mode 100755 index 00000000..bb90e7e0 --- /dev/null +++ b/x/wasihttp/internal/wasi/random/random/random.wit.go @@ -0,0 +1,53 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package random represents the imported interface "wasi:random/random@0.2.0". +// +// WASI Random is a random data API. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +package random + +import ( + "go.bytecodealliance.org/cm" +) + +// GetRandomBytes represents the imported function "get-random-bytes". +// +// Return `len` cryptographically-secure random or pseudo-random bytes. +// +// This function must produce data at least as cryptographically secure and +// fast as an adequately seeded cryptographically-secure pseudo-random +// number generator (CSPRNG). It must not block, from the perspective of +// the calling program, under any circumstances, including on the first +// request and on requests for numbers of bytes. The returned data must +// always be unpredictable. +// +// This function must always return fresh data. Deterministic environments +// must omit this function, rather than implementing it with deterministic +// data. +// +// get-random-bytes: func(len: u64) -> list +// +//go:nosplit +func GetRandomBytes(len_ uint64) (result cm.List[uint8]) { + len0 := (uint64)(len_) + wasmimport_GetRandomBytes((uint64)(len0), &result) + return +} + +// GetRandomU64 represents the imported function "get-random-u64". +// +// Return a cryptographically-secure random or pseudo-random `u64` value. +// +// This function returns the same type of data as `get-random-bytes`, +// represented as a `u64`. +// +// get-random-u64: func() -> u64 +// +//go:nosplit +func GetRandomU64() (result uint64) { + result0 := wasmimport_GetRandomU64() + result = (uint64)((uint64)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/sockets/instance-network/empty.s b/x/wasihttp/internal/wasi/sockets/instance-network/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/instance-network/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go b/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go new file mode 100755 index 00000000..eb113e21 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package instancenetwork + +// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". + +//go:wasmimport wasi:sockets/instance-network@0.2.0 instance-network +//go:noescape +func wasmimport_InstanceNetwork() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go b/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go new file mode 100755 index 00000000..b121bba8 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go @@ -0,0 +1,29 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package instancenetwork represents the imported interface "wasi:sockets/instance-network@0.2.0". +// +// This interface provides a value-export of the default network handle.. +package instancenetwork + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" +) + +// Network represents the imported type alias "wasi:sockets/instance-network@0.2.0#network". +// +// See [network.Network] for more information. +type Network = network.Network + +// InstanceNetwork represents the imported function "instance-network". +// +// Get a handle to the default network. +// +// instance-network: func() -> network +// +//go:nosplit +func InstanceNetwork() (result Network) { + result0 := wasmimport_InstanceNetwork() + result = cm.Reinterpret[Network]((uint32)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go new file mode 100755 index 00000000..a63f0d01 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go @@ -0,0 +1,14 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package ipnamelookup + +import ( + "go.bytecodealliance.org/cm" + "unsafe" +) + +// OptionIPAddressShape is used for storage in variant or result types. +type OptionIPAddressShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(cm.Option[IPAddress]{})]byte +} diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go new file mode 100755 index 00000000..da5fb000 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package ipnamelookup + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [resource-drop]resolve-address-stream +//go:noescape +func wasmimport_ResolveAddressStreamResourceDrop(self0 uint32) + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [method]resolve-address-stream.resolve-next-address +//go:noescape +func wasmimport_ResolveAddressStreamResolveNextAddress(self0 uint32, result *cm.Result[OptionIPAddressShape, cm.Option[IPAddress], ErrorCode]) + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [method]resolve-address-stream.subscribe +//go:noescape +func wasmimport_ResolveAddressStreamSubscribe(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 resolve-addresses +//go:noescape +func wasmimport_ResolveAddresses(network0 uint32, name0 *uint8, name1 uint32, result *cm.Result[ResolveAddressStream, ResolveAddressStream, ErrorCode]) diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go new file mode 100755 index 00000000..75850950 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go @@ -0,0 +1,125 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package ipnamelookup represents the imported interface "wasi:sockets/ip-name-lookup@0.2.0". +package ipnamelookup + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" +) + +// Pollable represents the imported type alias "wasi:sockets/ip-name-lookup@0.2.0#pollable". +// +// See [poll.Pollable] for more information. +type Pollable = poll.Pollable + +// Network represents the imported type alias "wasi:sockets/ip-name-lookup@0.2.0#network". +// +// See [network.Network] for more information. +type Network = network.Network + +// ErrorCode represents the type alias "wasi:sockets/ip-name-lookup@0.2.0#error-code". +// +// See [network.ErrorCode] for more information. +type ErrorCode = network.ErrorCode + +// IPAddress represents the type alias "wasi:sockets/ip-name-lookup@0.2.0#ip-address". +// +// See [network.IPAddress] for more information. +type IPAddress = network.IPAddress + +// ResolveAddressStream represents the imported resource "wasi:sockets/ip-name-lookup@0.2.0#resolve-address-stream". +// +// resource resolve-address-stream +type ResolveAddressStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "resolve-address-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self ResolveAddressStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ResolveAddressStreamResourceDrop((uint32)(self0)) + return +} + +// ResolveNextAddress represents the imported method "resolve-next-address". +// +// Returns the next address from the resolver. +// +// This function should be called multiple times. On each call, it will +// return the next address in connection order preference. If all +// addresses have been exhausted, this function returns `none`. +// +// This function never returns IPv4-mapped IPv6 addresses. +// +// # Typical errors +// - `name-unresolvable`: Name does not exist or has no suitable associated +// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) +// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. +// (EAI_AGAIN) +// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. +// (EAI_FAIL) +// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) +// +// resolve-next-address: func() -> result, error-code> +// +//go:nosplit +func (self ResolveAddressStream) ResolveNextAddress() (result cm.Result[OptionIPAddressShape, cm.Option[IPAddress], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ResolveAddressStreamResolveNextAddress((uint32)(self0), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the stream is ready for I/O. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self ResolveAddressStream) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_ResolveAddressStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// ResolveAddresses represents the imported function "resolve-addresses". +// +// Resolve an internet host name to a list of IP addresses. +// +// Unicode domain names are automatically converted to ASCII using IDNA encoding. +// If the input is an IP address string, the address is parsed and returned +// as-is without making any external requests. +// +// See the wasi-socket proposal README.md for a comparison with getaddrinfo. +// +// This function never blocks. It either immediately fails or immediately +// returns successfully with a `resolve-address-stream` that can be used +// to (asynchronously) fetch the results. +// +// # Typical errors +// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. +// +// # References: +// - +// - +// - +// - +// +// resolve-addresses: func(network: borrow, name: string) -> result +// +//go:nosplit +func ResolveAddresses(network_ Network, name string) (result cm.Result[ResolveAddressStream, ResolveAddressStream, ErrorCode]) { + network0 := cm.Reinterpret[uint32](network_) + name0, name1 := cm.LowerString(name) + wasmimport_ResolveAddresses((uint32)(network0), (*uint8)(name0), (uint32)(name1), &result) + return +} diff --git a/x/wasihttp/internal/wasi/sockets/network/abi.go b/x/wasihttp/internal/wasi/sockets/network/abi.go new file mode 100755 index 00000000..a088bd1d --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/network/abi.go @@ -0,0 +1,14 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package network + +import ( + "go.bytecodealliance.org/cm" + "unsafe" +) + +// IPv6SocketAddressShape is used for storage in variant or result types. +type IPv6SocketAddressShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(IPv6SocketAddress{})]byte +} diff --git a/x/wasihttp/internal/wasi/sockets/network/empty.s b/x/wasihttp/internal/wasi/sockets/network/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/network/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/network/network.wasm.go b/x/wasihttp/internal/wasi/sockets/network/network.wasm.go new file mode 100755 index 00000000..012a79ff --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/network/network.wasm.go @@ -0,0 +1,9 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package network + +// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". + +//go:wasmimport wasi:sockets/network@0.2.0 [resource-drop]network +//go:noescape +func wasmimport_NetworkResourceDrop(self0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/network/network.wit.go b/x/wasihttp/internal/wasi/sockets/network/network.wit.go new file mode 100755 index 00000000..a37b5b9a --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/network/network.wit.go @@ -0,0 +1,359 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package network represents the imported interface "wasi:sockets/network@0.2.0". +package network + +import ( + "go.bytecodealliance.org/cm" +) + +// Network represents the imported resource "wasi:sockets/network@0.2.0#network". +// +// An opaque resource that represents access to (a subset of) the network. +// This enables context-based security for networking. +// There is no need for this to map 1:1 to a physical network interface. +// +// resource network +type Network cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "network". +// +// Drops a resource handle. +// +//go:nosplit +func (self Network) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_NetworkResourceDrop((uint32)(self0)) + return +} + +// ErrorCode represents the enum "wasi:sockets/network@0.2.0#error-code". +// +// Error codes. +// +// In theory, every API can return any error code. +// In practice, API's typically only return the errors documented per API +// combined with a couple of errors that are always possible: +// - `unknown` +// - `access-denied` +// - `not-supported` +// - `out-of-memory` +// - `concurrency-conflict` +// +// See each individual API for what the POSIX equivalents are. They sometimes differ +// per API. +// +// enum error-code { +// unknown, +// access-denied, +// not-supported, +// invalid-argument, +// out-of-memory, +// timeout, +// concurrency-conflict, +// not-in-progress, +// would-block, +// invalid-state, +// new-socket-limit, +// address-not-bindable, +// address-in-use, +// remote-unreachable, +// connection-refused, +// connection-reset, +// connection-aborted, +// datagram-too-large, +// name-unresolvable, +// temporary-resolver-failure, +// permanent-resolver-failure +// } +type ErrorCode uint8 + +const ( + // Unknown error + ErrorCodeUnknown ErrorCode = iota + + // Access denied. + // + // POSIX equivalent: EACCES, EPERM + ErrorCodeAccessDenied + + // The operation is not supported. + // + // POSIX equivalent: EOPNOTSUPP + ErrorCodeNotSupported + + // One of the arguments is invalid. + // + // POSIX equivalent: EINVAL + ErrorCodeInvalidArgument + + // Not enough memory to complete the operation. + // + // POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + ErrorCodeOutOfMemory + + // The operation timed out before it could finish completely. + ErrorCodeTimeout + + // This operation is incompatible with another asynchronous operation that is already + // in progress. + // + // POSIX equivalent: EALREADY + ErrorCodeConcurrencyConflict + + // Trying to finish an asynchronous operation that: + // - has not been started yet, or: + // - was already finished by a previous `finish-*` call. + // + // Note: this is scheduled to be removed when `future`s are natively supported. + ErrorCodeNotInProgress + + // The operation has been aborted because it could not be completed immediately. + // + // Note: this is scheduled to be removed when `future`s are natively supported. + ErrorCodeWouldBlock + + // The operation is not valid in the socket's current state. + ErrorCodeInvalidState + + // A new socket resource could not be created because of a system limit. + ErrorCodeNewSocketLimit + + // A bind operation failed because the provided address is not an address that the + // `network` can bind to. + ErrorCodeAddressNotBindable + + // A bind operation failed because the provided address is already in use or because + // there are no ephemeral ports available. + ErrorCodeAddressInUse + + // The remote address is not reachable + ErrorCodeRemoteUnreachable + + // The TCP connection was forcefully rejected + ErrorCodeConnectionRefused + + // The TCP connection was reset. + ErrorCodeConnectionReset + + // A TCP connection was aborted. + ErrorCodeConnectionAborted + + // The size of a datagram sent to a UDP socket exceeded the maximum + // supported size. + ErrorCodeDatagramTooLarge + + // Name does not exist or has no suitable associated IP addresses. + ErrorCodeNameUnresolvable + + // A temporary failure in name resolution occurred. + ErrorCodeTemporaryResolverFailure + + // A permanent failure in name resolution occurred. + ErrorCodePermanentResolverFailure +) + +var _ErrorCodeStrings = [21]string{ + "unknown", + "access-denied", + "not-supported", + "invalid-argument", + "out-of-memory", + "timeout", + "concurrency-conflict", + "not-in-progress", + "would-block", + "invalid-state", + "new-socket-limit", + "address-not-bindable", + "address-in-use", + "remote-unreachable", + "connection-refused", + "connection-reset", + "connection-aborted", + "datagram-too-large", + "name-unresolvable", + "temporary-resolver-failure", + "permanent-resolver-failure", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e ErrorCode) String() string { + return _ErrorCodeStrings[e] +} + +// MarshalText implements [encoding.TextMarshaler]. +func (e ErrorCode) MarshalText() ([]byte, error) { + return []byte(e.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum +// case. Returns an error if the supplied text is not one of the enum cases. +func (e *ErrorCode) UnmarshalText(text []byte) error { + return _ErrorCodeUnmarshalCase(e, text) +} + +var _ErrorCodeUnmarshalCase = cm.CaseUnmarshaler[ErrorCode](_ErrorCodeStrings[:]) + +// IPAddressFamily represents the enum "wasi:sockets/network@0.2.0#ip-address-family". +// +// enum ip-address-family { +// ipv4, +// ipv6 +// } +type IPAddressFamily uint8 + +const ( + // Similar to `AF_INET` in POSIX. + IPAddressFamilyIPv4 IPAddressFamily = iota + + // Similar to `AF_INET6` in POSIX. + IPAddressFamilyIPv6 +) + +var _IPAddressFamilyStrings = [2]string{ + "ipv4", + "ipv6", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e IPAddressFamily) String() string { + return _IPAddressFamilyStrings[e] +} + +// MarshalText implements [encoding.TextMarshaler]. +func (e IPAddressFamily) MarshalText() ([]byte, error) { + return []byte(e.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum +// case. Returns an error if the supplied text is not one of the enum cases. +func (e *IPAddressFamily) UnmarshalText(text []byte) error { + return _IPAddressFamilyUnmarshalCase(e, text) +} + +var _IPAddressFamilyUnmarshalCase = cm.CaseUnmarshaler[IPAddressFamily](_IPAddressFamilyStrings[:]) + +// IPv4Address represents the tuple "wasi:sockets/network@0.2.0#ipv4-address". +// +// type ipv4-address = tuple +type IPv4Address [4]uint8 + +// IPv6Address represents the tuple "wasi:sockets/network@0.2.0#ipv6-address". +// +// type ipv6-address = tuple +type IPv6Address [8]uint16 + +// IPAddress represents the variant "wasi:sockets/network@0.2.0#ip-address". +// +// variant ip-address { +// ipv4(ipv4-address), +// ipv6(ipv6-address), +// } +type IPAddress cm.Variant[uint8, IPv6Address, IPv6Address] + +// IPAddressIPv4 returns a [IPAddress] of case "ipv4". +func IPAddressIPv4(data IPv4Address) IPAddress { + return cm.New[IPAddress](0, data) +} + +// IPv4 returns a non-nil *[IPv4Address] if [IPAddress] represents the variant case "ipv4". +func (self *IPAddress) IPv4() *IPv4Address { + return cm.Case[IPv4Address](self, 0) +} + +// IPAddressIPv6 returns a [IPAddress] of case "ipv6". +func IPAddressIPv6(data IPv6Address) IPAddress { + return cm.New[IPAddress](1, data) +} + +// IPv6 returns a non-nil *[IPv6Address] if [IPAddress] represents the variant case "ipv6". +func (self *IPAddress) IPv6() *IPv6Address { + return cm.Case[IPv6Address](self, 1) +} + +var _IPAddressStrings = [2]string{ + "ipv4", + "ipv6", +} + +// String implements [fmt.Stringer], returning the variant case name of v. +func (v IPAddress) String() string { + return _IPAddressStrings[v.Tag()] +} + +// IPv4SocketAddress represents the record "wasi:sockets/network@0.2.0#ipv4-socket-address". +// +// record ipv4-socket-address { +// port: u16, +// address: ipv4-address, +// } +type IPv4SocketAddress struct { + _ cm.HostLayout `json:"-"` + // sin_port + Port uint16 `json:"port"` + + // sin_addr + Address IPv4Address `json:"address"` +} + +// IPv6SocketAddress represents the record "wasi:sockets/network@0.2.0#ipv6-socket-address". +// +// record ipv6-socket-address { +// port: u16, +// flow-info: u32, +// address: ipv6-address, +// scope-id: u32, +// } +type IPv6SocketAddress struct { + _ cm.HostLayout `json:"-"` + // sin6_port + Port uint16 `json:"port"` + + // sin6_flowinfo + FlowInfo uint32 `json:"flow-info"` + + // sin6_addr + Address IPv6Address `json:"address"` + + // sin6_scope_id + ScopeID uint32 `json:"scope-id"` +} + +// IPSocketAddress represents the variant "wasi:sockets/network@0.2.0#ip-socket-address". +// +// variant ip-socket-address { +// ipv4(ipv4-socket-address), +// ipv6(ipv6-socket-address), +// } +type IPSocketAddress cm.Variant[uint8, IPv6SocketAddressShape, IPv6SocketAddress] + +// IPSocketAddressIPv4 returns a [IPSocketAddress] of case "ipv4". +func IPSocketAddressIPv4(data IPv4SocketAddress) IPSocketAddress { + return cm.New[IPSocketAddress](0, data) +} + +// IPv4 returns a non-nil *[IPv4SocketAddress] if [IPSocketAddress] represents the variant case "ipv4". +func (self *IPSocketAddress) IPv4() *IPv4SocketAddress { + return cm.Case[IPv4SocketAddress](self, 0) +} + +// IPSocketAddressIPv6 returns a [IPSocketAddress] of case "ipv6". +func IPSocketAddressIPv6(data IPv6SocketAddress) IPSocketAddress { + return cm.New[IPSocketAddress](1, data) +} + +// IPv6 returns a non-nil *[IPv6SocketAddress] if [IPSocketAddress] represents the variant case "ipv6". +func (self *IPSocketAddress) IPv6() *IPv6SocketAddress { + return cm.Case[IPv6SocketAddress](self, 1) +} + +var _IPSocketAddressStrings = [2]string{ + "ipv4", + "ipv6", +} + +// String implements [fmt.Stringer], returning the variant case name of v. +func (v IPSocketAddress) String() string { + return _IPSocketAddressStrings[v.Tag()] +} diff --git a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go new file mode 100755 index 00000000..b7b43155 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package tcpcreatesocket + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". + +//go:wasmimport wasi:sockets/tcp-create-socket@0.2.0 create-tcp-socket +//go:noescape +func wasmimport_CreateTCPSocket(addressFamily0 uint32, result *cm.Result[TCPSocket, TCPSocket, ErrorCode]) diff --git a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go new file mode 100755 index 00000000..b4becffe --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go @@ -0,0 +1,68 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package tcpcreatesocket represents the imported interface "wasi:sockets/tcp-create-socket@0.2.0". +package tcpcreatesocket + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/tcp" +) + +// Network represents the imported type alias "wasi:sockets/tcp-create-socket@0.2.0#network". +// +// See [network.Network] for more information. +type Network = network.Network + +// ErrorCode represents the type alias "wasi:sockets/tcp-create-socket@0.2.0#error-code". +// +// See [network.ErrorCode] for more information. +type ErrorCode = network.ErrorCode + +// IPAddressFamily represents the type alias "wasi:sockets/tcp-create-socket@0.2.0#ip-address-family". +// +// See [network.IPAddressFamily] for more information. +type IPAddressFamily = network.IPAddressFamily + +// TCPSocket represents the imported type alias "wasi:sockets/tcp-create-socket@0.2.0#tcp-socket". +// +// See [tcp.TCPSocket] for more information. +type TCPSocket = tcp.TCPSocket + +// CreateTCPSocket represents the imported function "create-tcp-socket". +// +// Create a new TCP socket. +// +// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. +// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. +// +// This function does not require a network capability handle. This is considered +// to be safe because +// at time of creation, the socket is not bound to any `network` yet. Up to the moment +// `bind`/`connect` +// is called, the socket is effectively an in-memory configuration object, unable +// to communicate with the outside world. +// +// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous +// operations. +// +// # Typical errors +// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) +// - `new-socket-limit`: The new socket resource could not be created because of +// a system limit. (EMFILE, ENFILE) +// +// # References +// - +// - +// - +// - +// +// create-tcp-socket: func(address-family: ip-address-family) -> result +// +//go:nosplit +func CreateTCPSocket(addressFamily IPAddressFamily) (result cm.Result[TCPSocket, TCPSocket, ErrorCode]) { + addressFamily0 := (uint32)(addressFamily) + wasmimport_CreateTCPSocket((uint32)(addressFamily0), &result) + return +} diff --git a/x/wasihttp/internal/wasi/sockets/tcp/abi.go b/x/wasihttp/internal/wasi/sockets/tcp/abi.go new file mode 100755 index 00000000..e8e14e07 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/tcp/abi.go @@ -0,0 +1,88 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package tcp + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" + "unsafe" +) + +// TupleTCPSocketInputStreamOutputStreamShape is used for storage in variant or result types. +type TupleTCPSocketInputStreamOutputStreamShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(cm.Tuple3[TCPSocket, InputStream, OutputStream]{})]byte +} + +// TupleInputStreamOutputStreamShape is used for storage in variant or result types. +type TupleInputStreamOutputStreamShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(cm.Tuple[InputStream, OutputStream]{})]byte +} + +// IPSocketAddressShape is used for storage in variant or result types. +type IPSocketAddressShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(IPSocketAddress{})]byte +} + +func lower_IPv4Address(v network.IPv4Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + return +} + +func lower_IPv4SocketAddress(v network.IPv4SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32) { + f0 = (uint32)(v.Port) + f1, f2, f3, f4 = lower_IPv4Address(v.Address) + return +} + +func lower_IPv6Address(v network.IPv6Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + f4 = (uint32)(v[4]) + f5 = (uint32)(v[5]) + f6 = (uint32)(v[6]) + f7 = (uint32)(v[7]) + return +} + +func lower_IPv6SocketAddress(v network.IPv6SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32) { + f0 = (uint32)(v.Port) + f1 = (uint32)(v.FlowInfo) + f2, f3, f4, f5, f6, f7, f8, f9 = lower_IPv6Address(v.Address) + f10 = (uint32)(v.ScopeID) + return +} + +func lower_IPSocketAddress(v network.IPSocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 0: // ipv4 + v1, v2, v3, v4, v5 := lower_IPv4SocketAddress(*cm.Case[network.IPv4SocketAddress](&v, 0)) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 1: // ipv6 + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 := lower_IPv6SocketAddress(*cm.Case[network.IPv6SocketAddress](&v, 1)) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + f8 = (uint32)(v8) + f9 = (uint32)(v9) + f10 = (uint32)(v10) + f11 = (uint32)(v11) + } + return +} diff --git a/x/wasihttp/internal/wasi/sockets/tcp/empty.s b/x/wasihttp/internal/wasi/sockets/tcp/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/tcp/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go b/x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go new file mode 100755 index 00000000..d6e56c26 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go @@ -0,0 +1,125 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package tcp + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". + +//go:wasmimport wasi:sockets/tcp@0.2.0 [resource-drop]tcp-socket +//go:noescape +func wasmimport_TCPSocketResourceDrop(self0 uint32) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.accept +//go:noescape +func wasmimport_TCPSocketAccept(self0 uint32, result *cm.Result[TupleTCPSocketInputStreamOutputStreamShape, cm.Tuple3[TCPSocket, InputStream, OutputStream], ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.address-family +//go:noescape +func wasmimport_TCPSocketAddressFamily(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-bind +//go:noescape +func wasmimport_TCPSocketFinishBind(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-connect +//go:noescape +func wasmimport_TCPSocketFinishConnect(self0 uint32, result *cm.Result[TupleInputStreamOutputStreamShape, cm.Tuple[InputStream, OutputStream], ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-listen +//go:noescape +func wasmimport_TCPSocketFinishListen(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.hop-limit +//go:noescape +func wasmimport_TCPSocketHopLimit(self0 uint32, result *cm.Result[uint8, uint8, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.is-listening +//go:noescape +func wasmimport_TCPSocketIsListening(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-count +//go:noescape +func wasmimport_TCPSocketKeepAliveCount(self0 uint32, result *cm.Result[uint32, uint32, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-enabled +//go:noescape +func wasmimport_TCPSocketKeepAliveEnabled(self0 uint32, result *cm.Result[ErrorCode, bool, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-idle-time +//go:noescape +func wasmimport_TCPSocketKeepAliveIdleTime(self0 uint32, result *cm.Result[uint64, Duration, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-interval +//go:noescape +func wasmimport_TCPSocketKeepAliveInterval(self0 uint32, result *cm.Result[uint64, Duration, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.local-address +//go:noescape +func wasmimport_TCPSocketLocalAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.receive-buffer-size +//go:noescape +func wasmimport_TCPSocketReceiveBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.remote-address +//go:noescape +func wasmimport_TCPSocketRemoteAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.send-buffer-size +//go:noescape +func wasmimport_TCPSocketSendBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-hop-limit +//go:noescape +func wasmimport_TCPSocketSetHopLimit(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-count +//go:noescape +func wasmimport_TCPSocketSetKeepAliveCount(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-enabled +//go:noescape +func wasmimport_TCPSocketSetKeepAliveEnabled(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-idle-time +//go:noescape +func wasmimport_TCPSocketSetKeepAliveIdleTime(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-interval +//go:noescape +func wasmimport_TCPSocketSetKeepAliveInterval(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-listen-backlog-size +//go:noescape +func wasmimport_TCPSocketSetListenBacklogSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-receive-buffer-size +//go:noescape +func wasmimport_TCPSocketSetReceiveBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-send-buffer-size +//go:noescape +func wasmimport_TCPSocketSetSendBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.shutdown +//go:noescape +func wasmimport_TCPSocketShutdown(self0 uint32, shutdownType0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-bind +//go:noescape +func wasmimport_TCPSocketStartBind(self0 uint32, network0 uint32, localAddress0 uint32, localAddress1 uint32, localAddress2 uint32, localAddress3 uint32, localAddress4 uint32, localAddress5 uint32, localAddress6 uint32, localAddress7 uint32, localAddress8 uint32, localAddress9 uint32, localAddress10 uint32, localAddress11 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-connect +//go:noescape +func wasmimport_TCPSocketStartConnect(self0 uint32, network0 uint32, remoteAddress0 uint32, remoteAddress1 uint32, remoteAddress2 uint32, remoteAddress3 uint32, remoteAddress4 uint32, remoteAddress5 uint32, remoteAddress6 uint32, remoteAddress7 uint32, remoteAddress8 uint32, remoteAddress9 uint32, remoteAddress10 uint32, remoteAddress11 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-listen +//go:noescape +func wasmimport_TCPSocketStartListen(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.subscribe +//go:noescape +func wasmimport_TCPSocketSubscribe(self0 uint32) (result0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go b/x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go new file mode 100755 index 00000000..99c9fe6b --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go @@ -0,0 +1,785 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package tcp represents the imported interface "wasi:sockets/tcp@0.2.0". +package tcp + +import ( + "go.bytecodealliance.org/cm" + monotonicclock "go.bytecodealliance.org/x/wasihttp/internal/wasi/clocks/monotonic-clock" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" +) + +// InputStream represents the imported type alias "wasi:sockets/tcp@0.2.0#input-stream". +// +// See [streams.InputStream] for more information. +type InputStream = streams.InputStream + +// OutputStream represents the imported type alias "wasi:sockets/tcp@0.2.0#output-stream". +// +// See [streams.OutputStream] for more information. +type OutputStream = streams.OutputStream + +// Pollable represents the imported type alias "wasi:sockets/tcp@0.2.0#pollable". +// +// See [poll.Pollable] for more information. +type Pollable = poll.Pollable + +// Duration represents the type alias "wasi:sockets/tcp@0.2.0#duration". +// +// See [monotonicclock.Duration] for more information. +type Duration = monotonicclock.Duration + +// Network represents the imported type alias "wasi:sockets/tcp@0.2.0#network". +// +// See [network.Network] for more information. +type Network = network.Network + +// ErrorCode represents the type alias "wasi:sockets/tcp@0.2.0#error-code". +// +// See [network.ErrorCode] for more information. +type ErrorCode = network.ErrorCode + +// IPSocketAddress represents the type alias "wasi:sockets/tcp@0.2.0#ip-socket-address". +// +// See [network.IPSocketAddress] for more information. +type IPSocketAddress = network.IPSocketAddress + +// IPAddressFamily represents the type alias "wasi:sockets/tcp@0.2.0#ip-address-family". +// +// See [network.IPAddressFamily] for more information. +type IPAddressFamily = network.IPAddressFamily + +// ShutdownType represents the enum "wasi:sockets/tcp@0.2.0#shutdown-type". +// +// enum shutdown-type { +// receive, +// send, +// both +// } +type ShutdownType uint8 + +const ( + // Similar to `SHUT_RD` in POSIX. + ShutdownTypeReceive ShutdownType = iota + + // Similar to `SHUT_WR` in POSIX. + ShutdownTypeSend + + // Similar to `SHUT_RDWR` in POSIX. + ShutdownTypeBoth +) + +var _ShutdownTypeStrings = [3]string{ + "receive", + "send", + "both", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e ShutdownType) String() string { + return _ShutdownTypeStrings[e] +} + +// MarshalText implements [encoding.TextMarshaler]. +func (e ShutdownType) MarshalText() ([]byte, error) { + return []byte(e.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum +// case. Returns an error if the supplied text is not one of the enum cases. +func (e *ShutdownType) UnmarshalText(text []byte) error { + return _ShutdownTypeUnmarshalCase(e, text) +} + +var _ShutdownTypeUnmarshalCase = cm.CaseUnmarshaler[ShutdownType](_ShutdownTypeStrings[:]) + +// TCPSocket represents the imported resource "wasi:sockets/tcp@0.2.0#tcp-socket". +// +// A TCP socket resource. +// +// The socket can be in one of the following states: +// - `unbound` +// - `bind-in-progress` +// - `bound` (See note below) +// - `listen-in-progress` +// - `listening` +// - `connect-in-progress` +// - `connected` +// - `closed` +// See +// for a more information. +// +// Note: Except where explicitly mentioned, whenever this documentation uses +// the term "bound" without backticks it actually means: in the `bound` state *or +// higher*. +// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) +// +// In addition to the general error codes documented on the +// `network::error-code` type, TCP socket methods may always return +// `error(invalid-state)` when in the `closed` state. +// +// resource tcp-socket +type TCPSocket cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "tcp-socket". +// +// Drops a resource handle. +// +//go:nosplit +func (self TCPSocket) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketResourceDrop((uint32)(self0)) + return +} + +// Accept represents the imported method "accept". +// +// Accept a new client socket. +// +// The returned socket is bound and in the `connected` state. The following properties +// are inherited from the listener socket: +// - `address-family` +// - `keep-alive-enabled` +// - `keep-alive-idle-time` +// - `keep-alive-interval` +// - `keep-alive-count` +// - `hop-limit` +// - `receive-buffer-size` +// - `send-buffer-size` +// +// On success, this function returns the newly accepted client socket along with +// a pair of streams that can be used to read & write to the connection. +// +// # Typical errors +// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) +// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) +// - `connection-aborted`: An incoming connection was pending, but was terminated +// by the client before this listener could accept it. (ECONNABORTED) +// - `new-socket-limit`: The new socket resource could not be created because of +// a system limit. (EMFILE, ENFILE) +// +// # References +// - +// - +// - +// - +// +// accept: func() -> result, error-code> +// +//go:nosplit +func (self TCPSocket) Accept() (result cm.Result[TupleTCPSocketInputStreamOutputStreamShape, cm.Tuple3[TCPSocket, InputStream, OutputStream], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketAccept((uint32)(self0), &result) + return +} + +// AddressFamily represents the imported method "address-family". +// +// Whether this is a IPv4 or IPv6 socket. +// +// Equivalent to the SO_DOMAIN socket option. +// +// address-family: func() -> ip-address-family +// +//go:nosplit +func (self TCPSocket) AddressFamily() (result IPAddressFamily) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_TCPSocketAddressFamily((uint32)(self0)) + result = (network.IPAddressFamily)((uint32)(result0)) + return +} + +// FinishBind represents the imported method "finish-bind". +// +// finish-bind: func() -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) FinishBind() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketFinishBind((uint32)(self0), &result) + return +} + +// FinishConnect represents the imported method "finish-connect". +// +// finish-connect: func() -> result, error-code> +// +//go:nosplit +func (self TCPSocket) FinishConnect() (result cm.Result[TupleInputStreamOutputStreamShape, cm.Tuple[InputStream, OutputStream], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketFinishConnect((uint32)(self0), &result) + return +} + +// FinishListen represents the imported method "finish-listen". +// +// finish-listen: func() -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) FinishListen() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketFinishListen((uint32)(self0), &result) + return +} + +// HopLimit represents the imported method "hop-limit". +// +// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// +// # Typical errors +// - `invalid-argument`: (set) The TTL value must be 1 or higher. +// +// hop-limit: func() -> result +// +//go:nosplit +func (self TCPSocket) HopLimit() (result cm.Result[uint8, uint8, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketHopLimit((uint32)(self0), &result) + return +} + +// IsListening represents the imported method "is-listening". +// +// Whether the socket is in the `listening` state. +// +// Equivalent to the SO_ACCEPTCONN socket option. +// +// is-listening: func() -> bool +// +//go:nosplit +func (self TCPSocket) IsListening() (result bool) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_TCPSocketIsListening((uint32)(self0)) + result = (bool)(cm.U32ToBool((uint32)(result0))) + return +} + +// KeepAliveCount represents the imported method "keep-alive-count". +// +// The maximum amount of keepalive packets TCP should send before aborting the connection. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the TCP_KEEPCNT socket option. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// keep-alive-count: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveCount() (result cm.Result[uint32, uint32, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveCount((uint32)(self0), &result) + return +} + +// KeepAliveEnabled represents the imported method "keep-alive-enabled". +// +// Enables or disables keepalive. +// +// The keepalive behavior can be adjusted using: +// - `keep-alive-idle-time` +// - `keep-alive-interval` +// - `keep-alive-count` +// These properties can be configured while `keep-alive-enabled` is false, but only +// come into effect when `keep-alive-enabled` is true. +// +// Equivalent to the SO_KEEPALIVE socket option. +// +// keep-alive-enabled: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveEnabled() (result cm.Result[ErrorCode, bool, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveEnabled((uint32)(self0), &result) + return +} + +// KeepAliveIdleTime represents the imported method "keep-alive-idle-time". +// +// Amount of time the connection has to be idle before TCP starts sending keepalive +// packets. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// keep-alive-idle-time: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveIdleTime() (result cm.Result[uint64, Duration, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveIdleTime((uint32)(self0), &result) + return +} + +// KeepAliveInterval represents the imported method "keep-alive-interval". +// +// The time between keepalive packets. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the TCP_KEEPINTVL socket option. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// keep-alive-interval: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveInterval() (result cm.Result[uint64, Duration, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveInterval((uint32)(self0), &result) + return +} + +// LocalAddress represents the imported method "local-address". +// +// Get the bound local address. +// +// POSIX mentions: +// > If the socket has not been bound to a local name, the value +// > stored in the object pointed to by `address` is unspecified. +// +// WASI is stricter and requires `local-address` to return `invalid-state` when the +// socket hasn't been bound yet. +// +// # Typical errors +// - `invalid-state`: The socket is not bound to any local address. +// +// # References +// - +// - +// - +// - +// +// local-address: func() -> result +// +//go:nosplit +func (self TCPSocket) LocalAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketLocalAddress((uint32)(self0), &result) + return +} + +// ReceiveBufferSize represents the imported method "receive-buffer-size". +// +// The kernel buffer space reserved for sends/receives on this socket. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// receive-buffer-size: func() -> result +// +//go:nosplit +func (self TCPSocket) ReceiveBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketReceiveBufferSize((uint32)(self0), &result) + return +} + +// RemoteAddress represents the imported method "remote-address". +// +// Get the remote address. +// +// # Typical errors +// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) +// +// # References +// - +// - +// - +// - +// +// remote-address: func() -> result +// +//go:nosplit +func (self TCPSocket) RemoteAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketRemoteAddress((uint32)(self0), &result) + return +} + +// SendBufferSize represents the imported method "send-buffer-size". +// +// send-buffer-size: func() -> result +// +//go:nosplit +func (self TCPSocket) SendBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketSendBufferSize((uint32)(self0), &result) + return +} + +// SetHopLimit represents the imported method "set-hop-limit". +// +// set-hop-limit: func(value: u8) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetHopLimit(value uint8) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint32)(value) + wasmimport_TCPSocketSetHopLimit((uint32)(self0), (uint32)(value0), &result) + return +} + +// SetKeepAliveCount represents the imported method "set-keep-alive-count". +// +// set-keep-alive-count: func(value: u32) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveCount(value uint32) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint32)(value) + wasmimport_TCPSocketSetKeepAliveCount((uint32)(self0), (uint32)(value0), &result) + return +} + +// SetKeepAliveEnabled represents the imported method "set-keep-alive-enabled". +// +// set-keep-alive-enabled: func(value: bool) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveEnabled(value bool) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint32)(cm.BoolToU32(value)) + wasmimport_TCPSocketSetKeepAliveEnabled((uint32)(self0), (uint32)(value0), &result) + return +} + +// SetKeepAliveIdleTime represents the imported method "set-keep-alive-idle-time". +// +// set-keep-alive-idle-time: func(value: duration) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveIdleTime(value Duration) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetKeepAliveIdleTime((uint32)(self0), (uint64)(value0), &result) + return +} + +// SetKeepAliveInterval represents the imported method "set-keep-alive-interval". +// +// set-keep-alive-interval: func(value: duration) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveInterval(value Duration) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetKeepAliveInterval((uint32)(self0), (uint64)(value0), &result) + return +} + +// SetListenBacklogSize represents the imported method "set-listen-backlog-size". +// +// Hints the desired listen queue size. Implementations are free to ignore this. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// +// # Typical errors +// - `not-supported`: (set) The platform does not support changing the backlog +// size after the initial listen. +// - `invalid-argument`: (set) The provided value was 0. +// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` +// state. +// +// set-listen-backlog-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetListenBacklogSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetListenBacklogSize((uint32)(self0), (uint64)(value0), &result) + return +} + +// SetReceiveBufferSize represents the imported method "set-receive-buffer-size". +// +// set-receive-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetReceiveBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetReceiveBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +// SetSendBufferSize represents the imported method "set-send-buffer-size". +// +// set-send-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetSendBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetSendBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +// Shutdown represents the imported method "shutdown". +// +// Initiate a graceful shutdown. +// +// - `receive`: The socket is not expecting to receive any data from +// the peer. The `input-stream` associated with this socket will be +// closed. Any data still in the receive queue at time of calling +// this method will be discarded. +// - `send`: The socket has no more data to send to the peer. The `output-stream` +// associated with this socket will be closed and a FIN packet will be sent. +// - `both`: Same effect as `receive` & `send` combined. +// +// This function is idempotent. Shutting a down a direction more than once +// has no effect and returns `ok`. +// +// The shutdown function does not close (drop) the socket. +// +// # Typical errors +// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) +// +// # References +// - +// - +// - +// - +// +// shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) Shutdown(shutdownType ShutdownType) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + shutdownType0 := (uint32)(shutdownType) + wasmimport_TCPSocketShutdown((uint32)(self0), (uint32)(shutdownType0), &result) + return +} + +// StartBind represents the imported method "start-bind". +// +// Bind the socket to a specific network on the provided IP address and port. +// +// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the +// implementation to decide which +// network interface(s) to bind to. +// If the TCP/UDP port is zero, the socket will be bound to a random free port. +// +// Bind can be attempted multiple times on the same socket, even with +// different arguments on each iteration. But never concurrently and +// only as long as the previous bind failed. Once a bind succeeds, the +// binding can't be changed anymore. +// +// # Typical errors +// - `invalid-argument`: The `local-address` has the wrong address family. +// (EAFNOSUPPORT, EFAULT on Windows) +// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) +// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. +// (EINVAL) +// - `invalid-state`: The socket is already bound. (EINVAL) +// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS +// on Windows) +// - `address-in-use`: Address is already in use. (EADDRINUSE) +// - `address-not-bindable`: `local-address` is not an address that the `network` +// can bind to. (EADDRNOTAVAIL) +// - `not-in-progress`: A `bind` operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// When binding to a non-zero port, this bind operation shouldn't be affected by the +// TIME_WAIT +// state of a recently closed socket on the same local address. In practice this means +// that the SO_REUSEADDR +// socket option should be set implicitly on all platforms, except on Windows where +// this is the default behavior +// and SO_REUSEADDR performs something different entirely. +// +// Unlike in POSIX, in WASI the bind operation is async. This enables +// interactive WASI hosts to inject permission prompts. Runtimes that +// don't want to make use of this ability can simply call the native +// `bind` as part of either `start-bind` or `finish-bind`. +// +// # References +// - +// - +// - +// - +// +// start-bind: func(network: borrow, local-address: ip-socket-address) -> +// result<_, error-code> +// +//go:nosplit +func (self TCPSocket) StartBind(network_ Network, localAddress IPSocketAddress) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + network0 := cm.Reinterpret[uint32](network_) + localAddress0, localAddress1, localAddress2, localAddress3, localAddress4, localAddress5, localAddress6, localAddress7, localAddress8, localAddress9, localAddress10, localAddress11 := lower_IPSocketAddress(localAddress) + wasmimport_TCPSocketStartBind((uint32)(self0), (uint32)(network0), (uint32)(localAddress0), (uint32)(localAddress1), (uint32)(localAddress2), (uint32)(localAddress3), (uint32)(localAddress4), (uint32)(localAddress5), (uint32)(localAddress6), (uint32)(localAddress7), (uint32)(localAddress8), (uint32)(localAddress9), (uint32)(localAddress10), (uint32)(localAddress11), &result) + return +} + +// StartConnect represents the imported method "start-connect". +// +// Connect to a remote endpoint. +// +// On success: +// - the socket is transitioned into the `connection` state. +// - a pair of streams is returned that can be used to read & write to the connection +// +// After a failed connection attempt, the socket will be in the `closed` +// state and the only valid action left is to `drop` the socket. A single +// socket can not be used to connect more than once. +// +// # Typical errors +// - `invalid-argument`: The `remote-address` has the wrong address family. +// (EAFNOSUPPORT) +// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, +// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) +// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. +// (EINVAL, EADDRNOTAVAIL on Illumos) +// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY +// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) +// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL +// on Windows) +// - `invalid-argument`: The socket is already attached to a different network. +// The `network` passed to `connect` must be identical to the one passed to `bind`. +// - `invalid-state`: The socket is already in the `connected` state. +// (EISCONN) +// - `invalid-state`: The socket is already in the `listening` state. +// (EOPNOTSUPP, EINVAL on Windows) +// - `timeout`: Connection timed out. (ETIMEDOUT) +// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) +// - `connection-reset`: The connection was reset. (ECONNRESET) +// - `connection-aborted`: The connection was aborted. (ECONNABORTED) +// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, +// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `address-in-use`: Tried to perform an implicit bind, but there were +// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) +// - `not-in-progress`: A connect operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// The POSIX equivalent of `start-connect` is the regular `connect` syscall. +// Because all WASI sockets are non-blocking this is expected to return +// EINPROGRESS, which should be translated to `ok()` in WASI. +// +// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` +// with a timeout of 0 on the socket descriptor. Followed by a check for +// the `SO_ERROR` socket option, in case the poll signaled readiness. +// +// # References +// - +// - +// - +// - +// +// start-connect: func(network: borrow, remote-address: ip-socket-address) +// -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) StartConnect(network_ Network, remoteAddress IPSocketAddress) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + network0 := cm.Reinterpret[uint32](network_) + remoteAddress0, remoteAddress1, remoteAddress2, remoteAddress3, remoteAddress4, remoteAddress5, remoteAddress6, remoteAddress7, remoteAddress8, remoteAddress9, remoteAddress10, remoteAddress11 := lower_IPSocketAddress(remoteAddress) + wasmimport_TCPSocketStartConnect((uint32)(self0), (uint32)(network0), (uint32)(remoteAddress0), (uint32)(remoteAddress1), (uint32)(remoteAddress2), (uint32)(remoteAddress3), (uint32)(remoteAddress4), (uint32)(remoteAddress5), (uint32)(remoteAddress6), (uint32)(remoteAddress7), (uint32)(remoteAddress8), (uint32)(remoteAddress9), (uint32)(remoteAddress10), (uint32)(remoteAddress11), &result) + return +} + +// StartListen represents the imported method "start-listen". +// +// Start listening for new connections. +// +// Transitions the socket into the `listening` state. +// +// Unlike POSIX, the socket must already be explicitly bound. +// +// # Typical errors +// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) +// - `invalid-state`: The socket is already in the `connected` state. +// (EISCONN, EINVAL on BSD) +// - `invalid-state`: The socket is already in the `listening` state. +// - `address-in-use`: Tried to perform an implicit bind, but there were +// no ephemeral ports available. (EADDRINUSE) +// - `not-in-progress`: A listen operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// Unlike in POSIX, in WASI the listen operation is async. This enables +// interactive WASI hosts to inject permission prompts. Runtimes that +// don't want to make use of this ability can simply call the native +// `listen` as part of either `start-listen` or `finish-listen`. +// +// # References +// - +// - +// - +// - +// +// start-listen: func() -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) StartListen() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketStartListen((uint32)(self0), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which can be used to poll for, or block on, +// completion of any of the asynchronous operations of this socket. +// +// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` +// return `error(would-block)`, this pollable can be used to wait for +// their success or failure, after which the method can be retried. +// +// The pollable is not limited to the async operation that happens to be +// in progress at the time of calling `subscribe` (if any). Theoretically, +// `subscribe` only has to be called once per socket and can then be +// (re)used for the remainder of the socket's lifetime. +// +// See +// for a more information. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self TCPSocket) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_TCPSocketSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} diff --git a/x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s b/x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go b/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go new file mode 100755 index 00000000..94b1ab67 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go @@ -0,0 +1,13 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package udpcreatesocket + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". + +//go:wasmimport wasi:sockets/udp-create-socket@0.2.0 create-udp-socket +//go:noescape +func wasmimport_CreateUDPSocket(addressFamily0 uint32, result *cm.Result[UDPSocket, UDPSocket, ErrorCode]) diff --git a/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go b/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go new file mode 100755 index 00000000..736bee8a --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go @@ -0,0 +1,68 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package udpcreatesocket represents the imported interface "wasi:sockets/udp-create-socket@0.2.0". +package udpcreatesocket + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/udp" +) + +// Network represents the imported type alias "wasi:sockets/udp-create-socket@0.2.0#network". +// +// See [network.Network] for more information. +type Network = network.Network + +// ErrorCode represents the type alias "wasi:sockets/udp-create-socket@0.2.0#error-code". +// +// See [network.ErrorCode] for more information. +type ErrorCode = network.ErrorCode + +// IPAddressFamily represents the type alias "wasi:sockets/udp-create-socket@0.2.0#ip-address-family". +// +// See [network.IPAddressFamily] for more information. +type IPAddressFamily = network.IPAddressFamily + +// UDPSocket represents the imported type alias "wasi:sockets/udp-create-socket@0.2.0#udp-socket". +// +// See [udp.UDPSocket] for more information. +type UDPSocket = udp.UDPSocket + +// CreateUDPSocket represents the imported function "create-udp-socket". +// +// Create a new UDP socket. +// +// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. +// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. +// +// This function does not require a network capability handle. This is considered +// to be safe because +// at time of creation, the socket is not bound to any `network` yet. Up to the moment +// `bind` is called, +// the socket is effectively an in-memory configuration object, unable to communicate +// with the outside world. +// +// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous +// operations. +// +// # Typical errors +// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) +// - `new-socket-limit`: The new socket resource could not be created because of +// a system limit. (EMFILE, ENFILE) +// +// # References: +// - +// - +// - +// - +// +// create-udp-socket: func(address-family: ip-address-family) -> result +// +//go:nosplit +func CreateUDPSocket(addressFamily IPAddressFamily) (result cm.Result[UDPSocket, UDPSocket, ErrorCode]) { + addressFamily0 := (uint32)(addressFamily) + wasmimport_CreateUDPSocket((uint32)(addressFamily0), &result) + return +} diff --git a/x/wasihttp/internal/wasi/sockets/udp/abi.go b/x/wasihttp/internal/wasi/sockets/udp/abi.go new file mode 100755 index 00000000..daa60bcb --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/udp/abi.go @@ -0,0 +1,103 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package udp + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" + "unsafe" +) + +// IPSocketAddressShape is used for storage in variant or result types. +type IPSocketAddressShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(IPSocketAddress{})]byte +} + +func lower_IPv4Address(v network.IPv4Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + return +} + +func lower_IPv4SocketAddress(v network.IPv4SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32) { + f0 = (uint32)(v.Port) + f1, f2, f3, f4 = lower_IPv4Address(v.Address) + return +} + +func lower_IPv6Address(v network.IPv6Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + f4 = (uint32)(v[4]) + f5 = (uint32)(v[5]) + f6 = (uint32)(v[6]) + f7 = (uint32)(v[7]) + return +} + +func lower_IPv6SocketAddress(v network.IPv6SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32) { + f0 = (uint32)(v.Port) + f1 = (uint32)(v.FlowInfo) + f2, f3, f4, f5, f6, f7, f8, f9 = lower_IPv6Address(v.Address) + f10 = (uint32)(v.ScopeID) + return +} + +func lower_IPSocketAddress(v network.IPSocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 0: // ipv4 + v1, v2, v3, v4, v5 := lower_IPv4SocketAddress(*cm.Case[network.IPv4SocketAddress](&v, 0)) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 1: // ipv6 + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 := lower_IPv6SocketAddress(*cm.Case[network.IPv6SocketAddress](&v, 1)) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + f8 = (uint32)(v8) + f9 = (uint32)(v9) + f10 = (uint32)(v10) + f11 = (uint32)(v11) + } + return +} + +// TupleIncomingDatagramStreamOutgoingDatagramStreamShape is used for storage in variant or result types. +type TupleIncomingDatagramStreamOutgoingDatagramStreamShape struct { + _ cm.HostLayout + shape [unsafe.Sizeof(cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream]{})]byte +} + +func lower_OptionIPSocketAddress(v cm.Option[IPSocketAddress]) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32, f12 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 := lower_IPSocketAddress(*some) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + f8 = (uint32)(v8) + f9 = (uint32)(v9) + f10 = (uint32)(v10) + f11 = (uint32)(v11) + f12 = (uint32)(v12) + } + return +} diff --git a/x/wasihttp/internal/wasi/sockets/udp/empty.s b/x/wasihttp/internal/wasi/sockets/udp/empty.s new file mode 100755 index 00000000..5444f200 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/udp/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go b/x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go new file mode 100755 index 00000000..83ce8ca7 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go @@ -0,0 +1,93 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package udp + +import ( + "go.bytecodealliance.org/cm" +) + +// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". + +//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]udp-socket +//go:noescape +func wasmimport_UDPSocketResourceDrop(self0 uint32) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.address-family +//go:noescape +func wasmimport_UDPSocketAddressFamily(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.finish-bind +//go:noescape +func wasmimport_UDPSocketFinishBind(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.local-address +//go:noescape +func wasmimport_UDPSocketLocalAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.receive-buffer-size +//go:noescape +func wasmimport_UDPSocketReceiveBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.remote-address +//go:noescape +func wasmimport_UDPSocketRemoteAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.send-buffer-size +//go:noescape +func wasmimport_UDPSocketSendBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-receive-buffer-size +//go:noescape +func wasmimport_UDPSocketSetReceiveBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-send-buffer-size +//go:noescape +func wasmimport_UDPSocketSetSendBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-unicast-hop-limit +//go:noescape +func wasmimport_UDPSocketSetUnicastHopLimit(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.start-bind +//go:noescape +func wasmimport_UDPSocketStartBind(self0 uint32, network0 uint32, localAddress0 uint32, localAddress1 uint32, localAddress2 uint32, localAddress3 uint32, localAddress4 uint32, localAddress5 uint32, localAddress6 uint32, localAddress7 uint32, localAddress8 uint32, localAddress9 uint32, localAddress10 uint32, localAddress11 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.stream +//go:noescape +func wasmimport_UDPSocketStream(self0 uint32, remoteAddress0 uint32, remoteAddress1 uint32, remoteAddress2 uint32, remoteAddress3 uint32, remoteAddress4 uint32, remoteAddress5 uint32, remoteAddress6 uint32, remoteAddress7 uint32, remoteAddress8 uint32, remoteAddress9 uint32, remoteAddress10 uint32, remoteAddress11 uint32, remoteAddress12 uint32, result *cm.Result[TupleIncomingDatagramStreamOutgoingDatagramStreamShape, cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream], ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.subscribe +//go:noescape +func wasmimport_UDPSocketSubscribe(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.unicast-hop-limit +//go:noescape +func wasmimport_UDPSocketUnicastHopLimit(self0 uint32, result *cm.Result[uint8, uint8, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]incoming-datagram-stream +//go:noescape +func wasmimport_IncomingDatagramStreamResourceDrop(self0 uint32) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]incoming-datagram-stream.receive +//go:noescape +func wasmimport_IncomingDatagramStreamReceive(self0 uint32, maxResults0 uint64, result *cm.Result[cm.List[IncomingDatagram], cm.List[IncomingDatagram], ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]incoming-datagram-stream.subscribe +//go:noescape +func wasmimport_IncomingDatagramStreamSubscribe(self0 uint32) (result0 uint32) + +//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]outgoing-datagram-stream +//go:noescape +func wasmimport_OutgoingDatagramStreamResourceDrop(self0 uint32) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.check-send +//go:noescape +func wasmimport_OutgoingDatagramStreamCheckSend(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.send +//go:noescape +func wasmimport_OutgoingDatagramStreamSend(self0 uint32, datagrams0 *OutgoingDatagram, datagrams1 uint32, result *cm.Result[uint64, uint64, ErrorCode]) + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.subscribe +//go:noescape +func wasmimport_OutgoingDatagramStreamSubscribe(self0 uint32) (result0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/udp/udp.wit.go b/x/wasihttp/internal/wasi/sockets/udp/udp.wit.go new file mode 100755 index 00000000..25a05cf9 --- /dev/null +++ b/x/wasihttp/internal/wasi/sockets/udp/udp.wit.go @@ -0,0 +1,584 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package udp represents the imported interface "wasi:sockets/udp@0.2.0". +package udp + +import ( + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" +) + +// Pollable represents the imported type alias "wasi:sockets/udp@0.2.0#pollable". +// +// See [poll.Pollable] for more information. +type Pollable = poll.Pollable + +// Network represents the imported type alias "wasi:sockets/udp@0.2.0#network". +// +// See [network.Network] for more information. +type Network = network.Network + +// ErrorCode represents the type alias "wasi:sockets/udp@0.2.0#error-code". +// +// See [network.ErrorCode] for more information. +type ErrorCode = network.ErrorCode + +// IPSocketAddress represents the type alias "wasi:sockets/udp@0.2.0#ip-socket-address". +// +// See [network.IPSocketAddress] for more information. +type IPSocketAddress = network.IPSocketAddress + +// IPAddressFamily represents the type alias "wasi:sockets/udp@0.2.0#ip-address-family". +// +// See [network.IPAddressFamily] for more information. +type IPAddressFamily = network.IPAddressFamily + +// IncomingDatagram represents the record "wasi:sockets/udp@0.2.0#incoming-datagram". +// +// A received datagram. +// +// record incoming-datagram { +// data: list, +// remote-address: ip-socket-address, +// } +type IncomingDatagram struct { + _ cm.HostLayout `json:"-"` + // The payload. + // + // Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + Data cm.List[uint8] `json:"data"` + + // The source address. + // + // This field is guaranteed to match the remote address the stream was initialized + // with, if any. + // + // Equivalent to the `src_addr` out parameter of `recvfrom`. + RemoteAddress IPSocketAddress `json:"remote-address"` +} + +// OutgoingDatagram represents the record "wasi:sockets/udp@0.2.0#outgoing-datagram". +// +// A datagram to be sent out. +// +// record outgoing-datagram { +// data: list, +// remote-address: option, +// } +type OutgoingDatagram struct { + _ cm.HostLayout `json:"-"` + // The payload. + Data cm.List[uint8] `json:"data"` + + // The destination address. + // + // The requirements on this field depend on how the stream was initialized: + // - with a remote address: this field must be None or match the stream's remote address + // exactly. + // - without a remote address: this field is required. + // + // If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise + // it is equivalent to `sendto`. + RemoteAddress cm.Option[IPSocketAddress] `json:"remote-address"` +} + +// UDPSocket represents the imported resource "wasi:sockets/udp@0.2.0#udp-socket". +// +// A UDP socket handle. +// +// resource udp-socket +type UDPSocket cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "udp-socket". +// +// Drops a resource handle. +// +//go:nosplit +func (self UDPSocket) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketResourceDrop((uint32)(self0)) + return +} + +// AddressFamily represents the imported method "address-family". +// +// Whether this is a IPv4 or IPv6 socket. +// +// Equivalent to the SO_DOMAIN socket option. +// +// address-family: func() -> ip-address-family +// +//go:nosplit +func (self UDPSocket) AddressFamily() (result IPAddressFamily) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_UDPSocketAddressFamily((uint32)(self0)) + result = (network.IPAddressFamily)((uint32)(result0)) + return +} + +// FinishBind represents the imported method "finish-bind". +// +// finish-bind: func() -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) FinishBind() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketFinishBind((uint32)(self0), &result) + return +} + +// LocalAddress represents the imported method "local-address". +// +// Get the current bound address. +// +// POSIX mentions: +// > If the socket has not been bound to a local name, the value +// > stored in the object pointed to by `address` is unspecified. +// +// WASI is stricter and requires `local-address` to return `invalid-state` when the +// socket hasn't been bound yet. +// +// # Typical errors +// - `invalid-state`: The socket is not bound to any local address. +// +// # References +// - +// - +// - +// - +// +// local-address: func() -> result +// +//go:nosplit +func (self UDPSocket) LocalAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketLocalAddress((uint32)(self0), &result) + return +} + +// ReceiveBufferSize represents the imported method "receive-buffer-size". +// +// The kernel buffer space reserved for sends/receives on this socket. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// receive-buffer-size: func() -> result +// +//go:nosplit +func (self UDPSocket) ReceiveBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketReceiveBufferSize((uint32)(self0), &result) + return +} + +// RemoteAddress represents the imported method "remote-address". +// +// Get the address the socket is currently streaming to. +// +// # Typical errors +// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) +// +// # References +// - +// - +// - +// - +// +// remote-address: func() -> result +// +//go:nosplit +func (self UDPSocket) RemoteAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketRemoteAddress((uint32)(self0), &result) + return +} + +// SendBufferSize represents the imported method "send-buffer-size". +// +// send-buffer-size: func() -> result +// +//go:nosplit +func (self UDPSocket) SendBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketSendBufferSize((uint32)(self0), &result) + return +} + +// SetReceiveBufferSize represents the imported method "set-receive-buffer-size". +// +// set-receive-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) SetReceiveBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_UDPSocketSetReceiveBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +// SetSendBufferSize represents the imported method "set-send-buffer-size". +// +// set-send-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) SetSendBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_UDPSocketSetSendBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +// SetUnicastHopLimit represents the imported method "set-unicast-hop-limit". +// +// set-unicast-hop-limit: func(value: u8) -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) SetUnicastHopLimit(value uint8) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint32)(value) + wasmimport_UDPSocketSetUnicastHopLimit((uint32)(self0), (uint32)(value0), &result) + return +} + +// StartBind represents the imported method "start-bind". +// +// Bind the socket to a specific network on the provided IP address and port. +// +// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the +// implementation to decide which +// network interface(s) to bind to. +// If the port is zero, the socket will be bound to a random free port. +// +// # Typical errors +// - `invalid-argument`: The `local-address` has the wrong address family. +// (EAFNOSUPPORT, EFAULT on Windows) +// - `invalid-state`: The socket is already bound. (EINVAL) +// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS +// on Windows) +// - `address-in-use`: Address is already in use. (EADDRINUSE) +// - `address-not-bindable`: `local-address` is not an address that the `network` +// can bind to. (EADDRNOTAVAIL) +// - `not-in-progress`: A `bind` operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// Unlike in POSIX, in WASI the bind operation is async. This enables +// interactive WASI hosts to inject permission prompts. Runtimes that +// don't want to make use of this ability can simply call the native +// `bind` as part of either `start-bind` or `finish-bind`. +// +// # References +// - +// - +// - +// - +// +// start-bind: func(network: borrow, local-address: ip-socket-address) -> +// result<_, error-code> +// +//go:nosplit +func (self UDPSocket) StartBind(network_ Network, localAddress IPSocketAddress) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + network0 := cm.Reinterpret[uint32](network_) + localAddress0, localAddress1, localAddress2, localAddress3, localAddress4, localAddress5, localAddress6, localAddress7, localAddress8, localAddress9, localAddress10, localAddress11 := lower_IPSocketAddress(localAddress) + wasmimport_UDPSocketStartBind((uint32)(self0), (uint32)(network0), (uint32)(localAddress0), (uint32)(localAddress1), (uint32)(localAddress2), (uint32)(localAddress3), (uint32)(localAddress4), (uint32)(localAddress5), (uint32)(localAddress6), (uint32)(localAddress7), (uint32)(localAddress8), (uint32)(localAddress9), (uint32)(localAddress10), (uint32)(localAddress11), &result) + return +} + +// Stream represents the imported method "stream". +// +// Set up inbound & outbound communication channels, optionally to a specific peer. +// +// This function only changes the local socket configuration and does not generate +// any network traffic. +// On success, the `remote-address` of the socket is updated. The `local-address` +// may be updated as well, +// based on the best network path to `remote-address`. +// +// When a `remote-address` is provided, the returned streams are limited to communicating +// with that specific peer: +// - `send` can only be used to send to this destination. +// - `receive` will only return datagrams sent from the provided `remote-address`. +// +// This method may be called multiple times on the same socket to change its association, +// but +// only the most recently returned pair of streams will be operational. Implementations +// may trap if +// the streams returned by a previous invocation haven't been dropped yet before calling +// `stream` again. +// +// The POSIX equivalent in pseudo-code is: +// +// if (was previously connected) { +// connect(s, AF_UNSPEC) +// } +// if (remote_address is Some) { +// connect(s, remote_address) +// } +// +// Unlike in POSIX, the socket must already be explicitly bound. +// +// # Typical errors +// - `invalid-argument`: The `remote-address` has the wrong address family. +// (EAFNOSUPPORT) +// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY +// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) +// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, +// EADDRNOTAVAIL) +// - `invalid-state`: The socket is not bound. +// - `address-in-use`: Tried to perform an implicit bind, but there were +// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) +// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, +// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `connection-refused`: The connection was refused. (ECONNREFUSED) +// +// # References +// - +// - +// - +// - +// +// %stream: func(remote-address: option) -> result, error-code> +// +//go:nosplit +func (self UDPSocket) Stream(remoteAddress cm.Option[IPSocketAddress]) (result cm.Result[TupleIncomingDatagramStreamOutgoingDatagramStreamShape, cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + remoteAddress0, remoteAddress1, remoteAddress2, remoteAddress3, remoteAddress4, remoteAddress5, remoteAddress6, remoteAddress7, remoteAddress8, remoteAddress9, remoteAddress10, remoteAddress11, remoteAddress12 := lower_OptionIPSocketAddress(remoteAddress) + wasmimport_UDPSocketStream((uint32)(self0), (uint32)(remoteAddress0), (uint32)(remoteAddress1), (uint32)(remoteAddress2), (uint32)(remoteAddress3), (uint32)(remoteAddress4), (uint32)(remoteAddress5), (uint32)(remoteAddress6), (uint32)(remoteAddress7), (uint32)(remoteAddress8), (uint32)(remoteAddress9), (uint32)(remoteAddress10), (uint32)(remoteAddress11), (uint32)(remoteAddress12), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the socket is ready for I/O. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self UDPSocket) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_UDPSocketSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// UnicastHopLimit represents the imported method "unicast-hop-limit". +// +// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// +// # Typical errors +// - `invalid-argument`: (set) The TTL value must be 1 or higher. +// +// unicast-hop-limit: func() -> result +// +//go:nosplit +func (self UDPSocket) UnicastHopLimit() (result cm.Result[uint8, uint8, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketUnicastHopLimit((uint32)(self0), &result) + return +} + +// IncomingDatagramStream represents the imported resource "wasi:sockets/udp@0.2.0#incoming-datagram-stream". +// +// resource incoming-datagram-stream +type IncomingDatagramStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-datagram-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingDatagramStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingDatagramStreamResourceDrop((uint32)(self0)) + return +} + +// Receive represents the imported method "receive". +// +// Receive messages on the socket. +// +// This function attempts to receive up to `max-results` datagrams on the socket without +// blocking. +// The returned list may contain fewer elements than requested, but never more. +// +// This function returns successfully with an empty list when either: +// - `max-results` is 0, or: +// - `max-results` is greater than 0, but no results are immediately available. +// This function never returns `error(would-block)`. +// +// # Typical errors +// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET +// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `connection-refused`: The connection was refused. (ECONNREFUSED) +// +// # References +// - +// - +// - +// - +// - +// - +// - +// - +// +// receive: func(max-results: u64) -> result, error-code> +// +//go:nosplit +func (self IncomingDatagramStream) Receive(maxResults uint64) (result cm.Result[cm.List[IncomingDatagram], cm.List[IncomingDatagram], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + maxResults0 := (uint64)(maxResults) + wasmimport_IncomingDatagramStreamReceive((uint32)(self0), (uint64)(maxResults0), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the stream is ready to receive again. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self IncomingDatagramStream) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingDatagramStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} + +// OutgoingDatagramStream represents the imported resource "wasi:sockets/udp@0.2.0#outgoing-datagram-stream". +// +// resource outgoing-datagram-stream +type OutgoingDatagramStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-datagram-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingDatagramStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingDatagramStreamResourceDrop((uint32)(self0)) + return +} + +// CheckSend represents the imported method "check-send". +// +// Check readiness for sending. This function never blocks. +// +// Returns the number of datagrams permitted for the next call to `send`, +// or an error. Calling `send` with more datagrams than this function has +// permitted will trap. +// +// When this function returns ok(0), the `subscribe` pollable will +// become ready when this function will report at least ok(1), or an +// error. +// +// Never returns `would-block`. +// +// check-send: func() -> result +// +//go:nosplit +func (self OutgoingDatagramStream) CheckSend() (result cm.Result[uint64, uint64, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingDatagramStreamCheckSend((uint32)(self0), &result) + return +} + +// Send represents the imported method "send". +// +// Send messages on the socket. +// +// This function attempts to send all provided `datagrams` on the socket without blocking +// and +// returns how many messages were actually sent (or queued for sending). This function +// never +// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` +// is returned. +// +// This function semantically behaves the same as iterating the `datagrams` list and +// sequentially +// sending each individual datagram until either the end of the list has been reached +// or the first error occurred. +// If at least one datagram has been sent successfully, this function never returns +// an error. +// +// If the input list is empty, the function returns `ok(0)`. +// +// Each call to `send` must be permitted by a preceding `check-send`. Implementations +// must trap if +// either `check-send` was not called or `datagrams` contains more items than `check-send` +// permitted. +// +// # Typical errors +// - `invalid-argument`: The `remote-address` has the wrong address family. +// (EAFNOSUPPORT) +// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY +// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) +// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, +// EADDRNOTAVAIL) +// - `invalid-argument`: The socket is in "connected" mode and `remote-address` +// is `some` value that does not match the address passed to `stream`. (EISCONN) +// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` +// was provided. (EDESTADDRREQ) +// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, +// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `connection-refused`: The connection was refused. (ECONNREFUSED) +// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) +// +// # References +// - +// - +// - +// - +// - +// - +// - +// - +// +// send: func(datagrams: list) -> result +// +//go:nosplit +func (self OutgoingDatagramStream) Send(datagrams cm.List[OutgoingDatagram]) (result cm.Result[uint64, uint64, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + datagrams0, datagrams1 := cm.LowerList(datagrams) + wasmimport_OutgoingDatagramStreamSend((uint32)(self0), (*OutgoingDatagram)(datagrams0), (uint32)(datagrams1), &result) + return +} + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the stream is ready to send again. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self OutgoingDatagramStream) Subscribe() (result Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingDatagramStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[Pollable]((uint32)(result0)) + return +} diff --git a/x/wasihttp/server.go b/x/wasihttp/server.go new file mode 100644 index 00000000..036e606d --- /dev/null +++ b/x/wasihttp/server.go @@ -0,0 +1,131 @@ +package wasihttp + +import ( + "errors" + "net/http" + + "go.bytecodealliance.org/cm" + incominghandler "go.bytecodealliance.org/x/wasihttp/internal/wasi/http/incoming-handler" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/http/types" +) + +var defaultHandler http.Handler + +// Serve sets the [http.Handler] that incoming [wasi-http] requests are routed to. +// By default, requests are routed to [http.DefaultServeMux]. +// +// [wasi-http]: https://github.com/webassembly/wasi-http +func Serve(h http.Handler) { + defaultHandler = h +} + +func init() { + // Assign the "wasi:http/incoming-handler@0.2.1#handle" export. + incominghandler.Exports.Handle = handleIncomingRequest +} + +func handleIncomingRequest(req types.IncomingRequest, out types.ResponseOutparam) { + h := defaultHandler + if h == nil { + h = http.DefaultServeMux + } + w, err := newResponseWriter(req, out) + if err != nil { + return // TODO: log error? + } + h.ServeHTTP(w, w.req) + w.finish() +} + +var _ http.ResponseWriter = &responseWriter{} + +type responseWriter struct { + out types.ResponseOutparam + req *http.Request + header http.Header + wroteHeader bool + status int // HTTP status code passed to WriteHeader + + res types.OutgoingResponse // valid after headers are sent + body types.OutgoingBody // valid after res.Body() is called + writer *bodyWriter // valid after body.Stream() is called + + finished bool +} + +func newResponseWriter(req types.IncomingRequest, out types.ResponseOutparam) (*responseWriter, error) { + r, err := incomingRequest(req) + w := &responseWriter{ + out: out, + req: r, + header: make(http.Header), + } + if err != nil { + w.fatal(types.ErrorCodeHTTPProtocolError()) + } + return w, err +} + +func (w *responseWriter) Header() http.Header { + // TODO: handle concurrent access to (or mutations of) w.header? + return w.header +} + +func (w *responseWriter) Write(p []byte) (int, error) { + if w.finished { + return 0, errors.New("wasihttp: write after close") + } + if !w.wroteHeader { + w.WriteHeader(http.StatusOK) + } + return w.writer.Write(p) +} + +func (w *responseWriter) WriteHeader(code int) { + if w.finished || w.wroteHeader { + // TODO: improve logging + return + } + + // TODO: handle 1xx informational headers? + + w.wroteHeader = true + w.status = code + + headers := toFields(w.header) + w.res = types.NewOutgoingResponse(headers) + w.res.SetStatusCode(types.StatusCode(code)) + + w.body, _, _ = w.res.Body().Result() // the first call should always return OK + w.writer = newBodyWriter(w.body, func() http.Header { + return nil + }) + + // Consume the response-outparam and outgoing-response. + types.ResponseOutparamSet(w.out, cm.OK[outgoingResult](w.res)) +} + +func (w *responseWriter) finish() error { + if w.finished { + return nil + } + if !w.wroteHeader { + // w.WriteHeader(http.StatusOK) + // If caller code did not set headers, status, or body, then respond with an error + // and let the server implementation handle the correct response. + w.fatal(types.ErrorCodeHTTPResponseIncomplete()) + return nil + } + + w.finished = true + return w.writer.finish() +} + +// fatal sets an error code on the response, to allow the implementation +// to determine how to respond with an HTTP error response. +func (w *responseWriter) fatal(e types.ErrorCode) { + w.finished = true + types.ResponseOutparamSet(w.out, cm.Err[outgoingResult](e)) +} + +type outgoingResult = cm.Result[types.ErrorCodeShape, types.OutgoingResponse, types.ErrorCode] diff --git a/x/wasihttp/transport.go b/x/wasihttp/transport.go new file mode 100644 index 00000000..836d6e1d --- /dev/null +++ b/x/wasihttp/transport.go @@ -0,0 +1,103 @@ +package wasihttp + +import ( + "errors" + "fmt" + "io" + "net/http" + + "go.bytecodealliance.org/cm" + outgoinghandler "go.bytecodealliance.org/x/wasihttp/internal/wasi/http/outgoing-handler" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/http/types" +) + +func init() { + // Override the default net/http transport and client. + http.DefaultTransport = &Transport{} + if http.DefaultClient != nil { + http.DefaultClient.Transport = &Transport{} // TinyGo has custom implementation of net/http + } +} + +// Transport implements [http.RoundTripper] using [wasi-http] APIs. +// +// [wasi-http]: https://github.com/webassembly/wasi-http +type Transport struct{} + +// RoundTrip executes a single HTTP transaction. +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + // Only close the body if it's not nil + if req.Body != nil { + defer req.Body.Close() + } + + // TODO: wrap this into a helper func outgoingRequest? + r := types.NewOutgoingRequest(toFields(req.Header)) + r.SetAuthority(cm.Some(requestAuthority(req))) // TODO: when should this be cm.None? + r.SetMethod(toMethod(req.Method)) + r.SetPathWithQuery(requestPath(req)) + r.SetScheme(cm.Some(toScheme(req.URL.Scheme))) // TODO: when should this be cm.None? + + body, _, _ := r.Body().Result() // the first call should always return OK + + // TODO: when are [options] used? + // [options]: https://github.com/WebAssembly/wasi-http/blob/main/wit/handler.wit#L38-L39 + incoming, err, isErr := outgoinghandler.Handle(r, cm.None[types.RequestOptions]()).Result() + if isErr { + // outgoing request is invalid or not allowed to be made + return nil, errors.New(err.String()) + } + defer incoming.ResourceDrop() + + // Write request body + w := newBodyWriter(body, func() http.Header { + // TODO: extract request trailers + return nil + }) + + // Only copy from req.Body if it's not nil + if req.Body != nil { + if _, err := io.Copy(w, req.Body); err != nil { + return nil, fmt.Errorf("wasihttp: %v", err) + } + } + w.finish() + + // Wait for response + poll := incoming.Subscribe() + if !poll.Ready() { + poll.Block() + } + poll.ResourceDrop() + + future := incoming.Get() + if future.None() { + return nil, fmt.Errorf("wasihttp: future response is None after blocking") + } + // TODO: figure out a better way to handle option>> + response, err, isErr := future.Some().OK().Result() // the first call should always return OK + if isErr { + // TODO: what do we do with the HTTP proxy error-code? + return nil, errors.New(err.String()) + } + // TODO: when should an incoming-response be dropped? + // defer response.ResourceDrop() + + return incomingResponse(response) +} + +func requestAuthority(req *http.Request) string { + if req.Host == "" { + return req.URL.Host + } else { + return req.Host + } +} + +func requestPath(req *http.Request) cm.Option[string] { + path := req.URL.RequestURI() + if path == "" { + return cm.None[string]() + } + return cm.Some(path) +} diff --git a/x/wasihttp/types.go b/x/wasihttp/types.go new file mode 100644 index 00000000..3b8c864d --- /dev/null +++ b/x/wasihttp/types.go @@ -0,0 +1,287 @@ +package wasihttp + +import ( + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "go.bytecodealliance.org/cm" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/http/types" + "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" +) + +func incomingRequest(req types.IncomingRequest) (*http.Request, error) { + r := &http.Request{ + Method: fromMethod(req.Method()), + URL: incomingURL(req), + // TODO: Proto, ProtoMajor, ProtoMinor + Header: fromFields(req.Headers()), + Host: req.Authority().Value(), + } + + body, _, isErr := req.Consume().Result() + if isErr { + return nil, errors.New("error consuming wasi-http request") + } + + r.Body = newBodyReader(body, func(h http.Header) { + r.Trailer = h + }) + + return r, nil +} + +func fromMethod(m types.Method) string { + if o := m.Other(); o != nil { + return strings.ToUpper(*o) + } + return strings.ToUpper(m.String()) +} + +func incomingURL(req types.IncomingRequest) *url.URL { + u := &url.URL{ + Scheme: fromScheme(req.Scheme().Value()), + Host: req.Authority().Value(), + } + u, _ = u.Parse(req.PathWithQuery().Value()) + return u +} + +func fromScheme(s types.Scheme) string { + if o := s.Other(); o != nil { + return strings.ToLower(*o) + } + return strings.ToLower(s.String()) +} + +func incomingResponse(res types.IncomingResponse) (*http.Response, error) { + r := &http.Response{ + Status: http.StatusText(int(res.Status())), + StatusCode: int(res.Status()), + Header: fromFields(res.Headers()), + } + + body, _, isErr := res.Consume().Result() + if isErr { + return nil, errors.New("error consuming wasi-http response") + } + + r.Body = newBodyReader(body, func(h http.Header) { r.Trailer = h }) + + return r, nil +} + +var _ io.ReadCloser = &bodyReader{} + +type bodyReader struct { + body types.IncomingBody + trailer func(http.Header) + stream streams.InputStream + finished bool +} + +func newBodyReader(body types.IncomingBody, trailer func(http.Header)) *bodyReader { + return &bodyReader{ + body: body, + trailer: trailer, + } +} + +// TODO: implement buffered reads +func (r *bodyReader) Read(p []byte) (int, error) { + if r.finished { + return 0, http.ErrBodyReadAfterClose + } + + if r.stream == cm.ResourceNone { + // the first call should always return OK + r.stream, _, _ = r.body.Stream().Result() + } + + // TODO: coordinate with runtime to block on multiple pollables. + poll := r.stream.Subscribe() + poll.Block() + poll.ResourceDrop() + + list, err, isErr := r.stream.Read(uint64(len(p))).Result() + if isErr { + if err.Closed() { + err2 := r.finish() // read trailers + if err2 != nil { + return 0, err2 + } + return 0, io.EOF + } + return 0, fmt.Errorf("failed to read from InputStream %s", err.LastOperationFailed().ToDebugString()) + } + + copy(p, list.Slice()) + return int(list.Len()), nil +} + +func (r *bodyReader) Close() error { + return r.finish() +} + +func (r *bodyReader) finish() error { + if r.finished { + return nil + } + r.finished = true + if r.stream != cm.ResourceNone { + r.stream.ResourceDrop() + } + + future := types.IncomingBodyFinish(r.body) + defer future.ResourceDrop() + p := future.Subscribe() + p.Block() + p.ResourceDrop() + trailersReady := future.Get() + // TODO: figure out a better way to handle option, error-code>>> + someTrailers, err, isErr := trailersReady.Some().OK().Result() + if isErr { + return errors.New(err.String()) + } + trailers := someTrailers.Some() + if trailers != nil { + r.trailer(fromFields(*trailers)) + } + + return nil +} + +var ( + _ io.Writer = &bodyWriter{} + _ http.Flusher = &bodyWriter{} +) + +type bodyWriter struct { + body types.OutgoingBody + trailer func() http.Header + stream streams.OutputStream + finished bool +} + +// newBodyWriter takes ownership of body, allowing it to be written to. +// Call finish to send the HTTP trailers provided by the trailer callback. +func newBodyWriter(body types.OutgoingBody, trailer func() http.Header) *bodyWriter { + return &bodyWriter{ + body: body, + trailer: trailer, + } +} + +// TODO: buffer writes +func (w *bodyWriter) Write(p []byte) (n int, err error) { + if w.stream == cm.ResourceNone { + w.stream, _, _ = w.body.Write().Result() + } + res := w.stream.BlockingWriteAndFlush(cm.ToList(p)) + if res.IsErr() { + return 0, fmt.Errorf("wasihttp: %v", res.Err()) + } + return len(p), nil +} + +// TODO: buffer writes +func (w *bodyWriter) Flush() { + if w.finished { + return + } + if w.stream != cm.ResourceNone { + w.stream.Flush() + } +} + +func (w *bodyWriter) finish() error { + if w.finished { + return nil + } + w.finished = true + if w.stream != cm.ResourceNone { + w.stream.Flush() + w.stream.ResourceDrop() + } + + var trailers cm.Option[types.Trailers] + if w.trailer != nil { + trailers = toTrailers(w.trailer()) + } + finished := types.OutgoingBodyFinish(w.body, trailers) + if finished.IsErr() { + return errors.New(finished.Err().String()) + } + + return nil +} + +func toScheme(s string) types.Scheme { + switch s { + case "http": + return types.SchemeHTTP() + case "https": + return types.SchemeHTTPS() + default: + // TODO: when should we set the scheme to `cm.None` if `req.URL.Scheme` is empty? + return types.SchemeOther(s) + } +} + +func toMethod(s string) types.Method { + switch s { + case http.MethodGet: + return types.MethodGet() + case http.MethodHead: + return types.MethodHead() + case http.MethodPost: + return types.MethodPost() + case http.MethodPut: + return types.MethodPut() + case http.MethodPatch: + return types.MethodPatch() + case http.MethodDelete: + return types.MethodDelete() + case http.MethodConnect: + return types.MethodConnect() + case http.MethodOptions: + return types.MethodOptions() + case http.MethodTrace: + return types.MethodTrace() + default: + // TODO: is other method allowed? or should we return GET? + // https://cs.opensource.google/go/go/+/refs/tags/go1.23.2:src/net/http/method.go + // https://github.com/WebAssembly/wasi-http/blob/main/wit/types.wit#L340C41-L341C69 + return types.MethodOther(s) + } +} + +func fromFields(f types.Fields) http.Header { + h := http.Header{} + for _, e := range f.Entries().Slice() { + h.Add(string(e.F0), string(e.F1.Slice())) + } + return h +} + +func toFields(h http.Header) types.Fields { + fields := types.NewFields() + for k, v := range h { + vals := make([]types.FieldValue, 0, len(v)) + for _, vv := range v { + vals = append(vals, types.FieldValue(cm.ToList([]uint8(vv)))) + } + fields.Set(types.FieldKey(k), cm.ToList(vals)) + } + return fields +} + +func toTrailers(h http.Header) cm.Option[types.Trailers] { + if h == nil || len(h) == 0 { + return cm.None[types.Trailers]() + } + return cm.Some(toFields(h)) +} diff --git a/x/wasihttp/wasip2-http.json b/x/wasihttp/wasip2-http.json new file mode 100644 index 00000000..f29d605c --- /dev/null +++ b/x/wasihttp/wasip2-http.json @@ -0,0 +1,6 @@ +{ + "inherits": ["wasip2"], + "wit-package": "./internal/go/http/proxy/proxy.wit", + "wit-world": "go:http/proxy", + "emulator": "wasmtime serve -Scli --dir={tmpDir}::/tmp {}" +} diff --git a/x/wasihttp/wasip2-roundtrip.json b/x/wasihttp/wasip2-roundtrip.json new file mode 100644 index 00000000..708a9f5d --- /dev/null +++ b/x/wasihttp/wasip2-roundtrip.json @@ -0,0 +1,6 @@ +{ + "inherits": ["wasip2"], + "wit-package": "./wit", + "wit-world": "go:http/proxy", + "emulator": "wasmtime run -Shttp -Sinherit-network -Sinherit-env {}" +} diff --git a/x/wasihttp/wit/deps/cli/command.wit b/x/wasihttp/wit/deps/cli/command.wit new file mode 100644 index 00000000..d8005bd3 --- /dev/null +++ b/x/wasihttp/wit/deps/cli/command.wit @@ -0,0 +1,7 @@ +package wasi:cli@0.2.0; + +world command { + include imports; + + export run; +} diff --git a/x/wasihttp/wit/deps/cli/environment.wit b/x/wasihttp/wit/deps/cli/environment.wit new file mode 100644 index 00000000..70065233 --- /dev/null +++ b/x/wasihttp/wit/deps/cli/environment.wit @@ -0,0 +1,18 @@ +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + initial-cwd: func() -> option; +} diff --git a/x/wasihttp/wit/deps/cli/exit.wit b/x/wasihttp/wit/deps/cli/exit.wit new file mode 100644 index 00000000..d0c2b82a --- /dev/null +++ b/x/wasihttp/wit/deps/cli/exit.wit @@ -0,0 +1,4 @@ +interface exit { + /// Exit the current instance and any linked instances. + exit: func(status: result); +} diff --git a/x/wasihttp/wit/deps/cli/imports.wit b/x/wasihttp/wit/deps/cli/imports.wit new file mode 100644 index 00000000..083b84a0 --- /dev/null +++ b/x/wasihttp/wit/deps/cli/imports.wit @@ -0,0 +1,20 @@ +package wasi:cli@0.2.0; + +world imports { + include wasi:clocks/imports@0.2.0; + include wasi:filesystem/imports@0.2.0; + include wasi:sockets/imports@0.2.0; + include wasi:random/imports@0.2.0; + include wasi:io/imports@0.2.0; + + import environment; + import exit; + import stdin; + import stdout; + import stderr; + import terminal-input; + import terminal-output; + import terminal-stdin; + import terminal-stdout; + import terminal-stderr; +} diff --git a/x/wasihttp/wit/deps/cli/run.wit b/x/wasihttp/wit/deps/cli/run.wit new file mode 100644 index 00000000..a70ee8c0 --- /dev/null +++ b/x/wasihttp/wit/deps/cli/run.wit @@ -0,0 +1,4 @@ +interface run { + /// Run the program. + run: func() -> result; +} diff --git a/x/wasihttp/wit/deps/cli/stdio.wit b/x/wasihttp/wit/deps/cli/stdio.wit new file mode 100644 index 00000000..31ef35b5 --- /dev/null +++ b/x/wasihttp/wit/deps/cli/stdio.wit @@ -0,0 +1,17 @@ +interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + + get-stdin: func() -> input-stream; +} + +interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + + get-stdout: func() -> output-stream; +} + +interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + + get-stderr: func() -> output-stream; +} diff --git a/x/wasihttp/wit/deps/cli/terminal.wit b/x/wasihttp/wit/deps/cli/terminal.wit new file mode 100644 index 00000000..38c724ef --- /dev/null +++ b/x/wasihttp/wit/deps/cli/terminal.wit @@ -0,0 +1,49 @@ +/// Terminal input. +/// +/// In the future, this may include functions for disabling echoing, +/// disabling input buffering so that keyboard events are sent through +/// immediately, querying supported features, and so on. +interface terminal-input { + /// The input side of a terminal. + resource terminal-input; +} + +/// Terminal output. +/// +/// In the future, this may include functions for querying the terminal +/// size, being notified of terminal size changes, querying supported +/// features, and so on. +interface terminal-output { + /// The output side of a terminal. + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +interface terminal-stdin { + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +interface terminal-stdout { + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +interface terminal-stderr { + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stderr: func() -> option; +} diff --git a/x/wasihttp/wit/deps/clocks/monotonic-clock.wit b/x/wasihttp/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 00000000..4e4dc3a1 --- /dev/null +++ b/x/wasihttp/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,45 @@ +package wasi:clocks@0.2.0; +/// WASI Monotonic Clock is a clock API intended to let users measure elapsed +/// time. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A monotonic clock is a clock which has an unspecified initial value, and +/// successive reads of the clock will produce non-decreasing values. +/// +/// It is intended for measuring elapsed time. +interface monotonic-clock { + use wasi:io/poll@0.2.0.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; + + /// A duration of time, in nanoseconds. + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/x/wasihttp/wit/deps/clocks/wall-clock.wit b/x/wasihttp/wit/deps/clocks/wall-clock.wit new file mode 100644 index 00000000..440ca0f3 --- /dev/null +++ b/x/wasihttp/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,42 @@ +package wasi:clocks@0.2.0; +/// WASI Wall Clock is a clock API intended to let users query the current +/// time. The name "wall" makes an analogy to a "clock on the wall", which +/// is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A wall clock is a clock which measures the date and time according to +/// some external reference. +/// +/// External references may be reset, so this clock is not necessarily +/// monotonic, making it unsuitable for measuring elapsed time. +/// +/// It is intended for reporting the current date and time for humans. +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; +} diff --git a/x/wasihttp/wit/deps/clocks/world.wit b/x/wasihttp/wit/deps/clocks/world.wit new file mode 100644 index 00000000..c0224572 --- /dev/null +++ b/x/wasihttp/wit/deps/clocks/world.wit @@ -0,0 +1,6 @@ +package wasi:clocks@0.2.0; + +world imports { + import monotonic-clock; + import wall-clock; +} diff --git a/x/wasihttp/wit/deps/filesystem/preopens.wit b/x/wasihttp/wit/deps/filesystem/preopens.wit new file mode 100644 index 00000000..da801f6d --- /dev/null +++ b/x/wasihttp/wit/deps/filesystem/preopens.wit @@ -0,0 +1,8 @@ +package wasi:filesystem@0.2.0; + +interface preopens { + use types.{descriptor}; + + /// Return the set of preopened directories, and their path. + get-directories: func() -> list>; +} diff --git a/x/wasihttp/wit/deps/filesystem/types.wit b/x/wasihttp/wit/deps/filesystem/types.wit new file mode 100644 index 00000000..11108fcd --- /dev/null +++ b/x/wasihttp/wit/deps/filesystem/types.wit @@ -0,0 +1,634 @@ +package wasi:filesystem@0.2.0; +/// WASI filesystem is a filesystem API primarily intended to let users run WASI +/// programs that access their files on their existing filesystems, without +/// significant overhead. +/// +/// It is intended to be roughly portable between Unix-family platforms and +/// Windows, though it does not hide many of the major differences. +/// +/// Paths are passed as interface-type `string`s, meaning they must consist of +/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +/// paths which are not accessible by this API. +/// +/// The directory separator in WASI is always the forward-slash (`/`). +/// +/// All paths in WASI are relative paths, and are interpreted relative to a +/// `descriptor` referring to a base directory. If a `path` argument to any WASI +/// function starts with `/`, or if any step of resolving a `path`, including +/// `..` and symbolic link steps, reaches a directory outside of the base +/// directory, or reaches a symlink to an absolute or rooted path in the +/// underlying filesystem, the function fails with `error-code::not-permitted`. +/// +/// For more information about WASI path resolution and sandboxing, see +/// [WASI filesystem path resolution]. +/// +/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +interface types { + use wasi:io/streams@0.2.0.{input-stream, output-stream, error}; + use wasi:clocks/wall-clock@0.2.0.{datetime}; + + /// File size or length of a region within a file. + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrety + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// Flags determining the method of how paths are resolved. + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device, + } + + /// File or memory access pattern advisory information. + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse, + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + resource descriptor { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + sync-data: func() -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-type: func() -> result; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + read-directory: func() -> result; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func( + /// The relative path of the symbolic link from which to read. + path: string, + ) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + is-same-object: func(other: borrow) -> bool; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encourated to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/x/wasihttp/wit/deps/filesystem/world.wit b/x/wasihttp/wit/deps/filesystem/world.wit new file mode 100644 index 00000000..663f5792 --- /dev/null +++ b/x/wasihttp/wit/deps/filesystem/world.wit @@ -0,0 +1,6 @@ +package wasi:filesystem@0.2.0; + +world imports { + import types; + import preopens; +} diff --git a/x/wasihttp/wit/deps/http/handler.wit b/x/wasihttp/wit/deps/http/handler.wit new file mode 100644 index 00000000..a34a0649 --- /dev/null +++ b/x/wasihttp/wit/deps/http/handler.wit @@ -0,0 +1,43 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +interface incoming-handler { + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func( + request: incoming-request, + response-out: response-outparam + ); +} + +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +interface outgoing-handler { + use types.{ + outgoing-request, request-options, future-incoming-response, error-code + }; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/x/wasihttp/wit/deps/http/proxy.wit b/x/wasihttp/wit/deps/http/proxy.wit new file mode 100644 index 00000000..687c24d2 --- /dev/null +++ b/x/wasihttp/wit/deps/http/proxy.wit @@ -0,0 +1,32 @@ +package wasi:http@0.2.0; + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +world proxy { + /// HTTP proxies have access to time and randomness. + include wasi:clocks/imports@0.2.0; + import wasi:random/random@0.2.0; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + import wasi:cli/stdout@0.2.0; + import wasi:cli/stderr@0.2.0; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + import wasi:cli/stdin@0.2.0; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + import outgoing-handler; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + export incoming-handler; +} diff --git a/x/wasihttp/wit/deps/http/types.wit b/x/wasihttp/wit/deps/http/types.wit new file mode 100644 index 00000000..755ac6a6 --- /dev/null +++ b/x/wasihttp/wit/deps/http/types.wit @@ -0,0 +1,570 @@ +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +interface types { + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use wasi:io/streams@0.2.0.{input-stream, output-stream}; + use wasi:io/error@0.2.0.{error as io-error}; + use wasi:io/poll@0.2.0.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option) + } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all keys + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields`, an empty list is returned. However, if the key is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + get: func(name: field-key) -> list; + + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + set: func(name: field-key, value: list) -> result<_, header-error>; + + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + delete: func(name: field-key) -> result<_, header-error>; + + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivelant in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + + /// Returns the method of the incoming request. + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + scheme: func() -> option; + + /// Returns the authority from the request, if it was present. + authority: func() -> option; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor( + headers: headers + ); + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the Method for the Request. + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + + /// Returns the status code from the incoming response. + status: func() -> status-code; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventaully return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occured, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occured receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occured. The implementation should propogate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventaully return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have recieved successfully, or that an error + /// occured. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + + } +} diff --git a/x/wasihttp/wit/deps/io/error.wit b/x/wasihttp/wit/deps/io/error.wit new file mode 100644 index 00000000..22e5b648 --- /dev/null +++ b/x/wasihttp/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.0; + + +interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } +} diff --git a/x/wasihttp/wit/deps/io/poll.wit b/x/wasihttp/wit/deps/io/poll.wit new file mode 100644 index 00000000..ddc67f8b --- /dev/null +++ b/x/wasihttp/wit/deps/io/poll.wit @@ -0,0 +1,41 @@ +package wasi:io@0.2.0; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; +} diff --git a/x/wasihttp/wit/deps/io/streams.wit b/x/wasihttp/wit/deps/io/streams.wit new file mode 100644 index 00000000..6d2f871e --- /dev/null +++ b/x/wasihttp/wit/deps/io/streams.wit @@ -0,0 +1,262 @@ +package wasi:io@0.2.0; + +/// WASI I/O is an I/O abstraction API which is currently focused on providing +/// stream types. +/// +/// In the future, the component model is expected to add built-in stream types; +/// when it does, they are expected to subsume this API. +interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + } + + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + check-write: func() -> result; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func( + contents: list + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/x/wasihttp/wit/deps/io/world.wit b/x/wasihttp/wit/deps/io/world.wit new file mode 100644 index 00000000..5f0b43fe --- /dev/null +++ b/x/wasihttp/wit/deps/io/world.wit @@ -0,0 +1,6 @@ +package wasi:io@0.2.0; + +world imports { + import streams; + import poll; +} diff --git a/x/wasihttp/wit/deps/random/insecure-seed.wit b/x/wasihttp/wit/deps/random/insecure-seed.wit new file mode 100644 index 00000000..47210ac6 --- /dev/null +++ b/x/wasihttp/wit/deps/random/insecure-seed.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.0; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; +} diff --git a/x/wasihttp/wit/deps/random/insecure.wit b/x/wasihttp/wit/deps/random/insecure.wit new file mode 100644 index 00000000..c58f4ee8 --- /dev/null +++ b/x/wasihttp/wit/deps/random/insecure.wit @@ -0,0 +1,22 @@ +package wasi:random@0.2.0; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; +} diff --git a/x/wasihttp/wit/deps/random/random.wit b/x/wasihttp/wit/deps/random/random.wit new file mode 100644 index 00000000..0c017f09 --- /dev/null +++ b/x/wasihttp/wit/deps/random/random.wit @@ -0,0 +1,26 @@ +package wasi:random@0.2.0; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; +} diff --git a/x/wasihttp/wit/deps/random/world.wit b/x/wasihttp/wit/deps/random/world.wit new file mode 100644 index 00000000..3da34914 --- /dev/null +++ b/x/wasihttp/wit/deps/random/world.wit @@ -0,0 +1,7 @@ +package wasi:random@0.2.0; + +world imports { + import random; + import insecure; + import insecure-seed; +} diff --git a/x/wasihttp/wit/deps/sockets/instance-network.wit b/x/wasihttp/wit/deps/sockets/instance-network.wit new file mode 100644 index 00000000..e455d0ff --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/instance-network.wit @@ -0,0 +1,9 @@ + +/// This interface provides a value-export of the default network handle.. +interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + +} diff --git a/x/wasihttp/wit/deps/sockets/ip-name-lookup.wit b/x/wasihttp/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 00000000..8e639ec5 --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,51 @@ + +interface ip-name-lookup { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network, error-code, ip-address}; + + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + + resource resolve-address-stream { + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } +} diff --git a/x/wasihttp/wit/deps/sockets/network.wit b/x/wasihttp/wit/deps/sockets/network.wit new file mode 100644 index 00000000..9cadf065 --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/network.wit @@ -0,0 +1,145 @@ + +interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + + /// The operation timed out before it could finish completely. + timeout, + + /// This operation is incompatible with another asynchronous operation that is already in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + + /// A bind operation failed because the provided address is not an address that the `network` can bind to. + address-not-bindable, + + /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. + address-in-use, + + /// The remote address is not reachable + remote-unreachable, + + + /// The TCP connection was forcefully rejected + connection-refused, + + /// The TCP connection was reset. + connection-reset, + + /// A TCP connection was aborted. + connection-aborted, + + + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + + + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + permanent-resolver-failure, + } + + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + type ipv4-address = tuple; + type ipv6-address = tuple; + + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + +} diff --git a/x/wasihttp/wit/deps/sockets/tcp-create-socket.wit b/x/wasihttp/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 00000000..c7ddf1f2 --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,27 @@ + +interface tcp-create-socket { + use network.{network, error-code, ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/x/wasihttp/wit/deps/sockets/tcp.wit b/x/wasihttp/wit/deps/sockets/tcp.wit new file mode 100644 index 00000000..5902b9ee --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/tcp.wit @@ -0,0 +1,353 @@ + +interface tcp { + use wasi:io/streams@0.2.0.{input-stream, output-stream}; + use wasi:io/poll@0.2.0.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + + /// Similar to `SHUT_WR` in POSIX. + send, + + /// Similar to `SHUT_RDWR` in POSIX. + both, + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for a more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + resource tcp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connection` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; + finish-listen: func() -> result<_, error-code>; + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + hop-limit: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for a more information. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent. Shutting a down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/x/wasihttp/wit/deps/sockets/udp-create-socket.wit b/x/wasihttp/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 00000000..0482d1fe --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,27 @@ + +interface udp-create-socket { + use network.{network, error-code, ip-address-family}; + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/x/wasihttp/wit/deps/sockets/udp.wit b/x/wasihttp/wit/deps/sockets/udp.wit new file mode 100644 index 00000000..d987a0a9 --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/udp.wit @@ -0,0 +1,266 @@ + +interface udp { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. + remote-address: option, + } + + + + /// A UDP socket handle. + resource udp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, but + /// only the most recently returned pair of streams will be operational. Implementations may trap if + /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + %stream: func(remote-address: option) -> result, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource incoming-datagram-stream { + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource outgoing-datagram-stream { + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without blocking and + /// returns how many messages were actually sent (or queued for sending). This function never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list and sequentially + /// sending each individual datagram until either the end of the list has been reached or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } +} diff --git a/x/wasihttp/wit/deps/sockets/world.wit b/x/wasihttp/wit/deps/sockets/world.wit new file mode 100644 index 00000000..f8bb92ae --- /dev/null +++ b/x/wasihttp/wit/deps/sockets/world.wit @@ -0,0 +1,11 @@ +package wasi:sockets@0.2.0; + +world imports { + import instance-network; + import network; + import udp; + import udp-create-socket; + import tcp; + import tcp-create-socket; + import ip-name-lookup; +} diff --git a/x/wasihttp/wit/proxy.wit b/x/wasihttp/wit/proxy.wit new file mode 100644 index 00000000..a2ed0bf5 --- /dev/null +++ b/x/wasihttp/wit/proxy.wit @@ -0,0 +1,8 @@ +package go:http@0.2.0; + +/// The `go:http/proxy` world implements a strict superset of `wasi:http/proxy`. +world proxy { + include wasi:http/proxy@0.2.0; + include wasi:cli/command@0.2.0; +} + From d4b2888583e328263709ac622c32bb6890294576 Mon Sep 17 00:00:00 2001 From: Jiaxiao Zhou Date: Thu, 13 Mar 2025 15:33:39 -0700 Subject: [PATCH 2/7] x/wasihttp: add Go module and Makefile Signed-off-by: Jiaxiao Zhou --- x/wasihttp/Makefile | 7 +++++++ x/wasihttp/go.mod | 5 +++++ x/wasihttp/go.sum | 2 ++ 3 files changed, 14 insertions(+) create mode 100644 x/wasihttp/Makefile create mode 100644 x/wasihttp/go.mod create mode 100644 x/wasihttp/go.sum diff --git a/x/wasihttp/Makefile b/x/wasihttp/Makefile new file mode 100644 index 00000000..60bdc9e8 --- /dev/null +++ b/x/wasihttp/Makefile @@ -0,0 +1,7 @@ +.PHONY: tools +tools: + go generate -tags tools ./... + +.PHONY: go-bindings +go-bindings: + go run go.bytecodealliance.org/cmd/wit-bindgen-go generate -o internal/ ./wit diff --git a/x/wasihttp/go.mod b/x/wasihttp/go.mod new file mode 100644 index 00000000..ab30e34d --- /dev/null +++ b/x/wasihttp/go.mod @@ -0,0 +1,5 @@ +module go.bytecodealliance.org/x/wasihttp + +go 1.23.0 + +require go.bytecodealliance.org/cm v0.1.0 diff --git a/x/wasihttp/go.sum b/x/wasihttp/go.sum new file mode 100644 index 00000000..a86cc3d7 --- /dev/null +++ b/x/wasihttp/go.sum @@ -0,0 +1,2 @@ +go.bytecodealliance.org/cm v0.1.0 h1:78Rk4d5rgir5Hm+LMFpDWhjmFBWrKDFPSKUwDBj+nwo= +go.bytecodealliance.org/cm v0.1.0/go.mod h1:NZ2UT0DyGhBfpIPOxPMCuG6g1YTR4YF3xweD7mHX5VQ= From 5ee95decf1a4311139be49946e3d5a75839266fe Mon Sep 17 00:00:00 2001 From: Jiaxiao Zhou Date: Wed, 19 Mar 2025 21:34:41 -0700 Subject: [PATCH 3/7] x/wasihttp: scope down the proxy world - also update go.work to include the new package - slice the proxy.wit to only include the necessary imports - re-generate the bindings Signed-off-by: Jiaxiao Zhou --- go.work | 1 + .../internal/go/http/proxy/proxy.wit.go | 2 +- .../internal/wasi/cli/environment/empty.s | 3 - .../wasi/cli/environment/environment.wasm.go | 21 - .../wasi/cli/environment/environment.wit.go | 52 - x/wasihttp/internal/wasi/cli/exit/empty.s | 3 - .../internal/wasi/cli/exit/exit.wasm.go | 9 - x/wasihttp/internal/wasi/cli/exit/exit.wit.go | 21 - x/wasihttp/internal/wasi/cli/run/empty.s | 3 - .../internal/wasi/cli/run/run.exports.go | 17 - x/wasihttp/internal/wasi/cli/run/run.wasm.go | 17 - x/wasihttp/internal/wasi/cli/run/run.wit.go | 4 - x/wasihttp/internal/wasi/cli/stderr/empty.s | 3 - .../internal/wasi/cli/stderr/stderr.wasm.go | 9 - .../internal/wasi/cli/stderr/stderr.wit.go | 25 - x/wasihttp/internal/wasi/cli/stdin/empty.s | 3 - .../internal/wasi/cli/stdin/stdin.wasm.go | 9 - .../internal/wasi/cli/stdin/stdin.wit.go | 25 - x/wasihttp/internal/wasi/cli/stdout/empty.s | 3 - .../internal/wasi/cli/stdout/stdout.wasm.go | 9 - .../internal/wasi/cli/stdout/stdout.wit.go | 25 - .../internal/wasi/cli/terminal-input/empty.s | 3 - .../cli/terminal-input/terminal-input.wasm.go | 9 - .../cli/terminal-input/terminal-input.wit.go | 32 - .../internal/wasi/cli/terminal-output/empty.s | 3 - .../terminal-output/terminal-output.wasm.go | 9 - .../terminal-output/terminal-output.wit.go | 32 - .../internal/wasi/cli/terminal-stderr/empty.s | 3 - .../terminal-stderr/terminal-stderr.wasm.go | 13 - .../terminal-stderr/terminal-stderr.wit.go | 30 - .../internal/wasi/cli/terminal-stdin/empty.s | 3 - .../cli/terminal-stdin/terminal-stdin.wasm.go | 13 - .../cli/terminal-stdin/terminal-stdin.wit.go | 30 - .../internal/wasi/cli/terminal-stdout/empty.s | 3 - .../terminal-stdout/terminal-stdout.wasm.go | 13 - .../terminal-stdout/terminal-stdout.wit.go | 30 - .../wasi/clocks/monotonic-clock/empty.s | 0 .../monotonic-clock/monotonic-clock.wasm.go | 0 .../monotonic-clock/monotonic-clock.wit.go | 0 .../internal/wasi/clocks/wall-clock/empty.s | 3 - .../wasi/clocks/wall-clock/wall-clock.wasm.go | 13 - .../wasi/clocks/wall-clock/wall-clock.wit.go | 75 - .../internal/wasi/filesystem/preopens/empty.s | 3 - .../wasi/filesystem/preopens/preopens.wasm.go | 13 - .../wasi/filesystem/preopens/preopens.wit.go | 26 - .../internal/wasi/filesystem/types/abi.go | 50 - .../internal/wasi/filesystem/types/empty.s | 3 - .../wasi/filesystem/types/types.wasm.go | 133 -- .../wasi/filesystem/types/types.wit.go | 1305 ----------------- .../wasi/http/incoming-handler/empty.s | 0 .../incoming-handler.exports.go | 0 .../incoming-handler/incoming-handler.wasm.go | 0 .../incoming-handler/incoming-handler.wit.go | 0 .../wasi/http/outgoing-handler/abi.go | 0 .../wasi/http/outgoing-handler/empty.s | 0 .../outgoing-handler/outgoing-handler.wasm.go | 0 .../outgoing-handler/outgoing-handler.wit.go | 0 x/wasihttp/internal/wasi/http/types/abi.go | 0 x/wasihttp/internal/wasi/http/types/empty.s | 0 .../internal/wasi/http/types/types.wasm.go | 0 .../internal/wasi/http/types/types.wit.go | 0 x/wasihttp/internal/wasi/io/error/empty.s | 0 .../internal/wasi/io/error/error.wasm.go | 0 .../internal/wasi/io/error/error.wit.go | 0 x/wasihttp/internal/wasi/io/poll/empty.s | 0 x/wasihttp/internal/wasi/io/poll/poll.wasm.go | 0 x/wasihttp/internal/wasi/io/poll/poll.wit.go | 0 x/wasihttp/internal/wasi/io/streams/empty.s | 0 .../internal/wasi/io/streams/streams.wasm.go | 0 .../internal/wasi/io/streams/streams.wit.go | 0 .../wasi/random/insecure-seed/empty.s | 3 - .../insecure-seed/insecure-seed.wasm.go | 9 - .../random/insecure-seed/insecure-seed.wit.go | 37 - .../internal/wasi/random/insecure/empty.s | 3 - .../wasi/random/insecure/insecure.wasm.go | 17 - .../wasi/random/insecure/insecure.wit.go | 49 - .../internal/wasi/random/random/empty.s | 3 - .../wasi/random/random/random.wasm.go | 17 - .../internal/wasi/random/random/random.wit.go | 53 - .../wasi/sockets/instance-network/empty.s | 3 - .../instance-network/instance-network.wasm.go | 9 - .../instance-network/instance-network.wit.go | 29 - .../wasi/sockets/ip-name-lookup/abi.go | 14 - .../wasi/sockets/ip-name-lookup/empty.s | 3 - .../ip-name-lookup/ip-name-lookup.wasm.go | 25 - .../ip-name-lookup/ip-name-lookup.wit.go | 125 -- .../internal/wasi/sockets/network/abi.go | 14 - .../internal/wasi/sockets/network/empty.s | 3 - .../wasi/sockets/network/network.wasm.go | 9 - .../wasi/sockets/network/network.wit.go | 359 ----- .../wasi/sockets/tcp-create-socket/empty.s | 3 - .../tcp-create-socket.wasm.go | 13 - .../tcp-create-socket.wit.go | 68 - x/wasihttp/internal/wasi/sockets/tcp/abi.go | 88 -- x/wasihttp/internal/wasi/sockets/tcp/empty.s | 3 - .../internal/wasi/sockets/tcp/tcp.wasm.go | 125 -- .../internal/wasi/sockets/tcp/tcp.wit.go | 785 ---------- .../wasi/sockets/udp-create-socket/empty.s | 3 - .../udp-create-socket.wasm.go | 13 - .../udp-create-socket.wit.go | 68 - x/wasihttp/internal/wasi/sockets/udp/abi.go | 103 -- x/wasihttp/internal/wasi/sockets/udp/empty.s | 3 - .../internal/wasi/sockets/udp/udp.wasm.go | 93 -- .../internal/wasi/sockets/udp/udp.wit.go | 584 -------- x/wasihttp/wit/deps/cli/command.wit | 7 - x/wasihttp/wit/deps/cli/environment.wit | 18 - x/wasihttp/wit/deps/cli/exit.wit | 4 - x/wasihttp/wit/deps/cli/imports.wit | 20 - x/wasihttp/wit/deps/cli/run.wit | 4 - x/wasihttp/wit/deps/cli/stdio.wit | 17 - x/wasihttp/wit/deps/cli/terminal.wit | 49 - x/wasihttp/wit/deps/filesystem/preopens.wit | 8 - x/wasihttp/wit/deps/filesystem/types.wit | 634 -------- x/wasihttp/wit/deps/filesystem/world.wit | 6 - x/wasihttp/wit/deps/http/proxy.wit | 31 - x/wasihttp/wit/deps/random/insecure-seed.wit | 25 - x/wasihttp/wit/deps/random/insecure.wit | 22 - x/wasihttp/wit/deps/random/random.wit | 26 - x/wasihttp/wit/deps/random/world.wit | 7 - .../wit/deps/sockets/instance-network.wit | 9 - .../wit/deps/sockets/ip-name-lookup.wit | 51 - x/wasihttp/wit/deps/sockets/network.wit | 145 -- .../wit/deps/sockets/tcp-create-socket.wit | 27 - x/wasihttp/wit/deps/sockets/tcp.wit | 353 ----- .../wit/deps/sockets/udp-create-socket.wit | 27 - x/wasihttp/wit/deps/sockets/udp.wit | 266 ---- x/wasihttp/wit/deps/sockets/world.wit | 11 - x/wasihttp/wit/proxy.wit | 13 +- 128 files changed, 11 insertions(+), 6619 deletions(-) mode change 100755 => 100644 x/wasihttp/internal/go/http/proxy/proxy.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/environment/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/environment/environment.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/environment/environment.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/exit/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/exit/exit.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/exit/exit.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/run/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/run/run.exports.go delete mode 100755 x/wasihttp/internal/wasi/cli/run/run.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/run/run.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/stderr/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/stdin/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/stdout/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-input/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-output/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go delete mode 100755 x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go mode change 100755 => 100644 x/wasihttp/internal/wasi/clocks/monotonic-clock/empty.s mode change 100755 => 100644 x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wasm.go mode change 100755 => 100644 x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wit.go delete mode 100755 x/wasihttp/internal/wasi/clocks/wall-clock/empty.s delete mode 100755 x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go delete mode 100755 x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go delete mode 100755 x/wasihttp/internal/wasi/filesystem/preopens/empty.s delete mode 100755 x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go delete mode 100755 x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go delete mode 100755 x/wasihttp/internal/wasi/filesystem/types/abi.go delete mode 100755 x/wasihttp/internal/wasi/filesystem/types/empty.s delete mode 100755 x/wasihttp/internal/wasi/filesystem/types/types.wasm.go delete mode 100755 x/wasihttp/internal/wasi/filesystem/types/types.wit.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/incoming-handler/empty.s mode change 100755 => 100644 x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.exports.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wasm.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wit.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/outgoing-handler/abi.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/outgoing-handler/empty.s mode change 100755 => 100644 x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wasm.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wit.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/types/abi.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/types/empty.s mode change 100755 => 100644 x/wasihttp/internal/wasi/http/types/types.wasm.go mode change 100755 => 100644 x/wasihttp/internal/wasi/http/types/types.wit.go mode change 100755 => 100644 x/wasihttp/internal/wasi/io/error/empty.s mode change 100755 => 100644 x/wasihttp/internal/wasi/io/error/error.wasm.go mode change 100755 => 100644 x/wasihttp/internal/wasi/io/error/error.wit.go mode change 100755 => 100644 x/wasihttp/internal/wasi/io/poll/empty.s mode change 100755 => 100644 x/wasihttp/internal/wasi/io/poll/poll.wasm.go mode change 100755 => 100644 x/wasihttp/internal/wasi/io/poll/poll.wit.go mode change 100755 => 100644 x/wasihttp/internal/wasi/io/streams/empty.s mode change 100755 => 100644 x/wasihttp/internal/wasi/io/streams/streams.wasm.go mode change 100755 => 100644 x/wasihttp/internal/wasi/io/streams/streams.wit.go delete mode 100755 x/wasihttp/internal/wasi/random/insecure-seed/empty.s delete mode 100755 x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go delete mode 100755 x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go delete mode 100755 x/wasihttp/internal/wasi/random/insecure/empty.s delete mode 100755 x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go delete mode 100755 x/wasihttp/internal/wasi/random/insecure/insecure.wit.go delete mode 100755 x/wasihttp/internal/wasi/random/random/empty.s delete mode 100755 x/wasihttp/internal/wasi/random/random/random.wasm.go delete mode 100755 x/wasihttp/internal/wasi/random/random/random.wit.go delete mode 100755 x/wasihttp/internal/wasi/sockets/instance-network/empty.s delete mode 100755 x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go delete mode 100755 x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go delete mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go delete mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s delete mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go delete mode 100755 x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go delete mode 100755 x/wasihttp/internal/wasi/sockets/network/abi.go delete mode 100755 x/wasihttp/internal/wasi/sockets/network/empty.s delete mode 100755 x/wasihttp/internal/wasi/sockets/network/network.wasm.go delete mode 100755 x/wasihttp/internal/wasi/sockets/network/network.wit.go delete mode 100755 x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s delete mode 100755 x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go delete mode 100755 x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go delete mode 100755 x/wasihttp/internal/wasi/sockets/tcp/abi.go delete mode 100755 x/wasihttp/internal/wasi/sockets/tcp/empty.s delete mode 100755 x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go delete mode 100755 x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go delete mode 100755 x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s delete mode 100755 x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go delete mode 100755 x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go delete mode 100755 x/wasihttp/internal/wasi/sockets/udp/abi.go delete mode 100755 x/wasihttp/internal/wasi/sockets/udp/empty.s delete mode 100755 x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go delete mode 100755 x/wasihttp/internal/wasi/sockets/udp/udp.wit.go delete mode 100644 x/wasihttp/wit/deps/cli/command.wit delete mode 100644 x/wasihttp/wit/deps/cli/environment.wit delete mode 100644 x/wasihttp/wit/deps/cli/exit.wit delete mode 100644 x/wasihttp/wit/deps/cli/imports.wit delete mode 100644 x/wasihttp/wit/deps/cli/run.wit delete mode 100644 x/wasihttp/wit/deps/cli/stdio.wit delete mode 100644 x/wasihttp/wit/deps/cli/terminal.wit delete mode 100644 x/wasihttp/wit/deps/filesystem/preopens.wit delete mode 100644 x/wasihttp/wit/deps/filesystem/types.wit delete mode 100644 x/wasihttp/wit/deps/filesystem/world.wit delete mode 100644 x/wasihttp/wit/deps/random/insecure-seed.wit delete mode 100644 x/wasihttp/wit/deps/random/insecure.wit delete mode 100644 x/wasihttp/wit/deps/random/random.wit delete mode 100644 x/wasihttp/wit/deps/random/world.wit delete mode 100644 x/wasihttp/wit/deps/sockets/instance-network.wit delete mode 100644 x/wasihttp/wit/deps/sockets/ip-name-lookup.wit delete mode 100644 x/wasihttp/wit/deps/sockets/network.wit delete mode 100644 x/wasihttp/wit/deps/sockets/tcp-create-socket.wit delete mode 100644 x/wasihttp/wit/deps/sockets/tcp.wit delete mode 100644 x/wasihttp/wit/deps/sockets/udp-create-socket.wit delete mode 100644 x/wasihttp/wit/deps/sockets/udp.wit delete mode 100644 x/wasihttp/wit/deps/sockets/world.wit diff --git a/go.work b/go.work index d89b68f7..03c5f73e 100644 --- a/go.work +++ b/go.work @@ -4,4 +4,5 @@ use ( . ./cm ./tests + ./x/wasihttp ) diff --git a/x/wasihttp/internal/go/http/proxy/proxy.wit.go b/x/wasihttp/internal/go/http/proxy/proxy.wit.go old mode 100755 new mode 100644 index 0cd2e7de..fa97dc72 --- a/x/wasihttp/internal/go/http/proxy/proxy.wit.go +++ b/x/wasihttp/internal/go/http/proxy/proxy.wit.go @@ -2,5 +2,5 @@ // Package proxy represents the world "go:http/proxy@0.2.0". // -// The `go:http/proxy` world implements a strict superset of `wasi:http/proxy`. +// The `go:http/proxy` world implements a subset of `wasi:http/proxy`. package proxy diff --git a/x/wasihttp/internal/wasi/cli/environment/empty.s b/x/wasihttp/internal/wasi/cli/environment/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/environment/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/environment/environment.wasm.go b/x/wasihttp/internal/wasi/cli/environment/environment.wasm.go deleted file mode 100755 index 89bb596b..00000000 --- a/x/wasihttp/internal/wasi/cli/environment/environment.wasm.go +++ /dev/null @@ -1,21 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package environment - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/environment@0.2.0 get-environment -//go:noescape -func wasmimport_GetEnvironment(result *cm.List[[2]string]) - -//go:wasmimport wasi:cli/environment@0.2.0 get-arguments -//go:noescape -func wasmimport_GetArguments(result *cm.List[string]) - -//go:wasmimport wasi:cli/environment@0.2.0 initial-cwd -//go:noescape -func wasmimport_InitialCWD(result *cm.Option[string]) diff --git a/x/wasihttp/internal/wasi/cli/environment/environment.wit.go b/x/wasihttp/internal/wasi/cli/environment/environment.wit.go deleted file mode 100755 index 3a3b6247..00000000 --- a/x/wasihttp/internal/wasi/cli/environment/environment.wit.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package environment represents the imported interface "wasi:cli/environment@0.2.0". -package environment - -import ( - "go.bytecodealliance.org/cm" -) - -// GetEnvironment represents the imported function "get-environment". -// -// Get the POSIX-style environment variables. -// -// Each environment variable is provided as a pair of string variable names -// and string value. -// -// Morally, these are a value import, but until value imports are available -// in the component model, this import function should return the same -// values each time it is called. -// -// get-environment: func() -> list> -// -//go:nosplit -func GetEnvironment() (result cm.List[[2]string]) { - wasmimport_GetEnvironment(&result) - return -} - -// GetArguments represents the imported function "get-arguments". -// -// Get the POSIX-style arguments to the program. -// -// get-arguments: func() -> list -// -//go:nosplit -func GetArguments() (result cm.List[string]) { - wasmimport_GetArguments(&result) - return -} - -// InitialCWD represents the imported function "initial-cwd". -// -// Return a path that programs should use as their initial current working -// directory, interpreting `.` as shorthand for this. -// -// initial-cwd: func() -> option -// -//go:nosplit -func InitialCWD() (result cm.Option[string]) { - wasmimport_InitialCWD(&result) - return -} diff --git a/x/wasihttp/internal/wasi/cli/exit/empty.s b/x/wasihttp/internal/wasi/cli/exit/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/exit/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/exit/exit.wasm.go b/x/wasihttp/internal/wasi/cli/exit/exit.wasm.go deleted file mode 100755 index 849d5f50..00000000 --- a/x/wasihttp/internal/wasi/cli/exit/exit.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package exit - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/exit@0.2.0 exit -//go:noescape -func wasmimport_Exit(status0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/exit/exit.wit.go b/x/wasihttp/internal/wasi/cli/exit/exit.wit.go deleted file mode 100755 index 947fa253..00000000 --- a/x/wasihttp/internal/wasi/cli/exit/exit.wit.go +++ /dev/null @@ -1,21 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package exit represents the imported interface "wasi:cli/exit@0.2.0". -package exit - -import ( - "go.bytecodealliance.org/cm" -) - -// Exit represents the imported function "exit". -// -// Exit the current instance and any linked instances. -// -// exit: func(status: result) -// -//go:nosplit -func Exit(status cm.BoolResult) { - status0 := (uint32)(cm.BoolToU32(status)) - wasmimport_Exit((uint32)(status0)) - return -} diff --git a/x/wasihttp/internal/wasi/cli/run/empty.s b/x/wasihttp/internal/wasi/cli/run/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/run/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/run/run.exports.go b/x/wasihttp/internal/wasi/cli/run/run.exports.go deleted file mode 100755 index 647b093c..00000000 --- a/x/wasihttp/internal/wasi/cli/run/run.exports.go +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package run - -import ( - "go.bytecodealliance.org/cm" -) - -// Exports represents the caller-defined exports from "wasi:cli/run@0.2.0". -var Exports struct { - // Run represents the caller-defined, exported function "run". - // - // Run the program. - // - // run: func() -> result - Run func() (result cm.BoolResult) -} diff --git a/x/wasihttp/internal/wasi/cli/run/run.wasm.go b/x/wasihttp/internal/wasi/cli/run/run.wasm.go deleted file mode 100755 index 43487234..00000000 --- a/x/wasihttp/internal/wasi/cli/run/run.wasm.go +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package run - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmexport wasi:cli/run@0.2.0#run -//export wasi:cli/run@0.2.0#run -func wasmexport_Run() (result0 uint32) { - result := Exports.Run() - result0 = (uint32)(cm.BoolToU32(result)) - return -} diff --git a/x/wasihttp/internal/wasi/cli/run/run.wit.go b/x/wasihttp/internal/wasi/cli/run/run.wit.go deleted file mode 100755 index 4cea75d3..00000000 --- a/x/wasihttp/internal/wasi/cli/run/run.wit.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package run represents the exported interface "wasi:cli/run@0.2.0". -package run diff --git a/x/wasihttp/internal/wasi/cli/stderr/empty.s b/x/wasihttp/internal/wasi/cli/stderr/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/stderr/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go b/x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go deleted file mode 100755 index 462cf172..00000000 --- a/x/wasihttp/internal/wasi/cli/stderr/stderr.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package stderr - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/stderr@0.2.0 get-stderr -//go:noescape -func wasmimport_GetStderr() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go b/x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go deleted file mode 100755 index 9731dd7a..00000000 --- a/x/wasihttp/internal/wasi/cli/stderr/stderr.wit.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package stderr represents the imported interface "wasi:cli/stderr@0.2.0". -package stderr - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" -) - -// OutputStream represents the imported type alias "wasi:cli/stderr@0.2.0#output-stream". -// -// See [streams.OutputStream] for more information. -type OutputStream = streams.OutputStream - -// GetStderr represents the imported function "get-stderr". -// -// get-stderr: func() -> output-stream -// -//go:nosplit -func GetStderr() (result OutputStream) { - result0 := wasmimport_GetStderr() - result = cm.Reinterpret[OutputStream]((uint32)(result0)) - return -} diff --git a/x/wasihttp/internal/wasi/cli/stdin/empty.s b/x/wasihttp/internal/wasi/cli/stdin/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/stdin/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go b/x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go deleted file mode 100755 index 374eb253..00000000 --- a/x/wasihttp/internal/wasi/cli/stdin/stdin.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package stdin - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/stdin@0.2.0 get-stdin -//go:noescape -func wasmimport_GetStdin() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go b/x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go deleted file mode 100755 index edb52a3e..00000000 --- a/x/wasihttp/internal/wasi/cli/stdin/stdin.wit.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package stdin represents the imported interface "wasi:cli/stdin@0.2.0". -package stdin - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" -) - -// InputStream represents the imported type alias "wasi:cli/stdin@0.2.0#input-stream". -// -// See [streams.InputStream] for more information. -type InputStream = streams.InputStream - -// GetStdin represents the imported function "get-stdin". -// -// get-stdin: func() -> input-stream -// -//go:nosplit -func GetStdin() (result InputStream) { - result0 := wasmimport_GetStdin() - result = cm.Reinterpret[InputStream]((uint32)(result0)) - return -} diff --git a/x/wasihttp/internal/wasi/cli/stdout/empty.s b/x/wasihttp/internal/wasi/cli/stdout/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/stdout/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go b/x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go deleted file mode 100755 index 68e4a3da..00000000 --- a/x/wasihttp/internal/wasi/cli/stdout/stdout.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package stdout - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/stdout@0.2.0 get-stdout -//go:noescape -func wasmimport_GetStdout() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go b/x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go deleted file mode 100755 index 46461fb1..00000000 --- a/x/wasihttp/internal/wasi/cli/stdout/stdout.wit.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package stdout represents the imported interface "wasi:cli/stdout@0.2.0". -package stdout - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" -) - -// OutputStream represents the imported type alias "wasi:cli/stdout@0.2.0#output-stream". -// -// See [streams.OutputStream] for more information. -type OutputStream = streams.OutputStream - -// GetStdout represents the imported function "get-stdout". -// -// get-stdout: func() -> output-stream -// -//go:nosplit -func GetStdout() (result OutputStream) { - result0 := wasmimport_GetStdout() - result = cm.Reinterpret[OutputStream]((uint32)(result0)) - return -} diff --git a/x/wasihttp/internal/wasi/cli/terminal-input/empty.s b/x/wasihttp/internal/wasi/cli/terminal-input/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-input/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go deleted file mode 100755 index 1df3794f..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package terminalinput - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/terminal-input@0.2.0 [resource-drop]terminal-input -//go:noescape -func wasmimport_TerminalInputResourceDrop(self0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go b/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go deleted file mode 100755 index fa12e90c..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-input/terminal-input.wit.go +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package terminalinput represents the imported interface "wasi:cli/terminal-input@0.2.0". -// -// Terminal input. -// -// In the future, this may include functions for disabling echoing, -// disabling input buffering so that keyboard events are sent through -// immediately, querying supported features, and so on. -package terminalinput - -import ( - "go.bytecodealliance.org/cm" -) - -// TerminalInput represents the imported resource "wasi:cli/terminal-input@0.2.0#terminal-input". -// -// The input side of a terminal. -// -// resource terminal-input -type TerminalInput cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "terminal-input". -// -// Drops a resource handle. -// -//go:nosplit -func (self TerminalInput) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TerminalInputResourceDrop((uint32)(self0)) - return -} diff --git a/x/wasihttp/internal/wasi/cli/terminal-output/empty.s b/x/wasihttp/internal/wasi/cli/terminal-output/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-output/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go deleted file mode 100755 index fb35fc41..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package terminaloutput - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/terminal-output@0.2.0 [resource-drop]terminal-output -//go:noescape -func wasmimport_TerminalOutputResourceDrop(self0 uint32) diff --git a/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go b/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go deleted file mode 100755 index 199e0cc0..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-output/terminal-output.wit.go +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package terminaloutput represents the imported interface "wasi:cli/terminal-output@0.2.0". -// -// Terminal output. -// -// In the future, this may include functions for querying the terminal -// size, being notified of terminal size changes, querying supported -// features, and so on. -package terminaloutput - -import ( - "go.bytecodealliance.org/cm" -) - -// TerminalOutput represents the imported resource "wasi:cli/terminal-output@0.2.0#terminal-output". -// -// The output side of a terminal. -// -// resource terminal-output -type TerminalOutput cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "terminal-output". -// -// Drops a resource handle. -// -//go:nosplit -func (self TerminalOutput) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TerminalOutputResourceDrop((uint32)(self0)) - return -} diff --git a/x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s b/x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stderr/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go deleted file mode 100755 index be9af72f..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wasm.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package terminalstderr - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/terminal-stderr@0.2.0 get-terminal-stderr -//go:noescape -func wasmimport_GetTerminalStderr(result *cm.Option[TerminalOutput]) diff --git a/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go b/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go deleted file mode 100755 index 219155fa..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stderr/terminal-stderr.wit.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package terminalstderr represents the imported interface "wasi:cli/terminal-stderr@0.2.0". -// -// An interface providing an optional `terminal-output` for stderr as a -// link-time authority. -package terminalstderr - -import ( - "go.bytecodealliance.org/cm" - terminaloutput "go.bytecodealliance.org/x/wasihttp/internal/wasi/cli/terminal-output" -) - -// TerminalOutput represents the imported type alias "wasi:cli/terminal-stderr@0.2.0#terminal-output". -// -// See [terminaloutput.TerminalOutput] for more information. -type TerminalOutput = terminaloutput.TerminalOutput - -// GetTerminalStderr represents the imported function "get-terminal-stderr". -// -// If stderr is connected to a terminal, return a `terminal-output` handle -// allowing further interaction with it. -// -// get-terminal-stderr: func() -> option -// -//go:nosplit -func GetTerminalStderr() (result cm.Option[TerminalOutput]) { - wasmimport_GetTerminalStderr(&result) - return -} diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s b/x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stdin/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go deleted file mode 100755 index e3b3ac61..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wasm.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package terminalstdin - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/terminal-stdin@0.2.0 get-terminal-stdin -//go:noescape -func wasmimport_GetTerminalStdin(result *cm.Option[TerminalInput]) diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go b/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go deleted file mode 100755 index 335b8cb1..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stdin/terminal-stdin.wit.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package terminalstdin represents the imported interface "wasi:cli/terminal-stdin@0.2.0". -// -// An interface providing an optional `terminal-input` for stdin as a -// link-time authority. -package terminalstdin - -import ( - "go.bytecodealliance.org/cm" - terminalinput "go.bytecodealliance.org/x/wasihttp/internal/wasi/cli/terminal-input" -) - -// TerminalInput represents the imported type alias "wasi:cli/terminal-stdin@0.2.0#terminal-input". -// -// See [terminalinput.TerminalInput] for more information. -type TerminalInput = terminalinput.TerminalInput - -// GetTerminalStdin represents the imported function "get-terminal-stdin". -// -// If stdin is connected to a terminal, return a `terminal-input` handle -// allowing further interaction with it. -// -// get-terminal-stdin: func() -> option -// -//go:nosplit -func GetTerminalStdin() (result cm.Option[TerminalInput]) { - wasmimport_GetTerminalStdin(&result) - return -} diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s b/x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stdout/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go b/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go deleted file mode 100755 index fa750ad9..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wasm.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package terminalstdout - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:cli@0.2.0". - -//go:wasmimport wasi:cli/terminal-stdout@0.2.0 get-terminal-stdout -//go:noescape -func wasmimport_GetTerminalStdout(result *cm.Option[TerminalOutput]) diff --git a/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go b/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go deleted file mode 100755 index 26abf43c..00000000 --- a/x/wasihttp/internal/wasi/cli/terminal-stdout/terminal-stdout.wit.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package terminalstdout represents the imported interface "wasi:cli/terminal-stdout@0.2.0". -// -// An interface providing an optional `terminal-output` for stdout as a -// link-time authority. -package terminalstdout - -import ( - "go.bytecodealliance.org/cm" - terminaloutput "go.bytecodealliance.org/x/wasihttp/internal/wasi/cli/terminal-output" -) - -// TerminalOutput represents the imported type alias "wasi:cli/terminal-stdout@0.2.0#terminal-output". -// -// See [terminaloutput.TerminalOutput] for more information. -type TerminalOutput = terminaloutput.TerminalOutput - -// GetTerminalStdout represents the imported function "get-terminal-stdout". -// -// If stdout is connected to a terminal, return a `terminal-output` handle -// allowing further interaction with it. -// -// get-terminal-stdout: func() -> option -// -//go:nosplit -func GetTerminalStdout() (result cm.Option[TerminalOutput]) { - wasmimport_GetTerminalStdout(&result) - return -} diff --git a/x/wasihttp/internal/wasi/clocks/monotonic-clock/empty.s b/x/wasihttp/internal/wasi/clocks/monotonic-clock/empty.s old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wasm.go b/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wasm.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wit.go b/x/wasihttp/internal/wasi/clocks/monotonic-clock/monotonic-clock.wit.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/clocks/wall-clock/empty.s b/x/wasihttp/internal/wasi/clocks/wall-clock/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/clocks/wall-clock/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go b/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go deleted file mode 100755 index 321ff3f1..00000000 --- a/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wasm.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package wallclock - -// This file contains wasmimport and wasmexport declarations for "wasi:clocks@0.2.0". - -//go:wasmimport wasi:clocks/wall-clock@0.2.0 now -//go:noescape -func wasmimport_Now(result *DateTime) - -//go:wasmimport wasi:clocks/wall-clock@0.2.0 resolution -//go:noescape -func wasmimport_Resolution(result *DateTime) diff --git a/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go b/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go deleted file mode 100755 index 9c0a9684..00000000 --- a/x/wasihttp/internal/wasi/clocks/wall-clock/wall-clock.wit.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package wallclock represents the imported interface "wasi:clocks/wall-clock@0.2.0". -// -// WASI Wall Clock is a clock API intended to let users query the current -// time. The name "wall" makes an analogy to a "clock on the wall", which -// is not necessarily monotonic as it may be reset. -// -// It is intended to be portable at least between Unix-family platforms and -// Windows. -// -// A wall clock is a clock which measures the date and time according to -// some external reference. -// -// External references may be reset, so this clock is not necessarily -// monotonic, making it unsuitable for measuring elapsed time. -// -// It is intended for reporting the current date and time for humans. -package wallclock - -import ( - "go.bytecodealliance.org/cm" -) - -// DateTime represents the record "wasi:clocks/wall-clock@0.2.0#datetime". -// -// A time and date in seconds plus nanoseconds. -// -// record datetime { -// seconds: u64, -// nanoseconds: u32, -// } -type DateTime struct { - _ cm.HostLayout `json:"-"` - Seconds uint64 `json:"seconds"` - Nanoseconds uint32 `json:"nanoseconds"` -} - -// Now represents the imported function "now". -// -// Read the current value of the clock. -// -// This clock is not monotonic, therefore calling this function repeatedly -// will not necessarily produce a sequence of non-decreasing values. -// -// The returned timestamps represent the number of seconds since -// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], -// also known as [Unix Time]. -// -// The nanoseconds field of the output is always less than 1000000000. -// -// now: func() -> datetime -// -// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 -// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time -// -//go:nosplit -func Now() (result DateTime) { - wasmimport_Now(&result) - return -} - -// Resolution represents the imported function "resolution". -// -// Query the resolution of the clock. -// -// The nanoseconds field of the output is always less than 1000000000. -// -// resolution: func() -> datetime -// -//go:nosplit -func Resolution() (result DateTime) { - wasmimport_Resolution(&result) - return -} diff --git a/x/wasihttp/internal/wasi/filesystem/preopens/empty.s b/x/wasihttp/internal/wasi/filesystem/preopens/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/filesystem/preopens/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go b/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go deleted file mode 100755 index 1bcd416a..00000000 --- a/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wasm.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package preopens - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:filesystem@0.2.0". - -//go:wasmimport wasi:filesystem/preopens@0.2.0 get-directories -//go:noescape -func wasmimport_GetDirectories(result *cm.List[cm.Tuple[Descriptor, string]]) diff --git a/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go b/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go deleted file mode 100755 index 652323e0..00000000 --- a/x/wasihttp/internal/wasi/filesystem/preopens/preopens.wit.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package preopens represents the imported interface "wasi:filesystem/preopens@0.2.0". -package preopens - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/filesystem/types" -) - -// Descriptor represents the imported type alias "wasi:filesystem/preopens@0.2.0#descriptor". -// -// See [types.Descriptor] for more information. -type Descriptor = types.Descriptor - -// GetDirectories represents the imported function "get-directories". -// -// Return the set of preopened directories, and their path. -// -// get-directories: func() -> list> -// -//go:nosplit -func GetDirectories() (result cm.List[cm.Tuple[Descriptor, string]]) { - wasmimport_GetDirectories(&result) - return -} diff --git a/x/wasihttp/internal/wasi/filesystem/types/abi.go b/x/wasihttp/internal/wasi/filesystem/types/abi.go deleted file mode 100755 index 06ee48d7..00000000 --- a/x/wasihttp/internal/wasi/filesystem/types/abi.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package types - -import ( - "go.bytecodealliance.org/cm" - wallclock "go.bytecodealliance.org/x/wasihttp/internal/wasi/clocks/wall-clock" - "unsafe" -) - -// MetadataHashValueShape is used for storage in variant or result types. -type MetadataHashValueShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(MetadataHashValue{})]byte -} - -// TupleListU8BoolShape is used for storage in variant or result types. -type TupleListU8BoolShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(cm.Tuple[cm.List[uint8], bool]{})]byte -} - -func lower_DateTime(v wallclock.DateTime) (f0 uint64, f1 uint32) { - f0 = (uint64)(v.Seconds) - f1 = (uint32)(v.Nanoseconds) - return -} - -func lower_NewTimestamp(v NewTimestamp) (f0 uint32, f1 uint64, f2 uint32) { - f0 = (uint32)(v.Tag()) - switch f0 { - case 2: // timestamp - v1, v2 := lower_DateTime(*cm.Case[DateTime](&v, 2)) - f1 = (uint64)(v1) - f2 = (uint32)(v2) - } - return -} - -// DescriptorStatShape is used for storage in variant or result types. -type DescriptorStatShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(DescriptorStat{})]byte -} - -// OptionDirectoryEntryShape is used for storage in variant or result types. -type OptionDirectoryEntryShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(cm.Option[DirectoryEntry]{})]byte -} diff --git a/x/wasihttp/internal/wasi/filesystem/types/empty.s b/x/wasihttp/internal/wasi/filesystem/types/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/filesystem/types/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/filesystem/types/types.wasm.go b/x/wasihttp/internal/wasi/filesystem/types/types.wasm.go deleted file mode 100755 index b97dad84..00000000 --- a/x/wasihttp/internal/wasi/filesystem/types/types.wasm.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package types - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:filesystem@0.2.0". - -//go:wasmimport wasi:filesystem/types@0.2.0 [resource-drop]descriptor -//go:noescape -func wasmimport_DescriptorResourceDrop(self0 uint32) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.advise -//go:noescape -func wasmimport_DescriptorAdvise(self0 uint32, offset0 uint64, length0 uint64, advice0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.append-via-stream -//go:noescape -func wasmimport_DescriptorAppendViaStream(self0 uint32, result *cm.Result[OutputStream, OutputStream, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.create-directory-at -//go:noescape -func wasmimport_DescriptorCreateDirectoryAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.get-flags -//go:noescape -func wasmimport_DescriptorGetFlags(self0 uint32, result *cm.Result[DescriptorFlags, DescriptorFlags, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.get-type -//go:noescape -func wasmimport_DescriptorGetType(self0 uint32, result *cm.Result[DescriptorType, DescriptorType, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.is-same-object -//go:noescape -func wasmimport_DescriptorIsSameObject(self0 uint32, other0 uint32) (result0 uint32) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.link-at -//go:noescape -func wasmimport_DescriptorLinkAt(self0 uint32, oldPathFlags0 uint32, oldPath0 *uint8, oldPath1 uint32, newDescriptor0 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.metadata-hash -//go:noescape -func wasmimport_DescriptorMetadataHash(self0 uint32, result *cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.metadata-hash-at -//go:noescape -func wasmimport_DescriptorMetadataHashAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, result *cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.open-at -//go:noescape -func wasmimport_DescriptorOpenAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, openFlags0 uint32, flags0 uint32, result *cm.Result[Descriptor, Descriptor, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read -//go:noescape -func wasmimport_DescriptorRead(self0 uint32, length0 uint64, offset0 uint64, result *cm.Result[TupleListU8BoolShape, cm.Tuple[cm.List[uint8], bool], ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read-directory -//go:noescape -func wasmimport_DescriptorReadDirectory(self0 uint32, result *cm.Result[DirectoryEntryStream, DirectoryEntryStream, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read-via-stream -//go:noescape -func wasmimport_DescriptorReadViaStream(self0 uint32, offset0 uint64, result *cm.Result[InputStream, InputStream, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.readlink-at -//go:noescape -func wasmimport_DescriptorReadLinkAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[string, string, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.remove-directory-at -//go:noescape -func wasmimport_DescriptorRemoveDirectoryAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.rename-at -//go:noescape -func wasmimport_DescriptorRenameAt(self0 uint32, oldPath0 *uint8, oldPath1 uint32, newDescriptor0 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-size -//go:noescape -func wasmimport_DescriptorSetSize(self0 uint32, size0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-times -//go:noescape -func wasmimport_DescriptorSetTimes(self0 uint32, dataAccessTimestamp0 uint32, dataAccessTimestamp1 uint64, dataAccessTimestamp2 uint32, dataModificationTimestamp0 uint32, dataModificationTimestamp1 uint64, dataModificationTimestamp2 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-times-at -//go:noescape -func wasmimport_DescriptorSetTimesAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, dataAccessTimestamp0 uint32, dataAccessTimestamp1 uint64, dataAccessTimestamp2 uint32, dataModificationTimestamp0 uint32, dataModificationTimestamp1 uint64, dataModificationTimestamp2 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.stat -//go:noescape -func wasmimport_DescriptorStat(self0 uint32, result *cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.stat-at -//go:noescape -func wasmimport_DescriptorStatAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, result *cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.symlink-at -//go:noescape -func wasmimport_DescriptorSymlinkAt(self0 uint32, oldPath0 *uint8, oldPath1 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.sync -//go:noescape -func wasmimport_DescriptorSync(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.sync-data -//go:noescape -func wasmimport_DescriptorSyncData(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.unlink-file-at -//go:noescape -func wasmimport_DescriptorUnlinkFileAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.write -//go:noescape -func wasmimport_DescriptorWrite(self0 uint32, buffer0 *uint8, buffer1 uint32, offset0 uint64, result *cm.Result[uint64, FileSize, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.write-via-stream -//go:noescape -func wasmimport_DescriptorWriteViaStream(self0 uint32, offset0 uint64, result *cm.Result[OutputStream, OutputStream, ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 [resource-drop]directory-entry-stream -//go:noescape -func wasmimport_DirectoryEntryStreamResourceDrop(self0 uint32) - -//go:wasmimport wasi:filesystem/types@0.2.0 [method]directory-entry-stream.read-directory-entry -//go:noescape -func wasmimport_DirectoryEntryStreamReadDirectoryEntry(self0 uint32, result *cm.Result[OptionDirectoryEntryShape, cm.Option[DirectoryEntry], ErrorCode]) - -//go:wasmimport wasi:filesystem/types@0.2.0 filesystem-error-code -//go:noescape -func wasmimport_FilesystemErrorCode(err0 uint32, result *cm.Option[ErrorCode]) diff --git a/x/wasihttp/internal/wasi/filesystem/types/types.wit.go b/x/wasihttp/internal/wasi/filesystem/types/types.wit.go deleted file mode 100755 index 7c4501e8..00000000 --- a/x/wasihttp/internal/wasi/filesystem/types/types.wit.go +++ /dev/null @@ -1,1305 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package types represents the imported interface "wasi:filesystem/types@0.2.0". -// -// WASI filesystem is a filesystem API primarily intended to let users run WASI -// programs that access their files on their existing filesystems, without -// significant overhead. -// -// It is intended to be roughly portable between Unix-family platforms and -// Windows, though it does not hide many of the major differences. -// -// Paths are passed as interface-type `string`s, meaning they must consist of -// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain -// paths which are not accessible by this API. -// -// The directory separator in WASI is always the forward-slash (`/`). -// -// All paths in WASI are relative paths, and are interpreted relative to a -// `descriptor` referring to a base directory. If a `path` argument to any WASI -// function starts with `/`, or if any step of resolving a `path`, including -// `..` and symbolic link steps, reaches a directory outside of the base -// directory, or reaches a symlink to an absolute or rooted path in the -// underlying filesystem, the function fails with `error-code::not-permitted`. -// -// For more information about WASI path resolution and sandboxing, see -// [WASI filesystem path resolution]. -// -// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md -package types - -import ( - "go.bytecodealliance.org/cm" - wallclock "go.bytecodealliance.org/x/wasihttp/internal/wasi/clocks/wall-clock" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" -) - -// InputStream represents the imported type alias "wasi:filesystem/types@0.2.0#input-stream". -// -// See [streams.InputStream] for more information. -type InputStream = streams.InputStream - -// OutputStream represents the imported type alias "wasi:filesystem/types@0.2.0#output-stream". -// -// See [streams.OutputStream] for more information. -type OutputStream = streams.OutputStream - -// Error represents the imported type alias "wasi:filesystem/types@0.2.0#error". -// -// See [streams.Error] for more information. -type Error = streams.Error - -// DateTime represents the type alias "wasi:filesystem/types@0.2.0#datetime". -// -// See [wallclock.DateTime] for more information. -type DateTime = wallclock.DateTime - -// FileSize represents the u64 "wasi:filesystem/types@0.2.0#filesize". -// -// File size or length of a region within a file. -// -// type filesize = u64 -type FileSize uint64 - -// DescriptorType represents the enum "wasi:filesystem/types@0.2.0#descriptor-type". -// -// The type of a filesystem object referenced by a descriptor. -// -// Note: This was called `filetype` in earlier versions of WASI. -// -// enum descriptor-type { -// unknown, -// block-device, -// character-device, -// directory, -// fifo, -// symbolic-link, -// regular-file, -// socket -// } -type DescriptorType uint8 - -const ( - // The type of the descriptor or file is unknown or is different from - // any of the other types specified. - DescriptorTypeUnknown DescriptorType = iota - - // The descriptor refers to a block device inode. - DescriptorTypeBlockDevice - - // The descriptor refers to a character device inode. - DescriptorTypeCharacterDevice - - // The descriptor refers to a directory inode. - DescriptorTypeDirectory - - // The descriptor refers to a named pipe. - DescriptorTypeFIFO - - // The file refers to a symbolic link inode. - DescriptorTypeSymbolicLink - - // The descriptor refers to a regular file inode. - DescriptorTypeRegularFile - - // The descriptor refers to a socket. - DescriptorTypeSocket -) - -var _DescriptorTypeStrings = [8]string{ - "unknown", - "block-device", - "character-device", - "directory", - "fifo", - "symbolic-link", - "regular-file", - "socket", -} - -// String implements [fmt.Stringer], returning the enum case name of e. -func (e DescriptorType) String() string { - return _DescriptorTypeStrings[e] -} - -// MarshalText implements [encoding.TextMarshaler]. -func (e DescriptorType) MarshalText() ([]byte, error) { - return []byte(e.String()), nil -} - -// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum -// case. Returns an error if the supplied text is not one of the enum cases. -func (e *DescriptorType) UnmarshalText(text []byte) error { - return _DescriptorTypeUnmarshalCase(e, text) -} - -var _DescriptorTypeUnmarshalCase = cm.CaseUnmarshaler[DescriptorType](_DescriptorTypeStrings[:]) - -// DescriptorFlags represents the flags "wasi:filesystem/types@0.2.0#descriptor-flags". -// -// Descriptor flags. -// -// Note: This was called `fdflags` in earlier versions of WASI. -// -// flags descriptor-flags { -// read, -// write, -// file-integrity-sync, -// data-integrity-sync, -// requested-write-sync, -// mutate-directory, -// } -type DescriptorFlags uint8 - -const ( - // Read mode: Data can be read. - DescriptorFlagsRead DescriptorFlags = 1 << iota - - // Write mode: Data can be written to. - DescriptorFlagsWrite - - // Request that writes be performed according to synchronized I/O file - // integrity completion. The data stored in the file and the file's - // metadata are synchronized. This is similar to `O_SYNC` in POSIX. - // - // The precise semantics of this operation have not yet been defined for - // WASI. At this time, it should be interpreted as a request, and not a - // requirement. - DescriptorFlagsFileIntegritySync - - // Request that writes be performed according to synchronized I/O data - // integrity completion. Only the data stored in the file is - // synchronized. This is similar to `O_DSYNC` in POSIX. - // - // The precise semantics of this operation have not yet been defined for - // WASI. At this time, it should be interpreted as a request, and not a - // requirement. - DescriptorFlagsDataIntegritySync - - // Requests that reads be performed at the same level of integrety - // requested for writes. This is similar to `O_RSYNC` in POSIX. - // - // The precise semantics of this operation have not yet been defined for - // WASI. At this time, it should be interpreted as a request, and not a - // requirement. - DescriptorFlagsRequestedWriteSync - - // Mutating directories mode: Directory contents may be mutated. - // - // When this flag is unset on a descriptor, operations using the - // descriptor which would create, rename, delete, modify the data or - // metadata of filesystem objects, or obtain another handle which - // would permit any of those, shall fail with `error-code::read-only` if - // they would otherwise succeed. - // - // This may only be set on directories. - DescriptorFlagsMutateDirectory -) - -// PathFlags represents the flags "wasi:filesystem/types@0.2.0#path-flags". -// -// Flags determining the method of how paths are resolved. -// -// flags path-flags { -// symlink-follow, -// } -type PathFlags uint8 - -const ( - // As long as the resolved path corresponds to a symbolic link, it is - // expanded. - PathFlagsSymlinkFollow PathFlags = 1 << iota -) - -// OpenFlags represents the flags "wasi:filesystem/types@0.2.0#open-flags". -// -// Open flags used by `open-at`. -// -// flags open-flags { -// create, -// directory, -// exclusive, -// truncate, -// } -type OpenFlags uint8 - -const ( - // Create file if it does not exist, similar to `O_CREAT` in POSIX. - OpenFlagsCreate OpenFlags = 1 << iota - - // Fail if not a directory, similar to `O_DIRECTORY` in POSIX. - OpenFlagsDirectory - - // Fail if file already exists, similar to `O_EXCL` in POSIX. - OpenFlagsExclusive - - // Truncate file to size 0, similar to `O_TRUNC` in POSIX. - OpenFlagsTruncate -) - -// LinkCount represents the u64 "wasi:filesystem/types@0.2.0#link-count". -// -// Number of hard links to an inode. -// -// type link-count = u64 -type LinkCount uint64 - -// DescriptorStat represents the record "wasi:filesystem/types@0.2.0#descriptor-stat". -// -// File attributes. -// -// Note: This was called `filestat` in earlier versions of WASI. -// -// record descriptor-stat { -// %type: descriptor-type, -// link-count: link-count, -// size: filesize, -// data-access-timestamp: option, -// data-modification-timestamp: option, -// status-change-timestamp: option, -// } -type DescriptorStat struct { - _ cm.HostLayout `json:"-"` - // File type. - Type DescriptorType `json:"type"` - - // Number of hard links to the file. - LinkCount LinkCount `json:"link-count"` - - // For regular files, the file size in bytes. For symbolic links, the - // length in bytes of the pathname contained in the symbolic link. - Size FileSize `json:"size"` - - // Last data access timestamp. - // - // If the `option` is none, the platform doesn't maintain an access - // timestamp for this file. - DataAccessTimestamp cm.Option[DateTime] `json:"data-access-timestamp"` - - // Last data modification timestamp. - // - // If the `option` is none, the platform doesn't maintain a - // modification timestamp for this file. - DataModificationTimestamp cm.Option[DateTime] `json:"data-modification-timestamp"` - - // Last file status-change timestamp. - // - // If the `option` is none, the platform doesn't maintain a - // status-change timestamp for this file. - StatusChangeTimestamp cm.Option[DateTime] `json:"status-change-timestamp"` -} - -// NewTimestamp represents the variant "wasi:filesystem/types@0.2.0#new-timestamp". -// -// When setting a timestamp, this gives the value to set it to. -// -// variant new-timestamp { -// no-change, -// now, -// timestamp(datetime), -// } -type NewTimestamp cm.Variant[uint8, DateTime, DateTime] - -// NewTimestampNoChange returns a [NewTimestamp] of case "no-change". -// -// Leave the timestamp set to its previous value. -func NewTimestampNoChange() NewTimestamp { - var data struct{} - return cm.New[NewTimestamp](0, data) -} - -// NoChange returns true if [NewTimestamp] represents the variant case "no-change". -func (self *NewTimestamp) NoChange() bool { - return self.Tag() == 0 -} - -// NewTimestampNow returns a [NewTimestamp] of case "now". -// -// Set the timestamp to the current time of the system clock associated -// with the filesystem. -func NewTimestampNow() NewTimestamp { - var data struct{} - return cm.New[NewTimestamp](1, data) -} - -// Now returns true if [NewTimestamp] represents the variant case "now". -func (self *NewTimestamp) Now() bool { - return self.Tag() == 1 -} - -// NewTimestampTimestamp returns a [NewTimestamp] of case "timestamp". -// -// Set the timestamp to the given value. -func NewTimestampTimestamp(data DateTime) NewTimestamp { - return cm.New[NewTimestamp](2, data) -} - -// Timestamp returns a non-nil *[DateTime] if [NewTimestamp] represents the variant case "timestamp". -func (self *NewTimestamp) Timestamp() *DateTime { - return cm.Case[DateTime](self, 2) -} - -var _NewTimestampStrings = [3]string{ - "no-change", - "now", - "timestamp", -} - -// String implements [fmt.Stringer], returning the variant case name of v. -func (v NewTimestamp) String() string { - return _NewTimestampStrings[v.Tag()] -} - -// DirectoryEntry represents the record "wasi:filesystem/types@0.2.0#directory-entry". -// -// A directory entry. -// -// record directory-entry { -// %type: descriptor-type, -// name: string, -// } -type DirectoryEntry struct { - _ cm.HostLayout `json:"-"` - // The type of the file referred to by this directory entry. - Type DescriptorType `json:"type"` - - // The name of the object. - Name string `json:"name"` -} - -// ErrorCode represents the enum "wasi:filesystem/types@0.2.0#error-code". -// -// Error codes returned by functions, similar to `errno` in POSIX. -// Not all of these error codes are returned by the functions provided by this -// API; some are used in higher-level library layers, and others are provided -// merely for alignment with POSIX. -// -// enum error-code { -// access, -// would-block, -// already, -// bad-descriptor, -// busy, -// deadlock, -// quota, -// exist, -// file-too-large, -// illegal-byte-sequence, -// in-progress, -// interrupted, -// invalid, -// io, -// is-directory, -// loop, -// too-many-links, -// message-size, -// name-too-long, -// no-device, -// no-entry, -// no-lock, -// insufficient-memory, -// insufficient-space, -// not-directory, -// not-empty, -// not-recoverable, -// unsupported, -// no-tty, -// no-such-device, -// overflow, -// not-permitted, -// pipe, -// read-only, -// invalid-seek, -// text-file-busy, -// cross-device -// } -type ErrorCode uint8 - -const ( - // Permission denied, similar to `EACCES` in POSIX. - ErrorCodeAccess ErrorCode = iota - - // Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` - // in POSIX. - ErrorCodeWouldBlock - - // Connection already in progress, similar to `EALREADY` in POSIX. - ErrorCodeAlready - - // Bad descriptor, similar to `EBADF` in POSIX. - ErrorCodeBadDescriptor - - // Device or resource busy, similar to `EBUSY` in POSIX. - ErrorCodeBusy - - // Resource deadlock would occur, similar to `EDEADLK` in POSIX. - ErrorCodeDeadlock - - // Storage quota exceeded, similar to `EDQUOT` in POSIX. - ErrorCodeQuota - - // File exists, similar to `EEXIST` in POSIX. - ErrorCodeExist - - // File too large, similar to `EFBIG` in POSIX. - ErrorCodeFileTooLarge - - // Illegal byte sequence, similar to `EILSEQ` in POSIX. - ErrorCodeIllegalByteSequence - - // Operation in progress, similar to `EINPROGRESS` in POSIX. - ErrorCodeInProgress - - // Interrupted function, similar to `EINTR` in POSIX. - ErrorCodeInterrupted - - // Invalid argument, similar to `EINVAL` in POSIX. - ErrorCodeInvalid - - // I/O error, similar to `EIO` in POSIX. - ErrorCodeIO - - // Is a directory, similar to `EISDIR` in POSIX. - ErrorCodeIsDirectory - - // Too many levels of symbolic links, similar to `ELOOP` in POSIX. - ErrorCodeLoop - - // Too many links, similar to `EMLINK` in POSIX. - ErrorCodeTooManyLinks - - // Message too large, similar to `EMSGSIZE` in POSIX. - ErrorCodeMessageSize - - // Filename too long, similar to `ENAMETOOLONG` in POSIX. - ErrorCodeNameTooLong - - // No such device, similar to `ENODEV` in POSIX. - ErrorCodeNoDevice - - // No such file or directory, similar to `ENOENT` in POSIX. - ErrorCodeNoEntry - - // No locks available, similar to `ENOLCK` in POSIX. - ErrorCodeNoLock - - // Not enough space, similar to `ENOMEM` in POSIX. - ErrorCodeInsufficientMemory - - // No space left on device, similar to `ENOSPC` in POSIX. - ErrorCodeInsufficientSpace - - // Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. - ErrorCodeNotDirectory - - // Directory not empty, similar to `ENOTEMPTY` in POSIX. - ErrorCodeNotEmpty - - // State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. - ErrorCodeNotRecoverable - - // Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. - ErrorCodeUnsupported - - // Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. - ErrorCodeNoTTY - - // No such device or address, similar to `ENXIO` in POSIX. - ErrorCodeNoSuchDevice - - // Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. - ErrorCodeOverflow - - // Operation not permitted, similar to `EPERM` in POSIX. - ErrorCodeNotPermitted - - // Broken pipe, similar to `EPIPE` in POSIX. - ErrorCodePipe - - // Read-only file system, similar to `EROFS` in POSIX. - ErrorCodeReadOnly - - // Invalid seek, similar to `ESPIPE` in POSIX. - ErrorCodeInvalidSeek - - // Text file busy, similar to `ETXTBSY` in POSIX. - ErrorCodeTextFileBusy - - // Cross-device link, similar to `EXDEV` in POSIX. - ErrorCodeCrossDevice -) - -var _ErrorCodeStrings = [37]string{ - "access", - "would-block", - "already", - "bad-descriptor", - "busy", - "deadlock", - "quota", - "exist", - "file-too-large", - "illegal-byte-sequence", - "in-progress", - "interrupted", - "invalid", - "io", - "is-directory", - "loop", - "too-many-links", - "message-size", - "name-too-long", - "no-device", - "no-entry", - "no-lock", - "insufficient-memory", - "insufficient-space", - "not-directory", - "not-empty", - "not-recoverable", - "unsupported", - "no-tty", - "no-such-device", - "overflow", - "not-permitted", - "pipe", - "read-only", - "invalid-seek", - "text-file-busy", - "cross-device", -} - -// String implements [fmt.Stringer], returning the enum case name of e. -func (e ErrorCode) String() string { - return _ErrorCodeStrings[e] -} - -// MarshalText implements [encoding.TextMarshaler]. -func (e ErrorCode) MarshalText() ([]byte, error) { - return []byte(e.String()), nil -} - -// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum -// case. Returns an error if the supplied text is not one of the enum cases. -func (e *ErrorCode) UnmarshalText(text []byte) error { - return _ErrorCodeUnmarshalCase(e, text) -} - -var _ErrorCodeUnmarshalCase = cm.CaseUnmarshaler[ErrorCode](_ErrorCodeStrings[:]) - -// Advice represents the enum "wasi:filesystem/types@0.2.0#advice". -// -// File or memory access pattern advisory information. -// -// enum advice { -// normal, -// sequential, -// random, -// will-need, -// dont-need, -// no-reuse -// } -type Advice uint8 - -const ( - // The application has no advice to give on its behavior with respect - // to the specified data. - AdviceNormal Advice = iota - - // The application expects to access the specified data sequentially - // from lower offsets to higher offsets. - AdviceSequential - - // The application expects to access the specified data in a random - // order. - AdviceRandom - - // The application expects to access the specified data in the near - // future. - AdviceWillNeed - - // The application expects that it will not access the specified data - // in the near future. - AdviceDontNeed - - // The application expects to access the specified data once and then - // not reuse it thereafter. - AdviceNoReuse -) - -var _AdviceStrings = [6]string{ - "normal", - "sequential", - "random", - "will-need", - "dont-need", - "no-reuse", -} - -// String implements [fmt.Stringer], returning the enum case name of e. -func (e Advice) String() string { - return _AdviceStrings[e] -} - -// MarshalText implements [encoding.TextMarshaler]. -func (e Advice) MarshalText() ([]byte, error) { - return []byte(e.String()), nil -} - -// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum -// case. Returns an error if the supplied text is not one of the enum cases. -func (e *Advice) UnmarshalText(text []byte) error { - return _AdviceUnmarshalCase(e, text) -} - -var _AdviceUnmarshalCase = cm.CaseUnmarshaler[Advice](_AdviceStrings[:]) - -// MetadataHashValue represents the record "wasi:filesystem/types@0.2.0#metadata-hash-value". -// -// A 128-bit hash value, split into parts because wasm doesn't have a -// 128-bit integer type. -// -// record metadata-hash-value { -// lower: u64, -// upper: u64, -// } -type MetadataHashValue struct { - _ cm.HostLayout `json:"-"` - // 64 bits of a 128-bit hash value. - Lower uint64 `json:"lower"` - - // Another 64 bits of a 128-bit hash value. - Upper uint64 `json:"upper"` -} - -// Descriptor represents the imported resource "wasi:filesystem/types@0.2.0#descriptor". -// -// A descriptor is a reference to a filesystem object, which may be a file, -// directory, named pipe, special file, or other object on which filesystem -// calls may be made. -// -// resource descriptor -type Descriptor cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "descriptor". -// -// Drops a resource handle. -// -//go:nosplit -func (self Descriptor) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorResourceDrop((uint32)(self0)) - return -} - -// Advise represents the imported method "advise". -// -// Provide file advisory information on a descriptor. -// -// This is similar to `posix_fadvise` in POSIX. -// -// advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) Advise(offset FileSize, length FileSize, advice Advice) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - offset0 := (uint64)(offset) - length0 := (uint64)(length) - advice0 := (uint32)(advice) - wasmimport_DescriptorAdvise((uint32)(self0), (uint64)(offset0), (uint64)(length0), (uint32)(advice0), &result) - return -} - -// AppendViaStream represents the imported method "append-via-stream". -// -// Return a stream for appending to a file, if available. -// -// May fail with an error-code describing why the file cannot be appended. -// -// Note: This allows using `write-stream`, which is similar to `write` with -// `O_APPEND` in in POSIX. -// -// append-via-stream: func() -> result -// -//go:nosplit -func (self Descriptor) AppendViaStream() (result cm.Result[OutputStream, OutputStream, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorAppendViaStream((uint32)(self0), &result) - return -} - -// CreateDirectoryAt represents the imported method "create-directory-at". -// -// Create a directory. -// -// Note: This is similar to `mkdirat` in POSIX. -// -// create-directory-at: func(path: string) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) CreateDirectoryAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - path0, path1 := cm.LowerString(path) - wasmimport_DescriptorCreateDirectoryAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) - return -} - -// GetFlags represents the imported method "get-flags". -// -// Get flags associated with a descriptor. -// -// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. -// -// Note: This returns the value that was the `fs_flags` value returned -// from `fdstat_get` in earlier versions of WASI. -// -// get-flags: func() -> result -// -//go:nosplit -func (self Descriptor) GetFlags() (result cm.Result[DescriptorFlags, DescriptorFlags, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorGetFlags((uint32)(self0), &result) - return -} - -// GetType represents the imported method "get-type". -// -// Get the dynamic type of a descriptor. -// -// Note: This returns the same value as the `type` field of the `fd-stat` -// returned by `stat`, `stat-at` and similar. -// -// Note: This returns similar flags to the `st_mode & S_IFMT` value provided -// by `fstat` in POSIX. -// -// Note: This returns the value that was the `fs_filetype` value returned -// from `fdstat_get` in earlier versions of WASI. -// -// get-type: func() -> result -// -//go:nosplit -func (self Descriptor) GetType() (result cm.Result[DescriptorType, DescriptorType, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorGetType((uint32)(self0), &result) - return -} - -// IsSameObject represents the imported method "is-same-object". -// -// Test whether two descriptors refer to the same filesystem object. -// -// In POSIX, this corresponds to testing whether the two descriptors have the -// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. -// wasi-filesystem does not expose device and inode numbers, so this function -// may be used instead. -// -// is-same-object: func(other: borrow) -> bool -// -//go:nosplit -func (self Descriptor) IsSameObject(other Descriptor) (result bool) { - self0 := cm.Reinterpret[uint32](self) - other0 := cm.Reinterpret[uint32](other) - result0 := wasmimport_DescriptorIsSameObject((uint32)(self0), (uint32)(other0)) - result = (bool)(cm.U32ToBool((uint32)(result0))) - return -} - -// LinkAt represents the imported method "link-at". -// -// Create a hard link. -// -// Note: This is similar to `linkat` in POSIX. -// -// link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, -// new-path: string) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) LinkAt(oldPathFlags PathFlags, oldPath string, newDescriptor Descriptor, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - oldPathFlags0 := (uint32)(oldPathFlags) - oldPath0, oldPath1 := cm.LowerString(oldPath) - newDescriptor0 := cm.Reinterpret[uint32](newDescriptor) - newPath0, newPath1 := cm.LowerString(newPath) - wasmimport_DescriptorLinkAt((uint32)(self0), (uint32)(oldPathFlags0), (*uint8)(oldPath0), (uint32)(oldPath1), (uint32)(newDescriptor0), (*uint8)(newPath0), (uint32)(newPath1), &result) - return -} - -// MetadataHash represents the imported method "metadata-hash". -// -// Return a hash of the metadata associated with a filesystem object referred -// to by a descriptor. -// -// This returns a hash of the last-modification timestamp and file size, and -// may also include the inode number, device number, birth timestamp, and -// other metadata fields that may change when the file is modified or -// replaced. It may also include a secret value chosen by the -// implementation and not otherwise exposed. -// -// Implementations are encourated to provide the following properties: -// -// - If the file is not modified or replaced, the computed hash value should -// usually not change. -// - If the object is modified or replaced, the computed hash value should -// usually change. -// - The inputs to the hash should not be easily computable from the -// computed hash. -// -// However, none of these is required. -// -// metadata-hash: func() -> result -// -//go:nosplit -func (self Descriptor) MetadataHash() (result cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorMetadataHash((uint32)(self0), &result) - return -} - -// MetadataHashAt represents the imported method "metadata-hash-at". -// -// Return a hash of the metadata associated with a filesystem object referred -// to by a directory descriptor and a relative path. -// -// This performs the same hash computation as `metadata-hash`. -// -// metadata-hash-at: func(path-flags: path-flags, path: string) -> result -// -//go:nosplit -func (self Descriptor) MetadataHashAt(pathFlags PathFlags, path string) (result cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - pathFlags0 := (uint32)(pathFlags) - path0, path1 := cm.LowerString(path) - wasmimport_DescriptorMetadataHashAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), &result) - return -} - -// OpenAt represents the imported method "open-at". -// -// Open a file or directory. -// -// The returned descriptor is not guaranteed to be the lowest-numbered -// descriptor not currently open/ it is randomized to prevent applications -// from depending on making assumptions about indexes, since this is -// error-prone in multi-threaded contexts. The returned descriptor is -// guaranteed to be less than 2**31. -// -// If `flags` contains `descriptor-flags::mutate-directory`, and the base -// descriptor doesn't have `descriptor-flags::mutate-directory` set, -// `open-at` fails with `error-code::read-only`. -// -// If `flags` contains `write` or `mutate-directory`, or `open-flags` -// contains `truncate` or `create`, and the base descriptor doesn't have -// `descriptor-flags::mutate-directory` set, `open-at` fails with -// `error-code::read-only`. -// -// Note: This is similar to `openat` in POSIX. -// -// open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: -// descriptor-flags) -> result -// -//go:nosplit -func (self Descriptor) OpenAt(pathFlags PathFlags, path string, openFlags OpenFlags, flags DescriptorFlags) (result cm.Result[Descriptor, Descriptor, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - pathFlags0 := (uint32)(pathFlags) - path0, path1 := cm.LowerString(path) - openFlags0 := (uint32)(openFlags) - flags0 := (uint32)(flags) - wasmimport_DescriptorOpenAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), (uint32)(openFlags0), (uint32)(flags0), &result) - return -} - -// Read represents the imported method "read". -// -// Read from a descriptor, without using and updating the descriptor's offset. -// -// This function returns a list of bytes containing the data that was -// read, along with a bool which, when true, indicates that the end of the -// file was reached. The returned list will contain up to `length` bytes; it -// may return fewer than requested, if the end of the file is reached or -// if the I/O operation is interrupted. -// -// In the future, this may change to return a `stream`. -// -// Note: This is similar to `pread` in POSIX. -// -// read: func(length: filesize, offset: filesize) -> result, bool>, -// error-code> -// -//go:nosplit -func (self Descriptor) Read(length FileSize, offset FileSize) (result cm.Result[TupleListU8BoolShape, cm.Tuple[cm.List[uint8], bool], ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - length0 := (uint64)(length) - offset0 := (uint64)(offset) - wasmimport_DescriptorRead((uint32)(self0), (uint64)(length0), (uint64)(offset0), &result) - return -} - -// ReadDirectory represents the imported method "read-directory". -// -// Read directory entries from a directory. -// -// On filesystems where directories contain entries referring to themselves -// and their parents, often named `.` and `..` respectively, these entries -// are omitted. -// -// This always returns a new stream which starts at the beginning of the -// directory. Multiple streams may be active on the same directory, and they -// do not interfere with each other. -// -// read-directory: func() -> result -// -//go:nosplit -func (self Descriptor) ReadDirectory() (result cm.Result[DirectoryEntryStream, DirectoryEntryStream, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorReadDirectory((uint32)(self0), &result) - return -} - -// ReadViaStream represents the imported method "read-via-stream". -// -// Return a stream for reading from a file, if available. -// -// May fail with an error-code describing why the file cannot be read. -// -// Multiple read, write, and append streams may be active on the same open -// file and they do not interfere with each other. -// -// Note: This allows using `read-stream`, which is similar to `read` in POSIX. -// -// read-via-stream: func(offset: filesize) -> result -// -//go:nosplit -func (self Descriptor) ReadViaStream(offset FileSize) (result cm.Result[InputStream, InputStream, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - offset0 := (uint64)(offset) - wasmimport_DescriptorReadViaStream((uint32)(self0), (uint64)(offset0), &result) - return -} - -// ReadLinkAt represents the imported method "readlink-at". -// -// Read the contents of a symbolic link. -// -// If the contents contain an absolute or rooted path in the underlying -// filesystem, this function fails with `error-code::not-permitted`. -// -// Note: This is similar to `readlinkat` in POSIX. -// -// readlink-at: func(path: string) -> result -// -//go:nosplit -func (self Descriptor) ReadLinkAt(path string) (result cm.Result[string, string, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - path0, path1 := cm.LowerString(path) - wasmimport_DescriptorReadLinkAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) - return -} - -// RemoveDirectoryAt represents the imported method "remove-directory-at". -// -// Remove a directory. -// -// Return `error-code::not-empty` if the directory is not empty. -// -// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. -// -// remove-directory-at: func(path: string) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) RemoveDirectoryAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - path0, path1 := cm.LowerString(path) - wasmimport_DescriptorRemoveDirectoryAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) - return -} - -// RenameAt represents the imported method "rename-at". -// -// Rename a filesystem object. -// -// Note: This is similar to `renameat` in POSIX. -// -// rename-at: func(old-path: string, new-descriptor: borrow, new-path: -// string) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) RenameAt(oldPath string, newDescriptor Descriptor, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - oldPath0, oldPath1 := cm.LowerString(oldPath) - newDescriptor0 := cm.Reinterpret[uint32](newDescriptor) - newPath0, newPath1 := cm.LowerString(newPath) - wasmimport_DescriptorRenameAt((uint32)(self0), (*uint8)(oldPath0), (uint32)(oldPath1), (uint32)(newDescriptor0), (*uint8)(newPath0), (uint32)(newPath1), &result) - return -} - -// SetSize represents the imported method "set-size". -// -// Adjust the size of an open file. If this increases the file's size, the -// extra bytes are filled with zeros. -// -// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. -// -// set-size: func(size: filesize) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) SetSize(size FileSize) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - size0 := (uint64)(size) - wasmimport_DescriptorSetSize((uint32)(self0), (uint64)(size0), &result) - return -} - -// SetTimes represents the imported method "set-times". -// -// Adjust the timestamps of an open file or directory. -// -// Note: This is similar to `futimens` in POSIX. -// -// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. -// -// set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: -// new-timestamp) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) SetTimes(dataAccessTimestamp NewTimestamp, dataModificationTimestamp NewTimestamp) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - dataAccessTimestamp0, dataAccessTimestamp1, dataAccessTimestamp2 := lower_NewTimestamp(dataAccessTimestamp) - dataModificationTimestamp0, dataModificationTimestamp1, dataModificationTimestamp2 := lower_NewTimestamp(dataModificationTimestamp) - wasmimport_DescriptorSetTimes((uint32)(self0), (uint32)(dataAccessTimestamp0), (uint64)(dataAccessTimestamp1), (uint32)(dataAccessTimestamp2), (uint32)(dataModificationTimestamp0), (uint64)(dataModificationTimestamp1), (uint32)(dataModificationTimestamp2), &result) - return -} - -// SetTimesAt represents the imported method "set-times-at". -// -// Adjust the timestamps of a file or directory. -// -// Note: This is similar to `utimensat` in POSIX. -// -// Note: This was called `path_filestat_set_times` in earlier versions of -// WASI. -// -// set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: -// new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) SetTimesAt(pathFlags PathFlags, path string, dataAccessTimestamp NewTimestamp, dataModificationTimestamp NewTimestamp) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - pathFlags0 := (uint32)(pathFlags) - path0, path1 := cm.LowerString(path) - dataAccessTimestamp0, dataAccessTimestamp1, dataAccessTimestamp2 := lower_NewTimestamp(dataAccessTimestamp) - dataModificationTimestamp0, dataModificationTimestamp1, dataModificationTimestamp2 := lower_NewTimestamp(dataModificationTimestamp) - wasmimport_DescriptorSetTimesAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), (uint32)(dataAccessTimestamp0), (uint64)(dataAccessTimestamp1), (uint32)(dataAccessTimestamp2), (uint32)(dataModificationTimestamp0), (uint64)(dataModificationTimestamp1), (uint32)(dataModificationTimestamp2), &result) - return -} - -// Stat represents the imported method "stat". -// -// Return the attributes of an open file or directory. -// -// Note: This is similar to `fstat` in POSIX, except that it does not return -// device and inode information. For testing whether two descriptors refer to -// the same underlying filesystem object, use `is-same-object`. To obtain -// additional data that can be used do determine whether a file has been -// modified, use `metadata-hash`. -// -// Note: This was called `fd_filestat_get` in earlier versions of WASI. -// -// stat: func() -> result -// -//go:nosplit -func (self Descriptor) Stat() (result cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorStat((uint32)(self0), &result) - return -} - -// StatAt represents the imported method "stat-at". -// -// Return the attributes of a file or directory. -// -// Note: This is similar to `fstatat` in POSIX, except that it does not -// return device and inode information. See the `stat` description for a -// discussion of alternatives. -// -// Note: This was called `path_filestat_get` in earlier versions of WASI. -// -// stat-at: func(path-flags: path-flags, path: string) -> result -// -//go:nosplit -func (self Descriptor) StatAt(pathFlags PathFlags, path string) (result cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - pathFlags0 := (uint32)(pathFlags) - path0, path1 := cm.LowerString(path) - wasmimport_DescriptorStatAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), &result) - return -} - -// SymlinkAt represents the imported method "symlink-at". -// -// Create a symbolic link (also known as a "symlink"). -// -// If `old-path` starts with `/`, the function fails with -// `error-code::not-permitted`. -// -// Note: This is similar to `symlinkat` in POSIX. -// -// symlink-at: func(old-path: string, new-path: string) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) SymlinkAt(oldPath string, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - oldPath0, oldPath1 := cm.LowerString(oldPath) - newPath0, newPath1 := cm.LowerString(newPath) - wasmimport_DescriptorSymlinkAt((uint32)(self0), (*uint8)(oldPath0), (uint32)(oldPath1), (*uint8)(newPath0), (uint32)(newPath1), &result) - return -} - -// Sync represents the imported method "sync". -// -// Synchronize the data and metadata of a file to disk. -// -// This function succeeds with no effect if the file descriptor is not -// opened for writing. -// -// Note: This is similar to `fsync` in POSIX. -// -// sync: func() -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) Sync() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorSync((uint32)(self0), &result) - return -} - -// SyncData represents the imported method "sync-data". -// -// Synchronize the data of a file to disk. -// -// This function succeeds with no effect if the file descriptor is not -// opened for writing. -// -// Note: This is similar to `fdatasync` in POSIX. -// -// sync-data: func() -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) SyncData() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DescriptorSyncData((uint32)(self0), &result) - return -} - -// UnlinkFileAt represents the imported method "unlink-file-at". -// -// Unlink a filesystem object that is not a directory. -// -// Return `error-code::is-directory` if the path refers to a directory. -// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. -// -// unlink-file-at: func(path: string) -> result<_, error-code> -// -//go:nosplit -func (self Descriptor) UnlinkFileAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - path0, path1 := cm.LowerString(path) - wasmimport_DescriptorUnlinkFileAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) - return -} - -// Write represents the imported method "write". -// -// Write to a descriptor, without using and updating the descriptor's offset. -// -// It is valid to write past the end of a file; the file is extended to the -// extent of the write, with bytes between the previous end and the start of -// the write set to zero. -// -// In the future, this may change to take a `stream`. -// -// Note: This is similar to `pwrite` in POSIX. -// -// write: func(buffer: list, offset: filesize) -> result -// -//go:nosplit -func (self Descriptor) Write(buffer cm.List[uint8], offset FileSize) (result cm.Result[uint64, FileSize, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - buffer0, buffer1 := cm.LowerList(buffer) - offset0 := (uint64)(offset) - wasmimport_DescriptorWrite((uint32)(self0), (*uint8)(buffer0), (uint32)(buffer1), (uint64)(offset0), &result) - return -} - -// WriteViaStream represents the imported method "write-via-stream". -// -// Return a stream for writing to a file, if available. -// -// May fail with an error-code describing why the file cannot be written. -// -// Note: This allows using `write-stream`, which is similar to `write` in -// POSIX. -// -// write-via-stream: func(offset: filesize) -> result -// -//go:nosplit -func (self Descriptor) WriteViaStream(offset FileSize) (result cm.Result[OutputStream, OutputStream, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - offset0 := (uint64)(offset) - wasmimport_DescriptorWriteViaStream((uint32)(self0), (uint64)(offset0), &result) - return -} - -// DirectoryEntryStream represents the imported resource "wasi:filesystem/types@0.2.0#directory-entry-stream". -// -// A stream of directory entries. -// -// resource directory-entry-stream -type DirectoryEntryStream cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "directory-entry-stream". -// -// Drops a resource handle. -// -//go:nosplit -func (self DirectoryEntryStream) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DirectoryEntryStreamResourceDrop((uint32)(self0)) - return -} - -// ReadDirectoryEntry represents the imported method "read-directory-entry". -// -// Read a single directory entry from a `directory-entry-stream`. -// -// read-directory-entry: func() -> result, error-code> -// -//go:nosplit -func (self DirectoryEntryStream) ReadDirectoryEntry() (result cm.Result[OptionDirectoryEntryShape, cm.Option[DirectoryEntry], ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_DirectoryEntryStreamReadDirectoryEntry((uint32)(self0), &result) - return -} - -// FilesystemErrorCode represents the imported function "filesystem-error-code". -// -// Attempts to extract a filesystem-related `error-code` from the stream -// `error` provided. -// -// Stream operations which return `stream-error::last-operation-failed` -// have a payload with more information about the operation that failed. -// This payload can be passed through to this function to see if there's -// filesystem-related information about the error to return. -// -// Note that this function is fallible because not all stream-related -// errors are filesystem-related errors. -// -// filesystem-error-code: func(err: borrow) -> option -// -//go:nosplit -func FilesystemErrorCode(err Error) (result cm.Option[ErrorCode]) { - err0 := cm.Reinterpret[uint32](err) - wasmimport_FilesystemErrorCode((uint32)(err0), &result) - return -} diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/empty.s b/x/wasihttp/internal/wasi/http/incoming-handler/empty.s old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.exports.go b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.exports.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wasm.go b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wasm.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wit.go b/x/wasihttp/internal/wasi/http/incoming-handler/incoming-handler.wit.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/abi.go b/x/wasihttp/internal/wasi/http/outgoing-handler/abi.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/empty.s b/x/wasihttp/internal/wasi/http/outgoing-handler/empty.s old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wasm.go b/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wasm.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wit.go b/x/wasihttp/internal/wasi/http/outgoing-handler/outgoing-handler.wit.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/types/abi.go b/x/wasihttp/internal/wasi/http/types/abi.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/types/empty.s b/x/wasihttp/internal/wasi/http/types/empty.s old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/types/types.wasm.go b/x/wasihttp/internal/wasi/http/types/types.wasm.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/http/types/types.wit.go b/x/wasihttp/internal/wasi/http/types/types.wit.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/error/empty.s b/x/wasihttp/internal/wasi/io/error/empty.s old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/error/error.wasm.go b/x/wasihttp/internal/wasi/io/error/error.wasm.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/error/error.wit.go b/x/wasihttp/internal/wasi/io/error/error.wit.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/poll/empty.s b/x/wasihttp/internal/wasi/io/poll/empty.s old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/poll/poll.wasm.go b/x/wasihttp/internal/wasi/io/poll/poll.wasm.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/poll/poll.wit.go b/x/wasihttp/internal/wasi/io/poll/poll.wit.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/streams/empty.s b/x/wasihttp/internal/wasi/io/streams/empty.s old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/streams/streams.wasm.go b/x/wasihttp/internal/wasi/io/streams/streams.wasm.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/io/streams/streams.wit.go b/x/wasihttp/internal/wasi/io/streams/streams.wit.go old mode 100755 new mode 100644 diff --git a/x/wasihttp/internal/wasi/random/insecure-seed/empty.s b/x/wasihttp/internal/wasi/random/insecure-seed/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/random/insecure-seed/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go b/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go deleted file mode 100755 index e94356df..00000000 --- a/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package insecureseed - -// This file contains wasmimport and wasmexport declarations for "wasi:random@0.2.0". - -//go:wasmimport wasi:random/insecure-seed@0.2.0 insecure-seed -//go:noescape -func wasmimport_InsecureSeed(result *[2]uint64) diff --git a/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go b/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go deleted file mode 100755 index 6f363673..00000000 --- a/x/wasihttp/internal/wasi/random/insecure-seed/insecure-seed.wit.go +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package insecureseed represents the imported interface "wasi:random/insecure-seed@0.2.0". -// -// The insecure-seed interface for seeding hash-map DoS resistance. -// -// It is intended to be portable at least between Unix-family platforms and -// Windows. -package insecureseed - -// InsecureSeed represents the imported function "insecure-seed". -// -// Return a 128-bit value that may contain a pseudo-random value. -// -// The returned value is not required to be computed from a CSPRNG, and may -// even be entirely deterministic. Host implementations are encouraged to -// provide pseudo-random values to any program exposed to -// attacker-controlled content, to enable DoS protection built into many -// languages' hash-map implementations. -// -// This function is intended to only be called once, by a source language -// to initialize Denial Of Service (DoS) protection in its hash-map -// implementation. -// -// # Expected future evolution -// -// This will likely be changed to a value import, to prevent it from being -// called multiple times and potentially used for purposes other than DoS -// protection. -// -// insecure-seed: func() -> tuple -// -//go:nosplit -func InsecureSeed() (result [2]uint64) { - wasmimport_InsecureSeed(&result) - return -} diff --git a/x/wasihttp/internal/wasi/random/insecure/empty.s b/x/wasihttp/internal/wasi/random/insecure/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/random/insecure/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go b/x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go deleted file mode 100755 index 498bfe4a..00000000 --- a/x/wasihttp/internal/wasi/random/insecure/insecure.wasm.go +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package insecure - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:random@0.2.0". - -//go:wasmimport wasi:random/insecure@0.2.0 get-insecure-random-bytes -//go:noescape -func wasmimport_GetInsecureRandomBytes(len0 uint64, result *cm.List[uint8]) - -//go:wasmimport wasi:random/insecure@0.2.0 get-insecure-random-u64 -//go:noescape -func wasmimport_GetInsecureRandomU64() (result0 uint64) diff --git a/x/wasihttp/internal/wasi/random/insecure/insecure.wit.go b/x/wasihttp/internal/wasi/random/insecure/insecure.wit.go deleted file mode 100755 index 295a1ada..00000000 --- a/x/wasihttp/internal/wasi/random/insecure/insecure.wit.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package insecure represents the imported interface "wasi:random/insecure@0.2.0". -// -// The insecure interface for insecure pseudo-random numbers. -// -// It is intended to be portable at least between Unix-family platforms and -// Windows. -package insecure - -import ( - "go.bytecodealliance.org/cm" -) - -// GetInsecureRandomBytes represents the imported function "get-insecure-random-bytes". -// -// Return `len` insecure pseudo-random bytes. -// -// This function is not cryptographically secure. Do not use it for -// anything related to security. -// -// There are no requirements on the values of the returned bytes, however -// implementations are encouraged to return evenly distributed values with -// a long period. -// -// get-insecure-random-bytes: func(len: u64) -> list -// -//go:nosplit -func GetInsecureRandomBytes(len_ uint64) (result cm.List[uint8]) { - len0 := (uint64)(len_) - wasmimport_GetInsecureRandomBytes((uint64)(len0), &result) - return -} - -// GetInsecureRandomU64 represents the imported function "get-insecure-random-u64". -// -// Return an insecure pseudo-random `u64` value. -// -// This function returns the same type of pseudo-random data as -// `get-insecure-random-bytes`, represented as a `u64`. -// -// get-insecure-random-u64: func() -> u64 -// -//go:nosplit -func GetInsecureRandomU64() (result uint64) { - result0 := wasmimport_GetInsecureRandomU64() - result = (uint64)((uint64)(result0)) - return -} diff --git a/x/wasihttp/internal/wasi/random/random/empty.s b/x/wasihttp/internal/wasi/random/random/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/random/random/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/random/random/random.wasm.go b/x/wasihttp/internal/wasi/random/random/random.wasm.go deleted file mode 100755 index 9096457b..00000000 --- a/x/wasihttp/internal/wasi/random/random/random.wasm.go +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package random - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:random@0.2.0". - -//go:wasmimport wasi:random/random@0.2.0 get-random-bytes -//go:noescape -func wasmimport_GetRandomBytes(len0 uint64, result *cm.List[uint8]) - -//go:wasmimport wasi:random/random@0.2.0 get-random-u64 -//go:noescape -func wasmimport_GetRandomU64() (result0 uint64) diff --git a/x/wasihttp/internal/wasi/random/random/random.wit.go b/x/wasihttp/internal/wasi/random/random/random.wit.go deleted file mode 100755 index bb90e7e0..00000000 --- a/x/wasihttp/internal/wasi/random/random/random.wit.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package random represents the imported interface "wasi:random/random@0.2.0". -// -// WASI Random is a random data API. -// -// It is intended to be portable at least between Unix-family platforms and -// Windows. -package random - -import ( - "go.bytecodealliance.org/cm" -) - -// GetRandomBytes represents the imported function "get-random-bytes". -// -// Return `len` cryptographically-secure random or pseudo-random bytes. -// -// This function must produce data at least as cryptographically secure and -// fast as an adequately seeded cryptographically-secure pseudo-random -// number generator (CSPRNG). It must not block, from the perspective of -// the calling program, under any circumstances, including on the first -// request and on requests for numbers of bytes. The returned data must -// always be unpredictable. -// -// This function must always return fresh data. Deterministic environments -// must omit this function, rather than implementing it with deterministic -// data. -// -// get-random-bytes: func(len: u64) -> list -// -//go:nosplit -func GetRandomBytes(len_ uint64) (result cm.List[uint8]) { - len0 := (uint64)(len_) - wasmimport_GetRandomBytes((uint64)(len0), &result) - return -} - -// GetRandomU64 represents the imported function "get-random-u64". -// -// Return a cryptographically-secure random or pseudo-random `u64` value. -// -// This function returns the same type of data as `get-random-bytes`, -// represented as a `u64`. -// -// get-random-u64: func() -> u64 -// -//go:nosplit -func GetRandomU64() (result uint64) { - result0 := wasmimport_GetRandomU64() - result = (uint64)((uint64)(result0)) - return -} diff --git a/x/wasihttp/internal/wasi/sockets/instance-network/empty.s b/x/wasihttp/internal/wasi/sockets/instance-network/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/sockets/instance-network/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go b/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go deleted file mode 100755 index eb113e21..00000000 --- a/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package instancenetwork - -// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". - -//go:wasmimport wasi:sockets/instance-network@0.2.0 instance-network -//go:noescape -func wasmimport_InstanceNetwork() (result0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go b/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go deleted file mode 100755 index b121bba8..00000000 --- a/x/wasihttp/internal/wasi/sockets/instance-network/instance-network.wit.go +++ /dev/null @@ -1,29 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package instancenetwork represents the imported interface "wasi:sockets/instance-network@0.2.0". -// -// This interface provides a value-export of the default network handle.. -package instancenetwork - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" -) - -// Network represents the imported type alias "wasi:sockets/instance-network@0.2.0#network". -// -// See [network.Network] for more information. -type Network = network.Network - -// InstanceNetwork represents the imported function "instance-network". -// -// Get a handle to the default network. -// -// instance-network: func() -> network -// -//go:nosplit -func InstanceNetwork() (result Network) { - result0 := wasmimport_InstanceNetwork() - result = cm.Reinterpret[Network]((uint32)(result0)) - return -} diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go deleted file mode 100755 index a63f0d01..00000000 --- a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/abi.go +++ /dev/null @@ -1,14 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package ipnamelookup - -import ( - "go.bytecodealliance.org/cm" - "unsafe" -) - -// OptionIPAddressShape is used for storage in variant or result types. -type OptionIPAddressShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(cm.Option[IPAddress]{})]byte -} diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go deleted file mode 100755 index da5fb000..00000000 --- a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wasm.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package ipnamelookup - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". - -//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [resource-drop]resolve-address-stream -//go:noescape -func wasmimport_ResolveAddressStreamResourceDrop(self0 uint32) - -//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [method]resolve-address-stream.resolve-next-address -//go:noescape -func wasmimport_ResolveAddressStreamResolveNextAddress(self0 uint32, result *cm.Result[OptionIPAddressShape, cm.Option[IPAddress], ErrorCode]) - -//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [method]resolve-address-stream.subscribe -//go:noescape -func wasmimport_ResolveAddressStreamSubscribe(self0 uint32) (result0 uint32) - -//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 resolve-addresses -//go:noescape -func wasmimport_ResolveAddresses(network0 uint32, name0 *uint8, name1 uint32, result *cm.Result[ResolveAddressStream, ResolveAddressStream, ErrorCode]) diff --git a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go b/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go deleted file mode 100755 index 75850950..00000000 --- a/x/wasihttp/internal/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go +++ /dev/null @@ -1,125 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package ipnamelookup represents the imported interface "wasi:sockets/ip-name-lookup@0.2.0". -package ipnamelookup - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" -) - -// Pollable represents the imported type alias "wasi:sockets/ip-name-lookup@0.2.0#pollable". -// -// See [poll.Pollable] for more information. -type Pollable = poll.Pollable - -// Network represents the imported type alias "wasi:sockets/ip-name-lookup@0.2.0#network". -// -// See [network.Network] for more information. -type Network = network.Network - -// ErrorCode represents the type alias "wasi:sockets/ip-name-lookup@0.2.0#error-code". -// -// See [network.ErrorCode] for more information. -type ErrorCode = network.ErrorCode - -// IPAddress represents the type alias "wasi:sockets/ip-name-lookup@0.2.0#ip-address". -// -// See [network.IPAddress] for more information. -type IPAddress = network.IPAddress - -// ResolveAddressStream represents the imported resource "wasi:sockets/ip-name-lookup@0.2.0#resolve-address-stream". -// -// resource resolve-address-stream -type ResolveAddressStream cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "resolve-address-stream". -// -// Drops a resource handle. -// -//go:nosplit -func (self ResolveAddressStream) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_ResolveAddressStreamResourceDrop((uint32)(self0)) - return -} - -// ResolveNextAddress represents the imported method "resolve-next-address". -// -// Returns the next address from the resolver. -// -// This function should be called multiple times. On each call, it will -// return the next address in connection order preference. If all -// addresses have been exhausted, this function returns `none`. -// -// This function never returns IPv4-mapped IPv6 addresses. -// -// # Typical errors -// - `name-unresolvable`: Name does not exist or has no suitable associated -// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) -// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. -// (EAI_AGAIN) -// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. -// (EAI_FAIL) -// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) -// -// resolve-next-address: func() -> result, error-code> -// -//go:nosplit -func (self ResolveAddressStream) ResolveNextAddress() (result cm.Result[OptionIPAddressShape, cm.Option[IPAddress], ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_ResolveAddressStreamResolveNextAddress((uint32)(self0), &result) - return -} - -// Subscribe represents the imported method "subscribe". -// -// Create a `pollable` which will resolve once the stream is ready for I/O. -// -// Note: this function is here for WASI Preview2 only. -// It's planned to be removed when `future` is natively supported in Preview3. -// -// subscribe: func() -> pollable -// -//go:nosplit -func (self ResolveAddressStream) Subscribe() (result Pollable) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_ResolveAddressStreamSubscribe((uint32)(self0)) - result = cm.Reinterpret[Pollable]((uint32)(result0)) - return -} - -// ResolveAddresses represents the imported function "resolve-addresses". -// -// Resolve an internet host name to a list of IP addresses. -// -// Unicode domain names are automatically converted to ASCII using IDNA encoding. -// If the input is an IP address string, the address is parsed and returned -// as-is without making any external requests. -// -// See the wasi-socket proposal README.md for a comparison with getaddrinfo. -// -// This function never blocks. It either immediately fails or immediately -// returns successfully with a `resolve-address-stream` that can be used -// to (asynchronously) fetch the results. -// -// # Typical errors -// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. -// -// # References: -// - -// - -// - -// - -// -// resolve-addresses: func(network: borrow, name: string) -> result -// -//go:nosplit -func ResolveAddresses(network_ Network, name string) (result cm.Result[ResolveAddressStream, ResolveAddressStream, ErrorCode]) { - network0 := cm.Reinterpret[uint32](network_) - name0, name1 := cm.LowerString(name) - wasmimport_ResolveAddresses((uint32)(network0), (*uint8)(name0), (uint32)(name1), &result) - return -} diff --git a/x/wasihttp/internal/wasi/sockets/network/abi.go b/x/wasihttp/internal/wasi/sockets/network/abi.go deleted file mode 100755 index a088bd1d..00000000 --- a/x/wasihttp/internal/wasi/sockets/network/abi.go +++ /dev/null @@ -1,14 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package network - -import ( - "go.bytecodealliance.org/cm" - "unsafe" -) - -// IPv6SocketAddressShape is used for storage in variant or result types. -type IPv6SocketAddressShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(IPv6SocketAddress{})]byte -} diff --git a/x/wasihttp/internal/wasi/sockets/network/empty.s b/x/wasihttp/internal/wasi/sockets/network/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/sockets/network/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/network/network.wasm.go b/x/wasihttp/internal/wasi/sockets/network/network.wasm.go deleted file mode 100755 index 012a79ff..00000000 --- a/x/wasihttp/internal/wasi/sockets/network/network.wasm.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package network - -// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". - -//go:wasmimport wasi:sockets/network@0.2.0 [resource-drop]network -//go:noescape -func wasmimport_NetworkResourceDrop(self0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/network/network.wit.go b/x/wasihttp/internal/wasi/sockets/network/network.wit.go deleted file mode 100755 index a37b5b9a..00000000 --- a/x/wasihttp/internal/wasi/sockets/network/network.wit.go +++ /dev/null @@ -1,359 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package network represents the imported interface "wasi:sockets/network@0.2.0". -package network - -import ( - "go.bytecodealliance.org/cm" -) - -// Network represents the imported resource "wasi:sockets/network@0.2.0#network". -// -// An opaque resource that represents access to (a subset of) the network. -// This enables context-based security for networking. -// There is no need for this to map 1:1 to a physical network interface. -// -// resource network -type Network cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "network". -// -// Drops a resource handle. -// -//go:nosplit -func (self Network) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_NetworkResourceDrop((uint32)(self0)) - return -} - -// ErrorCode represents the enum "wasi:sockets/network@0.2.0#error-code". -// -// Error codes. -// -// In theory, every API can return any error code. -// In practice, API's typically only return the errors documented per API -// combined with a couple of errors that are always possible: -// - `unknown` -// - `access-denied` -// - `not-supported` -// - `out-of-memory` -// - `concurrency-conflict` -// -// See each individual API for what the POSIX equivalents are. They sometimes differ -// per API. -// -// enum error-code { -// unknown, -// access-denied, -// not-supported, -// invalid-argument, -// out-of-memory, -// timeout, -// concurrency-conflict, -// not-in-progress, -// would-block, -// invalid-state, -// new-socket-limit, -// address-not-bindable, -// address-in-use, -// remote-unreachable, -// connection-refused, -// connection-reset, -// connection-aborted, -// datagram-too-large, -// name-unresolvable, -// temporary-resolver-failure, -// permanent-resolver-failure -// } -type ErrorCode uint8 - -const ( - // Unknown error - ErrorCodeUnknown ErrorCode = iota - - // Access denied. - // - // POSIX equivalent: EACCES, EPERM - ErrorCodeAccessDenied - - // The operation is not supported. - // - // POSIX equivalent: EOPNOTSUPP - ErrorCodeNotSupported - - // One of the arguments is invalid. - // - // POSIX equivalent: EINVAL - ErrorCodeInvalidArgument - - // Not enough memory to complete the operation. - // - // POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY - ErrorCodeOutOfMemory - - // The operation timed out before it could finish completely. - ErrorCodeTimeout - - // This operation is incompatible with another asynchronous operation that is already - // in progress. - // - // POSIX equivalent: EALREADY - ErrorCodeConcurrencyConflict - - // Trying to finish an asynchronous operation that: - // - has not been started yet, or: - // - was already finished by a previous `finish-*` call. - // - // Note: this is scheduled to be removed when `future`s are natively supported. - ErrorCodeNotInProgress - - // The operation has been aborted because it could not be completed immediately. - // - // Note: this is scheduled to be removed when `future`s are natively supported. - ErrorCodeWouldBlock - - // The operation is not valid in the socket's current state. - ErrorCodeInvalidState - - // A new socket resource could not be created because of a system limit. - ErrorCodeNewSocketLimit - - // A bind operation failed because the provided address is not an address that the - // `network` can bind to. - ErrorCodeAddressNotBindable - - // A bind operation failed because the provided address is already in use or because - // there are no ephemeral ports available. - ErrorCodeAddressInUse - - // The remote address is not reachable - ErrorCodeRemoteUnreachable - - // The TCP connection was forcefully rejected - ErrorCodeConnectionRefused - - // The TCP connection was reset. - ErrorCodeConnectionReset - - // A TCP connection was aborted. - ErrorCodeConnectionAborted - - // The size of a datagram sent to a UDP socket exceeded the maximum - // supported size. - ErrorCodeDatagramTooLarge - - // Name does not exist or has no suitable associated IP addresses. - ErrorCodeNameUnresolvable - - // A temporary failure in name resolution occurred. - ErrorCodeTemporaryResolverFailure - - // A permanent failure in name resolution occurred. - ErrorCodePermanentResolverFailure -) - -var _ErrorCodeStrings = [21]string{ - "unknown", - "access-denied", - "not-supported", - "invalid-argument", - "out-of-memory", - "timeout", - "concurrency-conflict", - "not-in-progress", - "would-block", - "invalid-state", - "new-socket-limit", - "address-not-bindable", - "address-in-use", - "remote-unreachable", - "connection-refused", - "connection-reset", - "connection-aborted", - "datagram-too-large", - "name-unresolvable", - "temporary-resolver-failure", - "permanent-resolver-failure", -} - -// String implements [fmt.Stringer], returning the enum case name of e. -func (e ErrorCode) String() string { - return _ErrorCodeStrings[e] -} - -// MarshalText implements [encoding.TextMarshaler]. -func (e ErrorCode) MarshalText() ([]byte, error) { - return []byte(e.String()), nil -} - -// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum -// case. Returns an error if the supplied text is not one of the enum cases. -func (e *ErrorCode) UnmarshalText(text []byte) error { - return _ErrorCodeUnmarshalCase(e, text) -} - -var _ErrorCodeUnmarshalCase = cm.CaseUnmarshaler[ErrorCode](_ErrorCodeStrings[:]) - -// IPAddressFamily represents the enum "wasi:sockets/network@0.2.0#ip-address-family". -// -// enum ip-address-family { -// ipv4, -// ipv6 -// } -type IPAddressFamily uint8 - -const ( - // Similar to `AF_INET` in POSIX. - IPAddressFamilyIPv4 IPAddressFamily = iota - - // Similar to `AF_INET6` in POSIX. - IPAddressFamilyIPv6 -) - -var _IPAddressFamilyStrings = [2]string{ - "ipv4", - "ipv6", -} - -// String implements [fmt.Stringer], returning the enum case name of e. -func (e IPAddressFamily) String() string { - return _IPAddressFamilyStrings[e] -} - -// MarshalText implements [encoding.TextMarshaler]. -func (e IPAddressFamily) MarshalText() ([]byte, error) { - return []byte(e.String()), nil -} - -// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum -// case. Returns an error if the supplied text is not one of the enum cases. -func (e *IPAddressFamily) UnmarshalText(text []byte) error { - return _IPAddressFamilyUnmarshalCase(e, text) -} - -var _IPAddressFamilyUnmarshalCase = cm.CaseUnmarshaler[IPAddressFamily](_IPAddressFamilyStrings[:]) - -// IPv4Address represents the tuple "wasi:sockets/network@0.2.0#ipv4-address". -// -// type ipv4-address = tuple -type IPv4Address [4]uint8 - -// IPv6Address represents the tuple "wasi:sockets/network@0.2.0#ipv6-address". -// -// type ipv6-address = tuple -type IPv6Address [8]uint16 - -// IPAddress represents the variant "wasi:sockets/network@0.2.0#ip-address". -// -// variant ip-address { -// ipv4(ipv4-address), -// ipv6(ipv6-address), -// } -type IPAddress cm.Variant[uint8, IPv6Address, IPv6Address] - -// IPAddressIPv4 returns a [IPAddress] of case "ipv4". -func IPAddressIPv4(data IPv4Address) IPAddress { - return cm.New[IPAddress](0, data) -} - -// IPv4 returns a non-nil *[IPv4Address] if [IPAddress] represents the variant case "ipv4". -func (self *IPAddress) IPv4() *IPv4Address { - return cm.Case[IPv4Address](self, 0) -} - -// IPAddressIPv6 returns a [IPAddress] of case "ipv6". -func IPAddressIPv6(data IPv6Address) IPAddress { - return cm.New[IPAddress](1, data) -} - -// IPv6 returns a non-nil *[IPv6Address] if [IPAddress] represents the variant case "ipv6". -func (self *IPAddress) IPv6() *IPv6Address { - return cm.Case[IPv6Address](self, 1) -} - -var _IPAddressStrings = [2]string{ - "ipv4", - "ipv6", -} - -// String implements [fmt.Stringer], returning the variant case name of v. -func (v IPAddress) String() string { - return _IPAddressStrings[v.Tag()] -} - -// IPv4SocketAddress represents the record "wasi:sockets/network@0.2.0#ipv4-socket-address". -// -// record ipv4-socket-address { -// port: u16, -// address: ipv4-address, -// } -type IPv4SocketAddress struct { - _ cm.HostLayout `json:"-"` - // sin_port - Port uint16 `json:"port"` - - // sin_addr - Address IPv4Address `json:"address"` -} - -// IPv6SocketAddress represents the record "wasi:sockets/network@0.2.0#ipv6-socket-address". -// -// record ipv6-socket-address { -// port: u16, -// flow-info: u32, -// address: ipv6-address, -// scope-id: u32, -// } -type IPv6SocketAddress struct { - _ cm.HostLayout `json:"-"` - // sin6_port - Port uint16 `json:"port"` - - // sin6_flowinfo - FlowInfo uint32 `json:"flow-info"` - - // sin6_addr - Address IPv6Address `json:"address"` - - // sin6_scope_id - ScopeID uint32 `json:"scope-id"` -} - -// IPSocketAddress represents the variant "wasi:sockets/network@0.2.0#ip-socket-address". -// -// variant ip-socket-address { -// ipv4(ipv4-socket-address), -// ipv6(ipv6-socket-address), -// } -type IPSocketAddress cm.Variant[uint8, IPv6SocketAddressShape, IPv6SocketAddress] - -// IPSocketAddressIPv4 returns a [IPSocketAddress] of case "ipv4". -func IPSocketAddressIPv4(data IPv4SocketAddress) IPSocketAddress { - return cm.New[IPSocketAddress](0, data) -} - -// IPv4 returns a non-nil *[IPv4SocketAddress] if [IPSocketAddress] represents the variant case "ipv4". -func (self *IPSocketAddress) IPv4() *IPv4SocketAddress { - return cm.Case[IPv4SocketAddress](self, 0) -} - -// IPSocketAddressIPv6 returns a [IPSocketAddress] of case "ipv6". -func IPSocketAddressIPv6(data IPv6SocketAddress) IPSocketAddress { - return cm.New[IPSocketAddress](1, data) -} - -// IPv6 returns a non-nil *[IPv6SocketAddress] if [IPSocketAddress] represents the variant case "ipv6". -func (self *IPSocketAddress) IPv6() *IPv6SocketAddress { - return cm.Case[IPv6SocketAddress](self, 1) -} - -var _IPSocketAddressStrings = [2]string{ - "ipv4", - "ipv6", -} - -// String implements [fmt.Stringer], returning the variant case name of v. -func (v IPSocketAddress) String() string { - return _IPSocketAddressStrings[v.Tag()] -} diff --git a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go deleted file mode 100755 index b7b43155..00000000 --- a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wasm.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package tcpcreatesocket - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". - -//go:wasmimport wasi:sockets/tcp-create-socket@0.2.0 create-tcp-socket -//go:noescape -func wasmimport_CreateTCPSocket(addressFamily0 uint32, result *cm.Result[TCPSocket, TCPSocket, ErrorCode]) diff --git a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go b/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go deleted file mode 100755 index b4becffe..00000000 --- a/x/wasihttp/internal/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package tcpcreatesocket represents the imported interface "wasi:sockets/tcp-create-socket@0.2.0". -package tcpcreatesocket - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/tcp" -) - -// Network represents the imported type alias "wasi:sockets/tcp-create-socket@0.2.0#network". -// -// See [network.Network] for more information. -type Network = network.Network - -// ErrorCode represents the type alias "wasi:sockets/tcp-create-socket@0.2.0#error-code". -// -// See [network.ErrorCode] for more information. -type ErrorCode = network.ErrorCode - -// IPAddressFamily represents the type alias "wasi:sockets/tcp-create-socket@0.2.0#ip-address-family". -// -// See [network.IPAddressFamily] for more information. -type IPAddressFamily = network.IPAddressFamily - -// TCPSocket represents the imported type alias "wasi:sockets/tcp-create-socket@0.2.0#tcp-socket". -// -// See [tcp.TCPSocket] for more information. -type TCPSocket = tcp.TCPSocket - -// CreateTCPSocket represents the imported function "create-tcp-socket". -// -// Create a new TCP socket. -// -// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. -// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. -// -// This function does not require a network capability handle. This is considered -// to be safe because -// at time of creation, the socket is not bound to any `network` yet. Up to the moment -// `bind`/`connect` -// is called, the socket is effectively an in-memory configuration object, unable -// to communicate with the outside world. -// -// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous -// operations. -// -// # Typical errors -// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) -// - `new-socket-limit`: The new socket resource could not be created because of -// a system limit. (EMFILE, ENFILE) -// -// # References -// - -// - -// - -// - -// -// create-tcp-socket: func(address-family: ip-address-family) -> result -// -//go:nosplit -func CreateTCPSocket(addressFamily IPAddressFamily) (result cm.Result[TCPSocket, TCPSocket, ErrorCode]) { - addressFamily0 := (uint32)(addressFamily) - wasmimport_CreateTCPSocket((uint32)(addressFamily0), &result) - return -} diff --git a/x/wasihttp/internal/wasi/sockets/tcp/abi.go b/x/wasihttp/internal/wasi/sockets/tcp/abi.go deleted file mode 100755 index e8e14e07..00000000 --- a/x/wasihttp/internal/wasi/sockets/tcp/abi.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package tcp - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" - "unsafe" -) - -// TupleTCPSocketInputStreamOutputStreamShape is used for storage in variant or result types. -type TupleTCPSocketInputStreamOutputStreamShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(cm.Tuple3[TCPSocket, InputStream, OutputStream]{})]byte -} - -// TupleInputStreamOutputStreamShape is used for storage in variant or result types. -type TupleInputStreamOutputStreamShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(cm.Tuple[InputStream, OutputStream]{})]byte -} - -// IPSocketAddressShape is used for storage in variant or result types. -type IPSocketAddressShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(IPSocketAddress{})]byte -} - -func lower_IPv4Address(v network.IPv4Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32) { - f0 = (uint32)(v[0]) - f1 = (uint32)(v[1]) - f2 = (uint32)(v[2]) - f3 = (uint32)(v[3]) - return -} - -func lower_IPv4SocketAddress(v network.IPv4SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32) { - f0 = (uint32)(v.Port) - f1, f2, f3, f4 = lower_IPv4Address(v.Address) - return -} - -func lower_IPv6Address(v network.IPv6Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { - f0 = (uint32)(v[0]) - f1 = (uint32)(v[1]) - f2 = (uint32)(v[2]) - f3 = (uint32)(v[3]) - f4 = (uint32)(v[4]) - f5 = (uint32)(v[5]) - f6 = (uint32)(v[6]) - f7 = (uint32)(v[7]) - return -} - -func lower_IPv6SocketAddress(v network.IPv6SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32) { - f0 = (uint32)(v.Port) - f1 = (uint32)(v.FlowInfo) - f2, f3, f4, f5, f6, f7, f8, f9 = lower_IPv6Address(v.Address) - f10 = (uint32)(v.ScopeID) - return -} - -func lower_IPSocketAddress(v network.IPSocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32) { - f0 = (uint32)(v.Tag()) - switch f0 { - case 0: // ipv4 - v1, v2, v3, v4, v5 := lower_IPv4SocketAddress(*cm.Case[network.IPv4SocketAddress](&v, 0)) - f1 = (uint32)(v1) - f2 = (uint32)(v2) - f3 = (uint32)(v3) - f4 = (uint32)(v4) - f5 = (uint32)(v5) - case 1: // ipv6 - v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 := lower_IPv6SocketAddress(*cm.Case[network.IPv6SocketAddress](&v, 1)) - f1 = (uint32)(v1) - f2 = (uint32)(v2) - f3 = (uint32)(v3) - f4 = (uint32)(v4) - f5 = (uint32)(v5) - f6 = (uint32)(v6) - f7 = (uint32)(v7) - f8 = (uint32)(v8) - f9 = (uint32)(v9) - f10 = (uint32)(v10) - f11 = (uint32)(v11) - } - return -} diff --git a/x/wasihttp/internal/wasi/sockets/tcp/empty.s b/x/wasihttp/internal/wasi/sockets/tcp/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/sockets/tcp/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go b/x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go deleted file mode 100755 index d6e56c26..00000000 --- a/x/wasihttp/internal/wasi/sockets/tcp/tcp.wasm.go +++ /dev/null @@ -1,125 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package tcp - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". - -//go:wasmimport wasi:sockets/tcp@0.2.0 [resource-drop]tcp-socket -//go:noescape -func wasmimport_TCPSocketResourceDrop(self0 uint32) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.accept -//go:noescape -func wasmimport_TCPSocketAccept(self0 uint32, result *cm.Result[TupleTCPSocketInputStreamOutputStreamShape, cm.Tuple3[TCPSocket, InputStream, OutputStream], ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.address-family -//go:noescape -func wasmimport_TCPSocketAddressFamily(self0 uint32) (result0 uint32) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-bind -//go:noescape -func wasmimport_TCPSocketFinishBind(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-connect -//go:noescape -func wasmimport_TCPSocketFinishConnect(self0 uint32, result *cm.Result[TupleInputStreamOutputStreamShape, cm.Tuple[InputStream, OutputStream], ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-listen -//go:noescape -func wasmimport_TCPSocketFinishListen(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.hop-limit -//go:noescape -func wasmimport_TCPSocketHopLimit(self0 uint32, result *cm.Result[uint8, uint8, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.is-listening -//go:noescape -func wasmimport_TCPSocketIsListening(self0 uint32) (result0 uint32) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-count -//go:noescape -func wasmimport_TCPSocketKeepAliveCount(self0 uint32, result *cm.Result[uint32, uint32, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-enabled -//go:noescape -func wasmimport_TCPSocketKeepAliveEnabled(self0 uint32, result *cm.Result[ErrorCode, bool, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-idle-time -//go:noescape -func wasmimport_TCPSocketKeepAliveIdleTime(self0 uint32, result *cm.Result[uint64, Duration, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-interval -//go:noescape -func wasmimport_TCPSocketKeepAliveInterval(self0 uint32, result *cm.Result[uint64, Duration, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.local-address -//go:noescape -func wasmimport_TCPSocketLocalAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.receive-buffer-size -//go:noescape -func wasmimport_TCPSocketReceiveBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.remote-address -//go:noescape -func wasmimport_TCPSocketRemoteAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.send-buffer-size -//go:noescape -func wasmimport_TCPSocketSendBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-hop-limit -//go:noescape -func wasmimport_TCPSocketSetHopLimit(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-count -//go:noescape -func wasmimport_TCPSocketSetKeepAliveCount(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-enabled -//go:noescape -func wasmimport_TCPSocketSetKeepAliveEnabled(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-idle-time -//go:noescape -func wasmimport_TCPSocketSetKeepAliveIdleTime(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-interval -//go:noescape -func wasmimport_TCPSocketSetKeepAliveInterval(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-listen-backlog-size -//go:noescape -func wasmimport_TCPSocketSetListenBacklogSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-receive-buffer-size -//go:noescape -func wasmimport_TCPSocketSetReceiveBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-send-buffer-size -//go:noescape -func wasmimport_TCPSocketSetSendBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.shutdown -//go:noescape -func wasmimport_TCPSocketShutdown(self0 uint32, shutdownType0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-bind -//go:noescape -func wasmimport_TCPSocketStartBind(self0 uint32, network0 uint32, localAddress0 uint32, localAddress1 uint32, localAddress2 uint32, localAddress3 uint32, localAddress4 uint32, localAddress5 uint32, localAddress6 uint32, localAddress7 uint32, localAddress8 uint32, localAddress9 uint32, localAddress10 uint32, localAddress11 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-connect -//go:noescape -func wasmimport_TCPSocketStartConnect(self0 uint32, network0 uint32, remoteAddress0 uint32, remoteAddress1 uint32, remoteAddress2 uint32, remoteAddress3 uint32, remoteAddress4 uint32, remoteAddress5 uint32, remoteAddress6 uint32, remoteAddress7 uint32, remoteAddress8 uint32, remoteAddress9 uint32, remoteAddress10 uint32, remoteAddress11 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-listen -//go:noescape -func wasmimport_TCPSocketStartListen(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.subscribe -//go:noescape -func wasmimport_TCPSocketSubscribe(self0 uint32) (result0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go b/x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go deleted file mode 100755 index 99c9fe6b..00000000 --- a/x/wasihttp/internal/wasi/sockets/tcp/tcp.wit.go +++ /dev/null @@ -1,785 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package tcp represents the imported interface "wasi:sockets/tcp@0.2.0". -package tcp - -import ( - "go.bytecodealliance.org/cm" - monotonicclock "go.bytecodealliance.org/x/wasihttp/internal/wasi/clocks/monotonic-clock" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/streams" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" -) - -// InputStream represents the imported type alias "wasi:sockets/tcp@0.2.0#input-stream". -// -// See [streams.InputStream] for more information. -type InputStream = streams.InputStream - -// OutputStream represents the imported type alias "wasi:sockets/tcp@0.2.0#output-stream". -// -// See [streams.OutputStream] for more information. -type OutputStream = streams.OutputStream - -// Pollable represents the imported type alias "wasi:sockets/tcp@0.2.0#pollable". -// -// See [poll.Pollable] for more information. -type Pollable = poll.Pollable - -// Duration represents the type alias "wasi:sockets/tcp@0.2.0#duration". -// -// See [monotonicclock.Duration] for more information. -type Duration = monotonicclock.Duration - -// Network represents the imported type alias "wasi:sockets/tcp@0.2.0#network". -// -// See [network.Network] for more information. -type Network = network.Network - -// ErrorCode represents the type alias "wasi:sockets/tcp@0.2.0#error-code". -// -// See [network.ErrorCode] for more information. -type ErrorCode = network.ErrorCode - -// IPSocketAddress represents the type alias "wasi:sockets/tcp@0.2.0#ip-socket-address". -// -// See [network.IPSocketAddress] for more information. -type IPSocketAddress = network.IPSocketAddress - -// IPAddressFamily represents the type alias "wasi:sockets/tcp@0.2.0#ip-address-family". -// -// See [network.IPAddressFamily] for more information. -type IPAddressFamily = network.IPAddressFamily - -// ShutdownType represents the enum "wasi:sockets/tcp@0.2.0#shutdown-type". -// -// enum shutdown-type { -// receive, -// send, -// both -// } -type ShutdownType uint8 - -const ( - // Similar to `SHUT_RD` in POSIX. - ShutdownTypeReceive ShutdownType = iota - - // Similar to `SHUT_WR` in POSIX. - ShutdownTypeSend - - // Similar to `SHUT_RDWR` in POSIX. - ShutdownTypeBoth -) - -var _ShutdownTypeStrings = [3]string{ - "receive", - "send", - "both", -} - -// String implements [fmt.Stringer], returning the enum case name of e. -func (e ShutdownType) String() string { - return _ShutdownTypeStrings[e] -} - -// MarshalText implements [encoding.TextMarshaler]. -func (e ShutdownType) MarshalText() ([]byte, error) { - return []byte(e.String()), nil -} - -// UnmarshalText implements [encoding.TextUnmarshaler], unmarshaling into an enum -// case. Returns an error if the supplied text is not one of the enum cases. -func (e *ShutdownType) UnmarshalText(text []byte) error { - return _ShutdownTypeUnmarshalCase(e, text) -} - -var _ShutdownTypeUnmarshalCase = cm.CaseUnmarshaler[ShutdownType](_ShutdownTypeStrings[:]) - -// TCPSocket represents the imported resource "wasi:sockets/tcp@0.2.0#tcp-socket". -// -// A TCP socket resource. -// -// The socket can be in one of the following states: -// - `unbound` -// - `bind-in-progress` -// - `bound` (See note below) -// - `listen-in-progress` -// - `listening` -// - `connect-in-progress` -// - `connected` -// - `closed` -// See -// for a more information. -// -// Note: Except where explicitly mentioned, whenever this documentation uses -// the term "bound" without backticks it actually means: in the `bound` state *or -// higher*. -// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) -// -// In addition to the general error codes documented on the -// `network::error-code` type, TCP socket methods may always return -// `error(invalid-state)` when in the `closed` state. -// -// resource tcp-socket -type TCPSocket cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "tcp-socket". -// -// Drops a resource handle. -// -//go:nosplit -func (self TCPSocket) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketResourceDrop((uint32)(self0)) - return -} - -// Accept represents the imported method "accept". -// -// Accept a new client socket. -// -// The returned socket is bound and in the `connected` state. The following properties -// are inherited from the listener socket: -// - `address-family` -// - `keep-alive-enabled` -// - `keep-alive-idle-time` -// - `keep-alive-interval` -// - `keep-alive-count` -// - `hop-limit` -// - `receive-buffer-size` -// - `send-buffer-size` -// -// On success, this function returns the newly accepted client socket along with -// a pair of streams that can be used to read & write to the connection. -// -// # Typical errors -// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) -// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) -// - `connection-aborted`: An incoming connection was pending, but was terminated -// by the client before this listener could accept it. (ECONNABORTED) -// - `new-socket-limit`: The new socket resource could not be created because of -// a system limit. (EMFILE, ENFILE) -// -// # References -// - -// - -// - -// - -// -// accept: func() -> result, error-code> -// -//go:nosplit -func (self TCPSocket) Accept() (result cm.Result[TupleTCPSocketInputStreamOutputStreamShape, cm.Tuple3[TCPSocket, InputStream, OutputStream], ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketAccept((uint32)(self0), &result) - return -} - -// AddressFamily represents the imported method "address-family". -// -// Whether this is a IPv4 or IPv6 socket. -// -// Equivalent to the SO_DOMAIN socket option. -// -// address-family: func() -> ip-address-family -// -//go:nosplit -func (self TCPSocket) AddressFamily() (result IPAddressFamily) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_TCPSocketAddressFamily((uint32)(self0)) - result = (network.IPAddressFamily)((uint32)(result0)) - return -} - -// FinishBind represents the imported method "finish-bind". -// -// finish-bind: func() -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) FinishBind() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketFinishBind((uint32)(self0), &result) - return -} - -// FinishConnect represents the imported method "finish-connect". -// -// finish-connect: func() -> result, error-code> -// -//go:nosplit -func (self TCPSocket) FinishConnect() (result cm.Result[TupleInputStreamOutputStreamShape, cm.Tuple[InputStream, OutputStream], ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketFinishConnect((uint32)(self0), &result) - return -} - -// FinishListen represents the imported method "finish-listen". -// -// finish-listen: func() -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) FinishListen() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketFinishListen((uint32)(self0), &result) - return -} - -// HopLimit represents the imported method "hop-limit". -// -// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// -// # Typical errors -// - `invalid-argument`: (set) The TTL value must be 1 or higher. -// -// hop-limit: func() -> result -// -//go:nosplit -func (self TCPSocket) HopLimit() (result cm.Result[uint8, uint8, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketHopLimit((uint32)(self0), &result) - return -} - -// IsListening represents the imported method "is-listening". -// -// Whether the socket is in the `listening` state. -// -// Equivalent to the SO_ACCEPTCONN socket option. -// -// is-listening: func() -> bool -// -//go:nosplit -func (self TCPSocket) IsListening() (result bool) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_TCPSocketIsListening((uint32)(self0)) - result = (bool)(cm.U32ToBool((uint32)(result0))) - return -} - -// KeepAliveCount represents the imported method "keep-alive-count". -// -// The maximum amount of keepalive packets TCP should send before aborting the connection. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// Any other value will never cause an error, but it might be silently clamped and/or -// rounded. -// I.e. after setting a value, reading the same setting back may return a different -// value. -// -// Equivalent to the TCP_KEEPCNT socket option. -// -// # Typical errors -// - `invalid-argument`: (set) The provided value was 0. -// -// keep-alive-count: func() -> result -// -//go:nosplit -func (self TCPSocket) KeepAliveCount() (result cm.Result[uint32, uint32, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketKeepAliveCount((uint32)(self0), &result) - return -} - -// KeepAliveEnabled represents the imported method "keep-alive-enabled". -// -// Enables or disables keepalive. -// -// The keepalive behavior can be adjusted using: -// - `keep-alive-idle-time` -// - `keep-alive-interval` -// - `keep-alive-count` -// These properties can be configured while `keep-alive-enabled` is false, but only -// come into effect when `keep-alive-enabled` is true. -// -// Equivalent to the SO_KEEPALIVE socket option. -// -// keep-alive-enabled: func() -> result -// -//go:nosplit -func (self TCPSocket) KeepAliveEnabled() (result cm.Result[ErrorCode, bool, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketKeepAliveEnabled((uint32)(self0), &result) - return -} - -// KeepAliveIdleTime represents the imported method "keep-alive-idle-time". -// -// Amount of time the connection has to be idle before TCP starts sending keepalive -// packets. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// Any other value will never cause an error, but it might be silently clamped and/or -// rounded. -// I.e. after setting a value, reading the same setting back may return a different -// value. -// -// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) -// -// # Typical errors -// - `invalid-argument`: (set) The provided value was 0. -// -// keep-alive-idle-time: func() -> result -// -//go:nosplit -func (self TCPSocket) KeepAliveIdleTime() (result cm.Result[uint64, Duration, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketKeepAliveIdleTime((uint32)(self0), &result) - return -} - -// KeepAliveInterval represents the imported method "keep-alive-interval". -// -// The time between keepalive packets. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// Any other value will never cause an error, but it might be silently clamped and/or -// rounded. -// I.e. after setting a value, reading the same setting back may return a different -// value. -// -// Equivalent to the TCP_KEEPINTVL socket option. -// -// # Typical errors -// - `invalid-argument`: (set) The provided value was 0. -// -// keep-alive-interval: func() -> result -// -//go:nosplit -func (self TCPSocket) KeepAliveInterval() (result cm.Result[uint64, Duration, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketKeepAliveInterval((uint32)(self0), &result) - return -} - -// LocalAddress represents the imported method "local-address". -// -// Get the bound local address. -// -// POSIX mentions: -// > If the socket has not been bound to a local name, the value -// > stored in the object pointed to by `address` is unspecified. -// -// WASI is stricter and requires `local-address` to return `invalid-state` when the -// socket hasn't been bound yet. -// -// # Typical errors -// - `invalid-state`: The socket is not bound to any local address. -// -// # References -// - -// - -// - -// - -// -// local-address: func() -> result -// -//go:nosplit -func (self TCPSocket) LocalAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketLocalAddress((uint32)(self0), &result) - return -} - -// ReceiveBufferSize represents the imported method "receive-buffer-size". -// -// The kernel buffer space reserved for sends/receives on this socket. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// Any other value will never cause an error, but it might be silently clamped and/or -// rounded. -// I.e. after setting a value, reading the same setting back may return a different -// value. -// -// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. -// -// # Typical errors -// - `invalid-argument`: (set) The provided value was 0. -// -// receive-buffer-size: func() -> result -// -//go:nosplit -func (self TCPSocket) ReceiveBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketReceiveBufferSize((uint32)(self0), &result) - return -} - -// RemoteAddress represents the imported method "remote-address". -// -// Get the remote address. -// -// # Typical errors -// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) -// -// # References -// - -// - -// - -// - -// -// remote-address: func() -> result -// -//go:nosplit -func (self TCPSocket) RemoteAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketRemoteAddress((uint32)(self0), &result) - return -} - -// SendBufferSize represents the imported method "send-buffer-size". -// -// send-buffer-size: func() -> result -// -//go:nosplit -func (self TCPSocket) SendBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketSendBufferSize((uint32)(self0), &result) - return -} - -// SetHopLimit represents the imported method "set-hop-limit". -// -// set-hop-limit: func(value: u8) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetHopLimit(value uint8) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint32)(value) - wasmimport_TCPSocketSetHopLimit((uint32)(self0), (uint32)(value0), &result) - return -} - -// SetKeepAliveCount represents the imported method "set-keep-alive-count". -// -// set-keep-alive-count: func(value: u32) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetKeepAliveCount(value uint32) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint32)(value) - wasmimport_TCPSocketSetKeepAliveCount((uint32)(self0), (uint32)(value0), &result) - return -} - -// SetKeepAliveEnabled represents the imported method "set-keep-alive-enabled". -// -// set-keep-alive-enabled: func(value: bool) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetKeepAliveEnabled(value bool) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint32)(cm.BoolToU32(value)) - wasmimport_TCPSocketSetKeepAliveEnabled((uint32)(self0), (uint32)(value0), &result) - return -} - -// SetKeepAliveIdleTime represents the imported method "set-keep-alive-idle-time". -// -// set-keep-alive-idle-time: func(value: duration) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetKeepAliveIdleTime(value Duration) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint64)(value) - wasmimport_TCPSocketSetKeepAliveIdleTime((uint32)(self0), (uint64)(value0), &result) - return -} - -// SetKeepAliveInterval represents the imported method "set-keep-alive-interval". -// -// set-keep-alive-interval: func(value: duration) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetKeepAliveInterval(value Duration) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint64)(value) - wasmimport_TCPSocketSetKeepAliveInterval((uint32)(self0), (uint64)(value0), &result) - return -} - -// SetListenBacklogSize represents the imported method "set-listen-backlog-size". -// -// Hints the desired listen queue size. Implementations are free to ignore this. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// Any other value will never cause an error, but it might be silently clamped and/or -// rounded. -// -// # Typical errors -// - `not-supported`: (set) The platform does not support changing the backlog -// size after the initial listen. -// - `invalid-argument`: (set) The provided value was 0. -// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` -// state. -// -// set-listen-backlog-size: func(value: u64) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetListenBacklogSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint64)(value) - wasmimport_TCPSocketSetListenBacklogSize((uint32)(self0), (uint64)(value0), &result) - return -} - -// SetReceiveBufferSize represents the imported method "set-receive-buffer-size". -// -// set-receive-buffer-size: func(value: u64) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetReceiveBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint64)(value) - wasmimport_TCPSocketSetReceiveBufferSize((uint32)(self0), (uint64)(value0), &result) - return -} - -// SetSendBufferSize represents the imported method "set-send-buffer-size". -// -// set-send-buffer-size: func(value: u64) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) SetSendBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint64)(value) - wasmimport_TCPSocketSetSendBufferSize((uint32)(self0), (uint64)(value0), &result) - return -} - -// Shutdown represents the imported method "shutdown". -// -// Initiate a graceful shutdown. -// -// - `receive`: The socket is not expecting to receive any data from -// the peer. The `input-stream` associated with this socket will be -// closed. Any data still in the receive queue at time of calling -// this method will be discarded. -// - `send`: The socket has no more data to send to the peer. The `output-stream` -// associated with this socket will be closed and a FIN packet will be sent. -// - `both`: Same effect as `receive` & `send` combined. -// -// This function is idempotent. Shutting a down a direction more than once -// has no effect and returns `ok`. -// -// The shutdown function does not close (drop) the socket. -// -// # Typical errors -// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) -// -// # References -// - -// - -// - -// - -// -// shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) Shutdown(shutdownType ShutdownType) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - shutdownType0 := (uint32)(shutdownType) - wasmimport_TCPSocketShutdown((uint32)(self0), (uint32)(shutdownType0), &result) - return -} - -// StartBind represents the imported method "start-bind". -// -// Bind the socket to a specific network on the provided IP address and port. -// -// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the -// implementation to decide which -// network interface(s) to bind to. -// If the TCP/UDP port is zero, the socket will be bound to a random free port. -// -// Bind can be attempted multiple times on the same socket, even with -// different arguments on each iteration. But never concurrently and -// only as long as the previous bind failed. Once a bind succeeds, the -// binding can't be changed anymore. -// -// # Typical errors -// - `invalid-argument`: The `local-address` has the wrong address family. -// (EAFNOSUPPORT, EFAULT on Windows) -// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) -// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. -// (EINVAL) -// - `invalid-state`: The socket is already bound. (EINVAL) -// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS -// on Windows) -// - `address-in-use`: Address is already in use. (EADDRINUSE) -// - `address-not-bindable`: `local-address` is not an address that the `network` -// can bind to. (EADDRNOTAVAIL) -// - `not-in-progress`: A `bind` operation is not in progress. -// - `would-block`: Can't finish the operation, it is still in progress. -// (EWOULDBLOCK, EAGAIN) -// -// # Implementors note -// When binding to a non-zero port, this bind operation shouldn't be affected by the -// TIME_WAIT -// state of a recently closed socket on the same local address. In practice this means -// that the SO_REUSEADDR -// socket option should be set implicitly on all platforms, except on Windows where -// this is the default behavior -// and SO_REUSEADDR performs something different entirely. -// -// Unlike in POSIX, in WASI the bind operation is async. This enables -// interactive WASI hosts to inject permission prompts. Runtimes that -// don't want to make use of this ability can simply call the native -// `bind` as part of either `start-bind` or `finish-bind`. -// -// # References -// - -// - -// - -// - -// -// start-bind: func(network: borrow, local-address: ip-socket-address) -> -// result<_, error-code> -// -//go:nosplit -func (self TCPSocket) StartBind(network_ Network, localAddress IPSocketAddress) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - network0 := cm.Reinterpret[uint32](network_) - localAddress0, localAddress1, localAddress2, localAddress3, localAddress4, localAddress5, localAddress6, localAddress7, localAddress8, localAddress9, localAddress10, localAddress11 := lower_IPSocketAddress(localAddress) - wasmimport_TCPSocketStartBind((uint32)(self0), (uint32)(network0), (uint32)(localAddress0), (uint32)(localAddress1), (uint32)(localAddress2), (uint32)(localAddress3), (uint32)(localAddress4), (uint32)(localAddress5), (uint32)(localAddress6), (uint32)(localAddress7), (uint32)(localAddress8), (uint32)(localAddress9), (uint32)(localAddress10), (uint32)(localAddress11), &result) - return -} - -// StartConnect represents the imported method "start-connect". -// -// Connect to a remote endpoint. -// -// On success: -// - the socket is transitioned into the `connection` state. -// - a pair of streams is returned that can be used to read & write to the connection -// -// After a failed connection attempt, the socket will be in the `closed` -// state and the only valid action left is to `drop` the socket. A single -// socket can not be used to connect more than once. -// -// # Typical errors -// - `invalid-argument`: The `remote-address` has the wrong address family. -// (EAFNOSUPPORT) -// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, -// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) -// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. -// (EINVAL, EADDRNOTAVAIL on Illumos) -// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY -// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) -// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL -// on Windows) -// - `invalid-argument`: The socket is already attached to a different network. -// The `network` passed to `connect` must be identical to the one passed to `bind`. -// - `invalid-state`: The socket is already in the `connected` state. -// (EISCONN) -// - `invalid-state`: The socket is already in the `listening` state. -// (EOPNOTSUPP, EINVAL on Windows) -// - `timeout`: Connection timed out. (ETIMEDOUT) -// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) -// - `connection-reset`: The connection was reset. (ECONNRESET) -// - `connection-aborted`: The connection was aborted. (ECONNABORTED) -// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, -// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) -// - `address-in-use`: Tried to perform an implicit bind, but there were -// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) -// - `not-in-progress`: A connect operation is not in progress. -// - `would-block`: Can't finish the operation, it is still in progress. -// (EWOULDBLOCK, EAGAIN) -// -// # Implementors note -// The POSIX equivalent of `start-connect` is the regular `connect` syscall. -// Because all WASI sockets are non-blocking this is expected to return -// EINPROGRESS, which should be translated to `ok()` in WASI. -// -// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` -// with a timeout of 0 on the socket descriptor. Followed by a check for -// the `SO_ERROR` socket option, in case the poll signaled readiness. -// -// # References -// - -// - -// - -// - -// -// start-connect: func(network: borrow, remote-address: ip-socket-address) -// -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) StartConnect(network_ Network, remoteAddress IPSocketAddress) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - network0 := cm.Reinterpret[uint32](network_) - remoteAddress0, remoteAddress1, remoteAddress2, remoteAddress3, remoteAddress4, remoteAddress5, remoteAddress6, remoteAddress7, remoteAddress8, remoteAddress9, remoteAddress10, remoteAddress11 := lower_IPSocketAddress(remoteAddress) - wasmimport_TCPSocketStartConnect((uint32)(self0), (uint32)(network0), (uint32)(remoteAddress0), (uint32)(remoteAddress1), (uint32)(remoteAddress2), (uint32)(remoteAddress3), (uint32)(remoteAddress4), (uint32)(remoteAddress5), (uint32)(remoteAddress6), (uint32)(remoteAddress7), (uint32)(remoteAddress8), (uint32)(remoteAddress9), (uint32)(remoteAddress10), (uint32)(remoteAddress11), &result) - return -} - -// StartListen represents the imported method "start-listen". -// -// Start listening for new connections. -// -// Transitions the socket into the `listening` state. -// -// Unlike POSIX, the socket must already be explicitly bound. -// -// # Typical errors -// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) -// - `invalid-state`: The socket is already in the `connected` state. -// (EISCONN, EINVAL on BSD) -// - `invalid-state`: The socket is already in the `listening` state. -// - `address-in-use`: Tried to perform an implicit bind, but there were -// no ephemeral ports available. (EADDRINUSE) -// - `not-in-progress`: A listen operation is not in progress. -// - `would-block`: Can't finish the operation, it is still in progress. -// (EWOULDBLOCK, EAGAIN) -// -// # Implementors note -// Unlike in POSIX, in WASI the listen operation is async. This enables -// interactive WASI hosts to inject permission prompts. Runtimes that -// don't want to make use of this ability can simply call the native -// `listen` as part of either `start-listen` or `finish-listen`. -// -// # References -// - -// - -// - -// - -// -// start-listen: func() -> result<_, error-code> -// -//go:nosplit -func (self TCPSocket) StartListen() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_TCPSocketStartListen((uint32)(self0), &result) - return -} - -// Subscribe represents the imported method "subscribe". -// -// Create a `pollable` which can be used to poll for, or block on, -// completion of any of the asynchronous operations of this socket. -// -// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` -// return `error(would-block)`, this pollable can be used to wait for -// their success or failure, after which the method can be retried. -// -// The pollable is not limited to the async operation that happens to be -// in progress at the time of calling `subscribe` (if any). Theoretically, -// `subscribe` only has to be called once per socket and can then be -// (re)used for the remainder of the socket's lifetime. -// -// See -// for a more information. -// -// Note: this function is here for WASI Preview2 only. -// It's planned to be removed when `future` is natively supported in Preview3. -// -// subscribe: func() -> pollable -// -//go:nosplit -func (self TCPSocket) Subscribe() (result Pollable) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_TCPSocketSubscribe((uint32)(self0)) - result = cm.Reinterpret[Pollable]((uint32)(result0)) - return -} diff --git a/x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s b/x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/sockets/udp-create-socket/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go b/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go deleted file mode 100755 index 94b1ab67..00000000 --- a/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wasm.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package udpcreatesocket - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". - -//go:wasmimport wasi:sockets/udp-create-socket@0.2.0 create-udp-socket -//go:noescape -func wasmimport_CreateUDPSocket(addressFamily0 uint32, result *cm.Result[UDPSocket, UDPSocket, ErrorCode]) diff --git a/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go b/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go deleted file mode 100755 index 736bee8a..00000000 --- a/x/wasihttp/internal/wasi/sockets/udp-create-socket/udp-create-socket.wit.go +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package udpcreatesocket represents the imported interface "wasi:sockets/udp-create-socket@0.2.0". -package udpcreatesocket - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/udp" -) - -// Network represents the imported type alias "wasi:sockets/udp-create-socket@0.2.0#network". -// -// See [network.Network] for more information. -type Network = network.Network - -// ErrorCode represents the type alias "wasi:sockets/udp-create-socket@0.2.0#error-code". -// -// See [network.ErrorCode] for more information. -type ErrorCode = network.ErrorCode - -// IPAddressFamily represents the type alias "wasi:sockets/udp-create-socket@0.2.0#ip-address-family". -// -// See [network.IPAddressFamily] for more information. -type IPAddressFamily = network.IPAddressFamily - -// UDPSocket represents the imported type alias "wasi:sockets/udp-create-socket@0.2.0#udp-socket". -// -// See [udp.UDPSocket] for more information. -type UDPSocket = udp.UDPSocket - -// CreateUDPSocket represents the imported function "create-udp-socket". -// -// Create a new UDP socket. -// -// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. -// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. -// -// This function does not require a network capability handle. This is considered -// to be safe because -// at time of creation, the socket is not bound to any `network` yet. Up to the moment -// `bind` is called, -// the socket is effectively an in-memory configuration object, unable to communicate -// with the outside world. -// -// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous -// operations. -// -// # Typical errors -// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) -// - `new-socket-limit`: The new socket resource could not be created because of -// a system limit. (EMFILE, ENFILE) -// -// # References: -// - -// - -// - -// - -// -// create-udp-socket: func(address-family: ip-address-family) -> result -// -//go:nosplit -func CreateUDPSocket(addressFamily IPAddressFamily) (result cm.Result[UDPSocket, UDPSocket, ErrorCode]) { - addressFamily0 := (uint32)(addressFamily) - wasmimport_CreateUDPSocket((uint32)(addressFamily0), &result) - return -} diff --git a/x/wasihttp/internal/wasi/sockets/udp/abi.go b/x/wasihttp/internal/wasi/sockets/udp/abi.go deleted file mode 100755 index daa60bcb..00000000 --- a/x/wasihttp/internal/wasi/sockets/udp/abi.go +++ /dev/null @@ -1,103 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package udp - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" - "unsafe" -) - -// IPSocketAddressShape is used for storage in variant or result types. -type IPSocketAddressShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(IPSocketAddress{})]byte -} - -func lower_IPv4Address(v network.IPv4Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32) { - f0 = (uint32)(v[0]) - f1 = (uint32)(v[1]) - f2 = (uint32)(v[2]) - f3 = (uint32)(v[3]) - return -} - -func lower_IPv4SocketAddress(v network.IPv4SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32) { - f0 = (uint32)(v.Port) - f1, f2, f3, f4 = lower_IPv4Address(v.Address) - return -} - -func lower_IPv6Address(v network.IPv6Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { - f0 = (uint32)(v[0]) - f1 = (uint32)(v[1]) - f2 = (uint32)(v[2]) - f3 = (uint32)(v[3]) - f4 = (uint32)(v[4]) - f5 = (uint32)(v[5]) - f6 = (uint32)(v[6]) - f7 = (uint32)(v[7]) - return -} - -func lower_IPv6SocketAddress(v network.IPv6SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32) { - f0 = (uint32)(v.Port) - f1 = (uint32)(v.FlowInfo) - f2, f3, f4, f5, f6, f7, f8, f9 = lower_IPv6Address(v.Address) - f10 = (uint32)(v.ScopeID) - return -} - -func lower_IPSocketAddress(v network.IPSocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32) { - f0 = (uint32)(v.Tag()) - switch f0 { - case 0: // ipv4 - v1, v2, v3, v4, v5 := lower_IPv4SocketAddress(*cm.Case[network.IPv4SocketAddress](&v, 0)) - f1 = (uint32)(v1) - f2 = (uint32)(v2) - f3 = (uint32)(v3) - f4 = (uint32)(v4) - f5 = (uint32)(v5) - case 1: // ipv6 - v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 := lower_IPv6SocketAddress(*cm.Case[network.IPv6SocketAddress](&v, 1)) - f1 = (uint32)(v1) - f2 = (uint32)(v2) - f3 = (uint32)(v3) - f4 = (uint32)(v4) - f5 = (uint32)(v5) - f6 = (uint32)(v6) - f7 = (uint32)(v7) - f8 = (uint32)(v8) - f9 = (uint32)(v9) - f10 = (uint32)(v10) - f11 = (uint32)(v11) - } - return -} - -// TupleIncomingDatagramStreamOutgoingDatagramStreamShape is used for storage in variant or result types. -type TupleIncomingDatagramStreamOutgoingDatagramStreamShape struct { - _ cm.HostLayout - shape [unsafe.Sizeof(cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream]{})]byte -} - -func lower_OptionIPSocketAddress(v cm.Option[IPSocketAddress]) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32, f12 uint32) { - some := v.Some() - if some != nil { - f0 = 1 - v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 := lower_IPSocketAddress(*some) - f1 = (uint32)(v1) - f2 = (uint32)(v2) - f3 = (uint32)(v3) - f4 = (uint32)(v4) - f5 = (uint32)(v5) - f6 = (uint32)(v6) - f7 = (uint32)(v7) - f8 = (uint32)(v8) - f9 = (uint32)(v9) - f10 = (uint32)(v10) - f11 = (uint32)(v11) - f12 = (uint32)(v12) - } - return -} diff --git a/x/wasihttp/internal/wasi/sockets/udp/empty.s b/x/wasihttp/internal/wasi/sockets/udp/empty.s deleted file mode 100755 index 5444f200..00000000 --- a/x/wasihttp/internal/wasi/sockets/udp/empty.s +++ /dev/null @@ -1,3 +0,0 @@ -// This file exists for testing this package without WebAssembly, -// allowing empty function bodies with a //go:wasmimport directive. -// See https://pkg.go.dev/cmd/compile for more information. diff --git a/x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go b/x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go deleted file mode 100755 index 83ce8ca7..00000000 --- a/x/wasihttp/internal/wasi/sockets/udp/udp.wasm.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -package udp - -import ( - "go.bytecodealliance.org/cm" -) - -// This file contains wasmimport and wasmexport declarations for "wasi:sockets@0.2.0". - -//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]udp-socket -//go:noescape -func wasmimport_UDPSocketResourceDrop(self0 uint32) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.address-family -//go:noescape -func wasmimport_UDPSocketAddressFamily(self0 uint32) (result0 uint32) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.finish-bind -//go:noescape -func wasmimport_UDPSocketFinishBind(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.local-address -//go:noescape -func wasmimport_UDPSocketLocalAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.receive-buffer-size -//go:noescape -func wasmimport_UDPSocketReceiveBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.remote-address -//go:noescape -func wasmimport_UDPSocketRemoteAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.send-buffer-size -//go:noescape -func wasmimport_UDPSocketSendBufferSize(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-receive-buffer-size -//go:noescape -func wasmimport_UDPSocketSetReceiveBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-send-buffer-size -//go:noescape -func wasmimport_UDPSocketSetSendBufferSize(self0 uint32, value0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-unicast-hop-limit -//go:noescape -func wasmimport_UDPSocketSetUnicastHopLimit(self0 uint32, value0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.start-bind -//go:noescape -func wasmimport_UDPSocketStartBind(self0 uint32, network0 uint32, localAddress0 uint32, localAddress1 uint32, localAddress2 uint32, localAddress3 uint32, localAddress4 uint32, localAddress5 uint32, localAddress6 uint32, localAddress7 uint32, localAddress8 uint32, localAddress9 uint32, localAddress10 uint32, localAddress11 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.stream -//go:noescape -func wasmimport_UDPSocketStream(self0 uint32, remoteAddress0 uint32, remoteAddress1 uint32, remoteAddress2 uint32, remoteAddress3 uint32, remoteAddress4 uint32, remoteAddress5 uint32, remoteAddress6 uint32, remoteAddress7 uint32, remoteAddress8 uint32, remoteAddress9 uint32, remoteAddress10 uint32, remoteAddress11 uint32, remoteAddress12 uint32, result *cm.Result[TupleIncomingDatagramStreamOutgoingDatagramStreamShape, cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream], ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.subscribe -//go:noescape -func wasmimport_UDPSocketSubscribe(self0 uint32) (result0 uint32) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.unicast-hop-limit -//go:noescape -func wasmimport_UDPSocketUnicastHopLimit(self0 uint32, result *cm.Result[uint8, uint8, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]incoming-datagram-stream -//go:noescape -func wasmimport_IncomingDatagramStreamResourceDrop(self0 uint32) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]incoming-datagram-stream.receive -//go:noescape -func wasmimport_IncomingDatagramStreamReceive(self0 uint32, maxResults0 uint64, result *cm.Result[cm.List[IncomingDatagram], cm.List[IncomingDatagram], ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]incoming-datagram-stream.subscribe -//go:noescape -func wasmimport_IncomingDatagramStreamSubscribe(self0 uint32) (result0 uint32) - -//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]outgoing-datagram-stream -//go:noescape -func wasmimport_OutgoingDatagramStreamResourceDrop(self0 uint32) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.check-send -//go:noescape -func wasmimport_OutgoingDatagramStreamCheckSend(self0 uint32, result *cm.Result[uint64, uint64, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.send -//go:noescape -func wasmimport_OutgoingDatagramStreamSend(self0 uint32, datagrams0 *OutgoingDatagram, datagrams1 uint32, result *cm.Result[uint64, uint64, ErrorCode]) - -//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.subscribe -//go:noescape -func wasmimport_OutgoingDatagramStreamSubscribe(self0 uint32) (result0 uint32) diff --git a/x/wasihttp/internal/wasi/sockets/udp/udp.wit.go b/x/wasihttp/internal/wasi/sockets/udp/udp.wit.go deleted file mode 100755 index 25a05cf9..00000000 --- a/x/wasihttp/internal/wasi/sockets/udp/udp.wit.go +++ /dev/null @@ -1,584 +0,0 @@ -// Code generated by wit-bindgen-go. DO NOT EDIT. - -// Package udp represents the imported interface "wasi:sockets/udp@0.2.0". -package udp - -import ( - "go.bytecodealliance.org/cm" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/io/poll" - "go.bytecodealliance.org/x/wasihttp/internal/wasi/sockets/network" -) - -// Pollable represents the imported type alias "wasi:sockets/udp@0.2.0#pollable". -// -// See [poll.Pollable] for more information. -type Pollable = poll.Pollable - -// Network represents the imported type alias "wasi:sockets/udp@0.2.0#network". -// -// See [network.Network] for more information. -type Network = network.Network - -// ErrorCode represents the type alias "wasi:sockets/udp@0.2.0#error-code". -// -// See [network.ErrorCode] for more information. -type ErrorCode = network.ErrorCode - -// IPSocketAddress represents the type alias "wasi:sockets/udp@0.2.0#ip-socket-address". -// -// See [network.IPSocketAddress] for more information. -type IPSocketAddress = network.IPSocketAddress - -// IPAddressFamily represents the type alias "wasi:sockets/udp@0.2.0#ip-address-family". -// -// See [network.IPAddressFamily] for more information. -type IPAddressFamily = network.IPAddressFamily - -// IncomingDatagram represents the record "wasi:sockets/udp@0.2.0#incoming-datagram". -// -// A received datagram. -// -// record incoming-datagram { -// data: list, -// remote-address: ip-socket-address, -// } -type IncomingDatagram struct { - _ cm.HostLayout `json:"-"` - // The payload. - // - // Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. - Data cm.List[uint8] `json:"data"` - - // The source address. - // - // This field is guaranteed to match the remote address the stream was initialized - // with, if any. - // - // Equivalent to the `src_addr` out parameter of `recvfrom`. - RemoteAddress IPSocketAddress `json:"remote-address"` -} - -// OutgoingDatagram represents the record "wasi:sockets/udp@0.2.0#outgoing-datagram". -// -// A datagram to be sent out. -// -// record outgoing-datagram { -// data: list, -// remote-address: option, -// } -type OutgoingDatagram struct { - _ cm.HostLayout `json:"-"` - // The payload. - Data cm.List[uint8] `json:"data"` - - // The destination address. - // - // The requirements on this field depend on how the stream was initialized: - // - with a remote address: this field must be None or match the stream's remote address - // exactly. - // - without a remote address: this field is required. - // - // If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise - // it is equivalent to `sendto`. - RemoteAddress cm.Option[IPSocketAddress] `json:"remote-address"` -} - -// UDPSocket represents the imported resource "wasi:sockets/udp@0.2.0#udp-socket". -// -// A UDP socket handle. -// -// resource udp-socket -type UDPSocket cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "udp-socket". -// -// Drops a resource handle. -// -//go:nosplit -func (self UDPSocket) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_UDPSocketResourceDrop((uint32)(self0)) - return -} - -// AddressFamily represents the imported method "address-family". -// -// Whether this is a IPv4 or IPv6 socket. -// -// Equivalent to the SO_DOMAIN socket option. -// -// address-family: func() -> ip-address-family -// -//go:nosplit -func (self UDPSocket) AddressFamily() (result IPAddressFamily) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_UDPSocketAddressFamily((uint32)(self0)) - result = (network.IPAddressFamily)((uint32)(result0)) - return -} - -// FinishBind represents the imported method "finish-bind". -// -// finish-bind: func() -> result<_, error-code> -// -//go:nosplit -func (self UDPSocket) FinishBind() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_UDPSocketFinishBind((uint32)(self0), &result) - return -} - -// LocalAddress represents the imported method "local-address". -// -// Get the current bound address. -// -// POSIX mentions: -// > If the socket has not been bound to a local name, the value -// > stored in the object pointed to by `address` is unspecified. -// -// WASI is stricter and requires `local-address` to return `invalid-state` when the -// socket hasn't been bound yet. -// -// # Typical errors -// - `invalid-state`: The socket is not bound to any local address. -// -// # References -// - -// - -// - -// - -// -// local-address: func() -> result -// -//go:nosplit -func (self UDPSocket) LocalAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_UDPSocketLocalAddress((uint32)(self0), &result) - return -} - -// ReceiveBufferSize represents the imported method "receive-buffer-size". -// -// The kernel buffer space reserved for sends/receives on this socket. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// Any other value will never cause an error, but it might be silently clamped and/or -// rounded. -// I.e. after setting a value, reading the same setting back may return a different -// value. -// -// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. -// -// # Typical errors -// - `invalid-argument`: (set) The provided value was 0. -// -// receive-buffer-size: func() -> result -// -//go:nosplit -func (self UDPSocket) ReceiveBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_UDPSocketReceiveBufferSize((uint32)(self0), &result) - return -} - -// RemoteAddress represents the imported method "remote-address". -// -// Get the address the socket is currently streaming to. -// -// # Typical errors -// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) -// -// # References -// - -// - -// - -// - -// -// remote-address: func() -> result -// -//go:nosplit -func (self UDPSocket) RemoteAddress() (result cm.Result[IPSocketAddressShape, IPSocketAddress, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_UDPSocketRemoteAddress((uint32)(self0), &result) - return -} - -// SendBufferSize represents the imported method "send-buffer-size". -// -// send-buffer-size: func() -> result -// -//go:nosplit -func (self UDPSocket) SendBufferSize() (result cm.Result[uint64, uint64, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_UDPSocketSendBufferSize((uint32)(self0), &result) - return -} - -// SetReceiveBufferSize represents the imported method "set-receive-buffer-size". -// -// set-receive-buffer-size: func(value: u64) -> result<_, error-code> -// -//go:nosplit -func (self UDPSocket) SetReceiveBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint64)(value) - wasmimport_UDPSocketSetReceiveBufferSize((uint32)(self0), (uint64)(value0), &result) - return -} - -// SetSendBufferSize represents the imported method "set-send-buffer-size". -// -// set-send-buffer-size: func(value: u64) -> result<_, error-code> -// -//go:nosplit -func (self UDPSocket) SetSendBufferSize(value uint64) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint64)(value) - wasmimport_UDPSocketSetSendBufferSize((uint32)(self0), (uint64)(value0), &result) - return -} - -// SetUnicastHopLimit represents the imported method "set-unicast-hop-limit". -// -// set-unicast-hop-limit: func(value: u8) -> result<_, error-code> -// -//go:nosplit -func (self UDPSocket) SetUnicastHopLimit(value uint8) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - value0 := (uint32)(value) - wasmimport_UDPSocketSetUnicastHopLimit((uint32)(self0), (uint32)(value0), &result) - return -} - -// StartBind represents the imported method "start-bind". -// -// Bind the socket to a specific network on the provided IP address and port. -// -// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the -// implementation to decide which -// network interface(s) to bind to. -// If the port is zero, the socket will be bound to a random free port. -// -// # Typical errors -// - `invalid-argument`: The `local-address` has the wrong address family. -// (EAFNOSUPPORT, EFAULT on Windows) -// - `invalid-state`: The socket is already bound. (EINVAL) -// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS -// on Windows) -// - `address-in-use`: Address is already in use. (EADDRINUSE) -// - `address-not-bindable`: `local-address` is not an address that the `network` -// can bind to. (EADDRNOTAVAIL) -// - `not-in-progress`: A `bind` operation is not in progress. -// - `would-block`: Can't finish the operation, it is still in progress. -// (EWOULDBLOCK, EAGAIN) -// -// # Implementors note -// Unlike in POSIX, in WASI the bind operation is async. This enables -// interactive WASI hosts to inject permission prompts. Runtimes that -// don't want to make use of this ability can simply call the native -// `bind` as part of either `start-bind` or `finish-bind`. -// -// # References -// - -// - -// - -// - -// -// start-bind: func(network: borrow, local-address: ip-socket-address) -> -// result<_, error-code> -// -//go:nosplit -func (self UDPSocket) StartBind(network_ Network, localAddress IPSocketAddress) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - network0 := cm.Reinterpret[uint32](network_) - localAddress0, localAddress1, localAddress2, localAddress3, localAddress4, localAddress5, localAddress6, localAddress7, localAddress8, localAddress9, localAddress10, localAddress11 := lower_IPSocketAddress(localAddress) - wasmimport_UDPSocketStartBind((uint32)(self0), (uint32)(network0), (uint32)(localAddress0), (uint32)(localAddress1), (uint32)(localAddress2), (uint32)(localAddress3), (uint32)(localAddress4), (uint32)(localAddress5), (uint32)(localAddress6), (uint32)(localAddress7), (uint32)(localAddress8), (uint32)(localAddress9), (uint32)(localAddress10), (uint32)(localAddress11), &result) - return -} - -// Stream represents the imported method "stream". -// -// Set up inbound & outbound communication channels, optionally to a specific peer. -// -// This function only changes the local socket configuration and does not generate -// any network traffic. -// On success, the `remote-address` of the socket is updated. The `local-address` -// may be updated as well, -// based on the best network path to `remote-address`. -// -// When a `remote-address` is provided, the returned streams are limited to communicating -// with that specific peer: -// - `send` can only be used to send to this destination. -// - `receive` will only return datagrams sent from the provided `remote-address`. -// -// This method may be called multiple times on the same socket to change its association, -// but -// only the most recently returned pair of streams will be operational. Implementations -// may trap if -// the streams returned by a previous invocation haven't been dropped yet before calling -// `stream` again. -// -// The POSIX equivalent in pseudo-code is: -// -// if (was previously connected) { -// connect(s, AF_UNSPEC) -// } -// if (remote_address is Some) { -// connect(s, remote_address) -// } -// -// Unlike in POSIX, the socket must already be explicitly bound. -// -// # Typical errors -// - `invalid-argument`: The `remote-address` has the wrong address family. -// (EAFNOSUPPORT) -// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY -// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) -// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, -// EADDRNOTAVAIL) -// - `invalid-state`: The socket is not bound. -// - `address-in-use`: Tried to perform an implicit bind, but there were -// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) -// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, -// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) -// - `connection-refused`: The connection was refused. (ECONNREFUSED) -// -// # References -// - -// - -// - -// - -// -// %stream: func(remote-address: option) -> result, error-code> -// -//go:nosplit -func (self UDPSocket) Stream(remoteAddress cm.Option[IPSocketAddress]) (result cm.Result[TupleIncomingDatagramStreamOutgoingDatagramStreamShape, cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream], ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - remoteAddress0, remoteAddress1, remoteAddress2, remoteAddress3, remoteAddress4, remoteAddress5, remoteAddress6, remoteAddress7, remoteAddress8, remoteAddress9, remoteAddress10, remoteAddress11, remoteAddress12 := lower_OptionIPSocketAddress(remoteAddress) - wasmimport_UDPSocketStream((uint32)(self0), (uint32)(remoteAddress0), (uint32)(remoteAddress1), (uint32)(remoteAddress2), (uint32)(remoteAddress3), (uint32)(remoteAddress4), (uint32)(remoteAddress5), (uint32)(remoteAddress6), (uint32)(remoteAddress7), (uint32)(remoteAddress8), (uint32)(remoteAddress9), (uint32)(remoteAddress10), (uint32)(remoteAddress11), (uint32)(remoteAddress12), &result) - return -} - -// Subscribe represents the imported method "subscribe". -// -// Create a `pollable` which will resolve once the socket is ready for I/O. -// -// Note: this function is here for WASI Preview2 only. -// It's planned to be removed when `future` is natively supported in Preview3. -// -// subscribe: func() -> pollable -// -//go:nosplit -func (self UDPSocket) Subscribe() (result Pollable) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_UDPSocketSubscribe((uint32)(self0)) - result = cm.Reinterpret[Pollable]((uint32)(result0)) - return -} - -// UnicastHopLimit represents the imported method "unicast-hop-limit". -// -// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. -// -// If the provided value is 0, an `invalid-argument` error is returned. -// -// # Typical errors -// - `invalid-argument`: (set) The TTL value must be 1 or higher. -// -// unicast-hop-limit: func() -> result -// -//go:nosplit -func (self UDPSocket) UnicastHopLimit() (result cm.Result[uint8, uint8, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_UDPSocketUnicastHopLimit((uint32)(self0), &result) - return -} - -// IncomingDatagramStream represents the imported resource "wasi:sockets/udp@0.2.0#incoming-datagram-stream". -// -// resource incoming-datagram-stream -type IncomingDatagramStream cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "incoming-datagram-stream". -// -// Drops a resource handle. -// -//go:nosplit -func (self IncomingDatagramStream) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_IncomingDatagramStreamResourceDrop((uint32)(self0)) - return -} - -// Receive represents the imported method "receive". -// -// Receive messages on the socket. -// -// This function attempts to receive up to `max-results` datagrams on the socket without -// blocking. -// The returned list may contain fewer elements than requested, but never more. -// -// This function returns successfully with an empty list when either: -// - `max-results` is 0, or: -// - `max-results` is greater than 0, but no results are immediately available. -// This function never returns `error(would-block)`. -// -// # Typical errors -// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET -// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) -// - `connection-refused`: The connection was refused. (ECONNREFUSED) -// -// # References -// - -// - -// - -// - -// - -// - -// - -// - -// -// receive: func(max-results: u64) -> result, error-code> -// -//go:nosplit -func (self IncomingDatagramStream) Receive(maxResults uint64) (result cm.Result[cm.List[IncomingDatagram], cm.List[IncomingDatagram], ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - maxResults0 := (uint64)(maxResults) - wasmimport_IncomingDatagramStreamReceive((uint32)(self0), (uint64)(maxResults0), &result) - return -} - -// Subscribe represents the imported method "subscribe". -// -// Create a `pollable` which will resolve once the stream is ready to receive again. -// -// Note: this function is here for WASI Preview2 only. -// It's planned to be removed when `future` is natively supported in Preview3. -// -// subscribe: func() -> pollable -// -//go:nosplit -func (self IncomingDatagramStream) Subscribe() (result Pollable) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_IncomingDatagramStreamSubscribe((uint32)(self0)) - result = cm.Reinterpret[Pollable]((uint32)(result0)) - return -} - -// OutgoingDatagramStream represents the imported resource "wasi:sockets/udp@0.2.0#outgoing-datagram-stream". -// -// resource outgoing-datagram-stream -type OutgoingDatagramStream cm.Resource - -// ResourceDrop represents the imported resource-drop for resource "outgoing-datagram-stream". -// -// Drops a resource handle. -// -//go:nosplit -func (self OutgoingDatagramStream) ResourceDrop() { - self0 := cm.Reinterpret[uint32](self) - wasmimport_OutgoingDatagramStreamResourceDrop((uint32)(self0)) - return -} - -// CheckSend represents the imported method "check-send". -// -// Check readiness for sending. This function never blocks. -// -// Returns the number of datagrams permitted for the next call to `send`, -// or an error. Calling `send` with more datagrams than this function has -// permitted will trap. -// -// When this function returns ok(0), the `subscribe` pollable will -// become ready when this function will report at least ok(1), or an -// error. -// -// Never returns `would-block`. -// -// check-send: func() -> result -// -//go:nosplit -func (self OutgoingDatagramStream) CheckSend() (result cm.Result[uint64, uint64, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - wasmimport_OutgoingDatagramStreamCheckSend((uint32)(self0), &result) - return -} - -// Send represents the imported method "send". -// -// Send messages on the socket. -// -// This function attempts to send all provided `datagrams` on the socket without blocking -// and -// returns how many messages were actually sent (or queued for sending). This function -// never -// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` -// is returned. -// -// This function semantically behaves the same as iterating the `datagrams` list and -// sequentially -// sending each individual datagram until either the end of the list has been reached -// or the first error occurred. -// If at least one datagram has been sent successfully, this function never returns -// an error. -// -// If the input list is empty, the function returns `ok(0)`. -// -// Each call to `send` must be permitted by a preceding `check-send`. Implementations -// must trap if -// either `check-send` was not called or `datagrams` contains more items than `check-send` -// permitted. -// -// # Typical errors -// - `invalid-argument`: The `remote-address` has the wrong address family. -// (EAFNOSUPPORT) -// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY -// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) -// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, -// EADDRNOTAVAIL) -// - `invalid-argument`: The socket is in "connected" mode and `remote-address` -// is `some` value that does not match the address passed to `stream`. (EISCONN) -// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` -// was provided. (EDESTADDRREQ) -// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, -// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) -// - `connection-refused`: The connection was refused. (ECONNREFUSED) -// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) -// -// # References -// - -// - -// - -// - -// - -// - -// - -// - -// -// send: func(datagrams: list) -> result -// -//go:nosplit -func (self OutgoingDatagramStream) Send(datagrams cm.List[OutgoingDatagram]) (result cm.Result[uint64, uint64, ErrorCode]) { - self0 := cm.Reinterpret[uint32](self) - datagrams0, datagrams1 := cm.LowerList(datagrams) - wasmimport_OutgoingDatagramStreamSend((uint32)(self0), (*OutgoingDatagram)(datagrams0), (uint32)(datagrams1), &result) - return -} - -// Subscribe represents the imported method "subscribe". -// -// Create a `pollable` which will resolve once the stream is ready to send again. -// -// Note: this function is here for WASI Preview2 only. -// It's planned to be removed when `future` is natively supported in Preview3. -// -// subscribe: func() -> pollable -// -//go:nosplit -func (self OutgoingDatagramStream) Subscribe() (result Pollable) { - self0 := cm.Reinterpret[uint32](self) - result0 := wasmimport_OutgoingDatagramStreamSubscribe((uint32)(self0)) - result = cm.Reinterpret[Pollable]((uint32)(result0)) - return -} diff --git a/x/wasihttp/wit/deps/cli/command.wit b/x/wasihttp/wit/deps/cli/command.wit deleted file mode 100644 index d8005bd3..00000000 --- a/x/wasihttp/wit/deps/cli/command.wit +++ /dev/null @@ -1,7 +0,0 @@ -package wasi:cli@0.2.0; - -world command { - include imports; - - export run; -} diff --git a/x/wasihttp/wit/deps/cli/environment.wit b/x/wasihttp/wit/deps/cli/environment.wit deleted file mode 100644 index 70065233..00000000 --- a/x/wasihttp/wit/deps/cli/environment.wit +++ /dev/null @@ -1,18 +0,0 @@ -interface environment { - /// Get the POSIX-style environment variables. - /// - /// Each environment variable is provided as a pair of string variable names - /// and string value. - /// - /// Morally, these are a value import, but until value imports are available - /// in the component model, this import function should return the same - /// values each time it is called. - get-environment: func() -> list>; - - /// Get the POSIX-style arguments to the program. - get-arguments: func() -> list; - - /// Return a path that programs should use as their initial current working - /// directory, interpreting `.` as shorthand for this. - initial-cwd: func() -> option; -} diff --git a/x/wasihttp/wit/deps/cli/exit.wit b/x/wasihttp/wit/deps/cli/exit.wit deleted file mode 100644 index d0c2b82a..00000000 --- a/x/wasihttp/wit/deps/cli/exit.wit +++ /dev/null @@ -1,4 +0,0 @@ -interface exit { - /// Exit the current instance and any linked instances. - exit: func(status: result); -} diff --git a/x/wasihttp/wit/deps/cli/imports.wit b/x/wasihttp/wit/deps/cli/imports.wit deleted file mode 100644 index 083b84a0..00000000 --- a/x/wasihttp/wit/deps/cli/imports.wit +++ /dev/null @@ -1,20 +0,0 @@ -package wasi:cli@0.2.0; - -world imports { - include wasi:clocks/imports@0.2.0; - include wasi:filesystem/imports@0.2.0; - include wasi:sockets/imports@0.2.0; - include wasi:random/imports@0.2.0; - include wasi:io/imports@0.2.0; - - import environment; - import exit; - import stdin; - import stdout; - import stderr; - import terminal-input; - import terminal-output; - import terminal-stdin; - import terminal-stdout; - import terminal-stderr; -} diff --git a/x/wasihttp/wit/deps/cli/run.wit b/x/wasihttp/wit/deps/cli/run.wit deleted file mode 100644 index a70ee8c0..00000000 --- a/x/wasihttp/wit/deps/cli/run.wit +++ /dev/null @@ -1,4 +0,0 @@ -interface run { - /// Run the program. - run: func() -> result; -} diff --git a/x/wasihttp/wit/deps/cli/stdio.wit b/x/wasihttp/wit/deps/cli/stdio.wit deleted file mode 100644 index 31ef35b5..00000000 --- a/x/wasihttp/wit/deps/cli/stdio.wit +++ /dev/null @@ -1,17 +0,0 @@ -interface stdin { - use wasi:io/streams@0.2.0.{input-stream}; - - get-stdin: func() -> input-stream; -} - -interface stdout { - use wasi:io/streams@0.2.0.{output-stream}; - - get-stdout: func() -> output-stream; -} - -interface stderr { - use wasi:io/streams@0.2.0.{output-stream}; - - get-stderr: func() -> output-stream; -} diff --git a/x/wasihttp/wit/deps/cli/terminal.wit b/x/wasihttp/wit/deps/cli/terminal.wit deleted file mode 100644 index 38c724ef..00000000 --- a/x/wasihttp/wit/deps/cli/terminal.wit +++ /dev/null @@ -1,49 +0,0 @@ -/// Terminal input. -/// -/// In the future, this may include functions for disabling echoing, -/// disabling input buffering so that keyboard events are sent through -/// immediately, querying supported features, and so on. -interface terminal-input { - /// The input side of a terminal. - resource terminal-input; -} - -/// Terminal output. -/// -/// In the future, this may include functions for querying the terminal -/// size, being notified of terminal size changes, querying supported -/// features, and so on. -interface terminal-output { - /// The output side of a terminal. - resource terminal-output; -} - -/// An interface providing an optional `terminal-input` for stdin as a -/// link-time authority. -interface terminal-stdin { - use terminal-input.{terminal-input}; - - /// If stdin is connected to a terminal, return a `terminal-input` handle - /// allowing further interaction with it. - get-terminal-stdin: func() -> option; -} - -/// An interface providing an optional `terminal-output` for stdout as a -/// link-time authority. -interface terminal-stdout { - use terminal-output.{terminal-output}; - - /// If stdout is connected to a terminal, return a `terminal-output` handle - /// allowing further interaction with it. - get-terminal-stdout: func() -> option; -} - -/// An interface providing an optional `terminal-output` for stderr as a -/// link-time authority. -interface terminal-stderr { - use terminal-output.{terminal-output}; - - /// If stderr is connected to a terminal, return a `terminal-output` handle - /// allowing further interaction with it. - get-terminal-stderr: func() -> option; -} diff --git a/x/wasihttp/wit/deps/filesystem/preopens.wit b/x/wasihttp/wit/deps/filesystem/preopens.wit deleted file mode 100644 index da801f6d..00000000 --- a/x/wasihttp/wit/deps/filesystem/preopens.wit +++ /dev/null @@ -1,8 +0,0 @@ -package wasi:filesystem@0.2.0; - -interface preopens { - use types.{descriptor}; - - /// Return the set of preopened directories, and their path. - get-directories: func() -> list>; -} diff --git a/x/wasihttp/wit/deps/filesystem/types.wit b/x/wasihttp/wit/deps/filesystem/types.wit deleted file mode 100644 index 11108fcd..00000000 --- a/x/wasihttp/wit/deps/filesystem/types.wit +++ /dev/null @@ -1,634 +0,0 @@ -package wasi:filesystem@0.2.0; -/// WASI filesystem is a filesystem API primarily intended to let users run WASI -/// programs that access their files on their existing filesystems, without -/// significant overhead. -/// -/// It is intended to be roughly portable between Unix-family platforms and -/// Windows, though it does not hide many of the major differences. -/// -/// Paths are passed as interface-type `string`s, meaning they must consist of -/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain -/// paths which are not accessible by this API. -/// -/// The directory separator in WASI is always the forward-slash (`/`). -/// -/// All paths in WASI are relative paths, and are interpreted relative to a -/// `descriptor` referring to a base directory. If a `path` argument to any WASI -/// function starts with `/`, or if any step of resolving a `path`, including -/// `..` and symbolic link steps, reaches a directory outside of the base -/// directory, or reaches a symlink to an absolute or rooted path in the -/// underlying filesystem, the function fails with `error-code::not-permitted`. -/// -/// For more information about WASI path resolution and sandboxing, see -/// [WASI filesystem path resolution]. -/// -/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md -interface types { - use wasi:io/streams@0.2.0.{input-stream, output-stream, error}; - use wasi:clocks/wall-clock@0.2.0.{datetime}; - - /// File size or length of a region within a file. - type filesize = u64; - - /// The type of a filesystem object referenced by a descriptor. - /// - /// Note: This was called `filetype` in earlier versions of WASI. - enum descriptor-type { - /// The type of the descriptor or file is unknown or is different from - /// any of the other types specified. - unknown, - /// The descriptor refers to a block device inode. - block-device, - /// The descriptor refers to a character device inode. - character-device, - /// The descriptor refers to a directory inode. - directory, - /// The descriptor refers to a named pipe. - fifo, - /// The file refers to a symbolic link inode. - symbolic-link, - /// The descriptor refers to a regular file inode. - regular-file, - /// The descriptor refers to a socket. - socket, - } - - /// Descriptor flags. - /// - /// Note: This was called `fdflags` in earlier versions of WASI. - flags descriptor-flags { - /// Read mode: Data can be read. - read, - /// Write mode: Data can be written to. - write, - /// Request that writes be performed according to synchronized I/O file - /// integrity completion. The data stored in the file and the file's - /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - file-integrity-sync, - /// Request that writes be performed according to synchronized I/O data - /// integrity completion. Only the data stored in the file is - /// synchronized. This is similar to `O_DSYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - data-integrity-sync, - /// Requests that reads be performed at the same level of integrety - /// requested for writes. This is similar to `O_RSYNC` in POSIX. - /// - /// The precise semantics of this operation have not yet been defined for - /// WASI. At this time, it should be interpreted as a request, and not a - /// requirement. - requested-write-sync, - /// Mutating directories mode: Directory contents may be mutated. - /// - /// When this flag is unset on a descriptor, operations using the - /// descriptor which would create, rename, delete, modify the data or - /// metadata of filesystem objects, or obtain another handle which - /// would permit any of those, shall fail with `error-code::read-only` if - /// they would otherwise succeed. - /// - /// This may only be set on directories. - mutate-directory, - } - - /// File attributes. - /// - /// Note: This was called `filestat` in earlier versions of WASI. - record descriptor-stat { - /// File type. - %type: descriptor-type, - /// Number of hard links to the file. - link-count: link-count, - /// For regular files, the file size in bytes. For symbolic links, the - /// length in bytes of the pathname contained in the symbolic link. - size: filesize, - /// Last data access timestamp. - /// - /// If the `option` is none, the platform doesn't maintain an access - /// timestamp for this file. - data-access-timestamp: option, - /// Last data modification timestamp. - /// - /// If the `option` is none, the platform doesn't maintain a - /// modification timestamp for this file. - data-modification-timestamp: option, - /// Last file status-change timestamp. - /// - /// If the `option` is none, the platform doesn't maintain a - /// status-change timestamp for this file. - status-change-timestamp: option, - } - - /// Flags determining the method of how paths are resolved. - flags path-flags { - /// As long as the resolved path corresponds to a symbolic link, it is - /// expanded. - symlink-follow, - } - - /// Open flags used by `open-at`. - flags open-flags { - /// Create file if it does not exist, similar to `O_CREAT` in POSIX. - create, - /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. - directory, - /// Fail if file already exists, similar to `O_EXCL` in POSIX. - exclusive, - /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. - truncate, - } - - /// Number of hard links to an inode. - type link-count = u64; - - /// When setting a timestamp, this gives the value to set it to. - variant new-timestamp { - /// Leave the timestamp set to its previous value. - no-change, - /// Set the timestamp to the current time of the system clock associated - /// with the filesystem. - now, - /// Set the timestamp to the given value. - timestamp(datetime), - } - - /// A directory entry. - record directory-entry { - /// The type of the file referred to by this directory entry. - %type: descriptor-type, - - /// The name of the object. - name: string, - } - - /// Error codes returned by functions, similar to `errno` in POSIX. - /// Not all of these error codes are returned by the functions provided by this - /// API; some are used in higher-level library layers, and others are provided - /// merely for alignment with POSIX. - enum error-code { - /// Permission denied, similar to `EACCES` in POSIX. - access, - /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. - would-block, - /// Connection already in progress, similar to `EALREADY` in POSIX. - already, - /// Bad descriptor, similar to `EBADF` in POSIX. - bad-descriptor, - /// Device or resource busy, similar to `EBUSY` in POSIX. - busy, - /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. - deadlock, - /// Storage quota exceeded, similar to `EDQUOT` in POSIX. - quota, - /// File exists, similar to `EEXIST` in POSIX. - exist, - /// File too large, similar to `EFBIG` in POSIX. - file-too-large, - /// Illegal byte sequence, similar to `EILSEQ` in POSIX. - illegal-byte-sequence, - /// Operation in progress, similar to `EINPROGRESS` in POSIX. - in-progress, - /// Interrupted function, similar to `EINTR` in POSIX. - interrupted, - /// Invalid argument, similar to `EINVAL` in POSIX. - invalid, - /// I/O error, similar to `EIO` in POSIX. - io, - /// Is a directory, similar to `EISDIR` in POSIX. - is-directory, - /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. - loop, - /// Too many links, similar to `EMLINK` in POSIX. - too-many-links, - /// Message too large, similar to `EMSGSIZE` in POSIX. - message-size, - /// Filename too long, similar to `ENAMETOOLONG` in POSIX. - name-too-long, - /// No such device, similar to `ENODEV` in POSIX. - no-device, - /// No such file or directory, similar to `ENOENT` in POSIX. - no-entry, - /// No locks available, similar to `ENOLCK` in POSIX. - no-lock, - /// Not enough space, similar to `ENOMEM` in POSIX. - insufficient-memory, - /// No space left on device, similar to `ENOSPC` in POSIX. - insufficient-space, - /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. - not-directory, - /// Directory not empty, similar to `ENOTEMPTY` in POSIX. - not-empty, - /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. - not-recoverable, - /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. - unsupported, - /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. - no-tty, - /// No such device or address, similar to `ENXIO` in POSIX. - no-such-device, - /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. - overflow, - /// Operation not permitted, similar to `EPERM` in POSIX. - not-permitted, - /// Broken pipe, similar to `EPIPE` in POSIX. - pipe, - /// Read-only file system, similar to `EROFS` in POSIX. - read-only, - /// Invalid seek, similar to `ESPIPE` in POSIX. - invalid-seek, - /// Text file busy, similar to `ETXTBSY` in POSIX. - text-file-busy, - /// Cross-device link, similar to `EXDEV` in POSIX. - cross-device, - } - - /// File or memory access pattern advisory information. - enum advice { - /// The application has no advice to give on its behavior with respect - /// to the specified data. - normal, - /// The application expects to access the specified data sequentially - /// from lower offsets to higher offsets. - sequential, - /// The application expects to access the specified data in a random - /// order. - random, - /// The application expects to access the specified data in the near - /// future. - will-need, - /// The application expects that it will not access the specified data - /// in the near future. - dont-need, - /// The application expects to access the specified data once and then - /// not reuse it thereafter. - no-reuse, - } - - /// A 128-bit hash value, split into parts because wasm doesn't have a - /// 128-bit integer type. - record metadata-hash-value { - /// 64 bits of a 128-bit hash value. - lower: u64, - /// Another 64 bits of a 128-bit hash value. - upper: u64, - } - - /// A descriptor is a reference to a filesystem object, which may be a file, - /// directory, named pipe, special file, or other object on which filesystem - /// calls may be made. - resource descriptor { - /// Return a stream for reading from a file, if available. - /// - /// May fail with an error-code describing why the file cannot be read. - /// - /// Multiple read, write, and append streams may be active on the same open - /// file and they do not interfere with each other. - /// - /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. - read-via-stream: func( - /// The offset within the file at which to start reading. - offset: filesize, - ) -> result; - - /// Return a stream for writing to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be written. - /// - /// Note: This allows using `write-stream`, which is similar to `write` in - /// POSIX. - write-via-stream: func( - /// The offset within the file at which to start writing. - offset: filesize, - ) -> result; - - /// Return a stream for appending to a file, if available. - /// - /// May fail with an error-code describing why the file cannot be appended. - /// - /// Note: This allows using `write-stream`, which is similar to `write` with - /// `O_APPEND` in in POSIX. - append-via-stream: func() -> result; - - /// Provide file advisory information on a descriptor. - /// - /// This is similar to `posix_fadvise` in POSIX. - advise: func( - /// The offset within the file to which the advisory applies. - offset: filesize, - /// The length of the region to which the advisory applies. - length: filesize, - /// The advice. - advice: advice - ) -> result<_, error-code>; - - /// Synchronize the data of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fdatasync` in POSIX. - sync-data: func() -> result<_, error-code>; - - /// Get flags associated with a descriptor. - /// - /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. - /// - /// Note: This returns the value that was the `fs_flags` value returned - /// from `fdstat_get` in earlier versions of WASI. - get-flags: func() -> result; - - /// Get the dynamic type of a descriptor. - /// - /// Note: This returns the same value as the `type` field of the `fd-stat` - /// returned by `stat`, `stat-at` and similar. - /// - /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided - /// by `fstat` in POSIX. - /// - /// Note: This returns the value that was the `fs_filetype` value returned - /// from `fdstat_get` in earlier versions of WASI. - get-type: func() -> result; - - /// Adjust the size of an open file. If this increases the file's size, the - /// extra bytes are filled with zeros. - /// - /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. - set-size: func(size: filesize) -> result<_, error-code>; - - /// Adjust the timestamps of an open file or directory. - /// - /// Note: This is similar to `futimens` in POSIX. - /// - /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. - set-times: func( - /// The desired values of the data access timestamp. - data-access-timestamp: new-timestamp, - /// The desired values of the data modification timestamp. - data-modification-timestamp: new-timestamp, - ) -> result<_, error-code>; - - /// Read from a descriptor, without using and updating the descriptor's offset. - /// - /// This function returns a list of bytes containing the data that was - /// read, along with a bool which, when true, indicates that the end of the - /// file was reached. The returned list will contain up to `length` bytes; it - /// may return fewer than requested, if the end of the file is reached or - /// if the I/O operation is interrupted. - /// - /// In the future, this may change to return a `stream`. - /// - /// Note: This is similar to `pread` in POSIX. - read: func( - /// The maximum number of bytes to read. - length: filesize, - /// The offset within the file at which to read. - offset: filesize, - ) -> result, bool>, error-code>; - - /// Write to a descriptor, without using and updating the descriptor's offset. - /// - /// It is valid to write past the end of a file; the file is extended to the - /// extent of the write, with bytes between the previous end and the start of - /// the write set to zero. - /// - /// In the future, this may change to take a `stream`. - /// - /// Note: This is similar to `pwrite` in POSIX. - write: func( - /// Data to write - buffer: list, - /// The offset within the file at which to write. - offset: filesize, - ) -> result; - - /// Read directory entries from a directory. - /// - /// On filesystems where directories contain entries referring to themselves - /// and their parents, often named `.` and `..` respectively, these entries - /// are omitted. - /// - /// This always returns a new stream which starts at the beginning of the - /// directory. Multiple streams may be active on the same directory, and they - /// do not interfere with each other. - read-directory: func() -> result; - - /// Synchronize the data and metadata of a file to disk. - /// - /// This function succeeds with no effect if the file descriptor is not - /// opened for writing. - /// - /// Note: This is similar to `fsync` in POSIX. - sync: func() -> result<_, error-code>; - - /// Create a directory. - /// - /// Note: This is similar to `mkdirat` in POSIX. - create-directory-at: func( - /// The relative path at which to create the directory. - path: string, - ) -> result<_, error-code>; - - /// Return the attributes of an open file or directory. - /// - /// Note: This is similar to `fstat` in POSIX, except that it does not return - /// device and inode information. For testing whether two descriptors refer to - /// the same underlying filesystem object, use `is-same-object`. To obtain - /// additional data that can be used do determine whether a file has been - /// modified, use `metadata-hash`. - /// - /// Note: This was called `fd_filestat_get` in earlier versions of WASI. - stat: func() -> result; - - /// Return the attributes of a file or directory. - /// - /// Note: This is similar to `fstatat` in POSIX, except that it does not - /// return device and inode information. See the `stat` description for a - /// discussion of alternatives. - /// - /// Note: This was called `path_filestat_get` in earlier versions of WASI. - stat-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the file or directory to inspect. - path: string, - ) -> result; - - /// Adjust the timestamps of a file or directory. - /// - /// Note: This is similar to `utimensat` in POSIX. - /// - /// Note: This was called `path_filestat_set_times` in earlier versions of - /// WASI. - set-times-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the file or directory to operate on. - path: string, - /// The desired values of the data access timestamp. - data-access-timestamp: new-timestamp, - /// The desired values of the data modification timestamp. - data-modification-timestamp: new-timestamp, - ) -> result<_, error-code>; - - /// Create a hard link. - /// - /// Note: This is similar to `linkat` in POSIX. - link-at: func( - /// Flags determining the method of how the path is resolved. - old-path-flags: path-flags, - /// The relative source path from which to link. - old-path: string, - /// The base directory for `new-path`. - new-descriptor: borrow, - /// The relative destination path at which to create the hard link. - new-path: string, - ) -> result<_, error-code>; - - /// Open a file or directory. - /// - /// The returned descriptor is not guaranteed to be the lowest-numbered - /// descriptor not currently open/ it is randomized to prevent applications - /// from depending on making assumptions about indexes, since this is - /// error-prone in multi-threaded contexts. The returned descriptor is - /// guaranteed to be less than 2**31. - /// - /// If `flags` contains `descriptor-flags::mutate-directory`, and the base - /// descriptor doesn't have `descriptor-flags::mutate-directory` set, - /// `open-at` fails with `error-code::read-only`. - /// - /// If `flags` contains `write` or `mutate-directory`, or `open-flags` - /// contains `truncate` or `create`, and the base descriptor doesn't have - /// `descriptor-flags::mutate-directory` set, `open-at` fails with - /// `error-code::read-only`. - /// - /// Note: This is similar to `openat` in POSIX. - open-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the object to open. - path: string, - /// The method by which to open the file. - open-flags: open-flags, - /// Flags to use for the resulting descriptor. - %flags: descriptor-flags, - ) -> result; - - /// Read the contents of a symbolic link. - /// - /// If the contents contain an absolute or rooted path in the underlying - /// filesystem, this function fails with `error-code::not-permitted`. - /// - /// Note: This is similar to `readlinkat` in POSIX. - readlink-at: func( - /// The relative path of the symbolic link from which to read. - path: string, - ) -> result; - - /// Remove a directory. - /// - /// Return `error-code::not-empty` if the directory is not empty. - /// - /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. - remove-directory-at: func( - /// The relative path to a directory to remove. - path: string, - ) -> result<_, error-code>; - - /// Rename a filesystem object. - /// - /// Note: This is similar to `renameat` in POSIX. - rename-at: func( - /// The relative source path of the file or directory to rename. - old-path: string, - /// The base directory for `new-path`. - new-descriptor: borrow, - /// The relative destination path to which to rename the file or directory. - new-path: string, - ) -> result<_, error-code>; - - /// Create a symbolic link (also known as a "symlink"). - /// - /// If `old-path` starts with `/`, the function fails with - /// `error-code::not-permitted`. - /// - /// Note: This is similar to `symlinkat` in POSIX. - symlink-at: func( - /// The contents of the symbolic link. - old-path: string, - /// The relative destination path at which to create the symbolic link. - new-path: string, - ) -> result<_, error-code>; - - /// Unlink a filesystem object that is not a directory. - /// - /// Return `error-code::is-directory` if the path refers to a directory. - /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. - unlink-file-at: func( - /// The relative path to a file to unlink. - path: string, - ) -> result<_, error-code>; - - /// Test whether two descriptors refer to the same filesystem object. - /// - /// In POSIX, this corresponds to testing whether the two descriptors have the - /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. - /// wasi-filesystem does not expose device and inode numbers, so this function - /// may be used instead. - is-same-object: func(other: borrow) -> bool; - - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a descriptor. - /// - /// This returns a hash of the last-modification timestamp and file size, and - /// may also include the inode number, device number, birth timestamp, and - /// other metadata fields that may change when the file is modified or - /// replaced. It may also include a secret value chosen by the - /// implementation and not otherwise exposed. - /// - /// Implementations are encourated to provide the following properties: - /// - /// - If the file is not modified or replaced, the computed hash value should - /// usually not change. - /// - If the object is modified or replaced, the computed hash value should - /// usually change. - /// - The inputs to the hash should not be easily computable from the - /// computed hash. - /// - /// However, none of these is required. - metadata-hash: func() -> result; - - /// Return a hash of the metadata associated with a filesystem object referred - /// to by a directory descriptor and a relative path. - /// - /// This performs the same hash computation as `metadata-hash`. - metadata-hash-at: func( - /// Flags determining the method of how the path is resolved. - path-flags: path-flags, - /// The relative path of the file or directory to inspect. - path: string, - ) -> result; - } - - /// A stream of directory entries. - resource directory-entry-stream { - /// Read a single directory entry from a `directory-entry-stream`. - read-directory-entry: func() -> result, error-code>; - } - - /// Attempts to extract a filesystem-related `error-code` from the stream - /// `error` provided. - /// - /// Stream operations which return `stream-error::last-operation-failed` - /// have a payload with more information about the operation that failed. - /// This payload can be passed through to this function to see if there's - /// filesystem-related information about the error to return. - /// - /// Note that this function is fallible because not all stream-related - /// errors are filesystem-related errors. - filesystem-error-code: func(err: borrow) -> option; -} diff --git a/x/wasihttp/wit/deps/filesystem/world.wit b/x/wasihttp/wit/deps/filesystem/world.wit deleted file mode 100644 index 663f5792..00000000 --- a/x/wasihttp/wit/deps/filesystem/world.wit +++ /dev/null @@ -1,6 +0,0 @@ -package wasi:filesystem@0.2.0; - -world imports { - import types; - import preopens; -} diff --git a/x/wasihttp/wit/deps/http/proxy.wit b/x/wasihttp/wit/deps/http/proxy.wit index 687c24d2..a0e9cb89 100644 --- a/x/wasihttp/wit/deps/http/proxy.wit +++ b/x/wasihttp/wit/deps/http/proxy.wit @@ -1,32 +1 @@ package wasi:http@0.2.0; - -/// The `wasi:http/proxy` world captures a widely-implementable intersection of -/// hosts that includes HTTP forward and reverse proxies. Components targeting -/// this world may concurrently stream in and out any number of incoming and -/// outgoing HTTP requests. -world proxy { - /// HTTP proxies have access to time and randomness. - include wasi:clocks/imports@0.2.0; - import wasi:random/random@0.2.0; - - /// Proxies have standard output and error streams which are expected to - /// terminate in a developer-facing console provided by the host. - import wasi:cli/stdout@0.2.0; - import wasi:cli/stderr@0.2.0; - - /// TODO: this is a temporary workaround until component tooling is able to - /// gracefully handle the absence of stdin. Hosts must return an eof stream - /// for this import, which is what wasi-libc + tooling will do automatically - /// when this import is properly removed. - import wasi:cli/stdin@0.2.0; - - /// This is the default handler to use when user code simply wants to make an - /// HTTP request (e.g., via `fetch()`). - import outgoing-handler; - - /// The host delivers incoming HTTP requests to a component by calling the - /// `handle` function of this exported interface. A host may arbitrarily reuse - /// or not reuse component instance when delivering incoming HTTP requests and - /// thus a component must be able to handle 0..N calls to `handle`. - export incoming-handler; -} diff --git a/x/wasihttp/wit/deps/random/insecure-seed.wit b/x/wasihttp/wit/deps/random/insecure-seed.wit deleted file mode 100644 index 47210ac6..00000000 --- a/x/wasihttp/wit/deps/random/insecure-seed.wit +++ /dev/null @@ -1,25 +0,0 @@ -package wasi:random@0.2.0; -/// The insecure-seed interface for seeding hash-map DoS resistance. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -interface insecure-seed { - /// Return a 128-bit value that may contain a pseudo-random value. - /// - /// The returned value is not required to be computed from a CSPRNG, and may - /// even be entirely deterministic. Host implementations are encouraged to - /// provide pseudo-random values to any program exposed to - /// attacker-controlled content, to enable DoS protection built into many - /// languages' hash-map implementations. - /// - /// This function is intended to only be called once, by a source language - /// to initialize Denial Of Service (DoS) protection in its hash-map - /// implementation. - /// - /// # Expected future evolution - /// - /// This will likely be changed to a value import, to prevent it from being - /// called multiple times and potentially used for purposes other than DoS - /// protection. - insecure-seed: func() -> tuple; -} diff --git a/x/wasihttp/wit/deps/random/insecure.wit b/x/wasihttp/wit/deps/random/insecure.wit deleted file mode 100644 index c58f4ee8..00000000 --- a/x/wasihttp/wit/deps/random/insecure.wit +++ /dev/null @@ -1,22 +0,0 @@ -package wasi:random@0.2.0; -/// The insecure interface for insecure pseudo-random numbers. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -interface insecure { - /// Return `len` insecure pseudo-random bytes. - /// - /// This function is not cryptographically secure. Do not use it for - /// anything related to security. - /// - /// There are no requirements on the values of the returned bytes, however - /// implementations are encouraged to return evenly distributed values with - /// a long period. - get-insecure-random-bytes: func(len: u64) -> list; - - /// Return an insecure pseudo-random `u64` value. - /// - /// This function returns the same type of pseudo-random data as - /// `get-insecure-random-bytes`, represented as a `u64`. - get-insecure-random-u64: func() -> u64; -} diff --git a/x/wasihttp/wit/deps/random/random.wit b/x/wasihttp/wit/deps/random/random.wit deleted file mode 100644 index 0c017f09..00000000 --- a/x/wasihttp/wit/deps/random/random.wit +++ /dev/null @@ -1,26 +0,0 @@ -package wasi:random@0.2.0; -/// WASI Random is a random data API. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -interface random { - /// Return `len` cryptographically-secure random or pseudo-random bytes. - /// - /// This function must produce data at least as cryptographically secure and - /// fast as an adequately seeded cryptographically-secure pseudo-random - /// number generator (CSPRNG). It must not block, from the perspective of - /// the calling program, under any circumstances, including on the first - /// request and on requests for numbers of bytes. The returned data must - /// always be unpredictable. - /// - /// This function must always return fresh data. Deterministic environments - /// must omit this function, rather than implementing it with deterministic - /// data. - get-random-bytes: func(len: u64) -> list; - - /// Return a cryptographically-secure random or pseudo-random `u64` value. - /// - /// This function returns the same type of data as `get-random-bytes`, - /// represented as a `u64`. - get-random-u64: func() -> u64; -} diff --git a/x/wasihttp/wit/deps/random/world.wit b/x/wasihttp/wit/deps/random/world.wit deleted file mode 100644 index 3da34914..00000000 --- a/x/wasihttp/wit/deps/random/world.wit +++ /dev/null @@ -1,7 +0,0 @@ -package wasi:random@0.2.0; - -world imports { - import random; - import insecure; - import insecure-seed; -} diff --git a/x/wasihttp/wit/deps/sockets/instance-network.wit b/x/wasihttp/wit/deps/sockets/instance-network.wit deleted file mode 100644 index e455d0ff..00000000 --- a/x/wasihttp/wit/deps/sockets/instance-network.wit +++ /dev/null @@ -1,9 +0,0 @@ - -/// This interface provides a value-export of the default network handle.. -interface instance-network { - use network.{network}; - - /// Get a handle to the default network. - instance-network: func() -> network; - -} diff --git a/x/wasihttp/wit/deps/sockets/ip-name-lookup.wit b/x/wasihttp/wit/deps/sockets/ip-name-lookup.wit deleted file mode 100644 index 8e639ec5..00000000 --- a/x/wasihttp/wit/deps/sockets/ip-name-lookup.wit +++ /dev/null @@ -1,51 +0,0 @@ - -interface ip-name-lookup { - use wasi:io/poll@0.2.0.{pollable}; - use network.{network, error-code, ip-address}; - - - /// Resolve an internet host name to a list of IP addresses. - /// - /// Unicode domain names are automatically converted to ASCII using IDNA encoding. - /// If the input is an IP address string, the address is parsed and returned - /// as-is without making any external requests. - /// - /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. - /// - /// This function never blocks. It either immediately fails or immediately - /// returns successfully with a `resolve-address-stream` that can be used - /// to (asynchronously) fetch the results. - /// - /// # Typical errors - /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. - /// - /// # References: - /// - - /// - - /// - - /// - - resolve-addresses: func(network: borrow, name: string) -> result; - - resource resolve-address-stream { - /// Returns the next address from the resolver. - /// - /// This function should be called multiple times. On each call, it will - /// return the next address in connection order preference. If all - /// addresses have been exhausted, this function returns `none`. - /// - /// This function never returns IPv4-mapped IPv6 addresses. - /// - /// # Typical errors - /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) - /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) - /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) - /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) - resolve-next-address: func() -> result, error-code>; - - /// Create a `pollable` which will resolve once the stream is ready for I/O. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } -} diff --git a/x/wasihttp/wit/deps/sockets/network.wit b/x/wasihttp/wit/deps/sockets/network.wit deleted file mode 100644 index 9cadf065..00000000 --- a/x/wasihttp/wit/deps/sockets/network.wit +++ /dev/null @@ -1,145 +0,0 @@ - -interface network { - /// An opaque resource that represents access to (a subset of) the network. - /// This enables context-based security for networking. - /// There is no need for this to map 1:1 to a physical network interface. - resource network; - - /// Error codes. - /// - /// In theory, every API can return any error code. - /// In practice, API's typically only return the errors documented per API - /// combined with a couple of errors that are always possible: - /// - `unknown` - /// - `access-denied` - /// - `not-supported` - /// - `out-of-memory` - /// - `concurrency-conflict` - /// - /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. - enum error-code { - /// Unknown error - unknown, - - /// Access denied. - /// - /// POSIX equivalent: EACCES, EPERM - access-denied, - - /// The operation is not supported. - /// - /// POSIX equivalent: EOPNOTSUPP - not-supported, - - /// One of the arguments is invalid. - /// - /// POSIX equivalent: EINVAL - invalid-argument, - - /// Not enough memory to complete the operation. - /// - /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY - out-of-memory, - - /// The operation timed out before it could finish completely. - timeout, - - /// This operation is incompatible with another asynchronous operation that is already in progress. - /// - /// POSIX equivalent: EALREADY - concurrency-conflict, - - /// Trying to finish an asynchronous operation that: - /// - has not been started yet, or: - /// - was already finished by a previous `finish-*` call. - /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - not-in-progress, - - /// The operation has been aborted because it could not be completed immediately. - /// - /// Note: this is scheduled to be removed when `future`s are natively supported. - would-block, - - - /// The operation is not valid in the socket's current state. - invalid-state, - - /// A new socket resource could not be created because of a system limit. - new-socket-limit, - - /// A bind operation failed because the provided address is not an address that the `network` can bind to. - address-not-bindable, - - /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. - address-in-use, - - /// The remote address is not reachable - remote-unreachable, - - - /// The TCP connection was forcefully rejected - connection-refused, - - /// The TCP connection was reset. - connection-reset, - - /// A TCP connection was aborted. - connection-aborted, - - - /// The size of a datagram sent to a UDP socket exceeded the maximum - /// supported size. - datagram-too-large, - - - /// Name does not exist or has no suitable associated IP addresses. - name-unresolvable, - - /// A temporary failure in name resolution occurred. - temporary-resolver-failure, - - /// A permanent failure in name resolution occurred. - permanent-resolver-failure, - } - - enum ip-address-family { - /// Similar to `AF_INET` in POSIX. - ipv4, - - /// Similar to `AF_INET6` in POSIX. - ipv6, - } - - type ipv4-address = tuple; - type ipv6-address = tuple; - - variant ip-address { - ipv4(ipv4-address), - ipv6(ipv6-address), - } - - record ipv4-socket-address { - /// sin_port - port: u16, - /// sin_addr - address: ipv4-address, - } - - record ipv6-socket-address { - /// sin6_port - port: u16, - /// sin6_flowinfo - flow-info: u32, - /// sin6_addr - address: ipv6-address, - /// sin6_scope_id - scope-id: u32, - } - - variant ip-socket-address { - ipv4(ipv4-socket-address), - ipv6(ipv6-socket-address), - } - -} diff --git a/x/wasihttp/wit/deps/sockets/tcp-create-socket.wit b/x/wasihttp/wit/deps/sockets/tcp-create-socket.wit deleted file mode 100644 index c7ddf1f2..00000000 --- a/x/wasihttp/wit/deps/sockets/tcp-create-socket.wit +++ /dev/null @@ -1,27 +0,0 @@ - -interface tcp-create-socket { - use network.{network, error-code, ip-address-family}; - use tcp.{tcp-socket}; - - /// Create a new TCP socket. - /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. - /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. - /// - /// This function does not require a network capability handle. This is considered to be safe because - /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` - /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. - /// - /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. - /// - /// # Typical errors - /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) - /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) - /// - /// # References - /// - - /// - - /// - - /// - - create-tcp-socket: func(address-family: ip-address-family) -> result; -} diff --git a/x/wasihttp/wit/deps/sockets/tcp.wit b/x/wasihttp/wit/deps/sockets/tcp.wit deleted file mode 100644 index 5902b9ee..00000000 --- a/x/wasihttp/wit/deps/sockets/tcp.wit +++ /dev/null @@ -1,353 +0,0 @@ - -interface tcp { - use wasi:io/streams@0.2.0.{input-stream, output-stream}; - use wasi:io/poll@0.2.0.{pollable}; - use wasi:clocks/monotonic-clock@0.2.0.{duration}; - use network.{network, error-code, ip-socket-address, ip-address-family}; - - enum shutdown-type { - /// Similar to `SHUT_RD` in POSIX. - receive, - - /// Similar to `SHUT_WR` in POSIX. - send, - - /// Similar to `SHUT_RDWR` in POSIX. - both, - } - - /// A TCP socket resource. - /// - /// The socket can be in one of the following states: - /// - `unbound` - /// - `bind-in-progress` - /// - `bound` (See note below) - /// - `listen-in-progress` - /// - `listening` - /// - `connect-in-progress` - /// - `connected` - /// - `closed` - /// See - /// for a more information. - /// - /// Note: Except where explicitly mentioned, whenever this documentation uses - /// the term "bound" without backticks it actually means: in the `bound` state *or higher*. - /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) - /// - /// In addition to the general error codes documented on the - /// `network::error-code` type, TCP socket methods may always return - /// `error(invalid-state)` when in the `closed` state. - resource tcp-socket { - /// Bind the socket to a specific network on the provided IP address and port. - /// - /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which - /// network interface(s) to bind to. - /// If the TCP/UDP port is zero, the socket will be bound to a random free port. - /// - /// Bind can be attempted multiple times on the same socket, even with - /// different arguments on each iteration. But never concurrently and - /// only as long as the previous bind failed. Once a bind succeeds, the - /// binding can't be changed anymore. - /// - /// # Typical errors - /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) - /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. (EINVAL) - /// - `invalid-state`: The socket is already bound. (EINVAL) - /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) - /// - `address-in-use`: Address is already in use. (EADDRINUSE) - /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) - /// - `not-in-progress`: A `bind` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # Implementors note - /// When binding to a non-zero port, this bind operation shouldn't be affected by the TIME_WAIT - /// state of a recently closed socket on the same local address. In practice this means that the SO_REUSEADDR - /// socket option should be set implicitly on all platforms, except on Windows where this is the default behavior - /// and SO_REUSEADDR performs something different entirely. - /// - /// Unlike in POSIX, in WASI the bind operation is async. This enables - /// interactive WASI hosts to inject permission prompts. Runtimes that - /// don't want to make use of this ability can simply call the native - /// `bind` as part of either `start-bind` or `finish-bind`. - /// - /// # References - /// - - /// - - /// - - /// - - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - finish-bind: func() -> result<_, error-code>; - - /// Connect to a remote endpoint. - /// - /// On success: - /// - the socket is transitioned into the `connection` state. - /// - a pair of streams is returned that can be used to read & write to the connection - /// - /// After a failed connection attempt, the socket will be in the `closed` - /// state and the only valid action left is to `drop` the socket. A single - /// socket can not be used to connect more than once. - /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) - /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) - /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. (EINVAL, EADDRNOTAVAIL on Illumos) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) - /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. - /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN) - /// - `invalid-state`: The socket is already in the `listening` state. (EOPNOTSUPP, EINVAL on Windows) - /// - `timeout`: Connection timed out. (ETIMEDOUT) - /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) - /// - `connection-reset`: The connection was reset. (ECONNRESET) - /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) - /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `not-in-progress`: A connect operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # Implementors note - /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. - /// Because all WASI sockets are non-blocking this is expected to return - /// EINPROGRESS, which should be translated to `ok()` in WASI. - /// - /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` - /// with a timeout of 0 on the socket descriptor. Followed by a check for - /// the `SO_ERROR` socket option, in case the poll signaled readiness. - /// - /// # References - /// - - /// - - /// - - /// - - start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; - finish-connect: func() -> result, error-code>; - - /// Start listening for new connections. - /// - /// Transitions the socket into the `listening` state. - /// - /// Unlike POSIX, the socket must already be explicitly bound. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) - /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN, EINVAL on BSD) - /// - `invalid-state`: The socket is already in the `listening` state. - /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) - /// - `not-in-progress`: A listen operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # Implementors note - /// Unlike in POSIX, in WASI the listen operation is async. This enables - /// interactive WASI hosts to inject permission prompts. Runtimes that - /// don't want to make use of this ability can simply call the native - /// `listen` as part of either `start-listen` or `finish-listen`. - /// - /// # References - /// - - /// - - /// - - /// - - start-listen: func() -> result<_, error-code>; - finish-listen: func() -> result<_, error-code>; - - /// Accept a new client socket. - /// - /// The returned socket is bound and in the `connected` state. The following properties are inherited from the listener socket: - /// - `address-family` - /// - `keep-alive-enabled` - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// - `hop-limit` - /// - `receive-buffer-size` - /// - `send-buffer-size` - /// - /// On success, this function returns the newly accepted client socket along with - /// a pair of streams that can be used to read & write to the connection. - /// - /// # Typical errors - /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) - /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) - /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) - /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) - /// - /// # References - /// - - /// - - /// - - /// - - accept: func() -> result, error-code>; - - /// Get the bound local address. - /// - /// POSIX mentions: - /// > If the socket has not been bound to a local name, the value - /// > stored in the object pointed to by `address` is unspecified. - /// - /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. - /// - /// # References - /// - - /// - - /// - - /// - - local-address: func() -> result; - - /// Get the remote address. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - - /// Whether the socket is in the `listening` state. - /// - /// Equivalent to the SO_ACCEPTCONN socket option. - is-listening: func() -> bool; - - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - address-family: func() -> ip-address-family; - - /// Hints the desired listen queue size. Implementations are free to ignore this. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// - /// # Typical errors - /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. - /// - `invalid-argument`: (set) The provided value was 0. - /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` state. - set-listen-backlog-size: func(value: u64) -> result<_, error-code>; - - /// Enables or disables keepalive. - /// - /// The keepalive behavior can be adjusted using: - /// - `keep-alive-idle-time` - /// - `keep-alive-interval` - /// - `keep-alive-count` - /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. - /// - /// Equivalent to the SO_KEEPALIVE socket option. - keep-alive-enabled: func() -> result; - set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; - - /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-idle-time: func() -> result; - set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; - - /// The time between keepalive packets. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the TCP_KEEPINTVL socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-interval: func() -> result; - set-keep-alive-interval: func(value: duration) -> result<_, error-code>; - - /// The maximum amount of keepalive packets TCP should send before aborting the connection. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the TCP_KEEPCNT socket option. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - keep-alive-count: func() -> result; - set-keep-alive-count: func(value: u32) -> result<_, error-code>; - - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - hop-limit: func() -> result; - set-hop-limit: func(value: u8) -> result<_, error-code>; - - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - receive-buffer-size: func() -> result; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - send-buffer-size: func() -> result; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; - - /// Create a `pollable` which can be used to poll for, or block on, - /// completion of any of the asynchronous operations of this socket. - /// - /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` - /// return `error(would-block)`, this pollable can be used to wait for - /// their success or failure, after which the method can be retried. - /// - /// The pollable is not limited to the async operation that happens to be - /// in progress at the time of calling `subscribe` (if any). Theoretically, - /// `subscribe` only has to be called once per socket and can then be - /// (re)used for the remainder of the socket's lifetime. - /// - /// See - /// for a more information. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - - /// Initiate a graceful shutdown. - /// - /// - `receive`: The socket is not expecting to receive any data from - /// the peer. The `input-stream` associated with this socket will be - /// closed. Any data still in the receive queue at time of calling - /// this method will be discarded. - /// - `send`: The socket has no more data to send to the peer. The `output-stream` - /// associated with this socket will be closed and a FIN packet will be sent. - /// - `both`: Same effect as `receive` & `send` combined. - /// - /// This function is idempotent. Shutting a down a direction more than once - /// has no effect and returns `ok`. - /// - /// The shutdown function does not close (drop) the socket. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; - } -} diff --git a/x/wasihttp/wit/deps/sockets/udp-create-socket.wit b/x/wasihttp/wit/deps/sockets/udp-create-socket.wit deleted file mode 100644 index 0482d1fe..00000000 --- a/x/wasihttp/wit/deps/sockets/udp-create-socket.wit +++ /dev/null @@ -1,27 +0,0 @@ - -interface udp-create-socket { - use network.{network, error-code, ip-address-family}; - use udp.{udp-socket}; - - /// Create a new UDP socket. - /// - /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. - /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. - /// - /// This function does not require a network capability handle. This is considered to be safe because - /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, - /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. - /// - /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. - /// - /// # Typical errors - /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) - /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) - /// - /// # References: - /// - - /// - - /// - - /// - - create-udp-socket: func(address-family: ip-address-family) -> result; -} diff --git a/x/wasihttp/wit/deps/sockets/udp.wit b/x/wasihttp/wit/deps/sockets/udp.wit deleted file mode 100644 index d987a0a9..00000000 --- a/x/wasihttp/wit/deps/sockets/udp.wit +++ /dev/null @@ -1,266 +0,0 @@ - -interface udp { - use wasi:io/poll@0.2.0.{pollable}; - use network.{network, error-code, ip-socket-address, ip-address-family}; - - /// A received datagram. - record incoming-datagram { - /// The payload. - /// - /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. - data: list, - - /// The source address. - /// - /// This field is guaranteed to match the remote address the stream was initialized with, if any. - /// - /// Equivalent to the `src_addr` out parameter of `recvfrom`. - remote-address: ip-socket-address, - } - - /// A datagram to be sent out. - record outgoing-datagram { - /// The payload. - data: list, - - /// The destination address. - /// - /// The requirements on this field depend on how the stream was initialized: - /// - with a remote address: this field must be None or match the stream's remote address exactly. - /// - without a remote address: this field is required. - /// - /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. - remote-address: option, - } - - - - /// A UDP socket handle. - resource udp-socket { - /// Bind the socket to a specific network on the provided IP address and port. - /// - /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which - /// network interface(s) to bind to. - /// If the port is zero, the socket will be bound to a random free port. - /// - /// # Typical errors - /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) - /// - `invalid-state`: The socket is already bound. (EINVAL) - /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) - /// - `address-in-use`: Address is already in use. (EADDRINUSE) - /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) - /// - `not-in-progress`: A `bind` operation is not in progress. - /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) - /// - /// # Implementors note - /// Unlike in POSIX, in WASI the bind operation is async. This enables - /// interactive WASI hosts to inject permission prompts. Runtimes that - /// don't want to make use of this ability can simply call the native - /// `bind` as part of either `start-bind` or `finish-bind`. - /// - /// # References - /// - - /// - - /// - - /// - - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - finish-bind: func() -> result<_, error-code>; - - /// Set up inbound & outbound communication channels, optionally to a specific peer. - /// - /// This function only changes the local socket configuration and does not generate any network traffic. - /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, - /// based on the best network path to `remote-address`. - /// - /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: - /// - `send` can only be used to send to this destination. - /// - `receive` will only return datagrams sent from the provided `remote-address`. - /// - /// This method may be called multiple times on the same socket to change its association, but - /// only the most recently returned pair of streams will be operational. Implementations may trap if - /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. - /// - /// The POSIX equivalent in pseudo-code is: - /// ```text - /// if (was previously connected) { - /// connect(s, AF_UNSPEC) - /// } - /// if (remote_address is Some) { - /// connect(s, remote_address) - /// } - /// ``` - /// - /// Unlike in POSIX, the socket must already be explicitly bound. - /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-state`: The socket is not bound. - /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - /// # References - /// - - /// - - /// - - /// - - %stream: func(remote-address: option) -> result, error-code>; - - /// Get the current bound address. - /// - /// POSIX mentions: - /// > If the socket has not been bound to a local name, the value - /// > stored in the object pointed to by `address` is unspecified. - /// - /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not bound to any local address. - /// - /// # References - /// - - /// - - /// - - /// - - local-address: func() -> result; - - /// Get the address the socket is currently streaming to. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - remote-address: func() -> result; - - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - address-family: func() -> ip-address-family; - - /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The TTL value must be 1 or higher. - unicast-hop-limit: func() -> result; - set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; - - /// The kernel buffer space reserved for sends/receives on this socket. - /// - /// If the provided value is 0, an `invalid-argument` error is returned. - /// Any other value will never cause an error, but it might be silently clamped and/or rounded. - /// I.e. after setting a value, reading the same setting back may return a different value. - /// - /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. - /// - /// # Typical errors - /// - `invalid-argument`: (set) The provided value was 0. - receive-buffer-size: func() -> result; - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - send-buffer-size: func() -> result; - set-send-buffer-size: func(value: u64) -> result<_, error-code>; - - /// Create a `pollable` which will resolve once the socket is ready for I/O. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } - - resource incoming-datagram-stream { - /// Receive messages on the socket. - /// - /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. - /// The returned list may contain fewer elements than requested, but never more. - /// - /// This function returns successfully with an empty list when either: - /// - `max-results` is 0, or: - /// - `max-results` is greater than 0, but no results are immediately available. - /// This function never returns `error(would-block)`. - /// - /// # Typical errors - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - receive: func(max-results: u64) -> result, error-code>; - - /// Create a `pollable` which will resolve once the stream is ready to receive again. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } - - resource outgoing-datagram-stream { - /// Check readiness for sending. This function never blocks. - /// - /// Returns the number of datagrams permitted for the next call to `send`, - /// or an error. Calling `send` with more datagrams than this function has - /// permitted will trap. - /// - /// When this function returns ok(0), the `subscribe` pollable will - /// become ready when this function will report at least ok(1), or an - /// error. - /// - /// Never returns `would-block`. - check-send: func() -> result; - - /// Send messages on the socket. - /// - /// This function attempts to send all provided `datagrams` on the socket without blocking and - /// returns how many messages were actually sent (or queued for sending). This function never - /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. - /// - /// This function semantically behaves the same as iterating the `datagrams` list and sequentially - /// sending each individual datagram until either the end of the list has been reached or the first error occurred. - /// If at least one datagram has been sent successfully, this function never returns an error. - /// - /// If the input list is empty, the function returns `ok(0)`. - /// - /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if - /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. - /// - /// # Typical errors - /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) - /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) - /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) - /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) - /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) - /// - `connection-refused`: The connection was refused. (ECONNREFUSED) - /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) - /// - /// # References - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - send: func(datagrams: list) -> result; - - /// Create a `pollable` which will resolve once the stream is ready to send again. - /// - /// Note: this function is here for WASI Preview2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - subscribe: func() -> pollable; - } -} diff --git a/x/wasihttp/wit/deps/sockets/world.wit b/x/wasihttp/wit/deps/sockets/world.wit deleted file mode 100644 index f8bb92ae..00000000 --- a/x/wasihttp/wit/deps/sockets/world.wit +++ /dev/null @@ -1,11 +0,0 @@ -package wasi:sockets@0.2.0; - -world imports { - import instance-network; - import network; - import udp; - import udp-create-socket; - import tcp; - import tcp-create-socket; - import ip-name-lookup; -} diff --git a/x/wasihttp/wit/proxy.wit b/x/wasihttp/wit/proxy.wit index a2ed0bf5..f20b1f66 100644 --- a/x/wasihttp/wit/proxy.wit +++ b/x/wasihttp/wit/proxy.wit @@ -1,8 +1,13 @@ package go:http@0.2.0; -/// The `go:http/proxy` world implements a strict superset of `wasi:http/proxy`. +/// The `go:http/proxy` world implements a subset of `wasi:http/proxy`. world proxy { - include wasi:http/proxy@0.2.0; - include wasi:cli/command@0.2.0; -} + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:http/types@0.2.0; + import wasi:http/outgoing-handler@0.2.0; + export wasi:http/incoming-handler@0.2.0; +} From 5f3f040060cea3caa4caa488714706109efdfa5a Mon Sep 17 00:00:00 2001 From: Jiaxiao Zhou Date: Wed, 19 Mar 2025 21:35:52 -0700 Subject: [PATCH 4/7] x/wasihttp/examples: add proxy and roundtrip WIT packages to examples and update the examples docs to refer to the right working directory and command to build. Signed-off-by: Jiaxiao Zhou --- x/wasihttp/examples/basic/basic.go | 3 +- x/wasihttp/examples/counter/counter.go | 3 +- x/wasihttp/examples/proxy.wit | 1631 +++++++++++ x/wasihttp/examples/proxy/proxy.go | 3 +- x/wasihttp/examples/roundtrip.wit | 2578 +++++++++++++++++ x/wasihttp/examples/roundtrip/roundtrip.go | 3 +- x/wasihttp/examples/wasip2-http.json | 6 + .../{ => examples}/wasip2-roundtrip.json | 4 +- 8 files changed, 4225 insertions(+), 6 deletions(-) create mode 100644 x/wasihttp/examples/proxy.wit create mode 100644 x/wasihttp/examples/roundtrip.wit create mode 100644 x/wasihttp/examples/wasip2-http.json rename x/wasihttp/{ => examples}/wasip2-roundtrip.json (58%) diff --git a/x/wasihttp/examples/basic/basic.go b/x/wasihttp/examples/basic/basic.go index 9d2da026..3f178052 100644 --- a/x/wasihttp/examples/basic/basic.go +++ b/x/wasihttp/examples/basic/basic.go @@ -1,6 +1,7 @@ // This example implements a basic web server. // -// To run: `tinygo run -target=wasip2-http.json ./examples/basic` +// working direcotry: "./x/wasihttp/examples" +// To run: `tinygo run -target=wasip2-http.json ./basic` // Test /: `curl -v 'http://0.0.0.0:8080/'` // Test /error: `curl -v 'http://0.0.0.0:8080/error'` diff --git a/x/wasihttp/examples/counter/counter.go b/x/wasihttp/examples/counter/counter.go index af3f2609..80815f5f 100644 --- a/x/wasihttp/examples/counter/counter.go +++ b/x/wasihttp/examples/counter/counter.go @@ -1,7 +1,8 @@ // This example implements a web server with a counter running in a goroutine. // This demonstrates instance reuse by the host. // -// To run: `tinygo run -target=wasip2-http.json ./examples/counter` +// working directory: "./x/wasihttp/examples" +// To run: `tinygo run -target=wasip2-http.json ./counter` // Test /: `curl -v 'http://0.0.0.0:8080/'` package main diff --git a/x/wasihttp/examples/proxy.wit b/x/wasihttp/examples/proxy.wit new file mode 100644 index 00000000..c2a1079c --- /dev/null +++ b/x/wasihttp/examples/proxy.wit @@ -0,0 +1,1631 @@ +package go:http@0.2.0; + +/// The `go:http/proxy` world implements a strict superset of `wasi:http/proxy`. +world proxy { + import wasi:cli/environment@0.2.0; + import wasi:random/random@0.2.0; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:cli/stdout@0.2.0; + import wasi:cli/stderr@0.2.0; + import wasi:cli/stdin@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:http/types@0.2.0; + import wasi:http/outgoing-handler@0.2.0; + import wasi:clocks/wall-clock@0.2.0; + import wasi:filesystem/types@0.2.0; + import wasi:filesystem/preopens@0.2.0; + export wasi:http/incoming-handler@0.2.0; +} + +package wasi:cli@0.2.0 { + interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + initial-cwd: func() -> option; + } + + interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + get-stdin: func() -> input-stream; + } + + interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + get-stdout: func() -> output-stream; + } + + interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + get-stderr: func() -> output-stream; + } +} + +package wasi:filesystem@0.2.0 { + /// WASI filesystem is a filesystem API primarily intended to let users run WASI + /// programs that access their files on their existing filesystems, without + /// significant overhead. + /// + /// It is intended to be roughly portable between Unix-family platforms and + /// Windows, though it does not hide many of the major differences. + /// + /// Paths are passed as interface-type `string`s, meaning they must consist of + /// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain + /// paths which are not accessible by this API. + /// + /// The directory separator in WASI is always the forward-slash (`/`). + /// + /// All paths in WASI are relative paths, and are interpreted relative to a + /// `descriptor` referring to a base directory. If a `path` argument to any WASI + /// function starts with `/`, or if any step of resolving a `path`, including + /// `..` and symbolic link steps, reaches a directory outside of the base + /// directory, or reaches a symlink to an absolute or rooted path in the + /// underlying filesystem, the function fails with `error-code::not-permitted`. + /// + /// For more information about WASI path resolution and sandboxing, see + /// [WASI filesystem path resolution]. + /// + /// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md + interface types { + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/streams@0.2.0.{error}; + use wasi:clocks/wall-clock@0.2.0.{datetime}; + + /// File size or length of a region within a file. + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrety + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// Flags determining the method of how paths are resolved. + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + type link-count = u64; + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// When setting a timestamp, this gives the value to set it to. + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` + /// in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device + } + + /// File or memory access pattern advisory information. + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + resource descriptor { + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + append-via-stream: func() -> result; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func(path: string) -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-type: func() -> result; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + is-same-object: func(other: borrow) -> bool; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encourated to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + metadata-hash-at: func(path-flags: path-flags, path: string) -> result; + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + read: func(length: filesize, offset: filesize) -> result, bool>, error-code>; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + read-directory: func() -> result; + + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + read-via-stream: func(offset: filesize) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func(path: string) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func(path: string) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + stat-at: func(path-flags: path-flags, path: string) -> result; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func(old-path: string, new-path: string) -> result<_, error-code>; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + sync-data: func() -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func(path: string) -> result<_, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + write: func(buffer: list, offset: filesize) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + write-via-stream: func(offset: filesize) -> result; + } + + /// A stream of directory entries. + resource directory-entry-stream { + + /// Read a single directory entry from a `directory-entry-stream`. + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + filesystem-error-code: func(err: borrow) -> option; + } + + interface preopens { + use types.{descriptor}; + + /// Return the set of preopened directories, and their path. + get-directories: func() -> list>; + } +} + +package wasi:http@0.2.0 { + /// This interface defines all of the types and methods for implementing + /// HTTP Requests and Responses, both incoming and outgoing, as well as + /// their headers, trailers, and bodies. + interface types { + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use wasi:io/streams@0.2.0.{input-stream}; + use wasi:io/streams@0.2.0.{output-stream}; + use wasi:io/error@0.2.0.{error as io-error}; + use wasi:io/poll@0.2.0.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string), + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { HTTP, HTTPS, other(string) } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option, + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option, + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option, + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option), + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + + /// Make a deep copy of the Fields. Equivelant in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + delete: func(name: field-key) -> result<_, header-error>; + + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields`, an empty list is returned. However, if the key is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + get: func(name: field-key) -> list; + + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + set: func(name: field-key, value: list) -> result<_, header-error>; + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all keys + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + from-list: static func(entries: list>) -> result; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + + /// Returns the authority from the request, if it was present. + authority: func() -> option; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + + /// Returns the method of the incoming request. + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + scheme: func() -> option; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor(headers: headers); + + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Get the Method for the Request. + method: func() -> method; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func(param: response-outparam, response: result); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + + /// Returns the status code from the incoming response. + status: func() -> status-code; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventaully return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + + /// Returns the contents of the trailers, or an error which occured, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occured receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occured. The implementation should propogate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func(this: outgoing-body, trailers: option) -> result<_, error-code>; + } + + /// Represents a future which may eventaully return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have recieved successfully, or that an error + /// occured. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; + } + + /// This interface defines a handler of incoming HTTP Requests. It should + /// be exported by components which can respond to HTTP Requests. + interface incoming-handler { + use types.{incoming-request}; + use types.{response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func(request: incoming-request, response-out: response-outparam); + } + + /// This interface defines a handler of outgoing HTTP Requests. It should be + /// imported by components which wish to make HTTP Requests. + interface outgoing-handler { + use types.{outgoing-request}; + use types.{request-options}; + use types.{future-incoming-response}; + use types.{error-code}; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func(request: outgoing-request, options: option) -> result; + } +} + +package wasi:clocks@0.2.0 { + /// WASI Monotonic Clock is a clock API intended to let users measure elapsed + /// time. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A monotonic clock is a clock which has an unspecified initial value, and + /// successive reads of the clock will produce non-decreasing values. + /// + /// It is intended for measuring elapsed time. + interface monotonic-clock { + use wasi:io/poll@0.2.0.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; + + /// A duration of time, in nanoseconds. + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func(when: instant) -> pollable; + + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func(when: duration) -> pollable; + } + + /// WASI Wall Clock is a clock API intended to let users query the current + /// time. The name "wall" makes an analogy to a "clock on the wall", which + /// is not necessarily monotonic as it may be reset. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A wall clock is a clock which measures the date and time according to + /// some external reference. + /// + /// External references may be reset, so this clock is not necessarily + /// monotonic, making it unsuitable for measuring elapsed time. + /// + /// It is intended for reporting the current date and time for humans. + interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; + } +} + +package wasi:io@0.2.0 { + interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } + } + + /// A poll API intended to let users wait for I/O events on multiple handles + /// at once. + interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; + } + + /// WASI I/O is an I/O abstraction API which is currently focused on providing + /// stream types. + /// + /// In the future, the component model is expected to add built-in stream types; + /// when it does, they are expected to subsume this API. + interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed, + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func(len: u64) -> result; + + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func(len: u64) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func(len: u64) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + } + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func(src: borrow, len: u64) -> result; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; + + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + check-write: func() -> result; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func(src: borrow, len: u64) -> result; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func(contents: list) -> result<_, stream-error>; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func(len: u64) -> result<_, stream-error>; + } + } +} + +package wasi:random@0.2.0 { + /// WASI Random is a random data API. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; + } +} diff --git a/x/wasihttp/examples/proxy/proxy.go b/x/wasihttp/examples/proxy/proxy.go index 69961e31..b5d7249c 100644 --- a/x/wasihttp/examples/proxy/proxy.go +++ b/x/wasihttp/examples/proxy/proxy.go @@ -1,6 +1,7 @@ // This example implements a reverse proxy that sends requests to postman-echo.com. // -// To run: `tinygo run -target=wasip2-http.json ./examples/proxy` +// working directory: "./x/wasihttp/examples" +// To run: `tinygo run -target=wasip2-http.json ./proxy` // Test GET: `curl -v 'http://0.0.0.0:8080/get'` // Test POST: `curl -v -d hello 'http://0.0.0.0:8080/post'` diff --git a/x/wasihttp/examples/roundtrip.wit b/x/wasihttp/examples/roundtrip.wit new file mode 100644 index 00000000..f2eb7641 --- /dev/null +++ b/x/wasihttp/examples/roundtrip.wit @@ -0,0 +1,2578 @@ +package go:http@0.2.0; + +/// The `go:http/roundtrip` world implements a strict superset of `wasi:http/proxy`. +world roundtrip { + import wasi:random/random@0.2.0; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:cli/stdout@0.2.0; + import wasi:cli/stderr@0.2.0; + import wasi:cli/stdin@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:http/types@0.2.0; + import wasi:http/outgoing-handler@0.2.0; + import wasi:clocks/wall-clock@0.2.0; + import wasi:cli/environment@0.2.0; + import wasi:cli/exit@0.2.0; + import wasi:cli/terminal-input@0.2.0; + import wasi:cli/terminal-output@0.2.0; + import wasi:cli/terminal-stdin@0.2.0; + import wasi:cli/terminal-stdout@0.2.0; + import wasi:cli/terminal-stderr@0.2.0; + import wasi:filesystem/types@0.2.0; + import wasi:filesystem/preopens@0.2.0; + import wasi:sockets/network@0.2.0; + import wasi:sockets/instance-network@0.2.0; + import wasi:sockets/udp@0.2.0; + import wasi:sockets/udp-create-socket@0.2.0; + import wasi:sockets/tcp@0.2.0; + import wasi:sockets/tcp-create-socket@0.2.0; + import wasi:sockets/ip-name-lookup@0.2.0; + import wasi:random/insecure@0.2.0; + import wasi:random/insecure-seed@0.2.0; + + export wasi:http/incoming-handler@0.2.0; + export wasi:cli/run@0.2.0; +} +package wasi:io@0.2.0 { + interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } + } + /// A poll API intended to let users wait for I/O events on multiple handles + /// at once. + interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; + } + /// WASI I/O is an I/O abstraction API which is currently focused on providing + /// stream types. + /// + /// In the future, the component model is expected to add built-in stream types; + /// when it does, they are expected to subsume this API. + interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed, + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func(len: u64) -> result, stream-error>; + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func(len: u64) -> result, stream-error>; + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func(len: u64) -> result; + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func(len: u64) -> result; + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + } + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + check-write: func() -> result; + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func(contents: list) -> result<_, stream-error>; + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func(len: u64) -> result<_, stream-error>; + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func(src: borrow, len: u64) -> result; + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func(src: borrow, len: u64) -> result; + } + } + world imports { + import error; + import poll; + import streams; + } +} + + +package wasi:clocks@0.2.0 { + /// WASI Monotonic Clock is a clock API intended to let users measure elapsed + /// time. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A monotonic clock is a clock which has an unspecified initial value, and + /// successive reads of the clock will produce non-decreasing values. + /// + /// It is intended for measuring elapsed time. + interface monotonic-clock { + use wasi:io/poll@0.2.0.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; + + /// A duration of time, in nanoseconds. + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func(when: instant) -> pollable; + + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func(when: duration) -> pollable; + } + /// WASI Wall Clock is a clock API intended to let users query the current + /// time. The name "wall" makes an analogy to a "clock on the wall", which + /// is not necessarily monotonic as it may be reset. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + /// + /// A wall clock is a clock which measures the date and time according to + /// some external reference. + /// + /// External references may be reset, so this clock is not necessarily + /// monotonic, making it unsuitable for measuring elapsed time. + /// + /// It is intended for reporting the current date and time for humans. + interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; + } + world imports { + import wasi:io/poll@0.2.0; + import monotonic-clock; + import wall-clock; + } +} + + +package wasi:random@0.2.0 { + /// The insecure-seed interface for seeding hash-map DoS resistance. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; + } + /// The insecure interface for insecure pseudo-random numbers. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; + } + /// WASI Random is a random data API. + /// + /// It is intended to be portable at least between Unix-family platforms and + /// Windows. + interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; + } + world imports { + import random; + import insecure; + import insecure-seed; + } +} + + +package wasi:filesystem@0.2.0 { + /// WASI filesystem is a filesystem API primarily intended to let users run WASI + /// programs that access their files on their existing filesystems, without + /// significant overhead. + /// + /// It is intended to be roughly portable between Unix-family platforms and + /// Windows, though it does not hide many of the major differences. + /// + /// Paths are passed as interface-type `string`s, meaning they must consist of + /// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain + /// paths which are not accessible by this API. + /// + /// The directory separator in WASI is always the forward-slash (`/`). + /// + /// All paths in WASI are relative paths, and are interpreted relative to a + /// `descriptor` referring to a base directory. If a `path` argument to any WASI + /// function starts with `/`, or if any step of resolving a `path`, including + /// `..` and symbolic link steps, reaches a directory outside of the base + /// directory, or reaches a symlink to an absolute or rooted path in the + /// underlying filesystem, the function fails with `error-code::not-permitted`. + /// + /// For more information about WASI path resolution and sandboxing, see + /// [WASI filesystem path resolution]. + /// + /// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md + interface types { + use wasi:io/streams@0.2.0.{input-stream, output-stream, error}; + use wasi:clocks/wall-clock@0.2.0.{datetime}; + + /// File size or length of a region within a file. + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrety + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// Flags determining the method of how paths are resolved. + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + type link-count = u64; + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// When setting a timestamp, this gives the value to set it to. + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device, + } + + /// File or memory access pattern advisory information. + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse, + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + resource descriptor { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + read-via-stream: func(offset: filesize) -> result; + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + write-via-stream: func(offset: filesize) -> result; + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + append-via-stream: func() -> result; + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + sync-data: func() -> result<_, error-code>; + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-flags: func() -> result; + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-type: func() -> result; + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> result<_, error-code>; + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + read: func(length: filesize, offset: filesize) -> result, bool>, error-code>; + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + write: func(buffer: list, offset: filesize) -> result; + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + read-directory: func() -> result; + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> result<_, error-code>; + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func(path: string) -> result<_, error-code>; + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat: func() -> result; + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + stat-at: func(path-flags: path-flags, path: string) -> result; + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func(path: string) -> result; + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func(path: string) -> result<_, error-code>; + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func(old-path: string, new-path: string) -> result<_, error-code>; + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func(path: string) -> result<_, error-code>; + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + is-same-object: func(other: borrow) -> bool; + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encourated to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + metadata-hash: func() -> result; + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + metadata-hash-at: func(path-flags: path-flags, path: string) -> result; + } + + /// A stream of directory entries. + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + filesystem-error-code: func(err: borrow) -> option; + } + interface preopens { + use types.{descriptor}; + + /// Return the set of preopened directories, and their path. + get-directories: func() -> list>; + } + world imports { + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:clocks/wall-clock@0.2.0; + import types; + import preopens; + } +} + + +package wasi:sockets@0.2.0 { + interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + enum error-code { + /// Unknown error + unknown, + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + /// The operation timed out before it could finish completely. + timeout, + /// This operation is incompatible with another asynchronous operation that is already in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + /// The operation is not valid in the socket's current state. + invalid-state, + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + /// A bind operation failed because the provided address is not an address that the `network` can bind to. + address-not-bindable, + /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. + address-in-use, + /// The remote address is not reachable + remote-unreachable, + /// The TCP connection was forcefully rejected + connection-refused, + /// The TCP connection was reset. + connection-reset, + /// A TCP connection was aborted. + connection-aborted, + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + /// A permanent failure in name resolution occurred. + permanent-resolver-failure, + } + + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + type ipv4-address = tuple; + + type ipv6-address = tuple; + + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + } + /// This interface provides a value-export of the default network handle.. + interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + } + interface ip-name-lookup { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network, error-code, ip-address}; + + resource resolve-address-stream { + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + } + interface tcp { + use wasi:io/streams@0.2.0.{input-stream, output-stream}; + use wasi:io/poll@0.2.0.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + /// Similar to `SHUT_WR` in POSIX. + send, + /// Similar to `SHUT_RDWR` in POSIX. + both, + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for a more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + resource tcp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connection` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; + finish-listen: func() -> result<_, error-code>; + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + hop-limit: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for a more information. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent. Shutting a down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } + } + interface tcp-create-socket { + use network.{network, error-code, ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; + } + interface udp { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + resource udp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, but + /// only the most recently returned pair of streams will be operational. Implementations may trap if + /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + %stream: func(remote-address: option) -> result, error-code>; + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource incoming-datagram-stream { + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource outgoing-datagram-stream { + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without blocking and + /// returns how many messages were actually sent (or queued for sending). This function never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list and sequentially + /// sending each individual datagram until either the end of the list has been reached or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + } + interface udp-create-socket { + use network.{network, error-code, ip-address-family}; + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + create-udp-socket: func(address-family: ip-address-family) -> result; + } + world imports { + import network; + import instance-network; + import wasi:io/poll@0.2.0; + import udp; + import udp-create-socket; + import wasi:io/error@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import tcp; + import tcp-create-socket; + import ip-name-lookup; + } +} + + +package wasi:cli@0.2.0 { + interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + initial-cwd: func() -> option; + } + interface exit { + /// Exit the current instance and any linked instances. + exit: func(status: result); + } + interface run { + /// Run the program. + run: func() -> result; + } + interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + + get-stdin: func() -> input-stream; + } + interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + + get-stdout: func() -> output-stream; + } + interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + + get-stderr: func() -> output-stream; + } + /// Terminal input. + /// + /// In the future, this may include functions for disabling echoing, + /// disabling input buffering so that keyboard events are sent through + /// immediately, querying supported features, and so on. + interface terminal-input { + /// The input side of a terminal. + resource terminal-input; + } + /// Terminal output. + /// + /// In the future, this may include functions for querying the terminal + /// size, being notified of terminal size changes, querying supported + /// features, and so on. + interface terminal-output { + /// The output side of a terminal. + resource terminal-output; + } + /// An interface providing an optional `terminal-input` for stdin as a + /// link-time authority. + interface terminal-stdin { + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + get-terminal-stdin: func() -> option; + } + /// An interface providing an optional `terminal-output` for stdout as a + /// link-time authority. + interface terminal-stdout { + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stdout: func() -> option; + } + /// An interface providing an optional `terminal-output` for stderr as a + /// link-time authority. + interface terminal-stderr { + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stderr: func() -> option; + } + world imports { + import environment; + import exit; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import stdin; + import stdout; + import stderr; + import terminal-input; + import terminal-output; + import terminal-stdin; + import terminal-stdout; + import terminal-stderr; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:clocks/wall-clock@0.2.0; + import wasi:filesystem/types@0.2.0; + import wasi:filesystem/preopens@0.2.0; + import wasi:sockets/network@0.2.0; + import wasi:sockets/instance-network@0.2.0; + import wasi:sockets/udp@0.2.0; + import wasi:sockets/udp-create-socket@0.2.0; + import wasi:sockets/tcp@0.2.0; + import wasi:sockets/tcp-create-socket@0.2.0; + import wasi:sockets/ip-name-lookup@0.2.0; + import wasi:random/random@0.2.0; + import wasi:random/insecure@0.2.0; + import wasi:random/insecure-seed@0.2.0; + } + world command { + import environment; + import exit; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import stdin; + import stdout; + import stderr; + import terminal-input; + import terminal-output; + import terminal-stdin; + import terminal-stdout; + import terminal-stderr; + import wasi:clocks/monotonic-clock@0.2.0; + import wasi:clocks/wall-clock@0.2.0; + import wasi:filesystem/types@0.2.0; + import wasi:filesystem/preopens@0.2.0; + import wasi:sockets/network@0.2.0; + import wasi:sockets/instance-network@0.2.0; + import wasi:sockets/udp@0.2.0; + import wasi:sockets/udp-create-socket@0.2.0; + import wasi:sockets/tcp@0.2.0; + import wasi:sockets/tcp-create-socket@0.2.0; + import wasi:sockets/ip-name-lookup@0.2.0; + import wasi:random/random@0.2.0; + import wasi:random/insecure@0.2.0; + import wasi:random/insecure-seed@0.2.0; + + export run; + } +} + + +package wasi:http@0.2.0 { + /// This interface defines all of the types and methods for implementing + /// HTTP Requests and Responses, both incoming and outgoing, as well as + /// their headers, trailers, and bodies. + interface types { + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use wasi:io/streams@0.2.0.{input-stream, output-stream}; + use wasi:io/error@0.2.0.{error as io-error}; + use wasi:io/poll@0.2.0.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string), + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { + HTTP, + HTTPS, + other(string), + } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option, + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option, + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option, + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option), + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all keys + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + from-list: static func(entries: list>) -> result; + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields`, an empty list is returned. However, if the key is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + get: func(name: field-key) -> list; + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + set: func(name: field-key, value: list) -> result<_, header-error>; + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + delete: func(name: field-key) -> result<_, header-error>; + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + /// Make a deep copy of the Fields. Equivelant in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + /// Returns the method of the incoming request. + method: func() -> method; + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + /// Returns the protocol scheme from the request. + scheme: func() -> option; + /// Returns the authority from the request, if it was present. + authority: func() -> option; + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor(headers: headers); + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + /// Get the Method for the Request. + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func(param: response-outparam, response: result); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + /// Returns the status code from the incoming response. + status: func() -> status-code; + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventaully return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + /// Returns the contents of the trailers, or an error which occured, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occured receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occured. The implementation should propogate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func(this: outgoing-body, trailers: option) -> result<_, error-code>; + } + + /// Represents a future which may eventaully return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have recieved successfully, or that an error + /// occured. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; + } + /// This interface defines a handler of incoming HTTP Requests. It should + /// be exported by components which can respond to HTTP Requests. + interface incoming-handler { + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func(request: incoming-request, response-out: response-outparam); + } + /// This interface defines a handler of outgoing HTTP Requests. It should be + /// imported by components which wish to make HTTP Requests. + interface outgoing-handler { + use types.{outgoing-request, request-options, future-incoming-response, error-code}; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func(request: outgoing-request, options: option) -> result; + } + /// The `wasi:http/proxy` world captures a widely-implementable intersection of + /// hosts that includes HTTP forward and reverse proxies. Components targeting + /// this world may concurrently stream in and out any number of incoming and + /// outgoing HTTP requests. + world proxy { + import wasi:random/random@0.2.0; + import wasi:io/error@0.2.0; + import wasi:io/poll@0.2.0; + import wasi:io/streams@0.2.0; + import wasi:cli/stdout@0.2.0; + import wasi:cli/stderr@0.2.0; + import wasi:cli/stdin@0.2.0; + import wasi:clocks/monotonic-clock@0.2.0; + import types; + import outgoing-handler; + import wasi:clocks/wall-clock@0.2.0; + + export incoming-handler; + } +} diff --git a/x/wasihttp/examples/roundtrip/roundtrip.go b/x/wasihttp/examples/roundtrip/roundtrip.go index c4aea66b..a3ff96dd 100644 --- a/x/wasihttp/examples/roundtrip/roundtrip.go +++ b/x/wasihttp/examples/roundtrip/roundtrip.go @@ -1,7 +1,8 @@ // This example is taken from https://github.com/dev-wasm/dev-wasm-go/blob/main/http/main.go // demonstrates how to use the wasihttp package to make HTTP requests using the `http.Client` interface. // -// To run: `tinygo build -target=wasip2-roundtrip.json -o roundtrip.wasm ./examples/roundtrip` +// working directory: "./x/wasihttp/examples" +// To run: `tinygo build -target=wasip2-roundtrip.json -o roundtrip.wasm ./roundtrip` // Test: `wasmtime run -Shttp -Sinherit-network -Sinherit-env roundtrip.wasm` package main diff --git a/x/wasihttp/examples/wasip2-http.json b/x/wasihttp/examples/wasip2-http.json new file mode 100644 index 00000000..0daad3aa --- /dev/null +++ b/x/wasihttp/examples/wasip2-http.json @@ -0,0 +1,6 @@ +{ + "inherits": ["wasip2"], + "wit-package": "./proxy.wit", + "wit-world": "go:http/proxy", + "emulator": "wasmtime serve -Scli --dir={tmpDir}::/tmp {}" +} diff --git a/x/wasihttp/wasip2-roundtrip.json b/x/wasihttp/examples/wasip2-roundtrip.json similarity index 58% rename from x/wasihttp/wasip2-roundtrip.json rename to x/wasihttp/examples/wasip2-roundtrip.json index 708a9f5d..d9fd4e9e 100644 --- a/x/wasihttp/wasip2-roundtrip.json +++ b/x/wasihttp/examples/wasip2-roundtrip.json @@ -1,6 +1,6 @@ { "inherits": ["wasip2"], - "wit-package": "./wit", - "wit-world": "go:http/proxy", + "wit-package": "./roundtrip.wit", + "wit-world": "go:http/roundtrip", "emulator": "wasmtime run -Shttp -Sinherit-network -Sinherit-env {}" } From 77d6ab4d8daee48f1624335f1b83ce761db242ac Mon Sep 17 00:00:00 2001 From: Jiaxiao Zhou Date: Wed, 19 Mar 2025 21:55:31 -0700 Subject: [PATCH 5/7] scripts: add test-wasihttp-basic and test-wasihttp-roundtrip Signed-off-by: Jiaxiao Zhou --- scripts/test-wasihttp-basic.sh | 25 ++++++++++++++++++++++ scripts/test-wasihttp-roundtrip.sh | 33 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100755 scripts/test-wasihttp-basic.sh create mode 100755 scripts/test-wasihttp-roundtrip.sh diff --git a/scripts/test-wasihttp-basic.sh b/scripts/test-wasihttp-basic.sh new file mode 100755 index 00000000..620ab6df --- /dev/null +++ b/scripts/test-wasihttp-basic.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -euo pipefail + +echo "Building basic example..." +cd ./x/wasihttp/examples +tinygo build -target=wasip2-http.json -o basic.wasm ./basic + +echo "Running basic example with wasmtime..." +wasmtime serve --addr 0.0.0.0:8088 -Scli basic.wasm & +SERVER_PID=$! + +echo "Testing / endpoint..." +ROOT_RESPONSE=$(curl -s 'http://0.0.0.0:8088/') +if [[ "$ROOT_RESPONSE" != "Hello world!"* ]]; then + echo "ERROR: Root endpoint test failed" + echo "Expected response containing 'Hello world!'" + echo "Actual response: $ROOT_RESPONSE" + kill $SERVER_PID 2>/dev/null + exit 1 +fi + +kill $SERVER_PID 2>/dev/null +rm basic.wasm + +echo "All basic tests passed!" diff --git a/scripts/test-wasihttp-roundtrip.sh b/scripts/test-wasihttp-roundtrip.sh new file mode 100755 index 00000000..381968dd --- /dev/null +++ b/scripts/test-wasihttp-roundtrip.sh @@ -0,0 +1,33 @@ +#!/bin/bash +set -euo pipefail + +echo "Building roundtrip example..." +cd ./x/wasihttp/examples +tinygo build -target=wasip2-roundtrip.json -o roundtrip.wasm ./roundtrip + +echo "Running roundtrip example..." +output=$(wasmtime run -Shttp -Sinherit-network -Sinherit-env roundtrip.wasm) + +# Verify GET request worked +if ! echo "$output" | grep -q "Status: 200" || ! echo "$output" | grep -q "https://postman-echo.com/get"; then + echo "ERROR: GET request verification failed" + echo "$output" + exit 1 +fi + +# Verify POST request worked +if ! echo "$output" | grep -q '"foo": "bar"'; then + echo "ERROR: POST request verification failed" + echo "$output" + exit 1 +fi + +# Verify PUT request worked +if ! echo "$output" | grep -q '"baz": "blah"'; then + echo "ERROR: PUT request verification failed" + echo "$output" + exit 1 +fi + +rm roundtrip.wasm +echo "All roundtrip tests passed!" From 555aa4a12fe5a71faf757e981696083fbd5cefdb Mon Sep 17 00:00:00 2001 From: Jiaxiao Zhou Date: Wed, 19 Mar 2025 21:55:46 -0700 Subject: [PATCH 6/7] ci: add GitHub Actions workflow for testing wasihttp Signed-off-by: Jiaxiao Zhou --- .github/workflows/test.yaml | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 50ef903c..49d939d4 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -175,3 +175,48 @@ jobs: - name: Verify repo is unchanged run: git diff --exit-code HEAD + + test-wasihttp: + name: Test wasihttp + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + matrix: + go-version: ["1.23", "1.24"] + tinygo-version: ["0.34.0", "0.35.0", "0.36.0"] + exclude: + - go-version: "1.24" + tinygo-version: "0.34.0" + - go-version: "1.24" + tinygo-version: "0.35.0" + steps: + - name: Checkout repo + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go-version }} + + - name: Set up TinyGo + uses: acifani/setup-tinygo@v2 + with: + tinygo-version: ${{ matrix.tinygo-version }} + + - name: Set up wasm-tools + uses: bytecodealliance/actions/wasm-tools/setup@v1 + with: + version: ${{ env.wasm-tools-version }} + + - name: Set up Wasmtime + uses: bytecodealliance/actions/wasmtime/setup@v1 + with: + version: ${{ env.wasmtime-version }} + + - name: Test wasihttp basic + run: ./scripts/test-wasihttp-basic.sh + + - name: Test wasihttp roundtrip + run: ./scripts/test-wasihttp-roundtrip.sh From ffdeed271325b31beb3f539af8f6b78d36bb1eeb Mon Sep 17 00:00:00 2001 From: Jiaxiao Zhou Date: Thu, 20 Mar 2025 13:39:14 -0700 Subject: [PATCH 7/7] scripts: add sleep before testing server Signed-off-by: Jiaxiao Zhou --- scripts/test-wasihttp-basic.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/test-wasihttp-basic.sh b/scripts/test-wasihttp-basic.sh index 620ab6df..1a82573e 100755 --- a/scripts/test-wasihttp-basic.sh +++ b/scripts/test-wasihttp-basic.sh @@ -9,6 +9,8 @@ echo "Running basic example with wasmtime..." wasmtime serve --addr 0.0.0.0:8088 -Scli basic.wasm & SERVER_PID=$! +sleep 10 + echo "Testing / endpoint..." ROOT_RESPONSE=$(curl -s 'http://0.0.0.0:8088/') if [[ "$ROOT_RESPONSE" != "Hello world!"* ]]; then