From d91a9d0decf5c17ccd9ce5a991a1c271bd32d05f Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 15 Sep 2025 17:02:20 -0400 Subject: [PATCH 01/50] This builds a wasm component. `cargo build --target wasm32-wasip2` --- .gitignore | 1 + Cargo.lock | 433 ++++ Cargo.toml | 10 + src/lib.rs | 5 + wit/deps/cli/command.wit | 10 + wit/deps/cli/environment.wit | 22 + wit/deps/cli/exit.wit | 17 + wit/deps/cli/imports.wit | 36 + wit/deps/cli/run.wit | 6 + wit/deps/cli/stdio.wit | 26 + wit/deps/cli/terminal.wit | 62 + wit/deps/clocks/monotonic-clock.wit | 50 + wit/deps/clocks/timezone.wit | 55 + wit/deps/clocks/wall-clock.wit | 46 + wit/deps/clocks/world.wit | 11 + wit/deps/fastly-adapter/adapter.wit | 112 + wit/deps/fastly/compute.wit | 2857 ++++++++++++++++++++++++ wit/deps/filesystem/preopens.wit | 11 + wit/deps/filesystem/types.wit | 676 ++++++ wit/deps/filesystem/world.wit | 9 + wit/deps/http/handler.wit | 49 + wit/deps/http/proxy.wit | 50 + wit/deps/http/types.wit | 688 ++++++ wit/deps/io/error.wit | 34 + wit/deps/io/poll.wit | 47 + wit/deps/io/streams.wit | 290 +++ wit/deps/io/world.wit | 10 + wit/deps/random/insecure-seed.wit | 27 + wit/deps/random/insecure.wit | 25 + wit/deps/random/random.wit | 29 + wit/deps/random/world.wit | 13 + wit/deps/sockets/instance-network.wit | 11 + wit/deps/sockets/ip-name-lookup.wit | 56 + wit/deps/sockets/network.wit | 169 ++ wit/deps/sockets/tcp-create-socket.wit | 30 + wit/deps/sockets/tcp.wit | 387 ++++ wit/deps/sockets/udp-create-socket.wit | 30 + wit/deps/sockets/udp.wit | 288 +++ wit/deps/sockets/world.wit | 19 + wit/virt.wit | 6 + 40 files changed, 6713 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/lib.rs create mode 100644 wit/deps/cli/command.wit create mode 100644 wit/deps/cli/environment.wit create mode 100644 wit/deps/cli/exit.wit create mode 100644 wit/deps/cli/imports.wit create mode 100644 wit/deps/cli/run.wit create mode 100644 wit/deps/cli/stdio.wit create mode 100644 wit/deps/cli/terminal.wit create mode 100644 wit/deps/clocks/monotonic-clock.wit create mode 100644 wit/deps/clocks/timezone.wit create mode 100644 wit/deps/clocks/wall-clock.wit create mode 100644 wit/deps/clocks/world.wit create mode 100644 wit/deps/fastly-adapter/adapter.wit create mode 100644 wit/deps/fastly/compute.wit create mode 100644 wit/deps/filesystem/preopens.wit create mode 100644 wit/deps/filesystem/types.wit create mode 100644 wit/deps/filesystem/world.wit create mode 100644 wit/deps/http/handler.wit create mode 100644 wit/deps/http/proxy.wit create mode 100644 wit/deps/http/types.wit create mode 100644 wit/deps/io/error.wit create mode 100644 wit/deps/io/poll.wit create mode 100644 wit/deps/io/streams.wit create mode 100644 wit/deps/io/world.wit create mode 100644 wit/deps/random/insecure-seed.wit create mode 100644 wit/deps/random/insecure.wit create mode 100644 wit/deps/random/random.wit create mode 100644 wit/deps/random/world.wit create mode 100644 wit/deps/sockets/instance-network.wit create mode 100644 wit/deps/sockets/ip-name-lookup.wit create mode 100644 wit/deps/sockets/network.wit create mode 100644 wit/deps/sockets/tcp-create-socket.wit create mode 100644 wit/deps/sockets/tcp.wit create mode 100644 wit/deps/sockets/udp-create-socket.wit create mode 100644 wit/deps/sockets/udp.wit create mode 100644 wit/deps/sockets/world.wit create mode 100644 wit/virt.wit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..17fe714 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,433 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100" + +[[package]] +name = "bitflags" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005" + +[[package]] +name = "indexmap" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "206a8042aec68fa4a62e8d3f7aa4ceb508177d9324faf261e1959e495b7a1921" +dependencies = [ + "equivalent", + "hashbrown", + "serde", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" + +[[package]] +name = "memchr" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "python-virt" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.224" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aaeb1e94f53b16384af593c71e20b095e958dab1d26939c1b70645c5cfbcc0b" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.224" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f39390fa6346e24defbcdd3d9544ba8a19985d0af74df8501fbfe9a64341ab" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.224" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ff78ab5e8561c9a675bfc1785cb07ae721f0ee53329a595cefd8c04c2ac4e0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "wasm-encoder" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be00faa2b4950c76fe618c409d2c3ea5a3c9422013e079482d78544bb2d184c" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20b3ec880a9ac69ccd92fbdbcf46ee833071cf09f82bb005b2327c7ae6025ae2" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9d90bb93e764f6beabf1d02028c70a2156a6583e63ac4218dd07ef733368b0" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +dependencies = [ + "bitflags", + "futures", + "once_cell", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabd629f94da277abc739c71353397046401518efb2c707669f805205f0b9890" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a4232e841089fa5f3c4fc732a92e1c74e1a3958db3b12f1de5934da2027f1f4" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0d4698c2913d8d9c2b220d116409c3f51a7aa8d7765151b886918367179ee9" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a866b19dba2c94d706ec58c92a4c62ab63e482b4c935d2a085ac94caecb136" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55c92c939d667b7bf0c6bf2d1f67196529758f99a2a45a3355cc56964fd5315d" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..159b0d5 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "python-virt" +version = "0.1.0" +edition = "2024" + +[dependencies] +wit-bindgen = "0.46.0" + +[lib] +crate-type = ["cdylib"] diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..9fe6f31 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,5 @@ +wit_bindgen::generate!({ + world: "python-virt", + path: "wit", + generate_all, +}); diff --git a/wit/deps/cli/command.wit b/wit/deps/cli/command.wit new file mode 100644 index 0000000..6d3cc83 --- /dev/null +++ b/wit/deps/cli/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.2.6; + +@since(version = 0.2.0) +world command { + @since(version = 0.2.0) + include imports; + + @since(version = 0.2.0) + export run; +} diff --git a/wit/deps/cli/environment.wit b/wit/deps/cli/environment.wit new file mode 100644 index 0000000..2f449bd --- /dev/null +++ b/wit/deps/cli/environment.wit @@ -0,0 +1,22 @@ +@since(version = 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. + @since(version = 0.2.0) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.2.0) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.2.0) + initial-cwd: func() -> option; +} diff --git a/wit/deps/cli/exit.wit b/wit/deps/cli/exit.wit new file mode 100644 index 0000000..427935c --- /dev/null +++ b/wit/deps/cli/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.2.0) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.2.0) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/wit/deps/cli/imports.wit b/wit/deps/cli/imports.wit new file mode 100644 index 0000000..d9fd017 --- /dev/null +++ b/wit/deps/cli/imports.wit @@ -0,0 +1,36 @@ +package wasi:cli@0.2.6; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + include wasi:clocks/imports@0.2.6; + @since(version = 0.2.0) + include wasi:filesystem/imports@0.2.6; + @since(version = 0.2.0) + include wasi:sockets/imports@0.2.6; + @since(version = 0.2.0) + include wasi:random/imports@0.2.6; + @since(version = 0.2.0) + include wasi:io/imports@0.2.6; + + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import stdin; + @since(version = 0.2.0) + import stdout; + @since(version = 0.2.0) + import stderr; + @since(version = 0.2.0) + import terminal-input; + @since(version = 0.2.0) + import terminal-output; + @since(version = 0.2.0) + import terminal-stdin; + @since(version = 0.2.0) + import terminal-stdout; + @since(version = 0.2.0) + import terminal-stderr; +} diff --git a/wit/deps/cli/run.wit b/wit/deps/cli/run.wit new file mode 100644 index 0000000..655346e --- /dev/null +++ b/wit/deps/cli/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.2.0) +interface run { + /// Run the program. + @since(version = 0.2.0) + run: func() -> result; +} diff --git a/wit/deps/cli/stdio.wit b/wit/deps/cli/stdio.wit new file mode 100644 index 0000000..cb8aea2 --- /dev/null +++ b/wit/deps/cli/stdio.wit @@ -0,0 +1,26 @@ +@since(version = 0.2.0) +interface stdin { + @since(version = 0.2.0) + use wasi:io/streams@0.2.6.{input-stream}; + + @since(version = 0.2.0) + get-stdin: func() -> input-stream; +} + +@since(version = 0.2.0) +interface stdout { + @since(version = 0.2.0) + use wasi:io/streams@0.2.6.{output-stream}; + + @since(version = 0.2.0) + get-stdout: func() -> output-stream; +} + +@since(version = 0.2.0) +interface stderr { + @since(version = 0.2.0) + use wasi:io/streams@0.2.6.{output-stream}; + + @since(version = 0.2.0) + get-stderr: func() -> output-stream; +} diff --git a/wit/deps/cli/terminal.wit b/wit/deps/cli/terminal.wit new file mode 100644 index 0000000..d305498 --- /dev/null +++ b/wit/deps/cli/terminal.wit @@ -0,0 +1,62 @@ +/// 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. +@since(version = 0.2.0) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.2.0) + 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. +@since(version = 0.2.0) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.2.0) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdin { + @since(version = 0.2.0) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdout { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stderr { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stderr: func() -> option; +} diff --git a/wit/deps/clocks/monotonic-clock.wit b/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 0000000..f3bc839 --- /dev/null +++ b/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,50 @@ +package wasi:clocks@0.2.6; +/// 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. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.6.{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. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/wit/deps/clocks/timezone.wit b/wit/deps/clocks/timezone.wit new file mode 100644 index 0000000..ca98ad1 --- /dev/null +++ b/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.6; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/wit/deps/clocks/wall-clock.wit b/wit/deps/clocks/wall-clock.wit new file mode 100644 index 0000000..76636a0 --- /dev/null +++ b/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.6; +/// 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. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + 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 + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/wit/deps/clocks/world.wit b/wit/deps/clocks/world.wit new file mode 100644 index 0000000..5c53c51 --- /dev/null +++ b/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.6; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/wit/deps/fastly-adapter/adapter.wit b/wit/deps/fastly-adapter/adapter.wit new file mode 100644 index 0000000..fedb9d4 --- /dev/null +++ b/wit/deps/fastly-adapter/adapter.wit @@ -0,0 +1,112 @@ +/// Interfaces available to the component adapter, which are not otherwise +/// part of the Fastly Compute platform. +package fastly:adapter; + +/// Adapter functions formerly of `fastly:compute/http-req`. +/// +/// These functions depend on the host maintaining an implicit downstream +/// request. They were deprecated and replaced by functions in the +/// `http-downstream` interface which do the same thing but take an explicit +/// `request` handle. +/// +/// We could almost polyfill these functions in the adapter, by having the +/// adapter remember the downstream request handle passed in and calling the +/// `http-downstream` versions with it, but not quite. Guest programs can call +/// `send` and pass it the downstream handle, which consumes the downstream +/// handle. If guest programs do that and later call one of these functions, +/// the polyfill no longer has a valid handle it can pass in. +/// +/// So instead, we moved them to be private functions, still implemented by +/// the host, and still accessible through the component adapter, but not +/// accessible to public Wit users. +interface adapter-http-req { + use fastly:compute/types.{error, ip-address}; + use fastly:compute/http-req.{client-cert-verify-result}; + + downstream-client-ip-addr: func() -> option; + downstream-server-ip-addr: func() -> option; + downstream-client-h2-fingerprint: func(max-len: u64) -> result; + downstream-client-request-id: func(max-len: u64) -> result; + downstream-client-oh-fingerprint: func(max-len: u64) -> result; + downstream-client-ddos-detected: func() -> result; + downstream-tls-cipher-openssl-name: func(max-len: u64) -> result>, error>; + downstream-tls-protocol: func(max-len: u64) -> result>, error>; + downstream-tls-client-hello: func(max-len: u64) -> result>, error>; + downstream-tls-client-cert-verify-result: func() -> result, error>; + downstream-tls-ja3-md5: func() -> result>, error>; + downstream-tls-ja4: func(max-len: u64) -> result, error>; + downstream-compliance-region: func(max-len: u64) -> result, error>; + + /// Deprecated, because it doesn't return `none` on an empty certificate. + downstream-tls-raw-client-certificate-deprecated: func(max-len: u64) -> result>, error>; + + get-original-header-names: func( + max-len: u64, + cursor: u32, + ) -> result>, error>; + + original-header-count: func() -> result; + + fastly-key-is-valid: func() -> result; + + /// Deprecated; use `redirect-to-websocket-proxy` instead. + redirect-to-websocket-proxy-deprecated: func(backend: string) -> result<_, error>; + + /// Deprecated; use `redirect-to-grip-proxy` instead. + redirect-to-grip-proxy-deprecated: func(backend: string) -> result<_, error>; +} + +interface adapter-http-downstream { + use fastly:compute/types.{error}; + use fastly:compute/http-req.{request}; + + /// Deprecated, because it doesn't return `none` on an empty certificate. + downstream-tls-raw-client-certificate-deprecated: func( + ds-request: borrow, + max-len: u64 + ) -> result>, error>; +} + +/// User-agent string parsing (deprecated). +/// +/// This was public in the Witx ABI, but it was deprecated, so now it's a +/// fastly-private API, available to existing code using the adapter, but +/// not available publicly. +interface adapter-uap { + use fastly:compute/types.{error}; + + resource user-agent { + family: func(max-len: u64) -> result; + major: func(max-len: u64) -> result; + minor: func(max-len: u64) -> result; + patch: func(max-len: u64) -> result; + } + + /// Parses a user agent string. + parse: func(user-agent: list) -> result; +} + +/// A world that just imports all the deprecated APIs, split out from the main +/// world below so that we can refer to it in tests. +world adapter-imports { + import adapter-http-req; + import adapter-http-downstream; + import adapter-uap; +} + +/// The `fastly:compute/service` world plus the deprecated interfaces. +world adapter-service { + // Make this world a superset of the public `service` world. + include fastly:compute/service; + + // And, add all the deprecated interfaces. + include adapter-imports; +} + +/// Like `adapter-service`, but only includes the imports, and not the +/// exports (`http-incoming.handle`), so that it can be used by library components +/// that don't have their own `main` function. +world adapter-service-imports { + include fastly:compute/service-imports; + include adapter-imports; +} diff --git a/wit/deps/fastly/compute.wit b/wit/deps/fastly/compute.wit new file mode 100644 index 0000000..5c2df02 --- /dev/null +++ b/wit/deps/fastly/compute.wit @@ -0,0 +1,2857 @@ +/// This is a [Wit] file defining the APIs of the [Fastly Compute platform]. +/// +/// This file defines the `fastly:compute/service` world, which defines the +/// set of interfaces available to, and expected of, Fastly Compute service +/// applications. +/// +/// [Wit]: https://component-model.bytecodealliance.org/design/wit.html +/// [Fastly Compute platform]: https://www.fastly.com/documentation/guides/compute/ +package fastly:compute; + +/// Types used by many interfaces in this package. +interface types { + /// A common error type used by many functions in this package. + /// + /// TODO: In the future this should be split up into more-specific error + /// enums so that it better documents which errors each function can actually + /// return and what they mean. + variant error { + /// Generic error value. + /// + /// This means that some unexpected error occurred. + generic-error, + /// Invalid argument. + invalid-argument, + /// Invalid handle. + /// + /// Returned when a handle is not valid, for example when no dictionary exists with the given + /// name. + bad-handle, + /// Buffer length error. + /// + /// Returned when a buffer is the wrong size. + /// Includes the buffer length that would allow the operation to succeed. + buffer-len(u64), + /// Unsupported operation error. + /// + /// This error is returned when some operation cannot be performed, because it is not supported. + unsupported, + /// Invalid HTTP error. + /// + /// This can be returned when a method, URI, header, or status is not valid. This can also + /// be returned if a message head is too large. + http-invalid, + /// HTTP user error. + /// + /// This is returned in cases where user code caused an HTTP error. For example, attempt to send + /// a 1xx response code, or a request with a non-absolute URI. This can also be caused by + /// an unexpected header: both `content-length` and `transfer-encoding`, for example. + http-user, + /// HTTP incomplete message error. + /// + /// This can be returned when a stream ended unexpectedly. + http-incomplete, + /// A “none” error. + /// + /// This status code is used to indicate when an optional value did not exist, as opposed to + /// an empty value. + optional-none, + /// Message head too large. + http-head-too-large, + /// Invalid HTTP status. + http-invalid-status, + /// Limit exceeded + /// + /// This is returned when an attempt to allocate a resource has exceeded the maximum number of + /// resources permitted. For example, creating too many response handles. + limit-exceeded, + } + + /// IPv4 addresses. + type ipv4-address = tuple; + + /// IPv6 addresses. + type ipv6-address = tuple; + + /// IPv4 or IPv6 addresses. + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } +} + +/// Types used by HTTP interfaces in this package. +interface http-types { + + /// HTTP protocol versions. + enum http-version { + /// HTTP/0.9 + http09, + /// HTTP/1.0 + http10, + /// HTTP/1.1 + http11, + /// HTTP/2.0 + h2, + /// HTTP/3.0 + h3 + } + + /// HTTP [content encoding] flags + /// + /// [content encoding]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-encoding + flags content-encodings { + /// [Gzip coding] + /// + /// [Gzip coding]: https://www.rfc-editor.org/rfc/rfc9110.html#gzip.coding + gzip + } + + /// Determines how the framing headers (`Content-Length`/`Transfer-Encoding`) are set for a + /// request or response. + enum framing-headers-mode { + /// Determine the framing headers automatically based on the message body, and discard any + /// framing headers already set in the message. This is the default behavior. + /// + /// In automatic mode, a `Content-Length` is used when the size of the body can be determined + /// before it is sent. Requests/responses sent in streaming mode, where headers are sent + /// immediately but the content of the body is streamed later, will receive a + /// `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. + automatic, + + /// Use the exact framing headers set in the message, falling back to `automatic` if invalid. + /// + /// In “from headers” mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. + /// You must ensure that those headers have correct values permitted by the + /// [HTTP/1.1 specification]. If the provided headers are not permitted by the spec, the headers + /// will revert to automatic mode and a log diagnostic will be issued about what was wrong. If a + /// `Content-Length` is permitted by the spec, but the value doesn't match the size of the + /// actual body, the body will either be truncated (if it is too long), or the connection will + /// be hung up early (if it is too short). + /// + /// [HTTP/1.1 specification]: https://www.rfc-editor.org/rfc/rfc7230#section-3.3.1 + manually-from-headers + } + + /// [Transport Layer Security] (TLS) version + /// + /// [Transport Layer Security]: https://www.rfc-editor.org/rfc/rfc8446.html + enum tls-version { + /// TLS 1.0 + tls1, + /// TLS 1.1 + tls11, + /// TLS 1.2 + tls12, + /// TLS 1.3 + tls13 + } + + /// HTTP [status codes]. + /// + /// [status codes]: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + type http-status = u16; +} + +/// HTTP bodies. +interface http-body { + + use types.{error}; + + /// An HTTP request or response body. + use async-io.{pollable as body}; + + /// Creates a new empty body that can be used for outgoing requests and responses. + new: func() -> result; + + /// Appends the contents of the body `src` to the body `dest`. + append: func(dest: borrow, src: body) -> result<_, error>; + + /// Reads from a body. + read: func(body: borrow, chunk-size: u32) -> result, error>; + + /// Writes to a body. + write: func(body: borrow, buf: list, end: write-end) -> result; + + /// Which side of a body to write to. + enum write-end { + /// Write to the back of the body; that is, append to it. + back, + + /// Write to the front of the body; that is, prepend to it. + front + } + + /// Frees a body. + /// + /// This releases resources associated with the body. + /// + /// For streaming bodies, this is a *successful* stream termination, which will signal + /// via framing that the body transfer is complete. + /// + /// If a handle is dropped without calling `close`, it's an *unsuccessful* stream + /// termination. + close: func(body: body) -> result<_, error>; + + /// Returns a `u64` body length if the length of a body is known, or `none` otherwise. + /// + /// If the length is unknown, it is likely due to the body arising from an HTTP/1.1 message with + /// chunked encoding, an HTTP/2 or later message with no `content-length`, or being a streaming + /// body. + /// + /// Receiving a length from this function does not guarantee that the full number of + /// bytes can actually be read from the body. For example, when proxying a response from a + /// backend, this length may reflect the `content-length` promised in the response, but if the + /// backend connection is closed prematurely, fewer bytes may be delivered before this body + /// handle can no longer be read. + get-known-length: func(body: borrow) -> option; + + /// Adds a body trailing header with given value. + append-trailer: func( + body: borrow, + name: string, + value: list, + ) -> result<_, error>; + + /// Gets the names of the trailers associated with this body. + /// + /// The first `cursor` names are skipped. The remaining names are encoded successively with + /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining + /// names don't fit, the returned `option` is the index of the first name that didn't fit, + /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, an + /// `error.buffer-len` error is returned, providing a recommended buffer size. + get-trailer-names: func( + body: borrow, + max-len: u64, + cursor: u32, + ) -> result>, error>; + + /// Gets the value for the trailer with the given name, or `none` if the trailer is not present. + /// + /// If there are multiple values for this header, only one is returned, which may be + /// any of the values. See `get-trailer-values` if you need to get all of the values. + /// + /// This functions returns `ok(some(v))` if the trailer with the given name is present, + /// and `ok(none)` if no trailer with the given name is present. If `max-len` is too + /// small to fit the value, an `error.buffer-len` error is returned, providing a + /// recommended buffer size. + get-trailer-value: func( + body: borrow, + name: string, + max-len: u64, + ) -> result>, error>; + + /// Gets multiple values associated with the trailer with the given name. + /// + /// As opposed to `get-trailer-value`, this function returns all of the values for this trailer. + /// + /// The first `cursor` values are skipped. The remaining values are encoded successively with + /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining + /// values don't fit, the returned `option` is the index of the first value that didn't + /// fit, or `none` if all the remaining values fit. If `max-len` is too small to fit any value, + /// an `error.buffer-len` error is returned, providing a recommended buffer size. + get-trailer-values: func( + body: borrow, + name: string, + max-len: u64, + cursor: u32 + ) -> result, option>, error>; +} + +/// Low-level interface to Fastly's [Real-Time Log Streaming] endpoints. +/// +/// [Real-Time Log Streaming]: https://docs.fastly.com/en/guides/about-fastlys-realtime-log-streaming-features +interface log { + + use types.{error}; + + /// A logging endpoint. + resource endpoint { + /// Tries to get an endpoint by name. + /// + /// Currently, the conditions on an endpoint name are: + /// - It must not be empty. + /// - It must not contain newlines (`\n`) or colons (`:`). + /// - It must not be `stdout` or `stderr`, which are reserved for debugging. + /// + /// Names are case sensitive. Calling `get-endpoint` with a name that doesn't correspond to any + /// logging endpoint available in your service will still return a usable endpoint, and writes + /// to that endpoint will succeed. Refer to your service dashboard to diagnose missing log + /// events. + get: static func(name: string) -> result; + + /// Writes a data to the given endpoint. + /// + /// Each call to `write` produces a single log event. On success, the number of bytes written + /// is returned. + write: func(msg: list) -> result; + } +} + +/// HTTP downstream requests and metadata. +/// +/// “Downstream” here refers to incoming HTTP requests. +interface http-downstream { + use types.{error, ip-address}; + use http-req.{ + request, client-cert-verify-result, error-with-detail, cache-override, request-promise, + request-with-body, + }; + + /// Configuration for `next-request`. + record next-request-options { + timeout-ms: option, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `next-request-options` + resource extra-next-request-options {} + + /// Starts waiting for the next request. + next-request: func( + options: next-request-options, + ) -> result; + + /// Waits until the next request is available, and then returns the resulting + /// request and body. + /// + /// Returns `ok(none)` if there are no more requests for this session. + await-next-request: func( + pending: request-promise, + ) -> result, error>; + + next-request-abandon: func( + pending: request-promise, + ) -> result<_, error>; + + /// Returns the client request's header names exactly as they were originally received. + /// + /// This includes both the original header name characters' cases, as well as the original order + /// of the received headers. + /// + /// The first `cursor` names are skipped. The remaining names are encoded successively with + /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining + /// names don't fit, the returned `option` is the index of the first name that didn't fit, + /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, + /// an `error.buffer-len` error is returned, providing a recommended buffer size. + downstream-original-header-names: func( + ds-request: borrow, + max-len: u64, + cursor: u32, + ) -> result>, error>; + + /// Returns the number of headers in the client request as originally received. + downstream-original-header-count: func( + ds-request: borrow + ) -> result; + + /// Returns the IP address of the client making the HTTP request, if known. + downstream-client-ip-addr: func( + ds-request: borrow + ) -> option; + + /// Returns the IP address on which this server received the HTTP request, if known. + downstream-server-ip-addr: func( + ds-request: borrow + ) -> option; + + /// Gets the HTTP/2 fingerprint of client request if available. + downstream-client-h2-fingerprint: func( + ds-request: borrow, + max-len: u64 + ) -> result; + + /// Gets the id of the current request if available. + downstream-client-request-id: func( + ds-request: borrow, + max-len: u64 + ) -> result; + + /// Gets the fingerprint of client request headers if available. + downstream-client-oh-fingerprint: func( + ds-request: borrow, + max-len: u64 + ) -> result; + + /// Returns whether the request was tagged as contributing to a DDoS attack. + downstream-client-ddos-detected: func( + ds-request: borrow + ) -> result; + + /// Gets the cipher suite used to secure the downstream client TLS connection. + /// + /// The value returned will be consistent with the [OpenSSL name] for the cipher suite. + /// + /// Returns `ok(none)` if the downstream client connection is not a TLS connection. + /// + /// [OpenSSL name]: https://testssl.sh/openssl-iana.mapping.html + downstream-tls-cipher-openssl-name: func( + ds-request: borrow, + max-len: u64 + ) -> result>, error>; + + /// Gets the TLS protocol version used to secure the downstream client TLS connection. + /// + /// Returns `ok(none)` if the downstream client connection is not a TLS connection. + downstream-tls-protocol: func( + ds-request: borrow, + max-len: u64 + ) -> result>, error>; + + /// Gets the raw bytes sent by the client in the TLS ClientHello message. + /// + /// See [RFC 5246] for details. + /// + /// Returns `ok(none)` if the downstream client connection is not a TLS connection. + /// + /// [RFC 5246]: https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2 + downstream-tls-client-hello: func( + ds-request: borrow, + max-len: u64 + ) -> result>, error>; + + /// Gets the raw client certificate used to secure the downstream client mTLS connection. + /// + /// The value returned will be based on PEM format. + /// + /// Returns `ok(none)` if the downstream client connection is not a TLS connection. + downstream-tls-raw-client-certificate: func( + ds-request: borrow, + max-len: u64 + ) -> result>, error>; + + /// Returns the `client-cert-verify-result` from the downstream client mTLS handshake. + /// + /// Returns `ok(none)` if the downstream client connection is not a TLS connection. + downstream-tls-client-cert-verify-result: func( + ds-request: borrow + ) -> result, error>; + + /// Returns the Server Name Indication from the downstream client TLS handshake. + /// + /// Returns `ok(none)` if not available. + downstream-tls-client-servername: func( + ds-request: borrow, + max-len: u64 + ) -> result, error>; + + /// Gets the JA3 hash of the TLS ClientHello message. + /// + /// Returns `ok(none)` if the downstream client connection is not a TLS connection. + downstream-tls-ja3-md5: func( + ds-request: borrow + ) -> result>, error>; + + /// Gets the JA4 hash of the TLS ClientHello message. + /// + /// Returns `ok(none)` if the downstream client connection is not a TLS connection. + downstream-tls-ja4: func( + ds-request: borrow, + max-len: u64 + ) -> result, error>; + + /// Gets the compliance region that the client IP address is in. + downstream-compliance-region: func( + ds-request: borrow, + max-len: u64 + ) -> result, error>; + + /// Returns whether or not the original client request arrived with a + /// Fastly-Key belonging to a user with the rights to purge content on this + /// service. + fastly-key-is-valid: func( + ds-request: borrow, + ) -> result; +} + +/// HTTP requests. +interface http-req { + + use types.{error, ip-address}; + use http-types.{http-version, content-encodings, framing-headers-mode, tls-version}; + use http-resp.{response}; + use http-body.{body}; + use http-resp.{response-with-body}; + + /// Handle that can be used to wait for a sent request. + use async-io.{pollable as pending-request}; + + /// Handle that can be used to wait for incoming requests. + use async-io.{pollable as request-promise}; + + /// An HTTP request. + resource request { + /// Creates a new `request` with no method, URL, or headers, and an empty body. + new: static func() -> result; + + /// Sets the cache override behavior for this request. + /// + /// This setting will override any cache directive headers returned in response to this request. + set-cache-override: func( + cache-override: cache-override, + ) -> result<_, error>; + + /// Reads the request's header names via a buffer of the provided size. + /// + /// The first `cursor` names are skipped. The remaining names are encoded successively with + /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining + /// names don't fit, the returned `option` is the index of the first name that didn't fit, + /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, + /// an `error.buffer-len` error is returned, providing a recommended buffer size. + get-header-names: func( + max-len: u64, + cursor: u32, + ) -> result>, error>; + + /// Gets the value of a header, or `none` if the header is not present. + /// + /// If there are multiple values for the header, only one is returned. See + /// `get-header-values` if you need to get all of the values. + /// + /// If header name requires more than `max-len` bytes, this will return an `error.buffer-len` + /// containing the required size. + get-header-value: func( + name: string, + max-len: u64, + ) -> result>, error>; + + /// Gets multiple header values for the given `name` via a buffer of the provided size. + /// + /// As opposed to `get-header-value`, this function returns all of the values for this header. + /// + /// The first `cursor` values are skipped. The remaining values are encoded successively with + /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining + /// values don't fit, the returned `option` is the index of the first value that didn't + /// fit, or `none` if all the remaining values fit. If `max-len` is too small to fit any value, + /// an `error.buffer-len` error is returned, providing a recommended buffer size. + get-header-values: func( + name: string, + max-len: u64, + cursor: u32 + ) -> result, option>, error>; + + /// Sets the values for the given header name, replacing any headers that previously existed for + /// that name. + set-header-values: func( + name: string, + /// contains multiple values each terminated by `\0` and concatenated + values: list + ) -> result<_, error>; + + /// Sets a request header to the given value, discarding any previous values for the given + /// header name. + insert-header: func(name: string, value: list) -> result<_, error>; + + /// Adds a request header with given value. + /// + /// Unlike `set-header-values`, this does not discard existing values for the same header name. + append-header: func( + name: string, + value: list, + ) -> result<_, error>; + + /// Removes all request headers of the given name + /// + /// Returns `ok` if any headers were successfully removed. + remove-header: func(name: string) -> result<_, error>; + + /// Gets the request method. + get-method: func(max-len: u64) -> result; + + /// Sets the request method. + set-method: func(method: string) -> result<_, error>; + + /// Gets the request URI. + get-uri: func(max-len: u64) -> result; + + /// Sets the request URI. + set-uri: func(uri: string) -> result<_, error>; + + /// Gets the HTTP version of this request. + get-version: func() -> result; + + /// Sets the HTTP version of this request. + set-version: func(version: http-version) -> result<_, error>; + + /// Sets the content encodings to automatically decompress responses to this request. + /// + /// If the response to this request is encoded by one of the encodings set by this method, the + /// response will be presented to the Compute program in decompressed form with the + /// `Content-Encoding` and `Content-Length` headers removed. + set-auto-decompress-response: func( + encodings: content-encodings, + ) -> result<_, error>; + + /// Passes the WebSocket directly to a backend. + /// + /// This can only be used on services that have the WebSockets feature enabled and on requests + /// that are valid WebSocket requests. + /// + /// The sending completes in the background. Once this method has been called, no other response + /// can be sent to this request, and the application can exit without affecting the send. + /// + /// See the [WebSockets passthrough] documentation for a high-level description of this feature. + /// + /// [WebSockets passthrough]: https://www.fastly.com/documentation/guides/concepts/real-time-messaging/websockets-tunnel/ + redirect-to-websocket-proxy: func( + backend: string, + ) -> result<_, error>; + + /// Sets how the framing headers `Content-Length` and `Transfer-Encoding` will be determined + /// when sending this request. + set-framing-headers-mode: func( + mode: framing-headers-mode, + ) -> result<_, error>; + + /// Inspects request HTTP traffic using the [NGWAF] lookaside service. + /// + /// Returns a JSON-encoded string. + /// + /// [NGWAF]: https://docs.fastly.com/en/ngwaf/ + inspect: func( + body: borrow, + options: inspect-options, + max-len: u64 + ) -> result; + + /// Instead of having this request cache in this service's space, use the + /// cache of the named service + on-behalf-of: func( + service: string, + ) -> result<_, error>; + + redirect-to-grip-proxy: func( + backend: string, + ) -> result<_, error>; + } + + /// Retrieves a response for the request, either from cache or by sending it + /// to the given backend server. + /// + /// Returns once the response headers have been received, or an error occurs. + send: func( + request: request, + body: body, + backend: string, + ) -> result; + + /// Sends the request directly to the backend server without performing any + /// caching or inserting any cache-related headers in the response. + /// + /// Returns once the response headers have been received, or an error occurs. + send-uncached: func( + request: request, + body: body, + backend: string, + ) -> result; + + /// Begins sending the request to the given backend server, and returns a + /// `pending-request` that can yield the backend response or an error. + /// + /// This method returns as soon as the request begins sending to the backend, + /// and transmission of the request body and headers will continue in the + /// background. + /// + /// This method allows for sending more than one request at once and receiving + /// their responses in arbitrary orders. See `pending-request` for more + /// details on how to wait on, poll, or select between pending requests. + /// + /// This method is also useful for sending requests where the response is + /// unimportant, but the request may take longer than the Compute program is + /// able to run, as the request will continue sending even after the program + /// that initiated it exits. + send-async: func( + request: request, + body: body, + backend: string + ) -> result; + + /// This is to `send-async` as `send-uncached` is to `send`. + /// + /// As with `send-uncached`, this function sends the request directly to the + /// backend server without performing any caching or inserting any + /// cache-related headers in the response. + send-async-uncached: func( + request: request, + body: body, + backend: string, + ) -> result; + + /// Begins sending the request to the given backend server, and returns a + /// `pending-request` that can yield the backend response or an error. + /// + /// The `body` argument is not consumed, so that it can accept further data to send. + /// + /// The backend connection is only closed once `http-body.close` is called. The + /// `pending-request` will not yield a `response` until the body is finished. + /// + /// This method is most useful for programs that do some sort of processing or + /// inspection of a potentially-large client request body. Streaming allows the + /// program to operate on small parts of the body rather than having to read it all + /// into memory at once. + /// + /// This method returns as soon as the request begins sending to the backend, + /// and transmission of the request body and headers will continue in the + /// background. + send-async-streaming: func( + request: request, + body: borrow, + backend: string, + ) -> result; + + /// This is to `send-async-streaming` as `send-uncached` is to `send`. + /// + /// As with `send-uncached`, this function sends the request directly to the + /// backend server without performing any caching or inserting any + /// cache-related headers in the response. + send-async-uncached-streaming: func( + request: request, + body: borrow, + backend: string, + ) -> result; + + type request-with-body = tuple; + + /// Optional override for response caching behavior. + variant cache-override { + /// Do not override the behavior specified in the origin response’s cache control headers. + none, + + /// Do not cache the response to this request, regardless of the origin response’s headers. + pass, + + /// Override particular cache control settings. + override(cache-override-details) + } + + /// The fields for the `override` arm of `cache-override`. + /// + /// The origin response’s cache control headers will be used for ttl and + /// `stale-while-revalidate` if `none`. + record cache-override-details { + ttl: option, + stale-while-revalidate: option, + pci: bool, + surrogate-key: option>, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `cache-override-details` + resource extra-cache-override-details {} + + /// TLS client certificate verified result from downstream. + enum client-cert-verify-result { + /// Success value. + /// + /// This indicates that client certificate verified successfully. + ok, + /// bad certificate error. + /// + /// This error means the certificate is corrupt + /// (for example, when the certificate signatures do not verify correctly). + bad-certificate, + /// certificate revoked error. + /// + /// This error means the client certificate is revoked by its signer. + certificate-revoked, + /// certificate expired error. + /// + /// This error means the client certificate has expired or is not currently valid. + certificate-expired, + /// unknown CA error. + /// + /// This error means the valid certificate chain or partial chain was received, + /// but the certificate was not accepted because the CA certificate could not be + /// located or could not be matched with a known trust anchor. + unknown-ca, + /// certificate missing error. + /// + /// This error means the client does not provide a certificate + /// during the handshake.. + certificate-missing, + /// certificate unknown error. + /// + /// This error means the client certificate was received, but some other (unspecified) + /// issue arose in processing the certificate, rendering it unacceptable. + certificate-unknown, + } + + enum send-error-detail-tag { + /// The $send_error_detail struct has not been populated. + uninitialized, + /// There was no send error. + ok, + /// The system encountered a timeout when trying to find an IP address for the backend + /// hostname. + dns-timeout, + /// The system encountered a DNS error when trying to find an IP address for the backend + /// hostname. The fields `dns-error-rcode` and `dns-error-info-code` may be set in the + /// $send_error_detail. + dns-error, + /// The system cannot determine which backend to use, or the specified backend was invalid. + destination-not-found, + /// The system considers the backend to be unavailable, for example when recent attempts to + /// communicate with it may have failed, or a health check may indicate that it is down. + destination-unavailable, + /// The system cannot find a route to the next-hop IP address. + destination-ip-unroutable, + /// The system's connection to the backend was refused. + connection-refused, + /// The system's connection to the backend was closed before a complete response was + /// received. + connection-terminated, + /// The system's attempt to open a connection to the backend timed out. + connection-timeout, + /// The system is configured to limit the number of connections it has to the backend, and + /// that limit has been exceeded. + connection-limit-reached, + /// The system encountered an error when verifying the certificate presented by the backend. + tls-certificate-error, + /// The system encountered an error with the backend TLS configuration. + tls-configuration-error, + /// The system received an incomplete response to the request from the backend. + http-incomplete-response, + /// The system received a response to the request whose header section was considered too + /// large. + http-response-header-section-too-large, + /// The system received a response to the request whose body was considered too large. + http-response-body-too-large, + /// The system reached a configured time limit waiting for the complete response. + http-response-timeout, + /// The system received a response to the request whose status code or reason phrase was + /// invalid. + http-response-status-invalid, + /// The process of negotiating an upgrade of the HTTP version between the system and the + /// backend failed. + http-upgrade-failed, + /// The system encountered an HTTP protocol error when communicating with the backend. + /// + /// This error will only be used when a more specific one is not defined. + http-protocol-error, + /// An invalid cache key was provided for the request. + http-request-cache-key-invalid, + /// An invalid URI was provided for the request. + http-request-uri-invalid, + /// The system encountered an unexpected internal error. + internal-error, + /// The system received a TLS alert from the backend. The field `tls-alert-id` may be set in + /// the $send_error_detail. + tls-alert-received, + /// The system encountered a TLS error when communicating with the backend, either during + /// the handshake or afterwards. + tls-protocol-error, + } + + record send-error-detail { + tag: send-error-detail-tag, + dns-error-rcode: option, + dns-error-info-code: option, + tls-alert-id: option, + } + + record error-with-detail { + detail: option, + error: error, + } + + /// Configuration for inspecting a `request` using Security. + record inspect-options { + corp: option, + workspace: option, + override-client-ip: option, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `inspect-options` + resource extra-inspect-options {} + + /// Waits until the request is completed, and then returns the resulting + /// response and body. + await-request: func( + pending: pending-request + ) -> result; + + /// Closes the `request`, releasing any associated resources. + /// + /// A `request` is automatically consumed when you send a request. You should call `close` + /// only if you have a `request` you don't intend to use anymore. + close: func(request: request) -> result<_, error>; + + upgrade-websocket: func(backend: string) -> result<_, error>; + +} + +/// HTTP responses. +interface http-resp { + use types.{error, ip-address}; + + use http-types.{ + http-version, http-status, + framing-headers-mode + }; + use http-body.{body}; + + /// An HTTP response. + resource response { + /// Create a new `response`. + /// + /// The new `response` is created with status code 200 OK, no headers, and an empty body. + new: static func() -> result; + + /// Read the response's header names via a buffer of the provided size. + /// + /// The first `cursor` names are skipped. The remaining names are encoded successively with + /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining + /// names don't fit, the returned `option` is the index of the first name that didn't fit, + /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, + /// an `error.buffer-len` error is returned, providing a recommended buffer size. + get-header-names: func( + max-len: u64, + cursor: u32, + ) -> result>, error>; + + /// Gets the value of a header, or `none` if the header is not present. + /// + /// If there are multiple values for the header, only one is returned. See + /// `get-header-values` if you need to get all of the values. + /// + /// If header name requires more than `max-len` bytes, this will return an `error.buffer-len` + /// containing the required size. + get-header-value: func( + name: string, + max-len: u64, + ) -> result>, error>; + + /// Gets multiple header values for the given `name` via a buffer of the provided size. + /// + /// As opposed to `get-header-value`, this function returns all of the values for this header. + /// + /// The first `cursor` values are skipped. The remaining values are encoded successively with + /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining + /// values don't fit, the returned `option` is the index of the first value that didn't + /// fit, or `none` if all the remaining values fit. If `max-len` is too small to fit any value, + /// an `error.buffer-len` error is returned, providing a recommended buffer size. + get-header-values: func( + name: string, + max-len: u64, + cursor: u32 + ) -> result, option>, error>; + + /// Sets the values for the given header name, replacing any headers that previously existed for + /// that name. + set-header-values: func( + name: string, + /// contains multiple values each terminated by `\0` and concatenated + values: list + ) -> result<_, error>; + + /// Sets a response header to the given value, discarding any previous values for the given + /// header name. + insert-header: func( + name: string, + value: list, + ) -> result<_, error>; + + /// Add a response header with given value. + /// + /// Unlike `set-header-values`, this does not discard existing values for the same header name. + append-header: func( + name: string, + value: list, + ) -> result<_, error>; + + /// Remove all response headers of the given name + /// + /// Returns `ok` if any headers were successfully removed. + remove-header: func(name: string) -> result<_, error>; + + /// Gets the HTTP version of this response. + get-version: func() -> result; + + /// Sets the HTTP version of this response. + set-version: func(version: http-version) -> result<_, error>; + + /// Gets the HTTP status code of the response. + get-status: func() -> result; + + /// Sets the HTTP status code of the response. + set-status: func(status: http-status) -> result<_, error>; + + /// Sets how the framing headers `Content-Length` and `Transfer-Encoding` will be determined + /// when sending this response. + set-framing-headers-mode: func(mode: framing-headers-mode) -> result<_, error>; + + /// Adjust the response's connection reuse mode. + set-http-keepalive-mode: func(mode: keepalive-mode) -> result<_, error>; + + /// Gets the destination IP address used for this response, if known. + get-remote-ip-addr: func() -> option; + + /// Gets the destination port used for this response, if known. + get-remote-port: func() -> option; + } + + /// Sends a response to the client that made the request passed to `http-incoming.handle`. + /// + /// This method returns as soon as the response header begins sending to the client, and + /// transmission of the response will continue in the background. + /// + /// Data for the body must be written before calling this function. To start a response + /// and write data to it afterwards, use `send-downstream-streaming` instead. + send-downstream: func( + response: response, + body: body, + ) -> result<_, error>; + + /// Starts a response to the client that made the request passed to `http-incoming.handle`. + /// + /// The body is left open, allowing data to be written after calling this function. + send-downstream-streaming: func( + response: response, + body: borrow, + ) -> result<_, error>; + + /// Closes the `response`, releasing any associated resources. + /// + /// A `response` is consumed when you send a response to a client or stream one to a + /// client. You should call `close` only if you have a `response` you don't intend + /// to use anymore. + close: func(response: response) -> result<_, error>; + + type response-with-body = tuple; + + enum keepalive-mode { + automatic, + no-keepalive, + } +} + +/// [Compute Dictionaries] (deprecated in favor of `config-store`) +/// +/// [Compute Dictionaries]: https://www.fastly.com/documentation/guides/concepts/edge-state/dynamic-config/#dictionaries +interface dictionary { + + use types.{error}; + + /// A Compute Dictionary. + resource dictionary { + /// Opens a dictionary, given its name. + /// + /// Names are case sensitive. + open: static func(name: string) -> result; + + /// Tries to look up a value in this dictionary. + /// + /// If the lookup is successful, this function returns `ok(some(s))` containing the found + /// string `s`, or `ok(none)` if no entry with the given key was found. + lookup: func( + key: string, + max-len: u64, + ) -> result, error>; + } +} + +/// [Geographic data] for IP addresses. +/// +/// [Geographic data]: https://www.fastly.com/blog/improve-performance-and-gain-better-end-user-intelligence-geoip-geography-detection +interface geo { + use types.{error, ip-address}; + + /// Looks up the geographic data associated with a particular IP address. + /// + /// Returns a list of bytes containing JSON-encoded geographic data. See [here] for descriptions + /// of the JSON fields. + /// + /// [here]: https://www.fastly.com/documentation/reference/vcl/variables/geolocation/ + lookup: func(ip-addr: ip-address, max-len: u64) -> result; +} + +/// Device detection based on the User-Agent header. +interface device-detection { + use types.{error}; + + /// Looks up the data associated with a particular User-Agent string. + /// + /// Returns a list of bytes containing JSON-encoded device data. See [here] for descriptions + /// of the JSON fields. + /// + /// [here]: https://www.fastly.com/documentation/reference/vcl/variables/client-request/client-identified/ + lookup: func(user-agent: string, max-len: u64) -> result, error>; +} + +/// [Edge rate limiting] API. +/// +/// [Edge rate limiting]: https://docs.fastly.com/products/edge-rate-limiting +interface erl { + use types.{error}; + + /// Increments an entry in a rate counter and check if the client has exceeded some average number + /// of requests per second (RPS) over the window. + /// + /// If the client is over the rps limit for the window, add to the penaltybox for ttl. Valid ttl + /// span is 1m to 1h and TTL value is truncated to the nearest minute. + check-rate: func( + rate-counter: string, + entry: string, + delta: u32, + window: u32, + limit: u32, + penalty-box: string, + ttl: u32, + ) -> result; + + /// Increments an entry in the ratecounter by `delta`. + ratecounter-increment: func( + rate-counter: string, + entry: string, + delta: u32, + ) -> result<_, error>; + + /// Looks up the current rate for entry in the ratecounter for a window. + ratecounter-lookup-rate: func( + rate-counter: string, + entry: string, + window: u32, + ) -> result; + + /// Looks up the current count for entry in the ratecounter for duration. + ratecounter-lookup-count: func( + rate-counter: string, + entry: string, + duration: u32, + ) -> result; + + /// Add `entry` to a the penaltybox for the duration of ttl. + /// + /// Valid ttl span is 1m to 1h and TTL value is truncated to the nearest minute. + penaltybox-add: func( + penalty-box: string, + entry: string, + ttl: u32, + ) -> result<_, error>; + + /// Checks if `entry` is in the penaltybox. + penaltybox-has: func( + penalty-box: string, + entry: string, + ) -> result; +} + +/// Interface to Fastly's [Compute KV Store]. +/// +/// For a high-level introduction to this feature, see this [blog post]. +/// +/// [Compute KV Store]: https://www.fastly.com/documentation/guides/concepts/edge-state/data-stores/#kv-stores +/// [blog post]: https://www.fastly.com/blog/introducing-the-compute-edge-kv-store-global-persistent-storage-for-compute-functions +interface kv-store { + + use types.{error}; + use http-body.{body}; + + /// A KV Store. + resource store { + /// Opens the KV Store with the given name. + /// + /// If there is no store by that name, this returns `ok(none)`. + open: static func(name: string) -> result, error>; + + /// Looks up a value in the KV Store. + /// + /// Returns `ok(some(v))` with the value `v` that was found, `ok(none)` if no value was + /// found, or `err(e)` indicating the error `e` occurred. + /// + /// This function waits until the operation completes. + lookup: func( + key: string, + ) -> result, kv-error>; + + /// Look up a value in the KV Store asynchronously. + /// + /// This function initiates an async lookup of a value in the KV Store. Use + /// `await-lookup` to finish the lookup. + lookup-async: func( + key: string, + ) -> result; + + /// Inserts a value into the KV Store. + /// + /// If the KV Store already contains a value for this key, the `mode` field + /// of the `options` argument specifies how the existing value is handled. + /// + /// This function waits until the operation completes. + insert: func( + key: string, + body: body, + options: insert-options, + ) -> result<_, kv-error>; + + /// Insert a value into the KV Store asynchronously. + /// + /// If the KV Store already contains a value for this key, the `mode` field + /// of the `options` argument specifies how the existing value is handled. + /// + /// This function initiates an async insert of a value in the KV Store. Use + /// `await-insert` to finish the lookup. + insert-async: func( + key: string, + body: body, + options: insert-options, + ) -> result; + + /// Deletes a value in the KV Store. + /// + /// Returns `ok(true)` if a value was successfully deleted, `ok(false)` if no value was + /// found, or `err(e)` indicating the error `e` occurred. + /// + /// This function waits until the operation completes. + delete: func( + key: string, + ) -> result; + + /// Delete of a value in the KV Store. + /// + /// This function initiates an async delete of a value in the KV Store. Use + /// `await-delete` to finish the lookup. + delete-async: func( + key: string, + ) -> result; + + /// Lists keys in the KV Store. + /// + /// Returns `ok(b)` with the body `b` on success, or `err(e)` indicating the error `e` + /// occurred. + /// + /// This function waits until the operation completes. + %list: func( + options: list-options, + ) -> result; + + /// List of keys in the KV Store. + /// + /// This function initiates an async list value in the KV Store. Use + /// `await-list` to finish the lookup. + list-async: func( + options: list-options, + ) -> result; + } + + /// An asynchronous KV Store lookup. Use `await-lookup` to resolve. + use async-io.{pollable as pending-lookup}; + + /// An asynchronous KV Store insert. Use `await-insert` to resolve. + use async-io.{pollable as pending-insert}; + + /// An asynchronous KV Store delete. Use `await-delete` to resolve. + use async-io.{pollable as pending-delete}; + + /// An asynchronous KV Store list. Use `await-list` to resolve. + use async-io.{pollable as pending-list}; + + /// A value indicating the status of a KV store operation. + enum kv-error { + /// KV store cannot or will not process the request due to something that is perceived to be a + /// client error. + /// + /// This will map to the api's 400 codes. + bad-request, + /// KV store cannot fulfill the request, as defined by the client's prerequisites, for example + /// `if-generation-match`. + /// + /// This will map to the api's 412 codes. + precondition-failed, + /// The size limit for a KV store key was exceeded. + /// + /// This will map to the api's 413 codes. + payload-too-large, + /// The system encountered an unexpected internal error. + /// + /// This will map to all remaining http error codes. + internal-error, + /// Too many requests have been made to the KV store. + /// + /// This will map to the api's 429 codes. + too-many-requests, + /// Generic error value. + /// + /// This means that some unexpected error occurred. + generic-error, + } + + /// Wait on the async lookup of a value in the KV Store. + /// + /// Returns `ok(some(v))` with the value `v` that was found, `ok(none)` if no value was + /// found, or `err(e)` indicating the error `e` occurred. + await-lookup: func( + handle: pending-lookup, + ) -> result, kv-error>; + + /// Wait on the async insert of a value in the KV Store. + /// + /// Returns `ok` if the `insert` succeeded, or an error code on failure. + await-insert: func( + handle: pending-insert, + ) -> result<_, kv-error>; + + /// Wait on the async delete of a value in the KV Store. + /// + /// Returns `ok(true)` if a value was successfully deleted, `ok(false)` if no value was + /// found, or `err(e)` indicating the error `e` occurred. + await-delete: func( + handle: pending-delete, + ) -> result; + + /// Wait on the async list of keys in the KV Store. + /// + /// Returns `ok(b)` with the body `b` on success, or `err(e)` indicating the error `e` + /// occurred. + await-list: func( + handle: pending-list, + ) -> result; + + /// A response from a KV Store Lookup operation. + /// + /// This type holds the `body`, metadata, and generation of found key. + resource entry { + /// Take and return the body from this `entry`, if it has one; otherwise return `none`. + /// + /// After calling this method, this entry will no longer have a body. + take-body: func() -> option; + + /// Read the metadata of the KV Store item, if present. + metadata: func(max-len: u64) -> result, error>; + + /// Read the current generation of the KV Store item. + generation: func() -> u64; + } + + /// Selects the behavior for an insert when the new key matches an existing key. + /// + /// A KV store maintains the property that its keys are unique from each other. If an insert + /// has a key that doesn't match any key already in the store, then the pair of the key and the + /// new value is inserted into the store. However, if the insert's key does match a key already + /// in the store, then no new key-value pair is inserted, and the insert's `insert-mode.mode` + /// determines what it does instead. + enum insert-mode { + /// Updates the existing key's value by overwriting it with the new value. + /// + /// This is the default mode. + overwrite, + + /// Fails, leaving the existing key's value unmodified. + /// + /// With this mode, the insert fails with a code of `kv-error.precondition-failed`, and + /// does not modify the existing value. Inserts with this mode will only “add” new key-value + /// pairs; they are prevented from modifying any existing ones. + add, + + /// Updates the existing key's value by appending the new value to it. + append, + + /// Updates the existing key's value by prepending the new value to it. + prepend, + } + + /// Options for configuring the behavior of the `insert` function. + record insert-options { + /// If set, allows fetching from the origin to occur in the background, enabling a faster + /// response with stale content. The cache will be updated with fresh content after the request + /// is completed. + background-fetch: bool, + + /// Requests for keys will return a “generation” header specific to the version of a key. The + /// generation header is a unique, non-serial 64-bit unsigned integer that can be used for + /// testing against a specific KV store value. + if-generation-match: option, + + /// Sets an arbitrary data field which can contain up to 2000B of data. + metadata: option, + + /// Sets a time for the key to expire. Deletion will take place up to 24 hours after the ttl + /// reaches 0. + time-to-live-sec: option, + + /// Select the behavior in the case when the new key matches an existing key. + mode: insert-mode, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `insert-options` + resource extra-insert-options {} + + /// Modes of KV Store list operations. + /// + /// This type serves to facilitate alternative methods of cache interactions with list operations. + enum list-mode { + /// Performs an un-cached list on every invocation. + /// + /// This is the default method of listing. + strong, + + /// Returns a cached list response to improve performance. + /// + /// The data may be slightly out of sync with the store, but repeated calls are faster. + /// + /// The word “eventual” here refers to eventual consistency. + eventual, + } + + record list-options { + mode: list-mode, + cursor: option, + limit: option, + prefix: option, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `list-options` + resource extra-list-options {} +} + +/// [Secret Store] API. +/// +/// [Secret Store]: https://www.fastly.com/documentation/reference/api/services/resources/secret-store/ +interface secret-store { + + use types.{error}; + + /// An individual secret. + resource secret { + /// Creates a new “secret” from the given memory. + /// + /// This is *not* the suggested way to create `secret`s; instead, we suggest using `get`. + /// This secret will *NOT* be shared with other sessions. + /// + /// This method can be used for data that should be secret, but is being obtained by + /// some other means than the secret store. New “secrets” created this way use plaintext + /// only, and live in the session's memory unencrypted for much longer than secrets + /// generated by `get`. They should thus only be used in situations in which an API requires + /// a `secret`, but you cannot (for whatever reason) use a `store` to store them. + /// + /// As the early note says, this `secret` will be local to the current session, and + /// will not be shared with other sessions of this service. + from-bytes: static func(bytes: list) -> result; + + /// Returns the plaintext value of this secret. + plaintext: func( + max-len: u64 + ) -> result>, error>; + } + + /// A Secret Store. + resource store { + /// Opens the Secret Store with the given name. + open: static func(name: string) -> result; + + /// Tries to look up a Secret by name in this secret store. + /// + /// If successful, this method returns `ok(some(s))` containing the found secret `s` if the + /// secret is found, or `ok(none)` if the secret was not found. + get: func( + key: string, + ) -> result, error>; + } +} + +/// Blocklists using [Access Control Lists] (ACLs) +/// +/// [Access Control Lists]: https://www.fastly.com/documentation/reference/api/acls/ +interface acl { + + use types.{error, ip-address}; + use http-body.{body}; + + /// An ACL. + resource acl { + /// Opens an ACL linked to the current service with the given link name. + open: static func(name: string) -> result; + + /// Performs a lookup of the given IP address in the ACL. + /// + /// If no matches are found, then `ok(none)` is returned. This corresponds + /// to an HTTP error code of 204, “No Content”. + lookup: func( + ip-addr: ip-address, + ) -> result, acl-error>; + } + + /// Errors returned on ACL lookup failure. + enum acl-error { + /// Too many requests have been made. + /// + /// This corresponds to an HTTP error code of 429, “Too Many Requests”. + too-many-requests, + + /// Generic error value. + /// + /// This means that some unexpected error occurred. + generic-error, + } +} + +/// [Backends] API. +/// +/// A backend represents a service that the application can send requests to, potentially +/// caching the responses received. +/// +/// Backends come in one of two flavors: +/// * **Static Backends**: These backends are created using the Fastly UI or API, +/// and are predefined by the user. Static backends typically have short names that are +/// usable across every session of a service. +/// * **Dynamic Backends**: These backends are created programmatically using the +/// `register-dynamic-backend` API. They are defined at runtime, and may or may not +/// be shared across sessions depending on how they are configured. +/// +/// To use a backend, pass it to a `send*` function. +/// +/// Future versions of this function may return an error if your service does not have a backend +/// with this name. +/// +/// [Backends]: https://www.fastly.com/documentation/guides/integrations/non-fastly-services/developer-guide-backends/ +interface backend { + use types.{error}; + use http-types.{tls-version}; + use secret-store.{secret}; + + /// Creates a new dynamic backend. + /// + /// The arguments are the name of the new backend to use, along with a string describing the + /// backend host. The latter can be of the form: + /// + /// - "" + /// - "" + /// - ":" + /// - ":" + /// + /// The name can be whatever you would like, as long as it does not match the name of any of the + /// static service backends nor match any other dynamic backends built during this session. + /// (Names can overlap between different sessions of the same service—they will be treated as + /// completely separate entities and will not be pooled—but you cannot, for example, declare + /// a dynamic backend named “dynamic-backend” twice in the same session.) + /// + /// Dynamic backends must be enabled for the Compute service. You can determine whether or not + /// dynamic backends have been allowed for the current service by checking for the + /// `error.unsupported` error result. This error only arises when attempting to use dynamic + /// backends with a service that has not had dynamic backends enabled, or dynamic backends have + /// been administratively prohibited for the node in response to an ongoing incident. + register-dynamic-backend: func( + prefix: string, + target: string, + options: dynamic-backend-options, + ) -> result<_, error>; + + /// Options for `register-dynamic-backend`. + resource dynamic-backend-options { + /// Constructs an options resource with default values for all other possible fields for the + /// backend, which can be overridden using the other methods provided. + constructor(); + + /// Sets a host header override when contacting this backend. + /// + /// This will force the value of the “Host” header to the given string when sending out the + /// origin request. If this is not set and no header already exists, the “Host” header will + /// default to the target. + /// + /// For more information, see [the Fastly documentation on override hosts]. + /// + /// [the Fastly documentation on override hosts]: https://docs.fastly.com/en/guides/specifying-an-override-host> + override-host: func(value: string); + + /// Sets the connection timeout, in milliseconds, for this backend. + /// + /// Defaults to 1,000ms (1s). + connect-timeout: func(value: u32); + + /// Sets a timeout, in milliseconds, that applies between the time of connection and the time we + /// get the first byte back. + /// + /// Defaults to 15,000ms (15s). + first-byte-timeout: func(value: u32); + + /// Sets a timeout, in milliseconds, that applies between any two bytes we receive across the + /// wire. + /// + /// Defaults to 10,000ms (10s). + between-bytes-timeout: func(value: u32); + + /// Enables or disables TLS to connect to the backend. + /// + /// When using TLS, Fastly checks the validity of the backend’s certificate, and fails the + /// connection if the certificate is invalid. This check is not optional: an invalid + /// certificate will cause the backend connection to fail (but read on). + /// + /// By default, the validity check does not require that the certificate hostname matches the + /// hostname of your request. You can use check_certificate to request a check of the + /// certificate hostname. + /// + /// By default, certificate validity uses a set of public certificate authorities. You can + /// specify an alternative CA using ca_certificate. + use-tls: func(value: bool); + + /// Sets the minimum TLS version for connecting to the backend. + /// + /// Setting this will enable TLS for the connection as a side effect. + tls-min-version: func(value: tls-version); + + /// Sets the maximum TLS version for connecting to the backend. + /// + /// Setting this will enable TLS for the connection as a side effect. ( + tls-max-version: func(value: tls-version); + + /// Defines the hostname that the server certificate should declare, and turn on validation + /// during backend connections. + /// + /// You should enable this if you are using TLS, and setting this will enable TLS for the + /// connection as a side effect. + /// + /// If `check-certificate` is not provided (default), the server certificate’s hostname may + /// have any value. + cert-hostname: func(value: string); + + /// Sets the CA certificate to use when checking the validity of the backend. + /// + /// Setting this will enable TLS for the connection as a side effect. + /// + /// If `ca-certificate` is not provided (default), the backends’s certificate is validated + /// using a set of public root CAs. + ca-certificate: func(value: string); + + /// Sets the acceptable cipher suites to use for TLS 1.0 - 1.2 connections. + /// + /// Setting this will enable TLS for the connection as a side effect. + tls-ciphers: func(value: string); + + /// Sets the SNI hostname for the backend connection. + /// + /// Setting this will enable TLS for the connection as a side effect. + sni-hostname: func(value: string); + + /// Provides the given client certificate to the server as part of the TLS handshake. + /// + /// Setting this will enable TLS for the connection as a side effect. Both the certificate and + /// the key to use should be in standard PEM format; providing the information in another + /// format will lead to an error. We suggest that (at least the) key should be held in + /// something like the Fastly secret store for security, with the handle passed to this + /// function without unpacking it via Secret::plaintext; the certificate can be held in a less + /// secure medium. + /// + /// (If it is absolutely necessary to get the key from another source, we suggest the use of + /// `secret.from-bytes`. + client-cert: func(client-cert: string, key: borrow); + + /// Configures up to how long to allow HTTP keepalive connections to remain idle in the + /// connection pool. + http-keepalive-time-ms: func(value: u32); + + /// Configures whether or not to use TCP keepalive on the connection to the backend. + tcp-keepalive-enable: func(value: u32); + + /// Configures how long to wait in between each TCP keepalive probe sent to the backend. + tcp-keepalive-interval-secs: func(value: u32); + + /// Configures up to how many TCP keepalive probes to send to the backend before the connection + /// is considered dead. + tcp-keepalive-probes: func(value: u32); + + /// Configures how long to wait after the last sent data over the TCP connection before starting + /// to send TCP keepalive probes. + tcp-keepalive-time-secs: func(value: u32); + + /// Determines whether or not connections to the same backend should be pooled across different + /// sessions. + /// + /// Fastly considers two backends “the same” if they’re registered with the same name and + /// the exact same settings. In those cases, when pooling is enabled, if Session 1 opens a + /// connection to this backend it will be left open, and can be re-used by Session 2. This can + /// help improve backend latency, by removing the need for the initial + /// network / TLS handshake(s). + /// + /// By default, pooling is enabled for dynamic backends. + pooling: func(value: bool); + + /// Sets whether or not this backend will be used for gRPC traffic. + /// + /// Warning: Setting this for backends that will not be used with gRPC may have unpredictable + /// effects. Fastly only currently guarantees that this connection will work for gRPC traffic. + grpc: func(value: bool); + } + + type timeout-ms = u32; + type timeout-secs = u32; + type probe-count = u32; + + /// Returns `true` if a backend with this name exists. + exists: func(backend: string) -> result; + + enum backend-health { + unknown, + healthy, + unhealthy, + } + + /// Return the health of the backend if configured and currently known. + /// + /// For backends without a configured healthcheck, this will always return + /// `backend-health.unknown`. + is-healthy: func(backend: string) -> result; + + /// Returns `true` if the backend is a “dynamic” backend. + is-dynamic: func(backend: string) -> result; + + /// Gets the host of this backend. + get-host: func(backend: string, max-len: u64) -> result; + + /// Gets the “override host” for this backend. + /// + /// This is used to change the `Host` header sent to the backend. See + /// [the Fastly documentation on override hosts]. + /// + /// [the Fastly documentation on override hosts]: https://docs.fastly.com/en/guides/specifying-an-override-host> + get-override-host: func( + backend: string, + max-len: u64, + ) -> result>, error>; + + /// Gets the remote TCP port of the backend connection for the request. + get-port: func(backend: string) -> result; + + /// Gets the connection timeout of the backend. + get-connect-timeout-ms: func(backend: string) -> result; + + /// Gets the first byte timeout of the backend. + /// + /// This timeout applies between the time of connection and the time we get the first byte back. + get-first-byte-timeout-ms: func(backend: string) -> result; + + /// Gets the between byte timeout of the backend. + /// + /// This timeout applies between any two bytes we receive across the wire. + get-between-bytes-timeout-ms: func(backend: string) -> result; + + /// Returns `true` if the backend is configured to use TLS. + is-tls: func(backend: string) -> result; + + /// Gets the minimum TLS version this backend will use. + get-tls-min-version: func(backend: string) -> result, error>; + + /// Gets the maximum TLS version this backend will use. + get-tls-max-version: func(backend: string) -> result, error>; + + /// Returns the time for this backend to hold onto an idle HTTP keepalive connection + /// after it was last used before closing it. + get-http-keepalive-time: func( + backend: string, + ) -> result; + + /// Returns `true` if TCP keepalives have been enabled for this backend. + get-tcp-keepalive-enable: func( + backend: string, + ) -> result; + + /// Returns the time to wait in between sending each TCP keepalive probe to this backend. + get-tcp-keepalive-interval: func( + backend: string, + ) -> result; + + /// Returns the time to wait after the last data was sent before starting to send TCP keepalive + /// probes to this backend. + get-tcp-keepalive-probes: func( + backend: string, + ) -> result; + + /// Returns the time to wait after the last data was sent before starting to send TCP keepalive + /// probes to this backend. + get-tcp-keepalive-time: func( + backend: string, + ) -> result; +} + +/// Async IO support. +/// +/// This module provides several utilities for performing I/O asynchronously. +/// See the documentation for `async-io.pollable` for a description of the kinds +/// of events it supports. +/// +/// In the future, this interface is expected to be replaced by +/// [integrated async features]. +/// +/// [integrated async features]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Async.md#-async-explainer +interface async-io { + /// An object supporting generic async operations. + /// + /// Can be a `http-body.body`, `http-req.pending-request`, `http-req.request-promise`, + /// `cache.pending-entry`. `kv-store.pending-lookup`, `kv-store.pending-insert`, + /// `kv-store.pending-delete`, or `kv-store.pending-list`. + /// + /// Each async item has an associated I/O action: + /// + /// * Pending requests: awaiting the response headers / `response` object + /// * Normal bodies: reading bytes from the body + /// * Streaming bodies: writing bytes to the body + /// + /// For writing bytes, there is a large buffer associated with the handle that bytes + /// can eagerly be written into, even before the origin itself consumes that data. + resource pollable { + /// Make a nonblocking attempt to complete the I/O operation. + /// + /// Returns `true` if the given async item is “ready” for its associated I/O action, `false` + /// otherwise. + /// + /// If an object is ready, the I/O action is guaranteed to complete without blocking. + /// + /// Valid object handles includes bodies and pending requests. See the `async-io.pollable` + /// definition for more details, including what I/O actions are associated with each handle + /// type. + is-ready: func() -> bool; + + /// Create a new trivial `pollable` which reports being immediately ready. + new-ready: static func() -> pollable; + } + + /// Blocks until one of the given objects is ready for I/O. + /// + /// If an object is ready, the I/O action is guaranteed to complete without blocking. + /// + /// Valid object handles includes bodies and pending requests. See the `async-io.pollable` + /// definition for more details, including what I/O actions are associated with each handle + /// type. + /// + /// Returns the *index* (not handle!) of the first object that is ready. + /// + /// Traps if the list is empty. + select: func(handles: list>) -> u32; + + /// Blocks until one of the given objects is ready for I/O, or the timeout expires. + /// + /// If an object is ready, the I/O action is guaranteed to complete without blocking. + /// + /// Valid object handles includes bodies and pending requests. See the `async-io.pollable` + /// definition for more details, including what I/O actions are associated with each handle + /// type. + /// + /// The timeout is specified in milliseconds. + /// + /// Returns the *index* (not handle!) of the first object that is ready, or `none` if the + /// timeout expires before any objects are ready for I/O. + select-with-timeout: func(handles: list>, timeout-ms: u32) -> option; +} + +/// [Cache Purging] API. +/// +/// [Cache Purging]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/ +interface purge { + + use types.{error}; + + record purge-options { + /// Perform a [soft purge] instead of a hard purge. + /// + /// [soft purge]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#soft-vs-hard-purging + soft-purge: bool, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `purge-options` + resource extra-purge-options {} + + /// Purge a surrogate key for the current service. + /// + /// A surrogate key can be a max of 1024 characters. + /// A surrogate key must contain only printable ASCII characters (those between `0x21` and `0x7E`, + /// inclusive). + /// + /// Returns a [JSON purge response]. + /// + /// [JSON purge response]: https://developer.fastly.com/reference/api/purging/#purge-tag + purge-surrogate-key: func( + surrogate-keys: string, + purge-options: purge-options, + ) -> result<_, error>; + + /// Purge a surrogate key for the current service, and return the purge id. + /// + /// This is similar to `purge-surrogate-key`, but on success, returns an + /// ASCII alphanumeric string identifying a purging. + purge-surrogate-key-verbose: func( + surrogate-keys: string, + purge-options: purge-options, + max-len: u64, + ) -> result; +} + +/// [Core Cache] API +/// +/// [Core Cache]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#core-cache +interface cache { + + use types.{error}; + use http-body.{body}; + use http-req.{request}; + + /// The outcome of a cache lookup (either bare or as part of a cache transaction) + resource entry { + /// Performs a non-request-collapsing cache lookup. + /// + /// Returns a result without waiting for any request collapsing that may be ongoing. + lookup: static func( + key: list, + options: lookup-options, + ) -> result; + + /// The entrypoint to the request-collapsing cache transaction API. + /// + /// This operation always participates in request collapsing and may return stale objects. To + /// bypass request collapsing, use `lookup` and `insert` instead. + transaction-lookup: static func( + key: list, + options: lookup-options, + ) -> result; + + /// The entrypoint to the request-collapsing cache transaction API, returning instead of waiting + /// on busy. + /// + /// This operation always participates in request collapsing and may return stale objects. To + /// bypass request collapsing, use `lookup` and `insert` instead. + transaction-lookup-async: static func( + key: list, + options: lookup-options, + ) -> result; + + /// Insert an object into the cache with the given metadata. + /// + /// Can only be used in if the cache handle state includes the `must-insert-or-update` flag. + /// + /// The returned handle is to a streaming body that is used for writing the object into + /// the cache. + transaction-insert: func( + options: write-options, + ) -> result; + + /// Insert an object into the cache with the given metadata, and return a readable stream of the + /// bytes as they are stored. + /// + /// This helps avoid the “slow reader” problem on a teed stream, for example when a program + /// wishes to store a backend request in the cache while simultaneously streaming to a client + /// in an HTTP response. + /// + /// The returned body handle is to a streaming body that is used for writing the object *into* + /// the cache. The returned cache handle provides a separate transaction for reading out the + /// newly cached object to send elsewhere. + transaction-insert-and-stream-back: func( + options: write-options, + ) -> result, error>; + + /// Update the metadata of an object in the cache without changing its data. + /// + /// Can only be used in if the cache handle state includes both of the flags: + /// - `found` + /// - `must-insert-or-update` + transaction-update: func( + options: write-options, + ) -> result<_, error>; + + get-state: func() -> result; + + /// Gets the user metadata of the found object, returning `ok(none)` if no object + /// was found. + get-user-metadata: func(max-len: u64) -> result>, error>; + + /// Gets a range of the found object body, returning `ok(none)` if there + /// was no found object. + /// + /// The returned `body` must be closed before calling this function again on the same + /// `entry`. + /// + /// Note: until the CacheD protocol is adjusted to fully support this functionality, + /// the body of objects that are past the stale-while-revalidate period will not + /// be available, even when other metadata is. + get-body: func( + options: get-body-options, + ) -> result; + + /// Gets the content length of the found object, returning `ok(none)` if + /// there was no found object, or no content length was provided. + get-length: func() -> result, error>; + + /// Gets the configured max age of the found object, returning `ok(none)` + /// if there was no found object. + get-max-age-ns: func() -> result, error>; + + /// Gets the configured stale-while-revalidate period of the found object, returning `ok(none)` + /// if there was no found object. + get-stale-while-revalidate-ns: func() -> result, error>; + + /// Gets the age of the found object, returning `ok(none)` if there + /// was no found object. + get-age-ns: func() -> result, error>; + + /// Gets the number of cache hits for the found object, returning `ok(none)` + /// if there was no found object. + get-hits: func() -> result, error>; + + /// Cancel an obligation to provide an object to the cache. + /// + /// Useful if there is an error before streaming is possible, for example if a backend is + /// unreachable. + transaction-cancel: func() -> result<_, error>; + } + /// Handle that can be used to check whether or not a cache lookup is waiting on another client. + use async-io.{pollable as pending-entry}; + + /// A replace operation. + type replace-entry = entry; + + /// The entrypoint to the replace API. + /// + /// This operation always participates in request collapsing and may return stale objects. + replace: func( + key: list, + options: replace-options, + ) -> result; + + /// Replace an object in the cache with the given metadata + /// + /// The returned handle is to a streaming body that is used for writing the object into + /// the cache. + replace-insert: func( + handle: borrow, + options: write-options, + ) -> result; + + /// Gets the age of the existing object during replace, returning + /// `ok(none)` if there was no object. + replace-get-age-ns: func( + handle: borrow, + ) -> result, error>; + + /// Gets a range of the existing object body, returning `ok(none)` if there + /// was no existing object. + /// + /// The returned `body` must be closed before calling this function + /// again on the same `replace-entry`. + replace-get-body: func( + handle: borrow, + options: get-body-options, + ) -> result, error>; + + /// Gets the number of cache hits for the existing object during replace, + /// returning `ok(none)` if there was no object. + replace-get-hits: func( + handle: borrow, + ) -> result, error>; + + /// Gets the content length of the existing object during replace, + /// returning `ok(none)` if there was no object, or no content + /// length was provided. + replace-get-length: func( + handle: borrow, + ) -> result, error>; + + /// Gets the configured max age of the existing object during replace, + /// returning `ok(none)` if there was no object. + replace-get-max-age-ns: func( + handle: borrow, + ) -> result, error>; + + /// Gets the configured stale-while-revalidate period of the existing + /// object during replace, returning `ok(none)` if there was no + /// object. + replace-get-stale-while-revalidate-ns: func( + handle: borrow, + ) -> result, error>; + + /// Gets the lookup state of the existing object during replace, returning + /// `ok(none)` if there was no object. + replace-get-state: func( + handle: borrow, + ) -> result, error>; + + /// Gets the user metadata of the existing object during replace, returning + /// `ok(none)` if there was no object. + replace-get-user-metadata: func( + handle: borrow, + max-len: u64, + ) -> result>, error>; + + type object-length = u64; + type duration-ns = u64; + type cache-hit-count = u64; + + /// Options for cache lookup operations; currently used for both `lookup` and + /// `transaction-lookup`. + record lookup-options { + /// A full request handle, but used only for its headers + /// + /// May be `none` if the `request-headers` option isn't enabled. + /// + request-headers: option>, + + service-id: option, + + always-use-requested-range: bool, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `lookup-options` + resource extra-lookup-options {} + + /// Configuration for several functions that write to the cache: + /// - `insert` + /// - `transaction-insert` + /// - `transaction-insert-and-stream-back` + /// - `transaction-update` + /// + /// Some options are only allowed for certain of these hostcalls; see the comments + /// on the fields. + record write-options { + /// this is a required field + max-age-ns: duration-ns, + /// a full request handle, but used only for its headers + /// + /// Only allowed for non-transactional `insert` + request-headers: option>, + /// a list of header names separated by spaces + vary-rule: option, + /// The initial age of the object in nanoseconds (default: 0). + /// + /// This age is used to determine the freshness lifetime of the object as well as to + /// prioritize which variant to return if a subsequent lookup matches more than one vary rule + initial-age-ns: option, + stale-while-revalidate-ns: option, + /// a list of surrogate keys separated by spaces + surrogate-keys: option, + length: option, + user-metadata: option>, + edge-max-age-ns: option, + service-id: option, + sensitive-data: bool, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `write-options` + resource extra-write-options {} + + record get-body-options { + %from: option, + to: option, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `get-body-options` + resource extra-get-body-options {} + + /// The status of this lookup (and potential transaction) + flags lookup-state { + /// a cached object was found + found, + /// the cached object is valid to use (implies found) + usable, + /// the cached object is stale (but may or may not be valid to use) + stale, + /// this client is requested to insert or revalidate an object + must-insert-or-update, + } + + /// Performs a non-request-collapsing cache insertion (or update). + /// + /// The returned handle is to a streaming body that is used for writing the object into + /// the cache. + insert: func( + key: list, + options: write-options, + ) -> result; + + /// Continues the lookup transaction from which the given busy handle was returned, + /// waiting for the leader transaction if request collapsed, and returns a cache handle. + await-entry: func( + handle: pending-entry, + ) -> result; + + /// Closes an interaction with the cache that has not yet finished request collapsing. + close-pending-entry: func(handle: pending-entry) -> result<_, error>; + + /// Closes an ongoing interaction with the cache. + /// + /// If the cache handle state includes the `must-insert-or-update` (and hence no insert or + /// update has been performed), closing the handle cancels any request collapsing, potentially + /// choosing a new waiter to perform the insertion/update. + /// + /// This may be passed either an `entry` or a `replace-entry`. + close-entry: func(handle: entry) -> result<_, error>; + + /// Options for cache replace operations + record replace-options { + /// a full request handle, but used only for its headers + request-headers: option>, + replace-strategy: option, + service-id: option, + always-use-requested-range: bool, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `replace-options` + resource extra-replace-options {} + + enum replace-strategy { + /// Immediately start the replace and do not wait for any other pending requests for the same + /// object, including insert requests. + /// + /// With this strategy a replace will race all other pending requests to update the object. + /// + /// The existing object will be accessible until this replace finishes providing the replacement + /// object. + /// + /// This is the default replace strategy. + immediate, + + /// Immediate, but remove the existing object immediately + /// + /// Requests for the same object that arrive after this replace starts will wait until this + /// replace starts providing the replacement object. + immediate-force-miss, + + /// Join the wait list behind other pending requests before starting this request. + /// + /// With this strategy this replace request will wait for an in-progress replace or insert + /// request before starting. + /// + /// This strategy allows implementing a counter, but may cause timeouts if too many requests + /// are waiting for in-progress and waiting updates to complete. + wait, + } +} + +/// [HTTP Cache] API. +/// +/// Overall, this should look very familiar to users of the Core Cache API. The primary differences +/// are: +/// +/// - HTTP `request`s and `response`s are used rather than relying on the user to +/// encode headers, status codes, etc in `user-metadata`. +/// +/// - Convenience functions specific to HTTP semantics are provided, such as `is-request-cacheable`, +/// `get-suggested-backend-request`, `get-suggested-write-options`, and +/// `transaction-record-not-cacheable`. +/// +/// The HTTP-specific behavior of these functions is intended to support applications that match the +/// normative guidance in [RFC 9111]. For example, `is-request-cacheable` returns `false` for `POST` +/// requests. However, this answer along with those of many of these functions explicitly provide +/// *suggestions*; they do not necessarily need to be followed if custom behavior is required, such +/// as caching `POST` responses when the application author knows that to be safe. +/// +/// The starting points for this API are `lookup` (no request collapsing) and `transaction-lookup` +/// (request collapsing). +/// +/// [HTTP Cache]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/cache-freshness/ +/// [RFC 9111]: https://www.rfc-editor.org/rfc/rfc9111.html +interface http-cache { + use types.{error}; + use http-body.{body}; + use http-req.{request}; + use http-resp.{response, response-with-body}; + use cache.{lookup-state, object-length, duration-ns, cache-hit-count}; + + /// An HTTP Cache transaction. + resource entry { + /// (DEPRECATED) Use transaction-lookup + lookup: static func( + req-handle: borrow, + options: lookup-options, + ) -> result; + + /// Performs a cache lookup based on the given request. + /// + /// This operation always participates in request collapsing and may return an obligation to + /// insert or update responses, and/or stale responses. To bypass request collapsing, use + /// `lookup` instead. + /// + /// The request is not consumed. + transaction-lookup: static func( + req-handle: borrow, + options: lookup-options, + ) -> result; + + /// Inserts a response into the cache with the given options, returning a streaming body handle + /// that is ready for writing or appending. + /// + /// Can only be used if the cache handle state includes the `must-insert-or-update` flag. + /// + /// The response is consumed. + transaction-insert: func( + resp-handle: response, + options: write-options, + ) -> result; + + /// Inserts a response into the cache with the given options, and return a fresh cache handle + /// that can be used to retrieve and stream the response while it's being inserted. + /// + /// This helps avoid the “slow reader” problem on a teed stream, for example when a program + /// wishes to store a backend request in the cache while simultaneously streaming to a client + /// in an HTTP response. + /// + /// The response is consumed. + transaction-insert-and-stream-back: func( + resp-handle: response, + options: write-options, + ) -> result, error>; + + /// Updates freshness lifetime, response headers, and caching settings without updating the + /// response body. + /// + /// Can only be used in if the cache handle state includes both of the flags: + /// - `found` + /// - `must-insert-or-update` + /// + /// The response is consumed. + transaction-update: func( + resp-handle: response, + options: write-options, + ) -> result<_, error>; + + /// Updates freshness lifetime, response headers, and caching settings without updating the + /// response body, and return a fresh cache handle that can be used to retrieve and stream the + /// stored response. + /// + /// Can only be used in if the cache handle state includes both of the flags: + /// - `found` + /// - `must-insert-or-update` + /// + /// The response is consumed. + transaction-update-and-return-fresh: func( + resp-handle: response, + options: write-options, + ) -> result; + + /// Disables request collapsing and response caching for this cache entry. + /// + /// In Varnish terms, this function stores a hit-for-pass object. + /// + /// Only the max age and, optionally, the vary rule are read from the `options` + /// for this function. + transaction-record-not-cacheable: func( + options: write-options, + ) -> result<_, error>; + + /// Prepares a suggested request to make to a backend to satisfy the looked-up request. + /// + /// If there is a stored, stale response, this suggested request may be for revalidation. If the + /// looked-up request is ranged, the suggested request will be unranged in order to try caching + /// the entire response. + get-suggested-backend-request: func() -> result; + + /// Prepares a suggested set of cache write options for a given request and response pair. + /// + /// The response is not consumed. + get-suggested-write-options: func( + response: borrow, + ) -> result; + + /// Adjusts a response into the appropriate form for storage and provides a storage action + /// recommendation. + /// + /// For example, if the looked-up request contains conditional headers, this function will + /// interpret a `304 Not Modified` response for revalidation by updating headers. + /// + /// In addition to the updated response, this function returns the recommended storage action. + prepare-response-for-storage: func( + response: borrow, + ) -> result, error>; + + /// Retrieves a stored response from the cache, returning `ok(none)` if + /// there was no response found. + /// + /// If `transform-for-client` is set, the response will be adjusted according to the looked-up + /// request. For example, a response retrieved for a range request may be transformed into a + /// `206 Partial Content` response with an appropriate `content-range` header. + get-found-response: func( + transform-for-client: u32, + ) -> result, error>; + + /// Gets the state of a cache transaction. + /// + /// Primarily useful after performing the lookup to determine what subsequent operations are + /// possible and whether any insertion or update obligations exist. + get-state: func( + ) -> result; + + /// Gets the length of the found response, returning `ok(none)` if there + /// was no response found or no length was provided. + get-length: func() -> result, error>; + + /// Gets the configured max age of the found response in nanoseconds, returning `ok(none)` + /// if there was no response found. + get-max-age-ns: func() -> result, error>; + + /// Gets the configured stale-while-revalidate period of the found response in nanoseconds, + /// returning `ok(none)` if there was no response found. + get-stale-while-revalidate-ns: func( + ) -> result, error>; + + /// Gets the age of the found response in nanoseconds, returning `ok(none)` + /// if there was no response found. + get-age-ns: func() -> result, error>; + + /// Gets the number of cache hits for the found response, returning `ok(none)` + /// if there was no response found. + /// + /// This figure only reflects hits for a stored response in a particular cache server + /// or cluster, not the entire Fastly network. + get-hits: func() -> result, error>; + + /// Gets whether a found response is marked as containing sensitive data, returning `ok(none)` + /// if there was no response found. + get-sensitive-data: func() -> result, error>; + + /// Gets the surrogate keys of the found response, returning `ok(none)` if + /// there was no response found. + /// + /// The output is a list of surrogate keys separated by spaces. + /// + /// If the full list requires more than `max-len` bytes, an `error.buffer-len` + /// error is returned containing the required size. + get-surrogate-keys: func( + max-len: u64, + ) -> result, error>; + + /// Gets the vary rule of the found response, returning `ok(none)` if there + /// was no response found. + /// + /// The output is a list of header names separated by spaces. + /// + /// If the full list requires more than `max-len` bytes, an `error.buffer-len` + /// error is returned containing the required size. + get-vary-rule: func( + max-len: u64, + ) -> result, error>; + + /// Abandons an obligation to provide a response to the cache. + /// + /// Useful if there is an error before streaming is possible, for example if a backend is + /// unreachable. + /// + /// If there are other requests collapsed on this transaction, one of those other requests will + /// be awoken and given the obligation to provide a response. If subsequent requests + /// are unlikely to yield cacheable responses, this may lead to undesired serialization of + /// requests. Consider using `transaction-record-not-cacheable` to make lookups for this request + /// bypass the cache. + transaction-abandon: func() -> result<_, error>; + } + + /// The suggested action to take for spec-recommended behavior following + /// `prepare-response-for-storage`. + enum storage-action { + /// Insert the response into cache (for `transaction-insert` and + /// `transaction-insert-and-stream-back`). + insert, + /// Update the stale response in cache (for `transaction-update` and + /// `transaction-update-and-return-fresh`). + update, + /// Do not store this response. + do-not-store, + /// Do not store this response, and furthermore record its non-cacheability for other pending + /// requests (`transaction-record-not-cacheable`). + record-uncacheable, + } + + /// Non-required options for cache lookups. + record lookup-options { + /// Cache key to use in lieu of the automatically-generated cache key based on the request's + /// properties. + override-key: option>, + /// Backend name that will be used for the eventual request. + backend-name: option, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `lookup-options` + resource extra-lookup-options {} + + /// Options for cache insertions and updates. + record write-options { + /// The maximum age of the response before it is considered stale, in nanoseconds. + /// + /// This field is required. + max-age-ns: duration-ns, + + /// A list of header names to use when calculating variants for this response. + /// + /// The format is a string containing header names separated by spaces. + vary-rule: option, + + /// The initial age of the response in nanoseconds. + /// + /// If this field is not set, the default value is zero. + /// + /// This age is used to determine the freshness lifetime of the response as well as to + /// prioritize which variant to return if a subsequent lookup matches more than one vary rule + initial-age-ns: option, + + /// The maximum duration after `max-age` during which the response may be delivered stale + /// while being revalidated, in nanoseconds. + /// + /// If this field is not set, the default value is zero. + stale-while-revalidate-ns: option, + + /// A list of surrogate keys that may be used to purge this response. + /// + /// The format is a string containing [valid surrogate keys] separated by spaces. + /// + /// If this field is not set, no surrogate keys will be associated with the response. This + /// means that the response cannot be purged except via a purge-all operation. + /// + /// [valid surrogate keys]: https://www.fastly.com/documentation/reference/http/http-headers/Surrogate-Key/ + surrogate-keys: option, + + /// The length of the response body. + /// + /// If this field is not set, the length of the body is treated as unknown. + /// + /// When possible, this field should be set so that other clients waiting to retrieve the + /// body have enough information to synthesize a `content-length` even before the complete + /// body is inserted to the cache. + length: option, + + /// Enable or disable PCI/HIPAA-compliant non-volatile caching. + /// + /// See the [Fastly PCI-Compliant Caching and Delivery documentation] for details. + /// + /// [Fastly PCI-Compliant Caching and Delivery documentation]: https://docs.fastly.com/products/pci-compliant-caching-and-delivery + sensitive-data: bool, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `write-options` + resource extra-write-options {} + + /// Determines whether a request is cacheable per conservative [RFC 9111] semantics. + /// + /// In particular, this function checks whether the request method is `GET` or `HEAD`, and + /// considers requests with other methods uncacheable. Applications where it is safe to cache + /// responses to other methods should consider using their own cacheability check instead of + /// this function. + /// + /// [RFC 9111]: https://www.rfc-editor.org/rfc/rfc9111.html + is-request-cacheable: func(request: borrow) -> result; + + /// Retrieves the default cache key for the request. + /// + /// If the full key requires more than `max-len` bytes, an `error.buffer-len` + /// error is returned containing the required size. + /// + /// At the moment, HTTP cache keys must always be 32 bytes. + get-suggested-cache-key: func( + request: borrow, + max-len: u64, + ) -> result, error>; + + /// Closes an ongoing interaction with the cache. + /// + /// If the cache handle state includes `must-insert-or-update` (and hence no insert or update + /// has been performed), closing the handle cancels any request collapsing, potentially choosing + /// a new waiter to perform the insertion/update. + close-entry: func( + handle: entry, + ) -> result<_, error>; + + /// The methods in this resource return values that correspond to the fields in a + /// `write-options`. This type is used when a `write-options` value would + /// be returned, so that it can use `max-len` parameters when returning + /// dynamically-sized data, and so that it excludes the `extra` field, since borrowed + /// handles cannot be returned from functions. + resource suggested-write-options { + /// Returns the suggested value for the `write-options.max-age-ns` field. + get-max-age-ns: func() -> duration-ns; + /// Returns the suggested value for the `write-options.vary-rule` field. + get-vary-rule: func(max-len: u64) -> result; + /// Returns the suggested value for the `write-options.initial-age-ns` field. + get-initial-age-ns: func() -> duration-ns; + /// Returns the suggested value for the `write-options.stale-while-revalidate-ns` field. + get-stale-while-revalidate-ns: func() -> duration-ns; + /// Returns the suggested value for the `write-options.surrogate-keys` field. + get-surrogate-keys: func(max-len: u64) -> result; + /// Returns the suggested value for the `write-options.length` field. + get-length: func() -> option; + /// Returns the suggested value for the `write-options.sensitive-data` field. + get-sensitive-data: func() -> bool; + } +} + +/// [Config Store] API. +/// +/// [Config Store]: https://www.fastly.com/documentation/guides/concepts/edge-state/dynamic-config/#config-stores +interface config-store { + use types.{error}; + + /// A Config Store. + resource store { + /// Attempts to open the named config store. + /// + /// Names are case sensitive. + open: static func(name: string) -> result; + + /// Fetches a value from the config store, returning `ok(none)` if it doesn't exist. + get: func( + key: string, + max-len: u64, + ) -> result, error>; + } +} + +/// [Shielding] API. +/// +/// [Shielding]: https://www.fastly.com/documentation/guides/concepts/shielding/ +interface shielding { + use types.{error}; + + shield-info: func( + name: string, + max-len: u64, + ) -> result; + + record shield-backend-options { + cache-key: option, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `shield-backend-options` + resource extra-shield-backend-options {} + + backend-for-shield: func( + name: string, + options: shield-backend-options, + max-len: u64, + ) -> result; +} + +/// [Image Optimizer] API. +/// +/// [Image Optimizer]: https://www.fastly.com/documentation/guides/full-site-delivery/image-optimization/about-fastly-image-optimizer/ +interface image-optimizer { + + use http-body.{body}; + use http-req.{request}; + use http-resp.{response-with-body}; + use types.{error}; + + record image-optimizer-transform-options { + /// Contains any Image Optimizer API parameters that were set + /// as well as the Image Optimizer region the request is meant for. + sdk-claims-opts: option, + + /// Additional options may be added in the future via this resource type. + extra: option>, + } + + /// Extensibility for `image-optimizer-transform-options` + resource extra-image-optimizer-transform-options {} + + transform-image-optimizer-request: func( + origin-image-request: borrow, + origin-image-request-body: option, + origin-image-request-backend: string, + io-transform-options: image-optimizer-transform-options, + ) -> result; +} + +/// The exported interface. +/// +/// The `handle` function serves as the main entrypoint to applications. Unlike the +/// rest of the interfaces in this package, this `http-incoming` interface is exported by +/// applications rather than imported, which means that this is a function defined +/// by the application and called from the outside, rather than a function called +/// by the application into the outside. +interface http-incoming { + use http-body.{body}; + use http-req.{request}; + + /// Handle the given request. + /// + /// Conceptually, `send` returns a response to the given request, however this isn't + /// modeled as a literal return value in this API. Instead, the `send-downstream` + /// function is used to send the response. This allows for the option of streaming the + /// response body, since that requires the program to continue executing after the + /// response has been initiated. + handle: func(request: request, body: body) -> result; +} + +/// Features for interacting with the Compute runtime. +interface compute-runtime { + /// A timestamp in milliseconds. + type vcpu-ms = u64; + + /// Gets the amount of vCPU time that has passed since this session was started, in milliseconds. + /// + /// This function returns only time spent running on a vCPU, and does not include time spent + /// performing any I/O operations. However, it is based on clock time passing, and so will include + /// time spent executing hostcalls, is heavily affected by what core of what CPU is running the + /// code, and can even be influenced by the state of the CPU. + /// + /// As a result, this function *should not be used in benchmarking across runs*. It can be used, + /// with caution, to compare the runtime of different operations within the same session. + get-vcpu-ms: func() -> vcpu-ms; + + /// A UUID generated by Fastly for each session. + /// + /// This is often a useful value to include in log messages, and also to send to upstream + /// servers as an additional custom HTTP header, allowing for straightforward correlation of + /// which WebAssembly session processed a request to requests later processed by an origin + /// server. If a session is used to process multiple downstream requests, then you may wish to + /// use the per-request UUID associated with each individual request handle instead of this + /// field. + /// + /// Equivalent to the "FASTLY_TRACE_ID" environment variable. + get-session-id: func() -> string; + + /// The hostname of the Fastly cache server which is executing the current session, for + /// example, `cache-jfk1034`. + /// + /// Equivalent to the "FASTLY_HOSTNAME" environment variable and to [`server.hostname`] in VCL. + /// + /// [`server.hostname`]: https://www.fastly.com/documentation/reference/vcl/variables/server/server-hostname/ + get-hostname: func() -> string; + + /// The three-character identifying code of the [Fastly POP] in which the current session is + /// running. + /// + /// Equivalent to the "FASTLY_POP" environment variable and to [`server.datacenter`] in VCL. + /// + /// [Fastly POP]: https://www.fastly.com/documentation/guides/concepts/pop/ + /// [`server.datacenter`]: https://www.fastly.com/documentation/reference/vcl/variables/server/server-datacenter/ + get-pop: func() -> string; + + /// A code representing the general geographic region in which the [Fastly POP] processing the + /// current Compute session resides. + /// + /// Equivalent to the "FASTLY_REGION" environment variable and to [`server.region`] in VCL, and + /// has the same possible values. + /// + /// [`server.region`]: https://www.fastly.com/documentation/reference/vcl/variables/server/server-region/ + /// [Fastly POP]: https://www.fastly.com/documentation/guides/concepts/pop/ + get-region: func() -> string; + + /// The current cache generation value for this Fastly service. + /// + /// The cache generation value is incremented by [purge-all operations]. + /// + /// Equivalent to the "FASTLY_CACHE_GENERATION" environment variable and to + /// [`req.vcl.generation`] in VCL. + /// + /// [purge-all operations]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/ + /// [`req.vcl.generation`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-vcl-generation/ + get-cache-generation: func() -> u64; + + /// The customer ID of the Fastly customer account to which the currently executing Fastly + /// service belongs. + /// + /// Equivalent to the "FASTLY_CUSTOMER_ID" environment variable and to [`req.customer_id`] in VCL. + /// + /// [`req.customer_id`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-customer-id/ + get-customer-id: func() -> string; + + /// Whether the request is running in the Fastly service's [staging environment]. + /// + /// `false` for production or `true` for staging. + /// + /// Equivalent to the "FASTLY_IS_STAGING" environment variable and to [`fastly.is_staging`] in VCL. + /// + /// [`fastly.is_staging`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/fastly-is-staging/ + /// [staging environment]: https://docs.fastly.com/products/staging + get-is-staging: func() -> bool; + + /// The identifier for the Fastly service that is processing the current request. + /// + /// Equivalent to the "FASTLY_SERVICE_ID" environment variable and to [`req.service_id`] in VCL. + /// + /// [`req.service_id`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-service-id/ + get-service-id: func() -> string; + + /// The version number for the Fastly service that is processing the current request. + /// + /// Equivalent to the "FASTLY_SERVICE_VERSION" environment variable and to [`req.vcl.version`] + /// in VCL. + /// + /// [`req.vcl.version`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-vcl-version/ + get-service-version: func() -> u64; + + /// This function is not suitable for general-purpose use. + get-namespace-id: func() -> string; +} + +/// Interfaces that a Fastly Compute service may import. +/// +/// This contains the imports used in the `service` world, factored out into a +/// separate world so that it can be used by library components. Library components +/// are components that do not export anything themselves. +world service-imports { + import wasi:clocks/wall-clock@0.2.6; + import wasi:clocks/monotonic-clock@0.2.6; + import wasi:io/error@0.2.6; + import wasi:io/streams@0.2.6; + import wasi:random/random@0.2.6; + import wasi:cli/environment@0.2.6; + import wasi:cli/exit@0.2.6; + import wasi:cli/stdout@0.2.6; + import wasi:cli/stderr@0.2.6; + import wasi:cli/stdin@0.2.6; + + import acl; + import async-io; + import backend; + import cache; + import compute-runtime; + import config-store; + import dictionary; + import geo; + import device-detection; + import erl; + import http-body; + import http-cache; + import http-downstream; + import http-req; + import http-resp; + import image-optimizer; + import log; + import kv-store; + import purge; + import secret-store; + import shielding; +} + +/// A Fastly Compute service. +/// +/// This defines the set of interfaces available to, and expected of, +/// Fastly Compute service applications. +/// +/// This `service` world includes all the `service-imports` imports, and adds the +/// `http-incoming` exports. +world service { + include service-imports; + + // Export the `http-incoming` interface. + export http-incoming; +} diff --git a/wit/deps/filesystem/preopens.wit b/wit/deps/filesystem/preopens.wit new file mode 100644 index 0000000..f228479 --- /dev/null +++ b/wit/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.2.6; + +@since(version = 0.2.0) +interface preopens { + @since(version = 0.2.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.2.0) + get-directories: func() -> list>; +} diff --git a/wit/deps/filesystem/types.wit b/wit/deps/filesystem/types.wit new file mode 100644 index 0000000..75c1904 --- /dev/null +++ b/wit/deps/filesystem/types.wit @@ -0,0 +1,676 @@ +package wasi:filesystem@0.2.6; +/// 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 +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:io/streams@0.2.6.{input-stream, output-stream, error}; + @since(version = 0.2.0) + use wasi:clocks/wall-clock@0.2.6.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.2.0) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 integrity + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 POSIX. + @since(version = 0.2.0) + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + /// + /// Fails with `error-code::no-entry` if the old path does not exist, + /// with `error-code::exist` if the new path already exists, and + /// `error-code::not-permitted` if the old path is not a file. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.2.0) + 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. + /// + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 encouraged 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/wit/deps/filesystem/world.wit b/wit/deps/filesystem/world.wit new file mode 100644 index 0000000..65597f9 --- /dev/null +++ b/wit/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.2.6; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/wit/deps/http/handler.wit b/wit/deps/http/handler.wit new file mode 100644 index 0000000..6a6c629 --- /dev/null +++ b/wit/deps/http/handler.wit @@ -0,0 +1,49 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +@since(version = 0.2.0) +interface incoming-handler { + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. +@since(version = 0.2.0) +interface outgoing-handler { + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/wit/deps/http/proxy.wit b/wit/deps/http/proxy.wit new file mode 100644 index 0000000..5bd9f99 --- /dev/null +++ b/wit/deps/http/proxy.wit @@ -0,0 +1,50 @@ +package wasi:http@0.2.6; + +/// The `wasi:http/imports` world imports all the APIs for HTTP proxies. +/// It is intended to be `include`d in other worlds. +@since(version = 0.2.0) +world imports { + /// HTTP proxies have access to time and randomness. + @since(version = 0.2.0) + import wasi:clocks/monotonic-clock@0.2.6; + @since(version = 0.2.0) + import wasi:clocks/wall-clock@0.2.6; + @since(version = 0.2.0) + import wasi:random/random@0.2.6; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + @since(version = 0.2.0) + import wasi:cli/stdout@0.2.6; + @since(version = 0.2.0) + import wasi:cli/stderr@0.2.6; + + /// 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. + @since(version = 0.2.0) + import wasi:cli/stdin@0.2.6; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + @since(version = 0.2.0) + import outgoing-handler; +} + +/// 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. +@since(version = 0.2.0) +world proxy { + @since(version = 0.2.0) + include imports; + + /// 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`. + @since(version = 0.2.0) + export incoming-handler; +} diff --git a/wit/deps/http/types.wit b/wit/deps/http/types.wit new file mode 100644 index 0000000..c9f3cc4 --- /dev/null +++ b/wit/deps/http/types.wit @@ -0,0 +1,688 @@ +/// 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. +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.6.{duration}; + @since(version = 0.2.0) + use wasi:io/streams@0.2.6.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/error@0.2.6.{error as io-error}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.6.{pollable}; + + /// This type corresponds to HTTP standard Methods. + @since(version = 0.2.0) + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + @since(version = 0.2.0) + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + @since(version = 0.2.0) + 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: + @since(version = 0.2.0) + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + @since(version = 0.2.0) + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + variant header-error { + /// This error indicates that a `field-name` 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-name` 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 names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + @since(version = 0.2.1) + type field-name = field-key; + + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + @since(version = 0.2.0) + @deprecated(version = 0.2.2) + 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. + @since(version = 0.2.0) + 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 + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + @since(version = 0.2.0) + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + @since(version = 0.2.0) + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + @since(version = 0.2.0) + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + @since(version = 0.2.0) + get: func(name: field-name) -> list; + + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + @since(version = 0.2.0) + has: func(name: field-name) -> bool; + + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + @since(version = 0.2.0) + set: func(name: field-name, value: list) -> result<_, header-error>; + + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + @since(version = 0.2.0) + delete: func(name: field-name) -> result<_, header-error>; + + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + @since(version = 0.2.0) + append: func(name: field-name, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + @since(version = 0.2.0) + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + @since(version = 0.2.0) + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + @since(version = 0.2.0) + type headers = fields; + + /// Trailers is an alias for Fields. + @since(version = 0.2.0) + type trailers = fields; + + /// Represents an incoming HTTP Request. + @since(version = 0.2.0) + resource incoming-request { + + /// Returns the method of the incoming request. + @since(version = 0.2.0) + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + @since(version = 0.2.0) + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + @since(version = 0.2.0) + scheme: func() -> option; + + /// Returns the authority of the Request's target URI, if present. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + body: func() -> result; + + /// Get the Method for the Request. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + set-scheme: func(scheme: option) -> result; + + /// Get the authority of the Request's target URI. 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. + @since(version = 0.2.0) + authority: func() -> option; + /// Set the authority of the Request's target URI. 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. + @since(version = 0.2.0) + 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 transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + resource request-options { + /// Construct a default `request-options` value. + @since(version = 0.2.0) + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + resource response-outparam { + /// Send an HTTP 1xx response. + /// + /// Unlike `response-outparam.set`, this does not consume the + /// `response-outparam`, allowing the guest to send an arbitrary number of + /// informational responses before sending the final response using + /// `response-outparam.set`. + /// + /// This will return an `HTTP-protocol-error` if `status` is not in the + /// range [100-199], or an `internal-error` if the implementation does not + /// support informational responses. + @unstable(feature = informational-outbound-responses) + send-informational: func( + status: u16, + headers: headers + ) -> result<_, error-code>; + + /// 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. + @since(version = 0.2.0) + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + @since(version = 0.2.0) + type status-code = u16; + + /// Represents an incoming HTTP Response. + @since(version = 0.2.0) + resource incoming-response { + + /// Returns the status code from the incoming response. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + %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. + @since(version = 0.2.0) + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventually 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. + @since(version = 0.2.0) + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occurred, + /// 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 occurred 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. + @since(version = 0.2.0) + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 occurred. The implementation should propagate 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventually 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. + @since(version = 0.2.0) + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + 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 received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + @since(version = 0.2.0) + get: func() -> option>>; + } +} diff --git a/wit/deps/io/error.wit b/wit/deps/io/error.wit new file mode 100644 index 0000000..784f74a --- /dev/null +++ b/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.6; + +@since(version = 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 + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/wit/deps/io/poll.wit b/wit/deps/io/poll.wit new file mode 100644 index 0000000..7f71183 --- /dev/null +++ b/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.6; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// 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 ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/wit/deps/io/streams.wit b/wit/deps/io/streams.wit new file mode 100644 index 0000000..c5da38c --- /dev/null +++ b/wit/deps/io/streams.wit @@ -0,0 +1,290 @@ +package wasi:io@0.2.6; + +/// 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. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 + /// ``` + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + 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 occurred. 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 + /// ``` + @since(version = 0.2.0) + 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 equivalent 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`. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/wit/deps/io/world.wit b/wit/deps/io/world.wit new file mode 100644 index 0000000..84c85c0 --- /dev/null +++ b/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.6; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/wit/deps/random/insecure-seed.wit b/wit/deps/random/insecure-seed.wit new file mode 100644 index 0000000..d3dc03a --- /dev/null +++ b/wit/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.2.6; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + insecure-seed: func() -> tuple; +} diff --git a/wit/deps/random/insecure.wit b/wit/deps/random/insecure.wit new file mode 100644 index 0000000..d4d0284 --- /dev/null +++ b/wit/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.6; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-insecure-random-u64: func() -> u64; +} diff --git a/wit/deps/random/random.wit b/wit/deps/random/random.wit new file mode 100644 index 0000000..a0ff956 --- /dev/null +++ b/wit/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.2.6; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +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. + @since(version = 0.2.0) + 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`. + @since(version = 0.2.0) + get-random-u64: func() -> u64; +} diff --git a/wit/deps/random/world.wit b/wit/deps/random/world.wit new file mode 100644 index 0000000..099f47b --- /dev/null +++ b/wit/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.2.6; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import random; + + @since(version = 0.2.0) + import insecure; + + @since(version = 0.2.0) + import insecure-seed; +} diff --git a/wit/deps/sockets/instance-network.wit b/wit/deps/sockets/instance-network.wit new file mode 100644 index 0000000..5f6e6c1 --- /dev/null +++ b/wit/deps/sockets/instance-network.wit @@ -0,0 +1,11 @@ + +/// This interface provides a value-export of the default network handle.. +@since(version = 0.2.0) +interface instance-network { + @since(version = 0.2.0) + use network.{network}; + + /// Get a handle to the default network. + @since(version = 0.2.0) + instance-network: func() -> network; +} diff --git a/wit/deps/sockets/ip-name-lookup.wit b/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 0000000..ee6419e --- /dev/null +++ b/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,56 @@ +@since(version = 0.2.0) +interface ip-name-lookup { + @since(version = 0.2.0) + use wasi:io/poll@0.2.6.{pollable}; + @since(version = 0.2.0) + 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + resolve-addresses: func(network: borrow, name: string) -> result; + + @since(version = 0.2.0) + 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) + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/wit/deps/sockets/network.wit b/wit/deps/sockets/network.wit new file mode 100644 index 0000000..6ca98b6 --- /dev/null +++ b/wit/deps/sockets/network.wit @@ -0,0 +1,169 @@ +@since(version = 0.2.0) +interface network { + @unstable(feature = network-error-code) + use wasi:io/error@0.2.6.{error}; + + /// 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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, + } + + /// Attempts to extract a network-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 + /// network-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are network-related errors. + @unstable(feature = network-error-code) + network-error-code: func(err: borrow) -> option; + + @since(version = 0.2.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.2.0) + type ipv4-address = tuple; + @since(version = 0.2.0) + type ipv6-address = tuple; + + @since(version = 0.2.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.2.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.2.0) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.2.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } +} diff --git a/wit/deps/sockets/tcp-create-socket.wit b/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 0000000..eedbd30 --- /dev/null +++ b/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface tcp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/wit/deps/sockets/tcp.wit b/wit/deps/sockets/tcp.wit new file mode 100644 index 0000000..beefd7b --- /dev/null +++ b/wit/deps/sockets/tcp.wit @@ -0,0 +1,387 @@ +@since(version = 0.2.0) +interface tcp { + @since(version = 0.2.0) + use wasi:io/streams@0.2.6.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.6.{pollable}; + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.6.{duration}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + @since(version = 0.2.0) + 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 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. + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connected` 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-listen: func() -> result<_, error-code>; + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.2.0) + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + keep-alive-enabled: func() -> result; + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + keep-alive-idle-time: func() -> result; + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + keep-alive-interval: func() -> result; + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + keep-alive-count: func() -> result; + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + hop-limit: func() -> result; + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + 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 more information. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + 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 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/wit/deps/sockets/udp-create-socket.wit b/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 0000000..e8eeacb --- /dev/null +++ b/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface udp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + 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: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/wit/deps/sockets/udp.wit b/wit/deps/sockets/udp.wit new file mode 100644 index 0000000..9dbe693 --- /dev/null +++ b/wit/deps/sockets/udp.wit @@ -0,0 +1,288 @@ +@since(version = 0.2.0) +interface udp { + @since(version = 0.2.0) + use wasi:io/poll@0.2.6.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + %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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + unicast-hop-limit: func() -> result; + @since(version = 0.2.0) + 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. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + 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 + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + 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 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/wit/deps/sockets/world.wit b/wit/deps/sockets/world.wit new file mode 100644 index 0000000..e86f02c --- /dev/null +++ b/wit/deps/sockets/world.wit @@ -0,0 +1,19 @@ +package wasi:sockets@0.2.6; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import tcp; + @since(version = 0.2.0) + import tcp-create-socket; + @since(version = 0.2.0) + import ip-name-lookup; +} diff --git a/wit/virt.wit b/wit/virt.wit new file mode 100644 index 0000000..54757fe --- /dev/null +++ b/wit/virt.wit @@ -0,0 +1,6 @@ +package python:virt; + +world python-virt { + export wasi:cli/terminal-input@0.2.6; +} +// version fairly arbitrary \ No newline at end of file From a818fe3577f554e74286962622cb8bc6e4d95163 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 26 Sep 2025 11:21:18 -0400 Subject: [PATCH 02/50] Add a non-working implementation of `terminal-input`. --- src/lib.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 9fe6f31..e15d68f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,3 +3,34 @@ wit_bindgen::generate!({ path: "wit", generate_all, }); + +// This already miraculously exports wasi::cli::terminal_input::TerminalInput! + +use exports::wasi::cli::terminal_input::{Guest, GuestTerminalInput, TerminalInput}; + +static mut ONE_TRUE_TERMINAL: u8 = 0; + +// TODO: Make less bogus so it stands a chance of not crashing at runtime. For now, I'm just seeing if I can get it to link. +impl GuestTerminalInput for TerminalInput { + unsafe fn _resource_new(val: *mut u8) -> u32 + where + Self: Sized, + { + 0 + } + + fn _resource_rep(handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut ONE_TRUE_TERMINAL + } +} + +struct MyComponent; + +impl Guest for MyComponent { + type TerminalInput = TerminalInput; +} + +export!(MyComponent); From 5e1ac71c4402fae9da01d009c4593e873af0c4d9 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 26 Sep 2025 11:25:39 -0400 Subject: [PATCH 03/50] Fix some warnings, and qualify the pathname to `Guest`, making room for more interfaces impls. --- src/lib.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e15d68f..5d2ce22 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,20 +6,21 @@ wit_bindgen::generate!({ // This already miraculously exports wasi::cli::terminal_input::TerminalInput! -use exports::wasi::cli::terminal_input::{Guest, GuestTerminalInput, TerminalInput}; +use exports::wasi::cli::terminal_input; +use exports::wasi::cli::terminal_input::{GuestTerminalInput, TerminalInput}; static mut ONE_TRUE_TERMINAL: u8 = 0; // TODO: Make less bogus so it stands a chance of not crashing at runtime. For now, I'm just seeing if I can get it to link. impl GuestTerminalInput for TerminalInput { - unsafe fn _resource_new(val: *mut u8) -> u32 + unsafe fn _resource_new(_val: *mut u8) -> u32 where Self: Sized, { 0 } - fn _resource_rep(handle: u32) -> *mut u8 + fn _resource_rep(_handle: u32) -> *mut u8 where Self: Sized, { @@ -29,7 +30,7 @@ impl GuestTerminalInput for TerminalInput { struct MyComponent; -impl Guest for MyComponent { +impl terminal_input::Guest for MyComponent { type TerminalInput = TerminalInput; } From 461bc338d49128a5a881b27748a91acf58a1150e Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 26 Sep 2025 14:39:00 -0400 Subject: [PATCH 04/50] Add implementation of `terminal-stdin`. --- src/lib.rs | 33 ++++++++++++++++++++++++++++++++- wit/virt.wit | 28 +++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5d2ce22..65f4fa1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,10 +8,14 @@ wit_bindgen::generate!({ use exports::wasi::cli::terminal_input; use exports::wasi::cli::terminal_input::{GuestTerminalInput, TerminalInput}; +use exports::wasi::cli::terminal_output; +use exports::wasi::cli::terminal_output::{GuestTerminalOutput, TerminalOutput}; +use exports::wasi::cli::terminal_stdin; static mut ONE_TRUE_TERMINAL: u8 = 0; -// TODO: Make less bogus so it stands a chance of not crashing at runtime. For now, I'm just seeing if I can get it to link. +// TODO: Make less bogus so it stands a chance of not crashing at runtime. For +// now, I'm just seeing if I can get it to link. impl GuestTerminalInput for TerminalInput { unsafe fn _resource_new(_val: *mut u8) -> u32 where @@ -34,4 +38,31 @@ impl terminal_input::Guest for MyComponent { type TerminalInput = TerminalInput; } +// TODO: Make less bogus, as above. +impl GuestTerminalOutput for TerminalOutput { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + 0 + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut ONE_TRUE_TERMINAL + } +} + +impl terminal_output::Guest for MyComponent { + type TerminalOutput = TerminalOutput; +} + +impl terminal_stdin::Guest for MyComponent { + fn get_terminal_stdin() -> Option<::TerminalInput> { + None + } +} + export!(MyComponent); diff --git a/wit/virt.wit b/wit/virt.wit index 54757fe..112a736 100644 --- a/wit/virt.wit +++ b/wit/virt.wit @@ -2,5 +2,31 @@ package python:virt; world python-virt { export wasi:cli/terminal-input@0.2.6; + export wasi:cli/terminal-output@0.2.6; + export wasi:cli/terminal-stdin@0.2.6; +// export wasi:cli/terminal-stdout@0.2.6; +// export wasi:cli/terminal-stderr@0.2.6; +// export wasi:io/error@0.2.6; +// export wasi:io/poll@0.2.6; +// export wasi:io/streams@0.2.6; +// export wasi:clocks/wall-clock@0.2.6; +// export wasi:filesystem/types@0.2.6; +// export wasi:filesystem/preopens@0.2.6; +// export wasi:sockets/network@0.2.6; +// export wasi:sockets/instance-network@0.2.6; +// export wasi:sockets/udp@0.2.6; +// export wasi:sockets/udp-create-socket@0.2.6; +// export wasi:clocks/monotonic-clock@0.2.6; +// export wasi:sockets/tcp@0.2.6; +// export wasi:sockets/tcp-create-socket@0.2.6; +// export wasi:sockets/ip-name-lookup@0.2.6; +// export wasi:random/insecure@0.2.6; +// export wasi:random/insecure-seed@0.2.6; +// export wasi:random/random@0.2.6; +// export wasi:cli/environment@0.2.6; +// export wasi:cli/exit@0.2.6; +// export wasi:cli/stdout@0.2.6; +// export wasi:cli/stderr@0.2.6; +// export wasi:cli/stdin@0.2.6; } -// version fairly arbitrary \ No newline at end of file +// Version numbers are fairly arbitrary. \ No newline at end of file From c875f6ab8bd224a186b8c580f729b2f3eb99d811 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 26 Sep 2025 14:47:07 -0400 Subject: [PATCH 05/50] Rename the whole shooting match to "Wasiless". --- Cargo.lock | 14 +++++++------- Cargo.toml | 3 ++- src/lib.rs | 16 +++++++++------- wit/virt.wit | 4 ++-- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 17fe714..4146831 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -208,13 +208,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "python-virt" -version = "0.1.0" -dependencies = [ - "wit-bindgen", -] - [[package]] name = "quote" version = "1.0.40" @@ -307,6 +300,13 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "wasiless" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-encoder" version = "0.239.0" diff --git a/Cargo.toml b/Cargo.toml index 159b0d5..57c9add 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,8 @@ [package] -name = "python-virt" +name = "wasiless" version = "0.1.0" edition = "2024" +description = "A null implementation of WASI, doing as little as possible while still allowing each function to return without trapping" [dependencies] wit-bindgen = "0.46.0" diff --git a/src/lib.rs b/src/lib.rs index 65f4fa1..e23d8ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ wit_bindgen::generate!({ - world: "python-virt", + world: "wasiless", path: "wit", generate_all, }); @@ -32,9 +32,11 @@ impl GuestTerminalInput for TerminalInput { } } -struct MyComponent; +/// Wasm component implementing WASI with as little functionality as possible +/// without trapping +struct Wasiless; -impl terminal_input::Guest for MyComponent { +impl terminal_input::Guest for Wasiless { type TerminalInput = TerminalInput; } @@ -55,14 +57,14 @@ impl GuestTerminalOutput for TerminalOutput { } } -impl terminal_output::Guest for MyComponent { +impl terminal_output::Guest for Wasiless { type TerminalOutput = TerminalOutput; } -impl terminal_stdin::Guest for MyComponent { - fn get_terminal_stdin() -> Option<::TerminalInput> { +impl terminal_stdin::Guest for Wasiless { + fn get_terminal_stdin() -> Option<::TerminalInput> { None } } -export!(MyComponent); +export!(Wasiless); diff --git a/wit/virt.wit b/wit/virt.wit index 112a736..f5f0d52 100644 --- a/wit/virt.wit +++ b/wit/virt.wit @@ -1,6 +1,6 @@ -package python:virt; +package fastly:wasiless; -world python-virt { +world wasiless { export wasi:cli/terminal-input@0.2.6; export wasi:cli/terminal-output@0.2.6; export wasi:cli/terminal-stdin@0.2.6; From 6a23b546016c69a87a00e0b641beddb9df6374a6 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 26 Sep 2025 15:22:22 -0400 Subject: [PATCH 06/50] Add `terminal-stdout` and `terminal-stderr`. --- src/lib.rs | 14 ++++++++++++++ wit/virt.wit | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e23d8ea..12e5ce8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,7 +10,9 @@ use exports::wasi::cli::terminal_input; use exports::wasi::cli::terminal_input::{GuestTerminalInput, TerminalInput}; use exports::wasi::cli::terminal_output; use exports::wasi::cli::terminal_output::{GuestTerminalOutput, TerminalOutput}; +use exports::wasi::cli::terminal_stderr; use exports::wasi::cli::terminal_stdin; +use exports::wasi::cli::terminal_stdout; static mut ONE_TRUE_TERMINAL: u8 = 0; @@ -67,4 +69,16 @@ impl terminal_stdin::Guest for Wasiless { } } +impl terminal_stdout::Guest for Wasiless { + fn get_terminal_stdout() -> Option<::TerminalOutput> { + None + } +} + +impl terminal_stderr::Guest for Wasiless { + fn get_terminal_stderr() -> Option<::TerminalOutput> { + None + } +} + export!(Wasiless); diff --git a/wit/virt.wit b/wit/virt.wit index f5f0d52..d36b094 100644 --- a/wit/virt.wit +++ b/wit/virt.wit @@ -4,8 +4,8 @@ world wasiless { export wasi:cli/terminal-input@0.2.6; export wasi:cli/terminal-output@0.2.6; export wasi:cli/terminal-stdin@0.2.6; -// export wasi:cli/terminal-stdout@0.2.6; -// export wasi:cli/terminal-stderr@0.2.6; + export wasi:cli/terminal-stdout@0.2.6; + export wasi:cli/terminal-stderr@0.2.6; // export wasi:io/error@0.2.6; // export wasi:io/poll@0.2.6; // export wasi:io/streams@0.2.6; From 418e1ecbbb1e64858ec703361b8d77271d039da4 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 26 Sep 2025 15:53:39 -0400 Subject: [PATCH 07/50] Implement `wasi:io/error`. Also rename the top-level WIT file, which I had forgot to do. --- src/lib.rs | 39 +++++++++++++++++++++++++++------- wit/{virt.wit => wasiless.wit} | 2 +- 2 files changed, 32 insertions(+), 9 deletions(-) rename wit/{virt.wit => wasiless.wit} (97%) diff --git a/src/lib.rs b/src/lib.rs index 12e5ce8..a06c917 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,15 +6,14 @@ wit_bindgen::generate!({ // This already miraculously exports wasi::cli::terminal_input::TerminalInput! -use exports::wasi::cli::terminal_input; -use exports::wasi::cli::terminal_input::{GuestTerminalInput, TerminalInput}; -use exports::wasi::cli::terminal_output; -use exports::wasi::cli::terminal_output::{GuestTerminalOutput, TerminalOutput}; +use exports::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; +use exports::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; use exports::wasi::cli::terminal_stderr; use exports::wasi::cli::terminal_stdin; use exports::wasi::cli::terminal_stdout; +use exports::wasi::io::error::{self, Error, GuestError}; -static mut ONE_TRUE_TERMINAL: u8 = 0; +static mut BOGUS_RESOURCE: u8 = 0; // TODO: Make less bogus so it stands a chance of not crashing at runtime. For // now, I'm just seeing if I can get it to link. @@ -30,7 +29,7 @@ impl GuestTerminalInput for TerminalInput { where Self: Sized, { - &raw mut ONE_TRUE_TERMINAL + &raw mut BOGUS_RESOURCE } } @@ -42,7 +41,7 @@ impl terminal_input::Guest for Wasiless { type TerminalInput = TerminalInput; } -// TODO: Make less bogus, as above. +// TODO: Make less bogus, as above. Make all BOGUS_RESOURCE users less bogus. impl GuestTerminalOutput for TerminalOutput { unsafe fn _resource_new(_val: *mut u8) -> u32 where @@ -55,7 +54,7 @@ impl GuestTerminalOutput for TerminalOutput { where Self: Sized, { - &raw mut ONE_TRUE_TERMINAL + &raw mut BOGUS_RESOURCE } } @@ -81,4 +80,28 @@ impl terminal_stderr::Guest for Wasiless { } } +impl GuestError for Error { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + 0 + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + fn to_debug_string(&self) -> String { + "".to_owned() + } +} + +impl error::Guest for Wasiless { + type Error = Error; +} + export!(Wasiless); diff --git a/wit/virt.wit b/wit/wasiless.wit similarity index 97% rename from wit/virt.wit rename to wit/wasiless.wit index d36b094..e1e7229 100644 --- a/wit/virt.wit +++ b/wit/wasiless.wit @@ -6,7 +6,7 @@ world wasiless { export wasi:cli/terminal-stdin@0.2.6; export wasi:cli/terminal-stdout@0.2.6; export wasi:cli/terminal-stderr@0.2.6; -// export wasi:io/error@0.2.6; + export wasi:io/error@0.2.6; // export wasi:io/poll@0.2.6; // export wasi:io/streams@0.2.6; // export wasi:clocks/wall-clock@0.2.6; From 7b2723db0a0a15c04306af5730933417313d874d Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 29 Sep 2025 10:23:30 -0400 Subject: [PATCH 08/50] Add `wasi:io/poll`. --- src/lib.rs | 33 +++++++++++++++++++++++++++++++++ wit/wasiless.wit | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index a06c917..1ca39e8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ use exports::wasi::cli::terminal_stderr; use exports::wasi::cli::terminal_stdin; use exports::wasi::cli::terminal_stdout; use exports::wasi::io::error::{self, Error, GuestError}; +use exports::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; static mut BOGUS_RESOURCE: u8 = 0; @@ -104,4 +105,36 @@ impl error::Guest for Wasiless { type Error = Error; } +impl GuestPollable for Pollable { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + 0 + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + fn ready(&self) -> bool { + false + } + + fn block(&self) -> () { + () + } +} + +impl poll::Guest for Wasiless { + type Pollable = Pollable; + + fn poll(_in: Vec) -> Vec { + vec![] + } +} + export!(Wasiless); diff --git a/wit/wasiless.wit b/wit/wasiless.wit index e1e7229..6e5529f 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -7,7 +7,7 @@ world wasiless { export wasi:cli/terminal-stdout@0.2.6; export wasi:cli/terminal-stderr@0.2.6; export wasi:io/error@0.2.6; -// export wasi:io/poll@0.2.6; + export wasi:io/poll@0.2.6; // export wasi:io/streams@0.2.6; // export wasi:clocks/wall-clock@0.2.6; // export wasi:filesystem/types@0.2.6; From 4fe46cd954545548afa5d87e6a48563ece087191 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 29 Sep 2025 11:12:43 -0400 Subject: [PATCH 09/50] Actually, it's a violation of contract to have `block()` return on an unready pollable. Stop doing that. Returning seems to me much preferable to freezing forever. --- src/lib.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1ca39e8..5e35a68 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -120,10 +120,12 @@ impl GuestPollable for Pollable { &raw mut BOGUS_RESOURCE } + /// Returns true for consistency with the fact that our block() doesn't block. fn ready(&self) -> bool { - false + true } + /// Never blocks, lest we block forever. fn block(&self) -> () { () } @@ -132,8 +134,24 @@ impl GuestPollable for Pollable { impl poll::Guest for Wasiless { type Pollable = Pollable; - fn poll(_in: Vec) -> Vec { - vec![] + /// This is a real implementation, in an attempt to present a consistent + /// picture of our fake reality to callers and thus avoid provoking crashes + /// unnecessarily. + fn poll(pollables: Vec) -> Vec { + if pollables.len() > (u32::MAX as usize) { + panic!("list of pollables too long to be indexed with a u32") + } + pollables + .iter() + .enumerate() + .filter_map(|(i, p)| { + if p.get::().ready() { + Some(i as u32) + } else { + None + } + }) + .collect() } } From 16d463bc9a9d4ef73f003642ea6fefb1b3ce2e5c Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 29 Sep 2025 14:02:47 -0400 Subject: [PATCH 10/50] Ignore the wit-bindgen output I use for reference. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index ea8c4bf..2f1c24c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +/wasiless.rs \ No newline at end of file From 0f11dd7d9cf945034dd6aa0edab6afbd556b0170 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 29 Sep 2025 14:31:10 -0400 Subject: [PATCH 11/50] Add `wasi:io/streams`. --- src/lib.rs | 119 +++++++++++++++++++++++++++++++++++++++++++++-- wit/wasiless.wit | 2 +- 2 files changed, 116 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5e35a68..ce23d3c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,10 @@ +// General philosophy thus far: Avoid returning error conditions; appear to +// succeed. But lie as little as possible beyond that: IO read and write +// routines claim 0 bytes were written, "successfully". This is in service of +// creating as little surprise for the caller as possible. Keep in mind this +// philosophy may be proven unhelpful through actual experience with the +// behavior of real-world clients. + wit_bindgen::generate!({ world: "wasiless", path: "wit", @@ -13,8 +20,13 @@ use exports::wasi::cli::terminal_stdin; use exports::wasi::cli::terminal_stdout; use exports::wasi::io::error::{self, Error, GuestError}; use exports::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; +use exports::wasi::io::streams::{ + self, GuestInputStream, GuestOutputStream, InputStream, InputStreamBorrow, OutputStream, + StreamError, +}; static mut BOGUS_RESOURCE: u8 = 0; +static BOGUS_HANDLE: u32 = 0; // TODO: Make less bogus so it stands a chance of not crashing at runtime. For // now, I'm just seeing if I can get it to link. @@ -23,7 +35,7 @@ impl GuestTerminalInput for TerminalInput { where Self: Sized, { - 0 + BOGUS_HANDLE } fn _resource_rep(_handle: u32) -> *mut u8 @@ -48,7 +60,7 @@ impl GuestTerminalOutput for TerminalOutput { where Self: Sized, { - 0 + BOGUS_HANDLE } fn _resource_rep(_handle: u32) -> *mut u8 @@ -86,7 +98,7 @@ impl GuestError for Error { where Self: Sized, { - 0 + BOGUS_HANDLE } fn _resource_rep(_handle: u32) -> *mut u8 @@ -110,7 +122,7 @@ impl GuestPollable for Pollable { where Self: Sized, { - 0 + BOGUS_HANDLE } fn _resource_rep(_handle: u32) -> *mut u8 @@ -155,4 +167,103 @@ impl poll::Guest for Wasiless { } } +impl GuestInputStream for InputStream { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + fn read(&self, _len: u64) -> Result, StreamError> { + Ok(Vec::new()) + } + + fn blocking_read(&self, _len: u64) -> Result, StreamError> { + Ok(Vec::new()) + } + + fn skip(&self, _len: u64) -> Result { + Ok(0) + } + + fn blocking_skip(&self, _len: u64) -> Result { + Ok(0) + } + + fn subscribe(&self) -> Pollable { + // TODO: Return a handle that points to a mock. Or maybe make this trap in the interrim. + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } +} + +/// Writes appear to go through without error but also report back that they wrote 0 bytes. +impl GuestOutputStream for OutputStream { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + fn check_write(&self) -> Result { + Ok(4096) // TODO: Make this interlock with subscribe(). + } + + fn write(&self, _contents: Vec) -> Result<(), StreamError> { + Ok(()) + } + + fn blocking_write_and_flush(&self, _contents: Vec) -> Result<(), StreamError> { + Ok(()) + } + + fn flush(&self) -> Result<(), StreamError> { + Ok(()) + } + + fn blocking_flush(&self) -> Result<(), StreamError> { + Ok(()) + } + + fn subscribe(&self) -> Pollable { + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } + + fn write_zeroes(&self, _len: u64) -> Result<(), StreamError> { + Ok(()) + } + + fn blocking_write_zeroes_and_flush(&self, _len: u64) -> Result<(), StreamError> { + Ok(()) + } + + fn splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { + Ok(0) + } + + fn blocking_splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { + Ok(0) + } +} + +impl streams::Guest for Wasiless { + type InputStream = InputStream; + type OutputStream = OutputStream; +} + export!(Wasiless); diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 6e5529f..c1a7e27 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -8,7 +8,7 @@ world wasiless { export wasi:cli/terminal-stderr@0.2.6; export wasi:io/error@0.2.6; export wasi:io/poll@0.2.6; -// export wasi:io/streams@0.2.6; + export wasi:io/streams@0.2.6; // export wasi:clocks/wall-clock@0.2.6; // export wasi:filesystem/types@0.2.6; // export wasi:filesystem/preopens@0.2.6; From 736c7fd795577d4c241b44513d896f6afe0488fe Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 11:00:14 -0400 Subject: [PATCH 12/50] Set the default build target to wasm/WASIp2. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit …so we can build it with just `cargo build`. --- .cargo/config | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .cargo/config diff --git a/.cargo/config b/.cargo/config new file mode 100644 index 0000000..dac2459 --- /dev/null +++ b/.cargo/config @@ -0,0 +1,2 @@ +[build] +target = "wasm32-wasip2" \ No newline at end of file From 7fd0adba63266d0dc34028ac3e00e78bb379b80c Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 11:37:32 -0400 Subject: [PATCH 13/50] Garden TODOs. --- src/lib.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index ce23d3c..13538e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,7 +3,8 @@ // routines claim 0 bytes were written, "successfully". This is in service of // creating as little surprise for the caller as possible. Keep in mind this // philosophy may be proven unhelpful through actual experience with the -// behavior of real-world clients. +// behavior of real-world clients. It may be helpful (and even less surprising) +// to crash as early as possible. wit_bindgen::generate!({ world: "wasiless", @@ -28,8 +29,9 @@ use exports::wasi::io::streams::{ static mut BOGUS_RESOURCE: u8 = 0; static BOGUS_HANDLE: u32 = 0; -// TODO: Make less bogus so it stands a chance of not crashing at runtime. For -// now, I'm just seeing if I can get it to link. +// TODO: Make less bogus so it stands a chance of not crashing at runtime. Same +// for other BOGUS_RESOURCE and BOGUS_HANDLE users. For now, I'm just seeing if +// I can get it to link. impl GuestTerminalInput for TerminalInput { unsafe fn _resource_new(_val: *mut u8) -> u32 where @@ -54,7 +56,6 @@ impl terminal_input::Guest for Wasiless { type TerminalInput = TerminalInput; } -// TODO: Make less bogus, as above. Make all BOGUS_RESOURCE users less bogus. impl GuestTerminalOutput for TerminalOutput { unsafe fn _resource_new(_val: *mut u8) -> u32 where @@ -199,7 +200,6 @@ impl GuestInputStream for InputStream { } fn subscribe(&self) -> Pollable { - // TODO: Return a handle that points to a mock. Or maybe make this trap in the interrim. unsafe { Pollable::from_handle(BOGUS_HANDLE) } } } From 63d24e210387704a16bb9a96f1f7a0f394f145d9 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 11:47:11 -0400 Subject: [PATCH 14/50] Add `wasi:clocks/wall-clock`. --- src/lib.rs | 17 +++++++++++++++++ wit/wasiless.wit | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 13538e5..1fea43c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ use exports::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOut use exports::wasi::cli::terminal_stderr; use exports::wasi::cli::terminal_stdin; use exports::wasi::cli::terminal_stdout; +use exports::wasi::clocks::wall_clock::{self, Datetime}; use exports::wasi::io::error::{self, Error, GuestError}; use exports::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; use exports::wasi::io::streams::{ @@ -266,4 +267,20 @@ impl streams::Guest for Wasiless { type OutputStream = OutputStream; } +impl wall_clock::Guest for Wasiless { + fn now() -> Datetime { + Datetime { + seconds: 0, + nanoseconds: 0, + } + } + + fn resolution() -> Datetime { + Datetime { + seconds: 0, + nanoseconds: 0, + } + } +} + export!(Wasiless); diff --git a/wit/wasiless.wit b/wit/wasiless.wit index c1a7e27..9aa2604 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -9,7 +9,7 @@ world wasiless { export wasi:io/error@0.2.6; export wasi:io/poll@0.2.6; export wasi:io/streams@0.2.6; -// export wasi:clocks/wall-clock@0.2.6; + export wasi:clocks/wall-clock@0.2.6; // export wasi:filesystem/types@0.2.6; // export wasi:filesystem/preopens@0.2.6; // export wasi:sockets/network@0.2.6; From 2e2fbec668404c52765aeec8f666d084c8f94bb3 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 11:54:43 -0400 Subject: [PATCH 15/50] Add `wasi:clocks/monotonic-clock`. --- src/lib.rs | 19 +++++++++++++++++++ wit/wasiless.wit | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 1fea43c..4c71b69 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ use exports::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOut use exports::wasi::cli::terminal_stderr; use exports::wasi::cli::terminal_stdin; use exports::wasi::cli::terminal_stdout; +use exports::wasi::clocks::monotonic_clock::{self, Duration, Instant}; use exports::wasi::clocks::wall_clock::{self, Datetime}; use exports::wasi::io::error::{self, Error, GuestError}; use exports::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; @@ -283,4 +284,22 @@ impl wall_clock::Guest for Wasiless { } } +impl monotonic_clock::Guest for Wasiless { + fn now() -> Instant { + 0 + } + + fn resolution() -> Duration { + 1 // A little less absurd than 0 + } + + fn subscribe_instant(_when: Instant) -> Pollable { + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } + + fn subscribe_duration(_when: Duration) -> Pollable { + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } +} + export!(Wasiless); diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 9aa2604..0e69c40 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -16,7 +16,7 @@ world wasiless { // export wasi:sockets/instance-network@0.2.6; // export wasi:sockets/udp@0.2.6; // export wasi:sockets/udp-create-socket@0.2.6; -// export wasi:clocks/monotonic-clock@0.2.6; + export wasi:clocks/monotonic-clock@0.2.6; // export wasi:sockets/tcp@0.2.6; // export wasi:sockets/tcp-create-socket@0.2.6; // export wasi:sockets/ip-name-lookup@0.2.6; From fb77dc24365de4f72734f95e9f939f7be83cee66 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 15:20:49 -0400 Subject: [PATCH 16/50] Add `wasi:filesystem/types`. --- src/lib.rs | 168 +++++++++++++++++++++++++++++++++++++++++++++++ wit/wasiless.wit | 2 +- 2 files changed, 169 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 4c71b69..5d901fa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,6 +21,14 @@ use exports::wasi::cli::terminal_stdin; use exports::wasi::cli::terminal_stdout; use exports::wasi::clocks::monotonic_clock::{self, Duration, Instant}; use exports::wasi::clocks::wall_clock::{self, Datetime}; +use exports::wasi::filesystem::{ + self, + types::{ + Advice, Descriptor, DescriptorBorrow, DescriptorFlags, DescriptorStat, DescriptorType, + DirectoryEntry, DirectoryEntryStream, ErrorBorrow, ErrorCode, Filesize, GuestDescriptor, + GuestDirectoryEntryStream, MetadataHashValue, NewTimestamp, OpenFlags, PathFlags, + }, +}; use exports::wasi::io::error::{self, Error, GuestError}; use exports::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; use exports::wasi::io::streams::{ @@ -302,4 +310,164 @@ impl monotonic_clock::Guest for Wasiless { } } +impl GuestDescriptor for Descriptor { + fn read_via_stream(&self, _offset: Filesize) -> Result { + Err(ErrorCode::Unsupported) + } + + fn write_via_stream(&self, _offset: Filesize) -> Result { + Err(ErrorCode::Unsupported) + } + + fn append_via_stream(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn advise( + &self, + _offset: Filesize, + _length: Filesize, + _advice: Advice, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn sync_data(&self) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn get_flags(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn get_type(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn set_size(&self, _size: Filesize) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn set_times( + &self, + _data_access_timestamp: NewTimestamp, + _data_modification_timestamp: NewTimestamp, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn read(&self, _length: Filesize, _offset: Filesize) -> Result<(Vec, bool), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn write(&self, _buffer: Vec, _offset: Filesize) -> Result { + Err(ErrorCode::Unsupported) + } + + fn read_directory(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn sync(&self) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn create_directory_at(&self, _path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn stat(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn stat_at(&self, _path_flags: PathFlags, _path: String) -> Result { + Err(ErrorCode::Unsupported) + } + + fn set_times_at( + &self, + _path_flags: PathFlags, + _path: String, + _data_access_timestamp: NewTimestamp, + _data_modification_timestamp: NewTimestamp, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn link_at( + &self, + _old_path_flags: PathFlags, + _old_path: String, + _new_descriptor: DescriptorBorrow<'_>, + _new_path: String, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn open_at( + &self, + _path_flags: PathFlags, + _path: String, + _open_flags: OpenFlags, + _flags: DescriptorFlags, + ) -> Result { + Err(ErrorCode::Unsupported) + } + + fn readlink_at(&self, _path: String) -> Result { + Err(ErrorCode::Unsupported) + } + + fn remove_directory_at(&self, _path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn rename_at( + &self, + _old_path: String, + _new_descriptor: DescriptorBorrow<'_>, + _new_path: String, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn symlink_at(&self, _old_path: String, _new_path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn unlink_file_at(&self, _path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn is_same_object(&self, _other: DescriptorBorrow<'_>) -> bool { + false // arbitrary + } + + fn metadata_hash(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn metadata_hash_at( + &self, + _path_flags: PathFlags, + _path: String, + ) -> Result { + Err(ErrorCode::Unsupported) + } +} + +impl GuestDirectoryEntryStream for DirectoryEntryStream { + fn read_directory_entry(&self) -> Result, ErrorCode> { + Err(ErrorCode::Unsupported) + } +} + +impl filesystem::types::Guest for Wasiless { + type Descriptor = Descriptor; + type DirectoryEntryStream = DirectoryEntryStream; + fn filesystem_error_code(_err: ErrorBorrow) -> Option { + None + } +} + export!(Wasiless); diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 0e69c40..b682fa8 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -10,7 +10,7 @@ world wasiless { export wasi:io/poll@0.2.6; export wasi:io/streams@0.2.6; export wasi:clocks/wall-clock@0.2.6; -// export wasi:filesystem/types@0.2.6; + export wasi:filesystem/types@0.2.6; // export wasi:filesystem/preopens@0.2.6; // export wasi:sockets/network@0.2.6; // export wasi:sockets/instance-network@0.2.6; From e48593e0cf2f9b5d74f6ffcbe60e373b70b82631 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 15:34:21 -0400 Subject: [PATCH 17/50] Begin moving each WASI package to its own Rust module. Here, move binding generation to its own module. --- src/bindings.rs | 7 +++++++ src/lib.rs | 33 +++++++++++++++------------------ 2 files changed, 22 insertions(+), 18 deletions(-) create mode 100644 src/bindings.rs diff --git a/src/bindings.rs b/src/bindings.rs new file mode 100644 index 0000000..4655185 --- /dev/null +++ b/src/bindings.rs @@ -0,0 +1,7 @@ +wit_bindgen::generate!({ + world: "wasiless", + path: "wit", + generate_all, +}); + +pub use exports::wasi; diff --git a/src/lib.rs b/src/lib.rs index 5d901fa..110cca6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,22 +6,19 @@ // behavior of real-world clients. It may be helpful (and even less surprising) // to crash as early as possible. -wit_bindgen::generate!({ - world: "wasiless", - path: "wit", - generate_all, -}); - // This already miraculously exports wasi::cli::terminal_input::TerminalInput! -use exports::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; -use exports::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; -use exports::wasi::cli::terminal_stderr; -use exports::wasi::cli::terminal_stdin; -use exports::wasi::cli::terminal_stdout; -use exports::wasi::clocks::monotonic_clock::{self, Duration, Instant}; -use exports::wasi::clocks::wall_clock::{self, Datetime}; -use exports::wasi::filesystem::{ +mod bindings; + +use bindings::export; +use bindings::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; +use bindings::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; +use bindings::wasi::cli::terminal_stderr; +use bindings::wasi::cli::terminal_stdin; +use bindings::wasi::cli::terminal_stdout; +use bindings::wasi::clocks::monotonic_clock::{self, Duration, Instant}; +use bindings::wasi::clocks::wall_clock::{self, Datetime}; +use bindings::wasi::filesystem::{ self, types::{ Advice, Descriptor, DescriptorBorrow, DescriptorFlags, DescriptorStat, DescriptorType, @@ -29,9 +26,9 @@ use exports::wasi::filesystem::{ GuestDirectoryEntryStream, MetadataHashValue, NewTimestamp, OpenFlags, PathFlags, }, }; -use exports::wasi::io::error::{self, Error, GuestError}; -use exports::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; -use exports::wasi::io::streams::{ +use bindings::wasi::io::error::{self, Error, GuestError}; +use bindings::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; +use bindings::wasi::io::streams::{ self, GuestInputStream, GuestOutputStream, InputStream, InputStreamBorrow, OutputStream, StreamError, }; @@ -470,4 +467,4 @@ impl filesystem::types::Guest for Wasiless { } } -export!(Wasiless); +export!(Wasiless with_types_in bindings); From 40982befe5f4174638dcf6e1c43b29a0299744c8 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 15:52:27 -0400 Subject: [PATCH 18/50] Finish moving every WASI package to its own Rust module. These files aren't getting any shorter. --- src/cli.rs | 67 +++++++ src/clocks.rs | 38 ++++ src/filesystem.rs | 170 +++++++++++++++++ src/io.rs | 181 ++++++++++++++++++ src/lib.rs | 454 +--------------------------------------------- 5 files changed, 460 insertions(+), 450 deletions(-) create mode 100644 src/cli.rs create mode 100644 src/clocks.rs create mode 100644 src/filesystem.rs create mode 100644 src/io.rs diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..2cb3458 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,67 @@ +use crate::bindings::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; +use crate::bindings::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; +use crate::bindings::wasi::cli::terminal_stderr; +use crate::bindings::wasi::cli::terminal_stdin; +use crate::bindings::wasi::cli::terminal_stdout; +use crate::{BOGUS_HANDLE, BOGUS_RESOURCE, Wasiless}; + +// TODO: Make less bogus so it stands a chance of not crashing at runtime. Same +// for other BOGUS_RESOURCE and BOGUS_HANDLE users. For now, I'm just seeing if +// I can get it to link. +impl GuestTerminalInput for TerminalInput { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } +} + +impl terminal_input::Guest for Wasiless { + type TerminalInput = TerminalInput; +} + +impl GuestTerminalOutput for TerminalOutput { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } +} + +impl terminal_output::Guest for Wasiless { + type TerminalOutput = TerminalOutput; +} + +impl terminal_stdin::Guest for Wasiless { + fn get_terminal_stdin() -> Option<::TerminalInput> { + None + } +} + +impl terminal_stdout::Guest for Wasiless { + fn get_terminal_stdout() -> Option<::TerminalOutput> { + None + } +} + +impl terminal_stderr::Guest for Wasiless { + fn get_terminal_stderr() -> Option<::TerminalOutput> { + None + } +} diff --git a/src/clocks.rs b/src/clocks.rs new file mode 100644 index 0000000..b573ced --- /dev/null +++ b/src/clocks.rs @@ -0,0 +1,38 @@ +use crate::bindings::wasi::clocks::monotonic_clock::{self, Duration, Instant}; +use crate::bindings::wasi::clocks::wall_clock::{self, Datetime}; +use crate::bindings::wasi::io::poll::Pollable; +use crate::{BOGUS_HANDLE, Wasiless}; + +impl wall_clock::Guest for Wasiless { + fn now() -> Datetime { + Datetime { + seconds: 0, + nanoseconds: 0, + } + } + + fn resolution() -> Datetime { + Datetime { + seconds: 0, + nanoseconds: 0, + } + } +} + +impl monotonic_clock::Guest for Wasiless { + fn now() -> Instant { + 0 + } + + fn resolution() -> Duration { + 1 // A little less absurd than 0 + } + + fn subscribe_instant(_when: Instant) -> Pollable { + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } + + fn subscribe_duration(_when: Duration) -> Pollable { + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } +} diff --git a/src/filesystem.rs b/src/filesystem.rs new file mode 100644 index 0000000..9b95ee6 --- /dev/null +++ b/src/filesystem.rs @@ -0,0 +1,170 @@ +use crate::Wasiless; +use crate::bindings::wasi::filesystem::{ + self, + types::{ + Advice, Descriptor, DescriptorBorrow, DescriptorFlags, DescriptorStat, DescriptorType, + DirectoryEntry, DirectoryEntryStream, ErrorBorrow, ErrorCode, Filesize, GuestDescriptor, + GuestDirectoryEntryStream, MetadataHashValue, NewTimestamp, OpenFlags, PathFlags, + }, +}; +use crate::bindings::wasi::io::streams::{InputStream, OutputStream}; + +impl GuestDescriptor for Descriptor { + fn read_via_stream(&self, _offset: Filesize) -> Result { + Err(ErrorCode::Unsupported) + } + + fn write_via_stream(&self, _offset: Filesize) -> Result { + Err(ErrorCode::Unsupported) + } + + fn append_via_stream(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn advise( + &self, + _offset: Filesize, + _length: Filesize, + _advice: Advice, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn sync_data(&self) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn get_flags(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn get_type(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn set_size(&self, _size: Filesize) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn set_times( + &self, + _data_access_timestamp: NewTimestamp, + _data_modification_timestamp: NewTimestamp, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn read(&self, _length: Filesize, _offset: Filesize) -> Result<(Vec, bool), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn write(&self, _buffer: Vec, _offset: Filesize) -> Result { + Err(ErrorCode::Unsupported) + } + + fn read_directory(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn sync(&self) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn create_directory_at(&self, _path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn stat(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn stat_at(&self, _path_flags: PathFlags, _path: String) -> Result { + Err(ErrorCode::Unsupported) + } + + fn set_times_at( + &self, + _path_flags: PathFlags, + _path: String, + _data_access_timestamp: NewTimestamp, + _data_modification_timestamp: NewTimestamp, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn link_at( + &self, + _old_path_flags: PathFlags, + _old_path: String, + _new_descriptor: DescriptorBorrow<'_>, + _new_path: String, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn open_at( + &self, + _path_flags: PathFlags, + _path: String, + _open_flags: OpenFlags, + _flags: DescriptorFlags, + ) -> Result { + Err(ErrorCode::Unsupported) + } + + fn readlink_at(&self, _path: String) -> Result { + Err(ErrorCode::Unsupported) + } + + fn remove_directory_at(&self, _path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn rename_at( + &self, + _old_path: String, + _new_descriptor: DescriptorBorrow<'_>, + _new_path: String, + ) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn symlink_at(&self, _old_path: String, _new_path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn unlink_file_at(&self, _path: String) -> Result<(), ErrorCode> { + Err(ErrorCode::Unsupported) + } + + fn is_same_object(&self, _other: DescriptorBorrow<'_>) -> bool { + false // arbitrary + } + + fn metadata_hash(&self) -> Result { + Err(ErrorCode::Unsupported) + } + + fn metadata_hash_at( + &self, + _path_flags: PathFlags, + _path: String, + ) -> Result { + Err(ErrorCode::Unsupported) + } +} + +impl GuestDirectoryEntryStream for DirectoryEntryStream { + fn read_directory_entry(&self) -> Result, ErrorCode> { + Err(ErrorCode::Unsupported) + } +} + +impl filesystem::types::Guest for Wasiless { + type Descriptor = Descriptor; + type DirectoryEntryStream = DirectoryEntryStream; + fn filesystem_error_code(_err: ErrorBorrow) -> Option { + None + } +} diff --git a/src/io.rs b/src/io.rs new file mode 100644 index 0000000..f9bb4a8 --- /dev/null +++ b/src/io.rs @@ -0,0 +1,181 @@ +use crate::bindings::wasi::io::error::{self, Error, GuestError}; +use crate::bindings::wasi::io::poll::Pollable; +use crate::bindings::wasi::io::poll::{self, GuestPollable, PollableBorrow}; +use crate::bindings::wasi::io::streams::{ + self, GuestInputStream, GuestOutputStream, InputStream, InputStreamBorrow, OutputStream, + StreamError, +}; +use crate::{BOGUS_HANDLE, BOGUS_RESOURCE, Wasiless}; + +impl GuestError for Error { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + fn to_debug_string(&self) -> String { + "".to_owned() + } +} + +impl error::Guest for Wasiless { + type Error = Error; +} + +impl GuestPollable for Pollable { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + /// Returns true for consistency with the fact that our block() doesn't block. + fn ready(&self) -> bool { + true + } + + /// Never blocks, lest we block forever. + fn block(&self) -> () { + () + } +} + +impl poll::Guest for Wasiless { + type Pollable = Pollable; + + /// This is a real implementation, in an attempt to present a consistent + /// picture of our fake reality to callers and thus avoid provoking crashes + /// unnecessarily. + fn poll(pollables: Vec) -> Vec { + if pollables.len() > (u32::MAX as usize) { + panic!("list of pollables too long to be indexed with a u32") + } + pollables + .iter() + .enumerate() + .filter_map(|(i, p)| { + if p.get::().ready() { + Some(i as u32) + } else { + None + } + }) + .collect() + } +} + +impl GuestInputStream for InputStream { + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + fn read(&self, _len: u64) -> Result, StreamError> { + Ok(Vec::new()) + } + + fn blocking_read(&self, _len: u64) -> Result, StreamError> { + Ok(Vec::new()) + } + + fn skip(&self, _len: u64) -> Result { + Ok(0) + } + + fn blocking_skip(&self, _len: u64) -> Result { + Ok(0) + } + + fn subscribe(&self) -> Pollable { + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } +} + +/// Writes appear to go through without error but also report back that they wrote 0 bytes. +impl GuestOutputStream for OutputStream { + // TODO: Maybe we can delete all these _resource*() funcs; the trait has a crashing default impl. + unsafe fn _resource_new(_val: *mut u8) -> u32 + where + Self: Sized, + { + BOGUS_HANDLE + } + + fn _resource_rep(_handle: u32) -> *mut u8 + where + Self: Sized, + { + &raw mut BOGUS_RESOURCE + } + + fn check_write(&self) -> Result { + Ok(4096) // TODO: Make this interlock with subscribe(). + } + + fn write(&self, _contents: Vec) -> Result<(), StreamError> { + Ok(()) + } + + fn blocking_write_and_flush(&self, _contents: Vec) -> Result<(), StreamError> { + Ok(()) + } + + fn flush(&self) -> Result<(), StreamError> { + Ok(()) + } + + fn blocking_flush(&self) -> Result<(), StreamError> { + Ok(()) + } + + fn subscribe(&self) -> Pollable { + unsafe { Pollable::from_handle(BOGUS_HANDLE) } + } + + fn write_zeroes(&self, _len: u64) -> Result<(), StreamError> { + Ok(()) + } + + fn blocking_write_zeroes_and_flush(&self, _len: u64) -> Result<(), StreamError> { + Ok(()) + } + + fn splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { + Ok(0) + } + + fn blocking_splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { + Ok(0) + } +} + +impl streams::Guest for Wasiless { + type InputStream = InputStream; + type OutputStream = OutputStream; +} diff --git a/src/lib.rs b/src/lib.rs index 110cca6..cdfd863 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,465 +6,19 @@ // behavior of real-world clients. It may be helpful (and even less surprising) // to crash as early as possible. -// This already miraculously exports wasi::cli::terminal_input::TerminalInput! - mod bindings; +mod cli; +mod clocks; +mod filesystem; +mod io; use bindings::export; -use bindings::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; -use bindings::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; -use bindings::wasi::cli::terminal_stderr; -use bindings::wasi::cli::terminal_stdin; -use bindings::wasi::cli::terminal_stdout; -use bindings::wasi::clocks::monotonic_clock::{self, Duration, Instant}; -use bindings::wasi::clocks::wall_clock::{self, Datetime}; -use bindings::wasi::filesystem::{ - self, - types::{ - Advice, Descriptor, DescriptorBorrow, DescriptorFlags, DescriptorStat, DescriptorType, - DirectoryEntry, DirectoryEntryStream, ErrorBorrow, ErrorCode, Filesize, GuestDescriptor, - GuestDirectoryEntryStream, MetadataHashValue, NewTimestamp, OpenFlags, PathFlags, - }, -}; -use bindings::wasi::io::error::{self, Error, GuestError}; -use bindings::wasi::io::poll::{self, GuestPollable, Pollable, PollableBorrow}; -use bindings::wasi::io::streams::{ - self, GuestInputStream, GuestOutputStream, InputStream, InputStreamBorrow, OutputStream, - StreamError, -}; static mut BOGUS_RESOURCE: u8 = 0; static BOGUS_HANDLE: u32 = 0; -// TODO: Make less bogus so it stands a chance of not crashing at runtime. Same -// for other BOGUS_RESOURCE and BOGUS_HANDLE users. For now, I'm just seeing if -// I can get it to link. -impl GuestTerminalInput for TerminalInput { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } -} - /// Wasm component implementing WASI with as little functionality as possible /// without trapping struct Wasiless; -impl terminal_input::Guest for Wasiless { - type TerminalInput = TerminalInput; -} - -impl GuestTerminalOutput for TerminalOutput { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } -} - -impl terminal_output::Guest for Wasiless { - type TerminalOutput = TerminalOutput; -} - -impl terminal_stdin::Guest for Wasiless { - fn get_terminal_stdin() -> Option<::TerminalInput> { - None - } -} - -impl terminal_stdout::Guest for Wasiless { - fn get_terminal_stdout() -> Option<::TerminalOutput> { - None - } -} - -impl terminal_stderr::Guest for Wasiless { - fn get_terminal_stderr() -> Option<::TerminalOutput> { - None - } -} - -impl GuestError for Error { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - - fn to_debug_string(&self) -> String { - "".to_owned() - } -} - -impl error::Guest for Wasiless { - type Error = Error; -} - -impl GuestPollable for Pollable { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - - /// Returns true for consistency with the fact that our block() doesn't block. - fn ready(&self) -> bool { - true - } - - /// Never blocks, lest we block forever. - fn block(&self) -> () { - () - } -} - -impl poll::Guest for Wasiless { - type Pollable = Pollable; - - /// This is a real implementation, in an attempt to present a consistent - /// picture of our fake reality to callers and thus avoid provoking crashes - /// unnecessarily. - fn poll(pollables: Vec) -> Vec { - if pollables.len() > (u32::MAX as usize) { - panic!("list of pollables too long to be indexed with a u32") - } - pollables - .iter() - .enumerate() - .filter_map(|(i, p)| { - if p.get::().ready() { - Some(i as u32) - } else { - None - } - }) - .collect() - } -} - -impl GuestInputStream for InputStream { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - - fn read(&self, _len: u64) -> Result, StreamError> { - Ok(Vec::new()) - } - - fn blocking_read(&self, _len: u64) -> Result, StreamError> { - Ok(Vec::new()) - } - - fn skip(&self, _len: u64) -> Result { - Ok(0) - } - - fn blocking_skip(&self, _len: u64) -> Result { - Ok(0) - } - - fn subscribe(&self) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } - } -} - -/// Writes appear to go through without error but also report back that they wrote 0 bytes. -impl GuestOutputStream for OutputStream { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - - fn check_write(&self) -> Result { - Ok(4096) // TODO: Make this interlock with subscribe(). - } - - fn write(&self, _contents: Vec) -> Result<(), StreamError> { - Ok(()) - } - - fn blocking_write_and_flush(&self, _contents: Vec) -> Result<(), StreamError> { - Ok(()) - } - - fn flush(&self) -> Result<(), StreamError> { - Ok(()) - } - - fn blocking_flush(&self) -> Result<(), StreamError> { - Ok(()) - } - - fn subscribe(&self) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } - } - - fn write_zeroes(&self, _len: u64) -> Result<(), StreamError> { - Ok(()) - } - - fn blocking_write_zeroes_and_flush(&self, _len: u64) -> Result<(), StreamError> { - Ok(()) - } - - fn splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { - Ok(0) - } - - fn blocking_splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { - Ok(0) - } -} - -impl streams::Guest for Wasiless { - type InputStream = InputStream; - type OutputStream = OutputStream; -} - -impl wall_clock::Guest for Wasiless { - fn now() -> Datetime { - Datetime { - seconds: 0, - nanoseconds: 0, - } - } - - fn resolution() -> Datetime { - Datetime { - seconds: 0, - nanoseconds: 0, - } - } -} - -impl monotonic_clock::Guest for Wasiless { - fn now() -> Instant { - 0 - } - - fn resolution() -> Duration { - 1 // A little less absurd than 0 - } - - fn subscribe_instant(_when: Instant) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } - } - - fn subscribe_duration(_when: Duration) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } - } -} - -impl GuestDescriptor for Descriptor { - fn read_via_stream(&self, _offset: Filesize) -> Result { - Err(ErrorCode::Unsupported) - } - - fn write_via_stream(&self, _offset: Filesize) -> Result { - Err(ErrorCode::Unsupported) - } - - fn append_via_stream(&self) -> Result { - Err(ErrorCode::Unsupported) - } - - fn advise( - &self, - _offset: Filesize, - _length: Filesize, - _advice: Advice, - ) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn sync_data(&self) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn get_flags(&self) -> Result { - Err(ErrorCode::Unsupported) - } - - fn get_type(&self) -> Result { - Err(ErrorCode::Unsupported) - } - - fn set_size(&self, _size: Filesize) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn set_times( - &self, - _data_access_timestamp: NewTimestamp, - _data_modification_timestamp: NewTimestamp, - ) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn read(&self, _length: Filesize, _offset: Filesize) -> Result<(Vec, bool), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn write(&self, _buffer: Vec, _offset: Filesize) -> Result { - Err(ErrorCode::Unsupported) - } - - fn read_directory(&self) -> Result { - Err(ErrorCode::Unsupported) - } - - fn sync(&self) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn create_directory_at(&self, _path: String) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn stat(&self) -> Result { - Err(ErrorCode::Unsupported) - } - - fn stat_at(&self, _path_flags: PathFlags, _path: String) -> Result { - Err(ErrorCode::Unsupported) - } - - fn set_times_at( - &self, - _path_flags: PathFlags, - _path: String, - _data_access_timestamp: NewTimestamp, - _data_modification_timestamp: NewTimestamp, - ) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn link_at( - &self, - _old_path_flags: PathFlags, - _old_path: String, - _new_descriptor: DescriptorBorrow<'_>, - _new_path: String, - ) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn open_at( - &self, - _path_flags: PathFlags, - _path: String, - _open_flags: OpenFlags, - _flags: DescriptorFlags, - ) -> Result { - Err(ErrorCode::Unsupported) - } - - fn readlink_at(&self, _path: String) -> Result { - Err(ErrorCode::Unsupported) - } - - fn remove_directory_at(&self, _path: String) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn rename_at( - &self, - _old_path: String, - _new_descriptor: DescriptorBorrow<'_>, - _new_path: String, - ) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn symlink_at(&self, _old_path: String, _new_path: String) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn unlink_file_at(&self, _path: String) -> Result<(), ErrorCode> { - Err(ErrorCode::Unsupported) - } - - fn is_same_object(&self, _other: DescriptorBorrow<'_>) -> bool { - false // arbitrary - } - - fn metadata_hash(&self) -> Result { - Err(ErrorCode::Unsupported) - } - - fn metadata_hash_at( - &self, - _path_flags: PathFlags, - _path: String, - ) -> Result { - Err(ErrorCode::Unsupported) - } -} - -impl GuestDirectoryEntryStream for DirectoryEntryStream { - fn read_directory_entry(&self) -> Result, ErrorCode> { - Err(ErrorCode::Unsupported) - } -} - -impl filesystem::types::Guest for Wasiless { - type Descriptor = Descriptor; - type DirectoryEntryStream = DirectoryEntryStream; - fn filesystem_error_code(_err: ErrorBorrow) -> Option { - None - } -} - export!(Wasiless with_types_in bindings); From 2b308c4f670bc720271fea9e0f7e4a18670ccc81 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 17:12:01 -0400 Subject: [PATCH 19/50] Add `wasi:filesystem/preopens`. --- src/filesystem.rs | 6 ++++++ wit/wasiless.wit | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/filesystem.rs b/src/filesystem.rs index 9b95ee6..d19985a 100644 --- a/src/filesystem.rs +++ b/src/filesystem.rs @@ -168,3 +168,9 @@ impl filesystem::types::Guest for Wasiless { None } } + +impl filesystem::preopens::Guest for Wasiless { + fn get_directories() -> Vec<(Descriptor, String)> { + Vec::new() + } +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index b682fa8..43ae203 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -11,7 +11,7 @@ world wasiless { export wasi:io/streams@0.2.6; export wasi:clocks/wall-clock@0.2.6; export wasi:filesystem/types@0.2.6; -// export wasi:filesystem/preopens@0.2.6; + export wasi:filesystem/preopens@0.2.6; // export wasi:sockets/network@0.2.6; // export wasi:sockets/instance-network@0.2.6; // export wasi:sockets/udp@0.2.6; From 84d75bb2def5fbe963b6b2741c430d9266256cbb Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 17:24:15 -0400 Subject: [PATCH 20/50] Add `wasi:sockets/network`. --- src/lib.rs | 1 + src/sockets.rs | 8 ++++++++ wit/wasiless.wit | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 src/sockets.rs diff --git a/src/lib.rs b/src/lib.rs index cdfd863..746f328 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ mod cli; mod clocks; mod filesystem; mod io; +mod sockets; use bindings::export; diff --git a/src/sockets.rs b/src/sockets.rs new file mode 100644 index 0000000..4170d45 --- /dev/null +++ b/src/sockets.rs @@ -0,0 +1,8 @@ +use crate::Wasiless; +use crate::bindings::wasi::sockets::network::{self, GuestNetwork, Network}; + +impl GuestNetwork for Network {} + +impl network::Guest for Wasiless { + type Network = Network; +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 43ae203..6bd7ee0 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -12,7 +12,7 @@ world wasiless { export wasi:clocks/wall-clock@0.2.6; export wasi:filesystem/types@0.2.6; export wasi:filesystem/preopens@0.2.6; -// export wasi:sockets/network@0.2.6; + export wasi:sockets/network@0.2.6; // export wasi:sockets/instance-network@0.2.6; // export wasi:sockets/udp@0.2.6; // export wasi:sockets/udp-create-socket@0.2.6; From 5f17fad81ce97f85c46fbf329db6db89ea5fe997 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 17:31:06 -0400 Subject: [PATCH 21/50] Add `wasi:sockets/instance-network`. --- src/sockets.rs | 9 ++++++++- wit/wasiless.wit | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/sockets.rs b/src/sockets.rs index 4170d45..f191577 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -1,8 +1,15 @@ -use crate::Wasiless; +use crate::bindings::wasi::sockets::instance_network::{self}; use crate::bindings::wasi::sockets::network::{self, GuestNetwork, Network}; +use crate::{BOGUS_HANDLE, Wasiless}; impl GuestNetwork for Network {} impl network::Guest for Wasiless { type Network = Network; } + +impl instance_network::Guest for Wasiless { + fn instance_network() -> Network { + unsafe { Network::from_handle(BOGUS_HANDLE) } + } +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 6bd7ee0..c66ee9b 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -13,7 +13,7 @@ world wasiless { export wasi:filesystem/types@0.2.6; export wasi:filesystem/preopens@0.2.6; export wasi:sockets/network@0.2.6; -// export wasi:sockets/instance-network@0.2.6; + export wasi:sockets/instance-network@0.2.6; // export wasi:sockets/udp@0.2.6; // export wasi:sockets/udp-create-socket@0.2.6; export wasi:clocks/monotonic-clock@0.2.6; From bb29df8f8d73dc8fd62aeddbeb7d08ffcb298972 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 17:49:49 -0400 Subject: [PATCH 22/50] Add `wasi:sockets/udp`. Starting to simply throw `unimplemented!()`. It makes the stubs faster to write, and it's not clear that eager failure isn't preferable, unless Python demands actual operational routines. It's likely I'll go back and change the present mock-ish implementations to `unimplemented!()` as well. --- src/sockets.rs | 100 ++++++++++++++++++++++++++++++++++++++++++++++- wit/wasiless.wit | 2 +- 2 files changed, 99 insertions(+), 3 deletions(-) diff --git a/src/sockets.rs b/src/sockets.rs index f191577..28c51b9 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -1,5 +1,12 @@ -use crate::bindings::wasi::sockets::instance_network::{self}; -use crate::bindings::wasi::sockets::network::{self, GuestNetwork, Network}; +use crate::bindings::wasi::io::poll::Pollable; +use crate::bindings::wasi::sockets::instance_network; +use crate::bindings::wasi::sockets::network::{ + self, ErrorCode, GuestNetwork, IpAddressFamily, IpSocketAddress, Network, NetworkBorrow, +}; +use crate::bindings::wasi::sockets::udp::{ + self, GuestIncomingDatagramStream, GuestOutgoingDatagramStream, GuestUdpSocket, + IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream, UdpSocket, +}; use crate::{BOGUS_HANDLE, Wasiless}; impl GuestNetwork for Network {} @@ -13,3 +20,92 @@ impl instance_network::Guest for Wasiless { unsafe { Network::from_handle(BOGUS_HANDLE) } } } + +impl GuestUdpSocket for UdpSocket { + fn start_bind( + &self, + _network: NetworkBorrow, + _local_address: IpSocketAddress, + ) -> Result<(), ErrorCode> { + unimplemented!() + } + + fn finish_bind(&self) -> Result<(), ErrorCode> { + unimplemented!() + } + + fn stream( + &self, + _remote_address: Option, + ) -> Result<(IncomingDatagramStream, OutgoingDatagramStream), ErrorCode> { + unimplemented!() + } + + fn local_address(&self) -> Result { + unreachable!() + } + + fn remote_address(&self) -> Result { + unreachable!() + } + + fn address_family(&self) -> IpAddressFamily { + unreachable!() + } + + fn unicast_hop_limit(&self) -> Result { + unreachable!() + } + + fn set_unicast_hop_limit(&self, _value: u8) -> Result<(), ErrorCode> { + unreachable!() + } + + fn receive_buffer_size(&self) -> Result { + unreachable!() + } + + fn set_receive_buffer_size(&self, _value: u64) -> Result<(), ErrorCode> { + unreachable!() + } + + fn send_buffer_size(&self) -> Result { + unreachable!() + } + + fn set_send_buffer_size(&self, _value: u64) -> Result<(), ErrorCode> { + unreachable!() + } + + fn subscribe(&self) -> Pollable { + unreachable!() + } +} + +impl GuestIncomingDatagramStream for IncomingDatagramStream { + fn receive(&self, _max_results: u64) -> Result, ErrorCode> { + unreachable!() + } + + fn subscribe(&self) -> Pollable { + unreachable!() + } +} + +impl GuestOutgoingDatagramStream for OutgoingDatagramStream { + fn check_send(&self) -> Result { + unreachable!() + } + fn send(&self, _datagrams: Vec) -> Result { + unreachable!() + } + fn subscribe(&self) -> Pollable { + unreachable!() + } +} + +impl udp::Guest for Wasiless { + type UdpSocket = UdpSocket; + type IncomingDatagramStream = IncomingDatagramStream; + type OutgoingDatagramStream = OutgoingDatagramStream; +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index c66ee9b..b2782f0 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -14,7 +14,7 @@ world wasiless { export wasi:filesystem/preopens@0.2.6; export wasi:sockets/network@0.2.6; export wasi:sockets/instance-network@0.2.6; -// export wasi:sockets/udp@0.2.6; + export wasi:sockets/udp@0.2.6; // export wasi:sockets/udp-create-socket@0.2.6; export wasi:clocks/monotonic-clock@0.2.6; // export wasi:sockets/tcp@0.2.6; From 261e322b8c9f49a0b2debb06ac02807f9baa8072 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 30 Sep 2025 17:52:57 -0400 Subject: [PATCH 23/50] Add `wasi:sockets/udp-create-socket`. --- src/sockets.rs | 7 +++++++ wit/wasiless.wit | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/sockets.rs b/src/sockets.rs index 28c51b9..d5faaee 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -7,6 +7,7 @@ use crate::bindings::wasi::sockets::udp::{ self, GuestIncomingDatagramStream, GuestOutgoingDatagramStream, GuestUdpSocket, IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream, UdpSocket, }; +use crate::bindings::wasi::sockets::udp_create_socket; use crate::{BOGUS_HANDLE, Wasiless}; impl GuestNetwork for Network {} @@ -109,3 +110,9 @@ impl udp::Guest for Wasiless { type IncomingDatagramStream = IncomingDatagramStream; type OutgoingDatagramStream = OutgoingDatagramStream; } + +impl udp_create_socket::Guest for Wasiless { + fn create_udp_socket(_address_family: IpAddressFamily) -> Result { + unimplemented!() + } +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index b2782f0..8209daf 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -15,7 +15,7 @@ world wasiless { export wasi:sockets/network@0.2.6; export wasi:sockets/instance-network@0.2.6; export wasi:sockets/udp@0.2.6; -// export wasi:sockets/udp-create-socket@0.2.6; + export wasi:sockets/udp-create-socket@0.2.6; export wasi:clocks/monotonic-clock@0.2.6; // export wasi:sockets/tcp@0.2.6; // export wasi:sockets/tcp-create-socket@0.2.6; From ae4c0a1d6ced4314f50c122eb8b134a65e6a25da Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Wed, 1 Oct 2025 10:46:57 -0400 Subject: [PATCH 24/50] Add `wasi:sockets/tcp`. --- src/sockets.rs | 129 +++++++++++++++++++++++++++++++++++++++++++++++ wit/wasiless.wit | 2 +- 2 files changed, 130 insertions(+), 1 deletion(-) diff --git a/src/sockets.rs b/src/sockets.rs index d5faaee..0f96e8b 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -3,6 +3,7 @@ use crate::bindings::wasi::sockets::instance_network; use crate::bindings::wasi::sockets::network::{ self, ErrorCode, GuestNetwork, IpAddressFamily, IpSocketAddress, Network, NetworkBorrow, }; +use crate::bindings::wasi::sockets::tcp::{self, GuestTcpSocket, TcpSocket}; use crate::bindings::wasi::sockets::udp::{ self, GuestIncomingDatagramStream, GuestOutgoingDatagramStream, GuestUdpSocket, IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream, UdpSocket, @@ -116,3 +117,131 @@ impl udp_create_socket::Guest for Wasiless { unimplemented!() } } + +impl GuestTcpSocket for TcpSocket { + fn start_bind( + &self, + _network: tcp::NetworkBorrow<'_>, + _local_address: tcp::IpSocketAddress, + ) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn finish_bind(&self) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn start_connect( + &self, + _network: tcp::NetworkBorrow<'_>, + _remote_address: tcp::IpSocketAddress, + ) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn finish_connect(&self) -> Result<(tcp::InputStream, tcp::OutputStream), tcp::ErrorCode> { + unreachable!() + } + + fn start_listen(&self) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn finish_listen(&self) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn accept( + &self, + ) -> Result<(tcp::TcpSocket, tcp::InputStream, tcp::OutputStream), tcp::ErrorCode> { + unreachable!() + } + + fn local_address(&self) -> Result { + unreachable!() + } + + fn remote_address(&self) -> Result { + unreachable!() + } + + fn is_listening(&self) -> bool { + unreachable!() + } + + fn address_family(&self) -> tcp::IpAddressFamily { + unreachable!() + } + + fn set_listen_backlog_size(&self, _value: u64) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn keep_alive_enabled(&self) -> Result { + unreachable!() + } + + fn set_keep_alive_enabled(&self, _value: bool) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn keep_alive_idle_time(&self) -> Result { + unreachable!() + } + + fn set_keep_alive_idle_time(&self, _value: tcp::Duration) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn keep_alive_interval(&self) -> Result { + unreachable!() + } + + fn set_keep_alive_interval(&self, _value: tcp::Duration) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn keep_alive_count(&self) -> Result { + unreachable!() + } + + fn set_keep_alive_count(&self, _value: u32) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn hop_limit(&self) -> Result { + unreachable!() + } + + fn set_hop_limit(&self, _value: u8) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn receive_buffer_size(&self) -> Result { + unreachable!() + } + + fn set_receive_buffer_size(&self, _value: u64) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn send_buffer_size(&self) -> Result { + unreachable!() + } + + fn set_send_buffer_size(&self, _value: u64) -> Result<(), tcp::ErrorCode> { + unreachable!() + } + + fn subscribe(&self) -> tcp::Pollable { + unreachable!() + } + + fn shutdown(&self, _shutdown_type: tcp::ShutdownType) -> Result<(), tcp::ErrorCode> { + unreachable!() + } +} + +impl tcp::Guest for Wasiless { + type TcpSocket = TcpSocket; +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 8209daf..9141e7b 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -17,7 +17,7 @@ world wasiless { export wasi:sockets/udp@0.2.6; export wasi:sockets/udp-create-socket@0.2.6; export wasi:clocks/monotonic-clock@0.2.6; -// export wasi:sockets/tcp@0.2.6; + export wasi:sockets/tcp@0.2.6; // export wasi:sockets/tcp-create-socket@0.2.6; // export wasi:sockets/ip-name-lookup@0.2.6; // export wasi:random/insecure@0.2.6; From ed84dc37196deb0271a691c0e76e799741329653 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 12:10:36 -0400 Subject: [PATCH 25/50] Switch to `wasm32-unknown-unknown` target, which will let this link under Viceroy. I skipped ahead using wit-bindgen to generate all the stubs to see what would happen, and I ran into a link error. It turns out that the `wasm32-wasip2` target adds a lot of extra imports, 0.2.3 WASI ones, which Viceroy doesn't provide and we obviously cannot provide to ourselves. We'll just have to wrap our output in a component ourselves with wasm-tools after building. We'll work that into the build process eventually. --- .cargo/config | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.cargo/config b/.cargo/config index dac2459..435ed75 100644 --- a/.cargo/config +++ b/.cargo/config @@ -1,2 +1,2 @@ [build] -target = "wasm32-wasip2" \ No newline at end of file +target = "wasm32-unknown-unknown" \ No newline at end of file From 4c0b69c10e99ef48f0f7a7afcce2efad0f5356a1 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 12:13:15 -0400 Subject: [PATCH 26/50] Add `wasi:sockets/tcp-create-socket` and `wasi:sockets/ip-name-lookup`. --- src/sockets.rs | 33 +++++++++++++++++++++++++++++++++ wit/wasiless.wit | 4 ++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/sockets.rs b/src/sockets.rs index 0f96e8b..56b9838 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -1,9 +1,11 @@ use crate::bindings::wasi::io::poll::Pollable; use crate::bindings::wasi::sockets::instance_network; +use crate::bindings::wasi::sockets::ip_name_lookup; use crate::bindings::wasi::sockets::network::{ self, ErrorCode, GuestNetwork, IpAddressFamily, IpSocketAddress, Network, NetworkBorrow, }; use crate::bindings::wasi::sockets::tcp::{self, GuestTcpSocket, TcpSocket}; +use crate::bindings::wasi::sockets::tcp_create_socket; use crate::bindings::wasi::sockets::udp::{ self, GuestIncomingDatagramStream, GuestOutgoingDatagramStream, GuestUdpSocket, IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream, UdpSocket, @@ -245,3 +247,34 @@ impl GuestTcpSocket for TcpSocket { impl tcp::Guest for Wasiless { type TcpSocket = TcpSocket; } + +impl tcp_create_socket::Guest for Wasiless { + fn create_tcp_socket( + _address_family: tcp_create_socket::IpAddressFamily, + ) -> Result { + unreachable!() + } +} + +impl ip_name_lookup::GuestResolveAddressStream for Wasiless { + #[allow(unused_variables)] + fn resolve_next_address( + &self, + ) -> Result, ip_name_lookup::ErrorCode> { + unreachable!() + } + #[allow(unused_variables)] + fn subscribe(&self) -> ip_name_lookup::Pollable { + unreachable!() + } +} +impl ip_name_lookup::Guest for Wasiless { + type ResolveAddressStream = Wasiless; + #[allow(unused_variables)] + fn resolve_addresses( + network: ip_name_lookup::NetworkBorrow<'_>, + name: String, + ) -> Result { + unreachable!() + } +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 9141e7b..ddd4601 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -18,8 +18,8 @@ world wasiless { export wasi:sockets/udp-create-socket@0.2.6; export wasi:clocks/monotonic-clock@0.2.6; export wasi:sockets/tcp@0.2.6; -// export wasi:sockets/tcp-create-socket@0.2.6; -// export wasi:sockets/ip-name-lookup@0.2.6; + export wasi:sockets/tcp-create-socket@0.2.6; + export wasi:sockets/ip-name-lookup@0.2.6; // export wasi:random/insecure@0.2.6; // export wasi:random/insecure-seed@0.2.6; // export wasi:random/random@0.2.6; From f58f09ce476919dfcf0506bfff71420e0df5de3b Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 14:45:05 -0400 Subject: [PATCH 27/50] Add `wasi:random/*`. --- src/lib.rs | 1 + src/random.rs | 31 +++++++++++++++++++++++++++++++ wit/wasiless.wit | 6 +++--- 3 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 src/random.rs diff --git a/src/lib.rs b/src/lib.rs index 746f328..a376f52 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ mod cli; mod clocks; mod filesystem; mod io; +mod random; mod sockets; use bindings::export; diff --git a/src/random.rs b/src/random.rs new file mode 100644 index 0000000..95fb3bc --- /dev/null +++ b/src/random.rs @@ -0,0 +1,31 @@ +use crate::Wasiless; +use crate::bindings::wasi::random; + +impl random::insecure::Guest for Wasiless { + #[allow(unused_variables)] + fn get_insecure_random_bytes(len: u64) -> Vec { + unreachable!() + } + #[allow(unused_variables)] + fn get_insecure_random_u64() -> u64 { + unreachable!() + } +} + +impl random::insecure_seed::Guest for Wasiless { + #[allow(unused_variables)] + fn insecure_seed() -> (u64, u64) { + unreachable!() + } +} + +impl random::random::Guest for Wasiless { + #[allow(unused_variables)] + fn get_random_bytes(len: u64) -> Vec { + unreachable!() + } + #[allow(unused_variables)] + fn get_random_u64() -> u64 { + unreachable!() + } +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index ddd4601..9ea4e5a 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -20,9 +20,9 @@ world wasiless { export wasi:sockets/tcp@0.2.6; export wasi:sockets/tcp-create-socket@0.2.6; export wasi:sockets/ip-name-lookup@0.2.6; -// export wasi:random/insecure@0.2.6; -// export wasi:random/insecure-seed@0.2.6; -// export wasi:random/random@0.2.6; + export wasi:random/insecure@0.2.6; + export wasi:random/insecure-seed@0.2.6; + export wasi:random/random@0.2.6; // export wasi:cli/environment@0.2.6; // export wasi:cli/exit@0.2.6; // export wasi:cli/stdout@0.2.6; From 5f39e6ecc2353bbf8c86b0d5673e391b839f344f Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 14:49:33 -0400 Subject: [PATCH 28/50] Add `wasi:cli/exit`, `stdout`, `stderr`, and `stdin`. Now we have at least panicking stubs for everything. --- src/cli.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++--- wit/wasiless.wit | 10 +++++----- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 2cb3458..311ef9e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,8 +1,8 @@ use crate::bindings::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; use crate::bindings::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; -use crate::bindings::wasi::cli::terminal_stderr; -use crate::bindings::wasi::cli::terminal_stdin; -use crate::bindings::wasi::cli::terminal_stdout; +use crate::bindings::wasi::cli::{ + environment, exit, stderr, stdin, stdout, terminal_stderr, terminal_stdin, terminal_stdout, +}; use crate::{BOGUS_HANDLE, BOGUS_RESOURCE, Wasiless}; // TODO: Make less bogus so it stands a chance of not crashing at runtime. Same @@ -65,3 +65,46 @@ impl terminal_stderr::Guest for Wasiless { None } } + +impl environment::Guest for Wasiless { + #[allow(unused_variables)] + fn get_environment() -> Vec<(String, String)> { + unreachable!() + } + #[allow(unused_variables)] + fn get_arguments() -> Vec { + unreachable!() + } + #[allow(unused_variables)] + fn initial_cwd() -> Option { + unreachable!() + } +} + +impl exit::Guest for Wasiless { + #[allow(unused_variables)] + fn exit(status: Result<(), ()>) -> () { + unreachable!() + } +} + +impl stdout::Guest for Wasiless { + #[allow(unused_variables)] + fn get_stdout() -> stdout::OutputStream { + unreachable!() + } +} + +impl stderr::Guest for Wasiless { + #[allow(unused_variables)] + fn get_stderr() -> stderr::OutputStream { + unreachable!() + } +} + +impl stdin::Guest for Wasiless { + #[allow(unused_variables)] + fn get_stdin() -> stdin::InputStream { + unreachable!() + } +} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 9ea4e5a..01906dd 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -23,10 +23,10 @@ world wasiless { export wasi:random/insecure@0.2.6; export wasi:random/insecure-seed@0.2.6; export wasi:random/random@0.2.6; -// export wasi:cli/environment@0.2.6; -// export wasi:cli/exit@0.2.6; -// export wasi:cli/stdout@0.2.6; -// export wasi:cli/stderr@0.2.6; -// export wasi:cli/stdin@0.2.6; + export wasi:cli/environment@0.2.6; + export wasi:cli/exit@0.2.6; + export wasi:cli/stdout@0.2.6; + export wasi:cli/stderr@0.2.6; + export wasi:cli/stdin@0.2.6; } // Version numbers are fairly arbitrary. \ No newline at end of file From 723d8a03fb7101130922eab98a5a0f106e565c99 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 15:14:59 -0400 Subject: [PATCH 29/50] Add null implementations for `get_environment()` and `get_arguments()`. CPython calls these on startup. --- src/cli.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 311ef9e..253f174 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -69,11 +69,11 @@ impl terminal_stderr::Guest for Wasiless { impl environment::Guest for Wasiless { #[allow(unused_variables)] fn get_environment() -> Vec<(String, String)> { - unreachable!() + Vec::new() } #[allow(unused_variables)] fn get_arguments() -> Vec { - unreachable!() + Vec::new() } #[allow(unused_variables)] fn initial_cwd() -> Option { From d7b9a0ca4f85b0d5377221ff8a2d95a1ccf71b8f Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 15:24:13 -0400 Subject: [PATCH 30/50] Add horribly bogus `get_random_bytes()` so CPython can start up. Rust stdlib has no RNGs yet. `rand` crate doesn't support JS-less wasm. Perhaps the experimental RNG stuff in Rust nightly would work. --- src/random.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/random.rs b/src/random.rs index 95fb3bc..dcaef59 100644 --- a/src/random.rs +++ b/src/random.rs @@ -22,7 +22,10 @@ impl random::insecure_seed::Guest for Wasiless { impl random::random::Guest for Wasiless { #[allow(unused_variables)] fn get_random_bytes(len: u64) -> Vec { - unreachable!() + // TODO: This isn't random at all, let alone cryptographically so. As + // such, it violates the WASI spec, which stipulates this must be left + // out if it can't be random. + Vec::with_capacity(len as usize) } #[allow(unused_variables)] fn get_random_u64() -> u64 { From 24b0ffb11c8faca30f5fbfcbbb3db00480d8d1a3 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 15:27:06 -0400 Subject: [PATCH 31/50] Stop constructing bogus resources that will almost certainly provoke a crash eventually. Crash promptly so the crash is easy to track down. --- src/cli.rs | 37 +++-------------------------- src/clocks.rs | 6 ++--- src/io.rs | 63 +++----------------------------------------------- src/lib.rs | 3 --- src/sockets.rs | 4 ++-- 5 files changed, 11 insertions(+), 102 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 253f174..80ce2b6 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,48 +1,17 @@ +use crate::Wasiless; use crate::bindings::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; use crate::bindings::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; use crate::bindings::wasi::cli::{ environment, exit, stderr, stdin, stdout, terminal_stderr, terminal_stdin, terminal_stdout, }; -use crate::{BOGUS_HANDLE, BOGUS_RESOURCE, Wasiless}; -// TODO: Make less bogus so it stands a chance of not crashing at runtime. Same -// for other BOGUS_RESOURCE and BOGUS_HANDLE users. For now, I'm just seeing if -// I can get it to link. -impl GuestTerminalInput for TerminalInput { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } -} +impl GuestTerminalInput for TerminalInput {} impl terminal_input::Guest for Wasiless { type TerminalInput = TerminalInput; } -impl GuestTerminalOutput for TerminalOutput { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } -} +impl GuestTerminalOutput for TerminalOutput {} impl terminal_output::Guest for Wasiless { type TerminalOutput = TerminalOutput; diff --git a/src/clocks.rs b/src/clocks.rs index b573ced..44f0be4 100644 --- a/src/clocks.rs +++ b/src/clocks.rs @@ -1,7 +1,7 @@ +use crate::Wasiless; use crate::bindings::wasi::clocks::monotonic_clock::{self, Duration, Instant}; use crate::bindings::wasi::clocks::wall_clock::{self, Datetime}; use crate::bindings::wasi::io::poll::Pollable; -use crate::{BOGUS_HANDLE, Wasiless}; impl wall_clock::Guest for Wasiless { fn now() -> Datetime { @@ -29,10 +29,10 @@ impl monotonic_clock::Guest for Wasiless { } fn subscribe_instant(_when: Instant) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } + unreachable!() } fn subscribe_duration(_when: Duration) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } + unreachable!() } } diff --git a/src/io.rs b/src/io.rs index f9bb4a8..bd4beaa 100644 --- a/src/io.rs +++ b/src/io.rs @@ -1,3 +1,4 @@ +use crate::Wasiless; use crate::bindings::wasi::io::error::{self, Error, GuestError}; use crate::bindings::wasi::io::poll::Pollable; use crate::bindings::wasi::io::poll::{self, GuestPollable, PollableBorrow}; @@ -5,23 +6,8 @@ use crate::bindings::wasi::io::streams::{ self, GuestInputStream, GuestOutputStream, InputStream, InputStreamBorrow, OutputStream, StreamError, }; -use crate::{BOGUS_HANDLE, BOGUS_RESOURCE, Wasiless}; impl GuestError for Error { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - fn to_debug_string(&self) -> String { "".to_owned() } @@ -32,20 +18,6 @@ impl error::Guest for Wasiless { } impl GuestPollable for Pollable { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - /// Returns true for consistency with the fact that our block() doesn't block. fn ready(&self) -> bool { true @@ -82,20 +54,6 @@ impl poll::Guest for Wasiless { } impl GuestInputStream for InputStream { - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - fn read(&self, _len: u64) -> Result, StreamError> { Ok(Vec::new()) } @@ -113,27 +71,12 @@ impl GuestInputStream for InputStream { } fn subscribe(&self) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } + unreachable!() } } /// Writes appear to go through without error but also report back that they wrote 0 bytes. impl GuestOutputStream for OutputStream { - // TODO: Maybe we can delete all these _resource*() funcs; the trait has a crashing default impl. - unsafe fn _resource_new(_val: *mut u8) -> u32 - where - Self: Sized, - { - BOGUS_HANDLE - } - - fn _resource_rep(_handle: u32) -> *mut u8 - where - Self: Sized, - { - &raw mut BOGUS_RESOURCE - } - fn check_write(&self) -> Result { Ok(4096) // TODO: Make this interlock with subscribe(). } @@ -155,7 +98,7 @@ impl GuestOutputStream for OutputStream { } fn subscribe(&self) -> Pollable { - unsafe { Pollable::from_handle(BOGUS_HANDLE) } + unreachable!() } fn write_zeroes(&self, _len: u64) -> Result<(), StreamError> { diff --git a/src/lib.rs b/src/lib.rs index a376f52..b458398 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,9 +16,6 @@ mod sockets; use bindings::export; -static mut BOGUS_RESOURCE: u8 = 0; -static BOGUS_HANDLE: u32 = 0; - /// Wasm component implementing WASI with as little functionality as possible /// without trapping struct Wasiless; diff --git a/src/sockets.rs b/src/sockets.rs index 56b9838..2ace13d 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -1,3 +1,4 @@ +use crate::Wasiless; use crate::bindings::wasi::io::poll::Pollable; use crate::bindings::wasi::sockets::instance_network; use crate::bindings::wasi::sockets::ip_name_lookup; @@ -11,7 +12,6 @@ use crate::bindings::wasi::sockets::udp::{ IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream, UdpSocket, }; use crate::bindings::wasi::sockets::udp_create_socket; -use crate::{BOGUS_HANDLE, Wasiless}; impl GuestNetwork for Network {} @@ -21,7 +21,7 @@ impl network::Guest for Wasiless { impl instance_network::Guest for Wasiless { fn instance_network() -> Network { - unsafe { Network::from_handle(BOGUS_HANDLE) } + unreachable!() } } From 10dbbba19230673feb570944d486efdd22bbe5e4 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 15:46:33 -0400 Subject: [PATCH 32/50] Rename `.cargo/config` to fix deprecation warning on `cargo build`. --- .cargo/{config => config.toml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .cargo/{config => config.toml} (100%) diff --git a/.cargo/config b/.cargo/config.toml similarity index 100% rename from .cargo/config rename to .cargo/config.toml From 90b0a1f7d6f5946d94f6726dfaab758cf889dfcc Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Fri, 3 Oct 2025 16:05:02 -0400 Subject: [PATCH 33/50] Add a minimal readme. --- Cargo.toml | 2 +- README.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 README.md diff --git a/Cargo.toml b/Cargo.toml index 57c9add..bd9e937 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "wasiless" version = "0.1.0" edition = "2024" -description = "A null implementation of WASI, doing as little as possible while still allowing each function to return without trapping" +description = "Minimal or trapping implementations of WASI interfaces, allowing ports from non-WASI environments to link and even sometimes run" [dependencies] wit-bindgen = "0.46.0" diff --git a/README.md b/README.md new file mode 100644 index 0000000..fe0ca3d --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# wasiless + +Wasiless is a component that provides minimal or trapping implementations of all WASI interfaces, meant to allow the porting of dynamic runtimes like CPython which expect a normal OS with normal affordances like filesystems and sockets. Build CPython (or what have you) as a component, satisfy its imports with wasiless, then you can run it on a Compute worker. + +Many of these stubs panic immediately, which is a nonissue if they are never actually called. This may be the overwhelmingly common case. In cases where it is not, we should instead return error codes like E_NOTSUP, which will allowed more graceful recovery or error reporting by the guest language (e.g. Python tracebacks). From 11f68561af136bc1093323c2d2ad174c316b2f69 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 6 Oct 2025 11:07:05 -0400 Subject: [PATCH 34/50] Polish readme. --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fe0ca3d..6884472 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,49 @@ # wasiless -Wasiless is a component that provides minimal or trapping implementations of all WASI interfaces, meant to allow the porting of dynamic runtimes like CPython which expect a normal OS with normal affordances like filesystems and sockets. Build CPython (or what have you) as a component, satisfy its imports with wasiless, then you can run it on a Compute worker. +Wasiless is a WebAssembly component that provides minimal or trapping implementations of all WASI interfaces, meant to allow the porting of dynamic runtimes like CPython which expect a normal OS, with normal affordances like filesystems and sockets. Build CPython (or some other runtime) as a component, satisfy its imports with wasiless, and you should be able to run it in an environment that provides only a subset of WASI, like [Viceroy](https://github.com/fastly/Viceroy). -Many of these stubs panic immediately, which is a nonissue if they are never actually called. This may be the overwhelmingly common case. In cases where it is not, we should instead return error codes like E_NOTSUP, which will allowed more graceful recovery or error reporting by the guest language (e.g. Python tracebacks). +Here is an example composition of wasiless and a Python component (built using componentize-py) for use with Viceroy: + +``` +package fastly:python-wasiless; + +// Instantiate wasiless, minimal or crashing implementations of irrelevant WASI interfaces: +let wasiless = new fastly:wasiless { + ... +}; + +// Instantiate the Python component. Pass in the 0.2.6 routines from wasiless, +// even when Python wants a different version: +let app = new app:component { + "wasi:cli/terminal-input@0.2.0": wasiless["wasi:cli/terminal-input@0.2.6"], + "wasi:cli/terminal-output@0.2.0": wasiless["wasi:cli/terminal-output@0.2.6"], + "wasi:cli/terminal-stdin@0.2.0": wasiless["wasi:cli/terminal-stdin@0.2.6"], + "wasi:cli/terminal-stdout@0.2.0": wasiless["wasi:cli/terminal-stdout@0.2.6"], + "wasi:cli/terminal-stderr@0.2.0": wasiless["wasi:cli/terminal-stderr@0.2.6"], + "wasi:filesystem/types@0.2.0": wasiless["wasi:filesystem/types@0.2.6"], + "wasi:filesystem/preopens@0.2.0": wasiless["wasi:filesystem/preopens@0.2.6"], + "wasi:sockets/network@0.2.0": wasiless["wasi:sockets/network@0.2.6"], + "wasi:sockets/instance-network@0.2.0": wasiless["wasi:sockets/instance-network@0.2.6"], + "wasi:sockets/udp@0.2.0": wasiless["wasi:sockets/udp@0.2.6"], + "wasi:sockets/udp-create-socket@0.2.0": wasiless["wasi:sockets/udp-create-socket@0.2.6"], + "wasi:sockets/tcp@0.2.0": wasiless["wasi:sockets/tcp@0.2.6"], + "wasi:sockets/tcp-create-socket@0.2.0": wasiless["wasi:sockets/tcp-create-socket@0.2.6"], + "wasi:sockets/ip-name-lookup@0.2.0": wasiless["wasi:sockets/ip-name-lookup@0.2.6"], + "wasi:random/insecure@0.2.0": wasiless["wasi:random/insecure@0.2.6"], + "wasi:random/insecure-seed@0.2.0": wasiless["wasi:random/insecure-seed@0.2.6"], + ... +}; + +export app.exports; +export app["fastly:compute/http-incoming"]; +``` + +To apply this, save it as `wrap_app_in_wasiless.wac`, then invoke wac like... + +``` +wac compose --dep fastly:wasiless=wasiless.wasm --dep app:component=python_app.wasm -o composed.wasm wrap_app_in_wasiless.wac +``` + +## Caveats and philosophy + +Many of wasiless’ functions panic immediately. This is a nonissue if they are never actually called, which appears to be the common case. Where this is not true, we strive instead to return error codes like `ENOTSUP`, which allows more graceful recovery or error reporting by the guest language (e.g. Python tracebacks). From a6f6e79e4d4d6729b14d08d39695871fa5e7d998 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Wed, 8 Oct 2025 12:44:39 -0400 Subject: [PATCH 35/50] Update compute.wit to match Viceroy `main` at f6b6b1045ce5e1f61cbecf4bbcc9e92e43545224. It made no different in the WIT of the emitted component. --- wit/deps/fastly/compute.wit | 236 ++++++++++++++++++++---------------- 1 file changed, 130 insertions(+), 106 deletions(-) diff --git a/wit/deps/fastly/compute.wit b/wit/deps/fastly/compute.wit index 5c2df02..9299e04 100644 --- a/wit/deps/fastly/compute.wit +++ b/wit/deps/fastly/compute.wit @@ -67,6 +67,31 @@ interface types { limit-exceeded, } + /// An error returned by `open`-like functions. + enum open-error { + /// The given name of the entity to open was invalid. + invalid-syntax, + /// The given name is longer the maximum permitted length. + name-too-long, + /// The given name is a reserved name that may not be opened. + reserved, + /// No entity by the given name was found. + not-found, + /// Unsupported operation error. + /// + /// This error is returned when some operation cannot be performed, because it is not supported. + unsupported, + /// Limit exceeded + /// + /// This is returned when an attempt to allocate a resource has exceeded the maximum number of + /// resources permitted. For example, creating too many response handles. + limit-exceeded, + /// Generic error value. + /// + /// This means that some unexpected error occurred. + generic-error, + } + /// IPv4 addresses. type ipv4-address = tuple; @@ -171,16 +196,15 @@ interface http-body { read: func(body: borrow, chunk-size: u32) -> result, error>; /// Writes to a body. - write: func(body: borrow, buf: list, end: write-end) -> result; - - /// Which side of a body to write to. - enum write-end { - /// Write to the back of the body; that is, append to it. - back, + /// + /// This function may write fewer bytes than requested; on success, the number of + /// bytes actually written is returned. + write: func(body: borrow, buf: list) -> result; - /// Write to the front of the body; that is, prepend to it. - front - } + /// Prepends bytes to the front of a body. + /// + /// On success, this function always writes all the bytes of `buf`. + write-front: func(body: borrow, buf: list) -> result<_, error>; /// Frees a body. /// @@ -224,7 +248,7 @@ interface http-body { body: borrow, max-len: u64, cursor: u32, - ) -> result>, error>; + ) -> result>, trailer-error>; /// Gets the value for the trailer with the given name, or `none` if the trailer is not present. /// @@ -239,7 +263,7 @@ interface http-body { body: borrow, name: string, max-len: u64, - ) -> result>, error>; + ) -> result>, trailer-error>; /// Gets multiple values associated with the trailer with the given name. /// @@ -255,15 +279,24 @@ interface http-body { name: string, max-len: u64, cursor: u32 - ) -> result, option>, error>; + ) -> result, option>, trailer-error>; + + /// Trailers aren't available until the body has been completely transmitted, so this error + /// type can either indicate that the errors aren't available yet, or that an error occurred. + variant trailer-error { + /// The trailers aren't available yet. + not-available-yet, + + /// An error occurred. + error(error), + } } /// Low-level interface to Fastly's [Real-Time Log Streaming] endpoints. /// /// [Real-Time Log Streaming]: https://docs.fastly.com/en/guides/about-fastlys-realtime-log-streaming-features interface log { - - use types.{error}; + use types.{error, open-error}; /// A logging endpoint. resource endpoint { @@ -278,7 +311,7 @@ interface log { /// logging endpoint available in your service will still return a usable endpoint, and writes /// to that endpoint will succeed. Refer to your service dashboard to diagnose missing log /// events. - get: static func(name: string) -> result; + open: static func(name: string) -> result; /// Writes a data to the given endpoint. /// @@ -294,7 +327,7 @@ interface log { interface http-downstream { use types.{error, ip-address}; use http-req.{ - request, client-cert-verify-result, error-with-detail, cache-override, request-promise, + request, client-cert-verify-result, error-with-detail, cache-override, pending-request, request-with-body, }; @@ -312,18 +345,18 @@ interface http-downstream { /// Starts waiting for the next request. next-request: func( options: next-request-options, - ) -> result; + ) -> result; /// Waits until the next request is available, and then returns the resulting /// request and body. /// /// Returns `ok(none)` if there are no more requests for this session. - await-next-request: func( - pending: request-promise, + await-request: func( + pending: pending-request, ) -> result, error>; next-request-abandon: func( - pending: request-promise, + pending: pending-request, ) -> result<_, error>; /// Returns the client request's header names exactly as they were originally received. @@ -475,11 +508,11 @@ interface http-req { use http-body.{body}; use http-resp.{response-with-body}; - /// Handle that can be used to wait for a sent request. - use async-io.{pollable as pending-request}; + /// Handle that can be used to wait for a response from a sent request. + use async-io.{pollable as pending-response}; /// Handle that can be used to wait for incoming requests. - use async-io.{pollable as request-promise}; + use async-io.{pollable as pending-request}; /// An HTTP request. resource request { @@ -605,23 +638,6 @@ interface http-req { mode: framing-headers-mode, ) -> result<_, error>; - /// Inspects request HTTP traffic using the [NGWAF] lookaside service. - /// - /// Returns a JSON-encoded string. - /// - /// [NGWAF]: https://docs.fastly.com/en/ngwaf/ - inspect: func( - body: borrow, - options: inspect-options, - max-len: u64 - ) -> result; - - /// Instead of having this request cache in this service's space, use the - /// cache of the named service - on-behalf-of: func( - service: string, - ) -> result<_, error>; - redirect-to-grip-proxy: func( backend: string, ) -> result<_, error>; @@ -648,15 +664,15 @@ interface http-req { ) -> result; /// Begins sending the request to the given backend server, and returns a - /// `pending-request` that can yield the backend response or an error. + /// `pending-response` that can yield the backend response or an error. /// /// This method returns as soon as the request begins sending to the backend, /// and transmission of the request body and headers will continue in the /// background. /// /// This method allows for sending more than one request at once and receiving - /// their responses in arbitrary orders. See `pending-request` for more - /// details on how to wait on, poll, or select between pending requests. + /// their responses in arbitrary orders. See `pending-response` for more + /// details on how to wait on, poll, or select between pending responses. /// /// This method is also useful for sending requests where the response is /// unimportant, but the request may take longer than the Compute program is @@ -666,7 +682,7 @@ interface http-req { request: request, body: body, backend: string - ) -> result; + ) -> result; /// This is to `send-async` as `send-uncached` is to `send`. /// @@ -677,15 +693,15 @@ interface http-req { request: request, body: body, backend: string, - ) -> result; + ) -> result; /// Begins sending the request to the given backend server, and returns a - /// `pending-request` that can yield the backend response or an error. + /// `pending-response` that can yield the backend response or an error. /// /// The `body` argument is not consumed, so that it can accept further data to send. /// /// The backend connection is only closed once `http-body.close` is called. The - /// `pending-request` will not yield a `response` until the body is finished. + /// `pending-response` will not yield a `response` until the body is finished. /// /// This method is most useful for programs that do some sort of processing or /// inspection of a potentially-large client request body. Streaming allows the @@ -699,7 +715,7 @@ interface http-req { request: request, body: borrow, backend: string, - ) -> result; + ) -> result; /// This is to `send-async-streaming` as `send-uncached` is to `send`. /// @@ -710,7 +726,7 @@ interface http-req { request: request, body: borrow, backend: string, - ) -> result; + ) -> result; type request-with-body = tuple; @@ -780,18 +796,14 @@ interface http-req { certificate-unknown, } - enum send-error-detail-tag { - /// The $send_error_detail struct has not been populated. - uninitialized, - /// There was no send error. - ok, + /// Information about errors encountered by sent requests. + variant send-error-detail { /// The system encountered a timeout when trying to find an IP address for the backend /// hostname. dns-timeout, /// The system encountered a DNS error when trying to find an IP address for the backend - /// hostname. The fields `dns-error-rcode` and `dns-error-info-code` may be set in the - /// $send_error_detail. - dns-error, + /// hostname. + dns-error(dns-error-detail), /// The system cannot determine which backend to use, or the specified backend was invalid. destination-not-found, /// The system considers the backend to be unavailable, for example when recent attempts to @@ -838,21 +850,25 @@ interface http-req { http-request-uri-invalid, /// The system encountered an unexpected internal error. internal-error, - /// The system received a TLS alert from the backend. The field `tls-alert-id` may be set in - /// the $send_error_detail. - tls-alert-received, + /// The system received a TLS alert from the backend. + tls-alert-received(tls-alert-received-detail), /// The system encountered a TLS error when communicating with the backend, either during /// the handshake or afterwards. tls-protocol-error, } - record send-error-detail { - tag: send-error-detail-tag, - dns-error-rcode: option, - dns-error-info-code: option, - tls-alert-id: option, + /// Variant fields for `send-error.dns-error`. + record dns-error-detail { + rcode: option, + info-code: option, + } + + /// Variant fields for `send-error.tls-alert-received`. + record tls-alert-received-detail { + id: option, } + /// An `error` code, optionally with extra request error information. record error-with-detail { detail: option, error: error, @@ -873,8 +889,8 @@ interface http-req { /// Waits until the request is completed, and then returns the resulting /// response and body. - await-request: func( - pending: pending-request + await-response: func( + pending: pending-response ) -> result; /// Closes the `request`, releasing any associated resources. @@ -887,6 +903,25 @@ interface http-req { } +/// [Fastly Next-Gen WAF] API. +/// +/// [Fastly Next-Gen WAF]: https://docs.fastly.com/en/ngwaf/ +interface security { + use http-req.{request, body, inspect-options, error}; + + /// Inspects request HTTP traffic using the [NGWAF] lookaside service. + /// + /// Returns a JSON-encoded string. + /// + /// [NGWAF]: https://docs.fastly.com/en/ngwaf/ + inspect: func( + request: borrow, + body: borrow, + options: inspect-options, + max-len: u64 + ) -> result; +} + /// HTTP responses. interface http-resp { use types.{error, ip-address}; @@ -1036,15 +1071,14 @@ interface http-resp { /// /// [Compute Dictionaries]: https://www.fastly.com/documentation/guides/concepts/edge-state/dynamic-config/#dictionaries interface dictionary { - - use types.{error}; + use types.{error, open-error}; /// A Compute Dictionary. resource dictionary { /// Opens a dictionary, given its name. /// /// Names are case sensitive. - open: static func(name: string) -> result; + open: static func(name: string) -> result; /// Tries to look up a value in this dictionary. /// @@ -1150,16 +1184,13 @@ interface erl { /// [Compute KV Store]: https://www.fastly.com/documentation/guides/concepts/edge-state/data-stores/#kv-stores /// [blog post]: https://www.fastly.com/blog/introducing-the-compute-edge-kv-store-global-persistent-storage-for-compute-functions interface kv-store { - - use types.{error}; + use types.{error, open-error}; use http-body.{body}; /// A KV Store. resource store { /// Opens the KV Store with the given name. - /// - /// If there is no store by that name, this returns `ok(none)`. - open: static func(name: string) -> result, error>; + open: static func(name: string) -> result; /// Looks up a value in the KV Store. /// @@ -1421,8 +1452,7 @@ interface kv-store { /// /// [Secret Store]: https://www.fastly.com/documentation/reference/api/services/resources/secret-store/ interface secret-store { - - use types.{error}; + use types.{error, open-error}; /// An individual secret. resource secret { @@ -1444,13 +1474,13 @@ interface secret-store { /// Returns the plaintext value of this secret. plaintext: func( max-len: u64 - ) -> result>, error>; + ) -> result, error>; } /// A Secret Store. resource store { /// Opens the Secret Store with the given name. - open: static func(name: string) -> result; + open: static func(name: string) -> result; /// Tries to look up a Secret by name in this secret store. /// @@ -1466,14 +1496,13 @@ interface secret-store { /// /// [Access Control Lists]: https://www.fastly.com/documentation/reference/api/acls/ interface acl { - - use types.{error, ip-address}; + use types.{error, open-error, ip-address}; use http-body.{body}; /// An ACL. resource acl { /// Opens an ACL linked to the current service with the given link name. - open: static func(name: string) -> result; + open: static func(name: string) -> result; /// Performs a lookup of the given IP address in the ACL. /// @@ -1788,7 +1817,7 @@ interface backend { interface async-io { /// An object supporting generic async operations. /// - /// Can be a `http-body.body`, `http-req.pending-request`, `http-req.request-promise`, + /// Can be a `http-body.body`, `http-req.pending-response`, `http-req.pending-request`, /// `cache.pending-entry`. `kv-store.pending-lookup`, `kv-store.pending-insert`, /// `kv-store.pending-delete`, or `kv-store.pending-list`. /// @@ -2097,8 +2126,6 @@ interface cache { /// request-headers: option>, - service-id: option, - always-use-requested-range: bool, /// Additional options may be added in the future via this resource type. @@ -2106,7 +2133,9 @@ interface cache { } /// Extensibility for `lookup-options` - resource extra-lookup-options {} + resource extra-lookup-options { + constructor(); + } /// Configuration for several functions that write to the cache: /// - `insert` @@ -2136,7 +2165,6 @@ interface cache { length: option, user-metadata: option>, edge-max-age-ns: option, - service-id: option, sensitive-data: bool, /// Additional options may be added in the future via this resource type. @@ -2144,7 +2172,9 @@ interface cache { } /// Extensibility for `write-options` - resource extra-write-options {} + resource extra-write-options { + constructor(); + } record get-body-options { %from: option, @@ -2201,7 +2231,6 @@ interface cache { /// a full request handle, but used only for its headers request-headers: option>, replace-strategy: option, - service-id: option, always-use-requested-range: bool, /// Additional options may be added in the future via this resource type. @@ -2209,7 +2238,9 @@ interface cache { } /// Extensibility for `replace-options` - resource extra-replace-options {} + resource extra-replace-options { + constructor(); + } enum replace-strategy { /// Immediately start the replace and do not wait for any other pending requests for the same @@ -2272,12 +2303,6 @@ interface http-cache { /// An HTTP Cache transaction. resource entry { - /// (DEPRECATED) Use transaction-lookup - lookup: static func( - req-handle: borrow, - options: lookup-options, - ) -> result; - /// Performs a cache lookup based on the given request. /// /// This operation always participates in request collapsing and may return an obligation to @@ -2603,14 +2628,14 @@ interface http-cache { /// /// [Config Store]: https://www.fastly.com/documentation/guides/concepts/edge-state/dynamic-config/#config-stores interface config-store { - use types.{error}; + use types.{error, open-error}; /// A Config Store. resource store { /// Attempts to open the named config store. /// /// Names are case sensitive. - open: static func(name: string) -> result; + open: static func(name: string) -> result; /// Fetches a value from the config store, returning `ok(none)` if it doesn't exist. get: func( @@ -2631,19 +2656,17 @@ interface shielding { max-len: u64, ) -> result; - record shield-backend-options { - cache-key: option, + /// Extensibility for `shield-backend-options` + resource shield-backend-options { + constructor(); - /// Additional options may be added in the future via this resource type. - extra: option>, + set-cache-key: func(cache-key: string); + set-first-byte-timeout: func(timeout-ms: u32); } - /// Extensibility for `shield-backend-options` - resource extra-shield-backend-options {} - backend-for-shield: func( name: string, - options: shield-backend-options, + options: option>, max-len: u64, ) -> result; } @@ -2839,6 +2862,7 @@ world service-imports { import kv-store; import purge; import secret-store; + import security; import shielding; } From b3698fff76f68a840266c2c9f7568686bb2b2e71 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Wed, 8 Oct 2025 13:15:51 -0400 Subject: [PATCH 36/50] Add `poll` to compute.wit. This solves the immediate `pollable` type mismatch when `wac`ing together a Python component. --- wit/deps/fastly/compute.wit | 1 + 1 file changed, 1 insertion(+) diff --git a/wit/deps/fastly/compute.wit b/wit/deps/fastly/compute.wit index 9299e04..068584d 100644 --- a/wit/deps/fastly/compute.wit +++ b/wit/deps/fastly/compute.wit @@ -2835,6 +2835,7 @@ world service-imports { import wasi:clocks/monotonic-clock@0.2.6; import wasi:io/error@0.2.6; import wasi:io/streams@0.2.6; + import wasi:io/poll@0.2.6; import wasi:random/random@0.2.6; import wasi:cli/environment@0.2.6; import wasi:cli/exit@0.2.6; From ad5869b633f9adb208b43c446d815775980e533b Mon Sep 17 00:00:00 2001 From: Paul Osborne Date: Wed, 8 Oct 2025 21:58:33 +0000 Subject: [PATCH 37/50] Add note on building against target wasm32-wasip2 --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 6884472..64b18d4 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,12 @@ export app.exports; export app["fastly:compute/http-incoming"]; ``` +Build wasiless as a p2 component as follows: + +``` shell +cargo build --release --target wasm32-wasip2 +``` + To apply this, save it as `wrap_app_in_wasiless.wac`, then invoke wac like... ``` From 1bc35d93895ef9f950a283db24b145251233b5f3 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Thu, 9 Oct 2025 13:20:39 -0400 Subject: [PATCH 38/50] Update readme: correct target, and add component-building wasm-tools invocation. See ed84dc37196deb0271a691c0e76e799741329653 for details on target selection. --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 64b18d4..8f01de5 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,8 @@ export app["fastly:compute/http-incoming"]; Build wasiless as a p2 component as follows: ``` shell -cargo build --release --target wasm32-wasip2 +cargo build --release +wasm-tools component new target/wasm32-unknown-unknown/debug/wasiless.wasm -o componentized.wasm ``` To apply this, save it as `wrap_app_in_wasiless.wac`, then invoke wac like... From 49b380d558ef8566336f4c1796c9de8a38dc9591 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Thu, 9 Oct 2025 17:20:18 -0400 Subject: [PATCH 39/50] Move the build instructions out from the middle of the use example. --- README.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8f01de5..26a6bd8 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,17 @@ Wasiless is a WebAssembly component that provides minimal or trapping implementations of all WASI interfaces, meant to allow the porting of dynamic runtimes like CPython which expect a normal OS, with normal affordances like filesystems and sockets. Build CPython (or some other runtime) as a component, satisfy its imports with wasiless, and you should be able to run it in an environment that provides only a subset of WASI, like [Viceroy](https://github.com/fastly/Viceroy). +## Build + +Build wasiless as a WASIp2 component as follows: + +``` shell +cargo build --release +wasm-tools component new target/wasm32-unknown-unknown/debug/wasiless.wasm -o componentized.wasm +``` + +## Use + Here is an example composition of wasiless and a Python component (built using componentize-py) for use with Viceroy: ``` @@ -38,13 +49,6 @@ export app.exports; export app["fastly:compute/http-incoming"]; ``` -Build wasiless as a p2 component as follows: - -``` shell -cargo build --release -wasm-tools component new target/wasm32-unknown-unknown/debug/wasiless.wasm -o componentized.wasm -``` - To apply this, save it as `wrap_app_in_wasiless.wac`, then invoke wac like... ``` From 871012632ba40e80ae6e828067036cad358bc54d Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 14 Oct 2025 12:47:12 -0400 Subject: [PATCH 40/50] Remove Fastly Compute WITs, which we weren't using and which make this less generic. --- wit/deps/fastly-adapter/adapter.wit | 112 -- wit/deps/fastly/compute.wit | 2882 --------------------------- 2 files changed, 2994 deletions(-) delete mode 100644 wit/deps/fastly-adapter/adapter.wit delete mode 100644 wit/deps/fastly/compute.wit diff --git a/wit/deps/fastly-adapter/adapter.wit b/wit/deps/fastly-adapter/adapter.wit deleted file mode 100644 index fedb9d4..0000000 --- a/wit/deps/fastly-adapter/adapter.wit +++ /dev/null @@ -1,112 +0,0 @@ -/// Interfaces available to the component adapter, which are not otherwise -/// part of the Fastly Compute platform. -package fastly:adapter; - -/// Adapter functions formerly of `fastly:compute/http-req`. -/// -/// These functions depend on the host maintaining an implicit downstream -/// request. They were deprecated and replaced by functions in the -/// `http-downstream` interface which do the same thing but take an explicit -/// `request` handle. -/// -/// We could almost polyfill these functions in the adapter, by having the -/// adapter remember the downstream request handle passed in and calling the -/// `http-downstream` versions with it, but not quite. Guest programs can call -/// `send` and pass it the downstream handle, which consumes the downstream -/// handle. If guest programs do that and later call one of these functions, -/// the polyfill no longer has a valid handle it can pass in. -/// -/// So instead, we moved them to be private functions, still implemented by -/// the host, and still accessible through the component adapter, but not -/// accessible to public Wit users. -interface adapter-http-req { - use fastly:compute/types.{error, ip-address}; - use fastly:compute/http-req.{client-cert-verify-result}; - - downstream-client-ip-addr: func() -> option; - downstream-server-ip-addr: func() -> option; - downstream-client-h2-fingerprint: func(max-len: u64) -> result; - downstream-client-request-id: func(max-len: u64) -> result; - downstream-client-oh-fingerprint: func(max-len: u64) -> result; - downstream-client-ddos-detected: func() -> result; - downstream-tls-cipher-openssl-name: func(max-len: u64) -> result>, error>; - downstream-tls-protocol: func(max-len: u64) -> result>, error>; - downstream-tls-client-hello: func(max-len: u64) -> result>, error>; - downstream-tls-client-cert-verify-result: func() -> result, error>; - downstream-tls-ja3-md5: func() -> result>, error>; - downstream-tls-ja4: func(max-len: u64) -> result, error>; - downstream-compliance-region: func(max-len: u64) -> result, error>; - - /// Deprecated, because it doesn't return `none` on an empty certificate. - downstream-tls-raw-client-certificate-deprecated: func(max-len: u64) -> result>, error>; - - get-original-header-names: func( - max-len: u64, - cursor: u32, - ) -> result>, error>; - - original-header-count: func() -> result; - - fastly-key-is-valid: func() -> result; - - /// Deprecated; use `redirect-to-websocket-proxy` instead. - redirect-to-websocket-proxy-deprecated: func(backend: string) -> result<_, error>; - - /// Deprecated; use `redirect-to-grip-proxy` instead. - redirect-to-grip-proxy-deprecated: func(backend: string) -> result<_, error>; -} - -interface adapter-http-downstream { - use fastly:compute/types.{error}; - use fastly:compute/http-req.{request}; - - /// Deprecated, because it doesn't return `none` on an empty certificate. - downstream-tls-raw-client-certificate-deprecated: func( - ds-request: borrow, - max-len: u64 - ) -> result>, error>; -} - -/// User-agent string parsing (deprecated). -/// -/// This was public in the Witx ABI, but it was deprecated, so now it's a -/// fastly-private API, available to existing code using the adapter, but -/// not available publicly. -interface adapter-uap { - use fastly:compute/types.{error}; - - resource user-agent { - family: func(max-len: u64) -> result; - major: func(max-len: u64) -> result; - minor: func(max-len: u64) -> result; - patch: func(max-len: u64) -> result; - } - - /// Parses a user agent string. - parse: func(user-agent: list) -> result; -} - -/// A world that just imports all the deprecated APIs, split out from the main -/// world below so that we can refer to it in tests. -world adapter-imports { - import adapter-http-req; - import adapter-http-downstream; - import adapter-uap; -} - -/// The `fastly:compute/service` world plus the deprecated interfaces. -world adapter-service { - // Make this world a superset of the public `service` world. - include fastly:compute/service; - - // And, add all the deprecated interfaces. - include adapter-imports; -} - -/// Like `adapter-service`, but only includes the imports, and not the -/// exports (`http-incoming.handle`), so that it can be used by library components -/// that don't have their own `main` function. -world adapter-service-imports { - include fastly:compute/service-imports; - include adapter-imports; -} diff --git a/wit/deps/fastly/compute.wit b/wit/deps/fastly/compute.wit deleted file mode 100644 index 068584d..0000000 --- a/wit/deps/fastly/compute.wit +++ /dev/null @@ -1,2882 +0,0 @@ -/// This is a [Wit] file defining the APIs of the [Fastly Compute platform]. -/// -/// This file defines the `fastly:compute/service` world, which defines the -/// set of interfaces available to, and expected of, Fastly Compute service -/// applications. -/// -/// [Wit]: https://component-model.bytecodealliance.org/design/wit.html -/// [Fastly Compute platform]: https://www.fastly.com/documentation/guides/compute/ -package fastly:compute; - -/// Types used by many interfaces in this package. -interface types { - /// A common error type used by many functions in this package. - /// - /// TODO: In the future this should be split up into more-specific error - /// enums so that it better documents which errors each function can actually - /// return and what they mean. - variant error { - /// Generic error value. - /// - /// This means that some unexpected error occurred. - generic-error, - /// Invalid argument. - invalid-argument, - /// Invalid handle. - /// - /// Returned when a handle is not valid, for example when no dictionary exists with the given - /// name. - bad-handle, - /// Buffer length error. - /// - /// Returned when a buffer is the wrong size. - /// Includes the buffer length that would allow the operation to succeed. - buffer-len(u64), - /// Unsupported operation error. - /// - /// This error is returned when some operation cannot be performed, because it is not supported. - unsupported, - /// Invalid HTTP error. - /// - /// This can be returned when a method, URI, header, or status is not valid. This can also - /// be returned if a message head is too large. - http-invalid, - /// HTTP user error. - /// - /// This is returned in cases where user code caused an HTTP error. For example, attempt to send - /// a 1xx response code, or a request with a non-absolute URI. This can also be caused by - /// an unexpected header: both `content-length` and `transfer-encoding`, for example. - http-user, - /// HTTP incomplete message error. - /// - /// This can be returned when a stream ended unexpectedly. - http-incomplete, - /// A “none” error. - /// - /// This status code is used to indicate when an optional value did not exist, as opposed to - /// an empty value. - optional-none, - /// Message head too large. - http-head-too-large, - /// Invalid HTTP status. - http-invalid-status, - /// Limit exceeded - /// - /// This is returned when an attempt to allocate a resource has exceeded the maximum number of - /// resources permitted. For example, creating too many response handles. - limit-exceeded, - } - - /// An error returned by `open`-like functions. - enum open-error { - /// The given name of the entity to open was invalid. - invalid-syntax, - /// The given name is longer the maximum permitted length. - name-too-long, - /// The given name is a reserved name that may not be opened. - reserved, - /// No entity by the given name was found. - not-found, - /// Unsupported operation error. - /// - /// This error is returned when some operation cannot be performed, because it is not supported. - unsupported, - /// Limit exceeded - /// - /// This is returned when an attempt to allocate a resource has exceeded the maximum number of - /// resources permitted. For example, creating too many response handles. - limit-exceeded, - /// Generic error value. - /// - /// This means that some unexpected error occurred. - generic-error, - } - - /// IPv4 addresses. - type ipv4-address = tuple; - - /// IPv6 addresses. - type ipv6-address = tuple; - - /// IPv4 or IPv6 addresses. - variant ip-address { - ipv4(ipv4-address), - ipv6(ipv6-address), - } -} - -/// Types used by HTTP interfaces in this package. -interface http-types { - - /// HTTP protocol versions. - enum http-version { - /// HTTP/0.9 - http09, - /// HTTP/1.0 - http10, - /// HTTP/1.1 - http11, - /// HTTP/2.0 - h2, - /// HTTP/3.0 - h3 - } - - /// HTTP [content encoding] flags - /// - /// [content encoding]: https://www.rfc-editor.org/rfc/rfc9110.html#field.content-encoding - flags content-encodings { - /// [Gzip coding] - /// - /// [Gzip coding]: https://www.rfc-editor.org/rfc/rfc9110.html#gzip.coding - gzip - } - - /// Determines how the framing headers (`Content-Length`/`Transfer-Encoding`) are set for a - /// request or response. - enum framing-headers-mode { - /// Determine the framing headers automatically based on the message body, and discard any - /// framing headers already set in the message. This is the default behavior. - /// - /// In automatic mode, a `Content-Length` is used when the size of the body can be determined - /// before it is sent. Requests/responses sent in streaming mode, where headers are sent - /// immediately but the content of the body is streamed later, will receive a - /// `Transfer-Encoding: chunked` to accommodate the dynamic generation of the body. - automatic, - - /// Use the exact framing headers set in the message, falling back to `automatic` if invalid. - /// - /// In “from headers” mode, any `Content-Length` or `Transfer-Encoding` headers will be honored. - /// You must ensure that those headers have correct values permitted by the - /// [HTTP/1.1 specification]. If the provided headers are not permitted by the spec, the headers - /// will revert to automatic mode and a log diagnostic will be issued about what was wrong. If a - /// `Content-Length` is permitted by the spec, but the value doesn't match the size of the - /// actual body, the body will either be truncated (if it is too long), or the connection will - /// be hung up early (if it is too short). - /// - /// [HTTP/1.1 specification]: https://www.rfc-editor.org/rfc/rfc7230#section-3.3.1 - manually-from-headers - } - - /// [Transport Layer Security] (TLS) version - /// - /// [Transport Layer Security]: https://www.rfc-editor.org/rfc/rfc8446.html - enum tls-version { - /// TLS 1.0 - tls1, - /// TLS 1.1 - tls11, - /// TLS 1.2 - tls12, - /// TLS 1.3 - tls13 - } - - /// HTTP [status codes]. - /// - /// [status codes]: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml - type http-status = u16; -} - -/// HTTP bodies. -interface http-body { - - use types.{error}; - - /// An HTTP request or response body. - use async-io.{pollable as body}; - - /// Creates a new empty body that can be used for outgoing requests and responses. - new: func() -> result; - - /// Appends the contents of the body `src` to the body `dest`. - append: func(dest: borrow, src: body) -> result<_, error>; - - /// Reads from a body. - read: func(body: borrow, chunk-size: u32) -> result, error>; - - /// Writes to a body. - /// - /// This function may write fewer bytes than requested; on success, the number of - /// bytes actually written is returned. - write: func(body: borrow, buf: list) -> result; - - /// Prepends bytes to the front of a body. - /// - /// On success, this function always writes all the bytes of `buf`. - write-front: func(body: borrow, buf: list) -> result<_, error>; - - /// Frees a body. - /// - /// This releases resources associated with the body. - /// - /// For streaming bodies, this is a *successful* stream termination, which will signal - /// via framing that the body transfer is complete. - /// - /// If a handle is dropped without calling `close`, it's an *unsuccessful* stream - /// termination. - close: func(body: body) -> result<_, error>; - - /// Returns a `u64` body length if the length of a body is known, or `none` otherwise. - /// - /// If the length is unknown, it is likely due to the body arising from an HTTP/1.1 message with - /// chunked encoding, an HTTP/2 or later message with no `content-length`, or being a streaming - /// body. - /// - /// Receiving a length from this function does not guarantee that the full number of - /// bytes can actually be read from the body. For example, when proxying a response from a - /// backend, this length may reflect the `content-length` promised in the response, but if the - /// backend connection is closed prematurely, fewer bytes may be delivered before this body - /// handle can no longer be read. - get-known-length: func(body: borrow) -> option; - - /// Adds a body trailing header with given value. - append-trailer: func( - body: borrow, - name: string, - value: list, - ) -> result<_, error>; - - /// Gets the names of the trailers associated with this body. - /// - /// The first `cursor` names are skipped. The remaining names are encoded successively with - /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining - /// names don't fit, the returned `option` is the index of the first name that didn't fit, - /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, an - /// `error.buffer-len` error is returned, providing a recommended buffer size. - get-trailer-names: func( - body: borrow, - max-len: u64, - cursor: u32, - ) -> result>, trailer-error>; - - /// Gets the value for the trailer with the given name, or `none` if the trailer is not present. - /// - /// If there are multiple values for this header, only one is returned, which may be - /// any of the values. See `get-trailer-values` if you need to get all of the values. - /// - /// This functions returns `ok(some(v))` if the trailer with the given name is present, - /// and `ok(none)` if no trailer with the given name is present. If `max-len` is too - /// small to fit the value, an `error.buffer-len` error is returned, providing a - /// recommended buffer size. - get-trailer-value: func( - body: borrow, - name: string, - max-len: u64, - ) -> result>, trailer-error>; - - /// Gets multiple values associated with the trailer with the given name. - /// - /// As opposed to `get-trailer-value`, this function returns all of the values for this trailer. - /// - /// The first `cursor` values are skipped. The remaining values are encoded successively with - /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining - /// values don't fit, the returned `option` is the index of the first value that didn't - /// fit, or `none` if all the remaining values fit. If `max-len` is too small to fit any value, - /// an `error.buffer-len` error is returned, providing a recommended buffer size. - get-trailer-values: func( - body: borrow, - name: string, - max-len: u64, - cursor: u32 - ) -> result, option>, trailer-error>; - - /// Trailers aren't available until the body has been completely transmitted, so this error - /// type can either indicate that the errors aren't available yet, or that an error occurred. - variant trailer-error { - /// The trailers aren't available yet. - not-available-yet, - - /// An error occurred. - error(error), - } -} - -/// Low-level interface to Fastly's [Real-Time Log Streaming] endpoints. -/// -/// [Real-Time Log Streaming]: https://docs.fastly.com/en/guides/about-fastlys-realtime-log-streaming-features -interface log { - use types.{error, open-error}; - - /// A logging endpoint. - resource endpoint { - /// Tries to get an endpoint by name. - /// - /// Currently, the conditions on an endpoint name are: - /// - It must not be empty. - /// - It must not contain newlines (`\n`) or colons (`:`). - /// - It must not be `stdout` or `stderr`, which are reserved for debugging. - /// - /// Names are case sensitive. Calling `get-endpoint` with a name that doesn't correspond to any - /// logging endpoint available in your service will still return a usable endpoint, and writes - /// to that endpoint will succeed. Refer to your service dashboard to diagnose missing log - /// events. - open: static func(name: string) -> result; - - /// Writes a data to the given endpoint. - /// - /// Each call to `write` produces a single log event. On success, the number of bytes written - /// is returned. - write: func(msg: list) -> result; - } -} - -/// HTTP downstream requests and metadata. -/// -/// “Downstream” here refers to incoming HTTP requests. -interface http-downstream { - use types.{error, ip-address}; - use http-req.{ - request, client-cert-verify-result, error-with-detail, cache-override, pending-request, - request-with-body, - }; - - /// Configuration for `next-request`. - record next-request-options { - timeout-ms: option, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `next-request-options` - resource extra-next-request-options {} - - /// Starts waiting for the next request. - next-request: func( - options: next-request-options, - ) -> result; - - /// Waits until the next request is available, and then returns the resulting - /// request and body. - /// - /// Returns `ok(none)` if there are no more requests for this session. - await-request: func( - pending: pending-request, - ) -> result, error>; - - next-request-abandon: func( - pending: pending-request, - ) -> result<_, error>; - - /// Returns the client request's header names exactly as they were originally received. - /// - /// This includes both the original header name characters' cases, as well as the original order - /// of the received headers. - /// - /// The first `cursor` names are skipped. The remaining names are encoded successively with - /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining - /// names don't fit, the returned `option` is the index of the first name that didn't fit, - /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, - /// an `error.buffer-len` error is returned, providing a recommended buffer size. - downstream-original-header-names: func( - ds-request: borrow, - max-len: u64, - cursor: u32, - ) -> result>, error>; - - /// Returns the number of headers in the client request as originally received. - downstream-original-header-count: func( - ds-request: borrow - ) -> result; - - /// Returns the IP address of the client making the HTTP request, if known. - downstream-client-ip-addr: func( - ds-request: borrow - ) -> option; - - /// Returns the IP address on which this server received the HTTP request, if known. - downstream-server-ip-addr: func( - ds-request: borrow - ) -> option; - - /// Gets the HTTP/2 fingerprint of client request if available. - downstream-client-h2-fingerprint: func( - ds-request: borrow, - max-len: u64 - ) -> result; - - /// Gets the id of the current request if available. - downstream-client-request-id: func( - ds-request: borrow, - max-len: u64 - ) -> result; - - /// Gets the fingerprint of client request headers if available. - downstream-client-oh-fingerprint: func( - ds-request: borrow, - max-len: u64 - ) -> result; - - /// Returns whether the request was tagged as contributing to a DDoS attack. - downstream-client-ddos-detected: func( - ds-request: borrow - ) -> result; - - /// Gets the cipher suite used to secure the downstream client TLS connection. - /// - /// The value returned will be consistent with the [OpenSSL name] for the cipher suite. - /// - /// Returns `ok(none)` if the downstream client connection is not a TLS connection. - /// - /// [OpenSSL name]: https://testssl.sh/openssl-iana.mapping.html - downstream-tls-cipher-openssl-name: func( - ds-request: borrow, - max-len: u64 - ) -> result>, error>; - - /// Gets the TLS protocol version used to secure the downstream client TLS connection. - /// - /// Returns `ok(none)` if the downstream client connection is not a TLS connection. - downstream-tls-protocol: func( - ds-request: borrow, - max-len: u64 - ) -> result>, error>; - - /// Gets the raw bytes sent by the client in the TLS ClientHello message. - /// - /// See [RFC 5246] for details. - /// - /// Returns `ok(none)` if the downstream client connection is not a TLS connection. - /// - /// [RFC 5246]: https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2 - downstream-tls-client-hello: func( - ds-request: borrow, - max-len: u64 - ) -> result>, error>; - - /// Gets the raw client certificate used to secure the downstream client mTLS connection. - /// - /// The value returned will be based on PEM format. - /// - /// Returns `ok(none)` if the downstream client connection is not a TLS connection. - downstream-tls-raw-client-certificate: func( - ds-request: borrow, - max-len: u64 - ) -> result>, error>; - - /// Returns the `client-cert-verify-result` from the downstream client mTLS handshake. - /// - /// Returns `ok(none)` if the downstream client connection is not a TLS connection. - downstream-tls-client-cert-verify-result: func( - ds-request: borrow - ) -> result, error>; - - /// Returns the Server Name Indication from the downstream client TLS handshake. - /// - /// Returns `ok(none)` if not available. - downstream-tls-client-servername: func( - ds-request: borrow, - max-len: u64 - ) -> result, error>; - - /// Gets the JA3 hash of the TLS ClientHello message. - /// - /// Returns `ok(none)` if the downstream client connection is not a TLS connection. - downstream-tls-ja3-md5: func( - ds-request: borrow - ) -> result>, error>; - - /// Gets the JA4 hash of the TLS ClientHello message. - /// - /// Returns `ok(none)` if the downstream client connection is not a TLS connection. - downstream-tls-ja4: func( - ds-request: borrow, - max-len: u64 - ) -> result, error>; - - /// Gets the compliance region that the client IP address is in. - downstream-compliance-region: func( - ds-request: borrow, - max-len: u64 - ) -> result, error>; - - /// Returns whether or not the original client request arrived with a - /// Fastly-Key belonging to a user with the rights to purge content on this - /// service. - fastly-key-is-valid: func( - ds-request: borrow, - ) -> result; -} - -/// HTTP requests. -interface http-req { - - use types.{error, ip-address}; - use http-types.{http-version, content-encodings, framing-headers-mode, tls-version}; - use http-resp.{response}; - use http-body.{body}; - use http-resp.{response-with-body}; - - /// Handle that can be used to wait for a response from a sent request. - use async-io.{pollable as pending-response}; - - /// Handle that can be used to wait for incoming requests. - use async-io.{pollable as pending-request}; - - /// An HTTP request. - resource request { - /// Creates a new `request` with no method, URL, or headers, and an empty body. - new: static func() -> result; - - /// Sets the cache override behavior for this request. - /// - /// This setting will override any cache directive headers returned in response to this request. - set-cache-override: func( - cache-override: cache-override, - ) -> result<_, error>; - - /// Reads the request's header names via a buffer of the provided size. - /// - /// The first `cursor` names are skipped. The remaining names are encoded successively with - /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining - /// names don't fit, the returned `option` is the index of the first name that didn't fit, - /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, - /// an `error.buffer-len` error is returned, providing a recommended buffer size. - get-header-names: func( - max-len: u64, - cursor: u32, - ) -> result>, error>; - - /// Gets the value of a header, or `none` if the header is not present. - /// - /// If there are multiple values for the header, only one is returned. See - /// `get-header-values` if you need to get all of the values. - /// - /// If header name requires more than `max-len` bytes, this will return an `error.buffer-len` - /// containing the required size. - get-header-value: func( - name: string, - max-len: u64, - ) -> result>, error>; - - /// Gets multiple header values for the given `name` via a buffer of the provided size. - /// - /// As opposed to `get-header-value`, this function returns all of the values for this header. - /// - /// The first `cursor` values are skipped. The remaining values are encoded successively with - /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining - /// values don't fit, the returned `option` is the index of the first value that didn't - /// fit, or `none` if all the remaining values fit. If `max-len` is too small to fit any value, - /// an `error.buffer-len` error is returned, providing a recommended buffer size. - get-header-values: func( - name: string, - max-len: u64, - cursor: u32 - ) -> result, option>, error>; - - /// Sets the values for the given header name, replacing any headers that previously existed for - /// that name. - set-header-values: func( - name: string, - /// contains multiple values each terminated by `\0` and concatenated - values: list - ) -> result<_, error>; - - /// Sets a request header to the given value, discarding any previous values for the given - /// header name. - insert-header: func(name: string, value: list) -> result<_, error>; - - /// Adds a request header with given value. - /// - /// Unlike `set-header-values`, this does not discard existing values for the same header name. - append-header: func( - name: string, - value: list, - ) -> result<_, error>; - - /// Removes all request headers of the given name - /// - /// Returns `ok` if any headers were successfully removed. - remove-header: func(name: string) -> result<_, error>; - - /// Gets the request method. - get-method: func(max-len: u64) -> result; - - /// Sets the request method. - set-method: func(method: string) -> result<_, error>; - - /// Gets the request URI. - get-uri: func(max-len: u64) -> result; - - /// Sets the request URI. - set-uri: func(uri: string) -> result<_, error>; - - /// Gets the HTTP version of this request. - get-version: func() -> result; - - /// Sets the HTTP version of this request. - set-version: func(version: http-version) -> result<_, error>; - - /// Sets the content encodings to automatically decompress responses to this request. - /// - /// If the response to this request is encoded by one of the encodings set by this method, the - /// response will be presented to the Compute program in decompressed form with the - /// `Content-Encoding` and `Content-Length` headers removed. - set-auto-decompress-response: func( - encodings: content-encodings, - ) -> result<_, error>; - - /// Passes the WebSocket directly to a backend. - /// - /// This can only be used on services that have the WebSockets feature enabled and on requests - /// that are valid WebSocket requests. - /// - /// The sending completes in the background. Once this method has been called, no other response - /// can be sent to this request, and the application can exit without affecting the send. - /// - /// See the [WebSockets passthrough] documentation for a high-level description of this feature. - /// - /// [WebSockets passthrough]: https://www.fastly.com/documentation/guides/concepts/real-time-messaging/websockets-tunnel/ - redirect-to-websocket-proxy: func( - backend: string, - ) -> result<_, error>; - - /// Sets how the framing headers `Content-Length` and `Transfer-Encoding` will be determined - /// when sending this request. - set-framing-headers-mode: func( - mode: framing-headers-mode, - ) -> result<_, error>; - - redirect-to-grip-proxy: func( - backend: string, - ) -> result<_, error>; - } - - /// Retrieves a response for the request, either from cache or by sending it - /// to the given backend server. - /// - /// Returns once the response headers have been received, or an error occurs. - send: func( - request: request, - body: body, - backend: string, - ) -> result; - - /// Sends the request directly to the backend server without performing any - /// caching or inserting any cache-related headers in the response. - /// - /// Returns once the response headers have been received, or an error occurs. - send-uncached: func( - request: request, - body: body, - backend: string, - ) -> result; - - /// Begins sending the request to the given backend server, and returns a - /// `pending-response` that can yield the backend response or an error. - /// - /// This method returns as soon as the request begins sending to the backend, - /// and transmission of the request body and headers will continue in the - /// background. - /// - /// This method allows for sending more than one request at once and receiving - /// their responses in arbitrary orders. See `pending-response` for more - /// details on how to wait on, poll, or select between pending responses. - /// - /// This method is also useful for sending requests where the response is - /// unimportant, but the request may take longer than the Compute program is - /// able to run, as the request will continue sending even after the program - /// that initiated it exits. - send-async: func( - request: request, - body: body, - backend: string - ) -> result; - - /// This is to `send-async` as `send-uncached` is to `send`. - /// - /// As with `send-uncached`, this function sends the request directly to the - /// backend server without performing any caching or inserting any - /// cache-related headers in the response. - send-async-uncached: func( - request: request, - body: body, - backend: string, - ) -> result; - - /// Begins sending the request to the given backend server, and returns a - /// `pending-response` that can yield the backend response or an error. - /// - /// The `body` argument is not consumed, so that it can accept further data to send. - /// - /// The backend connection is only closed once `http-body.close` is called. The - /// `pending-response` will not yield a `response` until the body is finished. - /// - /// This method is most useful for programs that do some sort of processing or - /// inspection of a potentially-large client request body. Streaming allows the - /// program to operate on small parts of the body rather than having to read it all - /// into memory at once. - /// - /// This method returns as soon as the request begins sending to the backend, - /// and transmission of the request body and headers will continue in the - /// background. - send-async-streaming: func( - request: request, - body: borrow, - backend: string, - ) -> result; - - /// This is to `send-async-streaming` as `send-uncached` is to `send`. - /// - /// As with `send-uncached`, this function sends the request directly to the - /// backend server without performing any caching or inserting any - /// cache-related headers in the response. - send-async-uncached-streaming: func( - request: request, - body: borrow, - backend: string, - ) -> result; - - type request-with-body = tuple; - - /// Optional override for response caching behavior. - variant cache-override { - /// Do not override the behavior specified in the origin response’s cache control headers. - none, - - /// Do not cache the response to this request, regardless of the origin response’s headers. - pass, - - /// Override particular cache control settings. - override(cache-override-details) - } - - /// The fields for the `override` arm of `cache-override`. - /// - /// The origin response’s cache control headers will be used for ttl and - /// `stale-while-revalidate` if `none`. - record cache-override-details { - ttl: option, - stale-while-revalidate: option, - pci: bool, - surrogate-key: option>, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `cache-override-details` - resource extra-cache-override-details {} - - /// TLS client certificate verified result from downstream. - enum client-cert-verify-result { - /// Success value. - /// - /// This indicates that client certificate verified successfully. - ok, - /// bad certificate error. - /// - /// This error means the certificate is corrupt - /// (for example, when the certificate signatures do not verify correctly). - bad-certificate, - /// certificate revoked error. - /// - /// This error means the client certificate is revoked by its signer. - certificate-revoked, - /// certificate expired error. - /// - /// This error means the client certificate has expired or is not currently valid. - certificate-expired, - /// unknown CA error. - /// - /// This error means the valid certificate chain or partial chain was received, - /// but the certificate was not accepted because the CA certificate could not be - /// located or could not be matched with a known trust anchor. - unknown-ca, - /// certificate missing error. - /// - /// This error means the client does not provide a certificate - /// during the handshake.. - certificate-missing, - /// certificate unknown error. - /// - /// This error means the client certificate was received, but some other (unspecified) - /// issue arose in processing the certificate, rendering it unacceptable. - certificate-unknown, - } - - /// Information about errors encountered by sent requests. - variant send-error-detail { - /// The system encountered a timeout when trying to find an IP address for the backend - /// hostname. - dns-timeout, - /// The system encountered a DNS error when trying to find an IP address for the backend - /// hostname. - dns-error(dns-error-detail), - /// The system cannot determine which backend to use, or the specified backend was invalid. - destination-not-found, - /// The system considers the backend to be unavailable, for example when recent attempts to - /// communicate with it may have failed, or a health check may indicate that it is down. - destination-unavailable, - /// The system cannot find a route to the next-hop IP address. - destination-ip-unroutable, - /// The system's connection to the backend was refused. - connection-refused, - /// The system's connection to the backend was closed before a complete response was - /// received. - connection-terminated, - /// The system's attempt to open a connection to the backend timed out. - connection-timeout, - /// The system is configured to limit the number of connections it has to the backend, and - /// that limit has been exceeded. - connection-limit-reached, - /// The system encountered an error when verifying the certificate presented by the backend. - tls-certificate-error, - /// The system encountered an error with the backend TLS configuration. - tls-configuration-error, - /// The system received an incomplete response to the request from the backend. - http-incomplete-response, - /// The system received a response to the request whose header section was considered too - /// large. - http-response-header-section-too-large, - /// The system received a response to the request whose body was considered too large. - http-response-body-too-large, - /// The system reached a configured time limit waiting for the complete response. - http-response-timeout, - /// The system received a response to the request whose status code or reason phrase was - /// invalid. - http-response-status-invalid, - /// The process of negotiating an upgrade of the HTTP version between the system and the - /// backend failed. - http-upgrade-failed, - /// The system encountered an HTTP protocol error when communicating with the backend. - /// - /// This error will only be used when a more specific one is not defined. - http-protocol-error, - /// An invalid cache key was provided for the request. - http-request-cache-key-invalid, - /// An invalid URI was provided for the request. - http-request-uri-invalid, - /// The system encountered an unexpected internal error. - internal-error, - /// The system received a TLS alert from the backend. - tls-alert-received(tls-alert-received-detail), - /// The system encountered a TLS error when communicating with the backend, either during - /// the handshake or afterwards. - tls-protocol-error, - } - - /// Variant fields for `send-error.dns-error`. - record dns-error-detail { - rcode: option, - info-code: option, - } - - /// Variant fields for `send-error.tls-alert-received`. - record tls-alert-received-detail { - id: option, - } - - /// An `error` code, optionally with extra request error information. - record error-with-detail { - detail: option, - error: error, - } - - /// Configuration for inspecting a `request` using Security. - record inspect-options { - corp: option, - workspace: option, - override-client-ip: option, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `inspect-options` - resource extra-inspect-options {} - - /// Waits until the request is completed, and then returns the resulting - /// response and body. - await-response: func( - pending: pending-response - ) -> result; - - /// Closes the `request`, releasing any associated resources. - /// - /// A `request` is automatically consumed when you send a request. You should call `close` - /// only if you have a `request` you don't intend to use anymore. - close: func(request: request) -> result<_, error>; - - upgrade-websocket: func(backend: string) -> result<_, error>; - -} - -/// [Fastly Next-Gen WAF] API. -/// -/// [Fastly Next-Gen WAF]: https://docs.fastly.com/en/ngwaf/ -interface security { - use http-req.{request, body, inspect-options, error}; - - /// Inspects request HTTP traffic using the [NGWAF] lookaside service. - /// - /// Returns a JSON-encoded string. - /// - /// [NGWAF]: https://docs.fastly.com/en/ngwaf/ - inspect: func( - request: borrow, - body: borrow, - options: inspect-options, - max-len: u64 - ) -> result; -} - -/// HTTP responses. -interface http-resp { - use types.{error, ip-address}; - - use http-types.{ - http-version, http-status, - framing-headers-mode - }; - use http-body.{body}; - - /// An HTTP response. - resource response { - /// Create a new `response`. - /// - /// The new `response` is created with status code 200 OK, no headers, and an empty body. - new: static func() -> result; - - /// Read the response's header names via a buffer of the provided size. - /// - /// The first `cursor` names are skipped. The remaining names are encoded successively with - /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining - /// names don't fit, the returned `option` is the index of the first name that didn't fit, - /// or `none` if all the remaining names fit. If `max-len` is too small to fit any name, - /// an `error.buffer-len` error is returned, providing a recommended buffer size. - get-header-names: func( - max-len: u64, - cursor: u32, - ) -> result>, error>; - - /// Gets the value of a header, or `none` if the header is not present. - /// - /// If there are multiple values for the header, only one is returned. See - /// `get-header-values` if you need to get all of the values. - /// - /// If header name requires more than `max-len` bytes, this will return an `error.buffer-len` - /// containing the required size. - get-header-value: func( - name: string, - max-len: u64, - ) -> result>, error>; - - /// Gets multiple header values for the given `name` via a buffer of the provided size. - /// - /// As opposed to `get-header-value`, this function returns all of the values for this header. - /// - /// The first `cursor` values are skipped. The remaining values are encoded successively with - /// a NUL byte after each into a list of bytes at most `max-len` long. If any of the remaining - /// values don't fit, the returned `option` is the index of the first value that didn't - /// fit, or `none` if all the remaining values fit. If `max-len` is too small to fit any value, - /// an `error.buffer-len` error is returned, providing a recommended buffer size. - get-header-values: func( - name: string, - max-len: u64, - cursor: u32 - ) -> result, option>, error>; - - /// Sets the values for the given header name, replacing any headers that previously existed for - /// that name. - set-header-values: func( - name: string, - /// contains multiple values each terminated by `\0` and concatenated - values: list - ) -> result<_, error>; - - /// Sets a response header to the given value, discarding any previous values for the given - /// header name. - insert-header: func( - name: string, - value: list, - ) -> result<_, error>; - - /// Add a response header with given value. - /// - /// Unlike `set-header-values`, this does not discard existing values for the same header name. - append-header: func( - name: string, - value: list, - ) -> result<_, error>; - - /// Remove all response headers of the given name - /// - /// Returns `ok` if any headers were successfully removed. - remove-header: func(name: string) -> result<_, error>; - - /// Gets the HTTP version of this response. - get-version: func() -> result; - - /// Sets the HTTP version of this response. - set-version: func(version: http-version) -> result<_, error>; - - /// Gets the HTTP status code of the response. - get-status: func() -> result; - - /// Sets the HTTP status code of the response. - set-status: func(status: http-status) -> result<_, error>; - - /// Sets how the framing headers `Content-Length` and `Transfer-Encoding` will be determined - /// when sending this response. - set-framing-headers-mode: func(mode: framing-headers-mode) -> result<_, error>; - - /// Adjust the response's connection reuse mode. - set-http-keepalive-mode: func(mode: keepalive-mode) -> result<_, error>; - - /// Gets the destination IP address used for this response, if known. - get-remote-ip-addr: func() -> option; - - /// Gets the destination port used for this response, if known. - get-remote-port: func() -> option; - } - - /// Sends a response to the client that made the request passed to `http-incoming.handle`. - /// - /// This method returns as soon as the response header begins sending to the client, and - /// transmission of the response will continue in the background. - /// - /// Data for the body must be written before calling this function. To start a response - /// and write data to it afterwards, use `send-downstream-streaming` instead. - send-downstream: func( - response: response, - body: body, - ) -> result<_, error>; - - /// Starts a response to the client that made the request passed to `http-incoming.handle`. - /// - /// The body is left open, allowing data to be written after calling this function. - send-downstream-streaming: func( - response: response, - body: borrow, - ) -> result<_, error>; - - /// Closes the `response`, releasing any associated resources. - /// - /// A `response` is consumed when you send a response to a client or stream one to a - /// client. You should call `close` only if you have a `response` you don't intend - /// to use anymore. - close: func(response: response) -> result<_, error>; - - type response-with-body = tuple; - - enum keepalive-mode { - automatic, - no-keepalive, - } -} - -/// [Compute Dictionaries] (deprecated in favor of `config-store`) -/// -/// [Compute Dictionaries]: https://www.fastly.com/documentation/guides/concepts/edge-state/dynamic-config/#dictionaries -interface dictionary { - use types.{error, open-error}; - - /// A Compute Dictionary. - resource dictionary { - /// Opens a dictionary, given its name. - /// - /// Names are case sensitive. - open: static func(name: string) -> result; - - /// Tries to look up a value in this dictionary. - /// - /// If the lookup is successful, this function returns `ok(some(s))` containing the found - /// string `s`, or `ok(none)` if no entry with the given key was found. - lookup: func( - key: string, - max-len: u64, - ) -> result, error>; - } -} - -/// [Geographic data] for IP addresses. -/// -/// [Geographic data]: https://www.fastly.com/blog/improve-performance-and-gain-better-end-user-intelligence-geoip-geography-detection -interface geo { - use types.{error, ip-address}; - - /// Looks up the geographic data associated with a particular IP address. - /// - /// Returns a list of bytes containing JSON-encoded geographic data. See [here] for descriptions - /// of the JSON fields. - /// - /// [here]: https://www.fastly.com/documentation/reference/vcl/variables/geolocation/ - lookup: func(ip-addr: ip-address, max-len: u64) -> result; -} - -/// Device detection based on the User-Agent header. -interface device-detection { - use types.{error}; - - /// Looks up the data associated with a particular User-Agent string. - /// - /// Returns a list of bytes containing JSON-encoded device data. See [here] for descriptions - /// of the JSON fields. - /// - /// [here]: https://www.fastly.com/documentation/reference/vcl/variables/client-request/client-identified/ - lookup: func(user-agent: string, max-len: u64) -> result, error>; -} - -/// [Edge rate limiting] API. -/// -/// [Edge rate limiting]: https://docs.fastly.com/products/edge-rate-limiting -interface erl { - use types.{error}; - - /// Increments an entry in a rate counter and check if the client has exceeded some average number - /// of requests per second (RPS) over the window. - /// - /// If the client is over the rps limit for the window, add to the penaltybox for ttl. Valid ttl - /// span is 1m to 1h and TTL value is truncated to the nearest minute. - check-rate: func( - rate-counter: string, - entry: string, - delta: u32, - window: u32, - limit: u32, - penalty-box: string, - ttl: u32, - ) -> result; - - /// Increments an entry in the ratecounter by `delta`. - ratecounter-increment: func( - rate-counter: string, - entry: string, - delta: u32, - ) -> result<_, error>; - - /// Looks up the current rate for entry in the ratecounter for a window. - ratecounter-lookup-rate: func( - rate-counter: string, - entry: string, - window: u32, - ) -> result; - - /// Looks up the current count for entry in the ratecounter for duration. - ratecounter-lookup-count: func( - rate-counter: string, - entry: string, - duration: u32, - ) -> result; - - /// Add `entry` to a the penaltybox for the duration of ttl. - /// - /// Valid ttl span is 1m to 1h and TTL value is truncated to the nearest minute. - penaltybox-add: func( - penalty-box: string, - entry: string, - ttl: u32, - ) -> result<_, error>; - - /// Checks if `entry` is in the penaltybox. - penaltybox-has: func( - penalty-box: string, - entry: string, - ) -> result; -} - -/// Interface to Fastly's [Compute KV Store]. -/// -/// For a high-level introduction to this feature, see this [blog post]. -/// -/// [Compute KV Store]: https://www.fastly.com/documentation/guides/concepts/edge-state/data-stores/#kv-stores -/// [blog post]: https://www.fastly.com/blog/introducing-the-compute-edge-kv-store-global-persistent-storage-for-compute-functions -interface kv-store { - use types.{error, open-error}; - use http-body.{body}; - - /// A KV Store. - resource store { - /// Opens the KV Store with the given name. - open: static func(name: string) -> result; - - /// Looks up a value in the KV Store. - /// - /// Returns `ok(some(v))` with the value `v` that was found, `ok(none)` if no value was - /// found, or `err(e)` indicating the error `e` occurred. - /// - /// This function waits until the operation completes. - lookup: func( - key: string, - ) -> result, kv-error>; - - /// Look up a value in the KV Store asynchronously. - /// - /// This function initiates an async lookup of a value in the KV Store. Use - /// `await-lookup` to finish the lookup. - lookup-async: func( - key: string, - ) -> result; - - /// Inserts a value into the KV Store. - /// - /// If the KV Store already contains a value for this key, the `mode` field - /// of the `options` argument specifies how the existing value is handled. - /// - /// This function waits until the operation completes. - insert: func( - key: string, - body: body, - options: insert-options, - ) -> result<_, kv-error>; - - /// Insert a value into the KV Store asynchronously. - /// - /// If the KV Store already contains a value for this key, the `mode` field - /// of the `options` argument specifies how the existing value is handled. - /// - /// This function initiates an async insert of a value in the KV Store. Use - /// `await-insert` to finish the lookup. - insert-async: func( - key: string, - body: body, - options: insert-options, - ) -> result; - - /// Deletes a value in the KV Store. - /// - /// Returns `ok(true)` if a value was successfully deleted, `ok(false)` if no value was - /// found, or `err(e)` indicating the error `e` occurred. - /// - /// This function waits until the operation completes. - delete: func( - key: string, - ) -> result; - - /// Delete of a value in the KV Store. - /// - /// This function initiates an async delete of a value in the KV Store. Use - /// `await-delete` to finish the lookup. - delete-async: func( - key: string, - ) -> result; - - /// Lists keys in the KV Store. - /// - /// Returns `ok(b)` with the body `b` on success, or `err(e)` indicating the error `e` - /// occurred. - /// - /// This function waits until the operation completes. - %list: func( - options: list-options, - ) -> result; - - /// List of keys in the KV Store. - /// - /// This function initiates an async list value in the KV Store. Use - /// `await-list` to finish the lookup. - list-async: func( - options: list-options, - ) -> result; - } - - /// An asynchronous KV Store lookup. Use `await-lookup` to resolve. - use async-io.{pollable as pending-lookup}; - - /// An asynchronous KV Store insert. Use `await-insert` to resolve. - use async-io.{pollable as pending-insert}; - - /// An asynchronous KV Store delete. Use `await-delete` to resolve. - use async-io.{pollable as pending-delete}; - - /// An asynchronous KV Store list. Use `await-list` to resolve. - use async-io.{pollable as pending-list}; - - /// A value indicating the status of a KV store operation. - enum kv-error { - /// KV store cannot or will not process the request due to something that is perceived to be a - /// client error. - /// - /// This will map to the api's 400 codes. - bad-request, - /// KV store cannot fulfill the request, as defined by the client's prerequisites, for example - /// `if-generation-match`. - /// - /// This will map to the api's 412 codes. - precondition-failed, - /// The size limit for a KV store key was exceeded. - /// - /// This will map to the api's 413 codes. - payload-too-large, - /// The system encountered an unexpected internal error. - /// - /// This will map to all remaining http error codes. - internal-error, - /// Too many requests have been made to the KV store. - /// - /// This will map to the api's 429 codes. - too-many-requests, - /// Generic error value. - /// - /// This means that some unexpected error occurred. - generic-error, - } - - /// Wait on the async lookup of a value in the KV Store. - /// - /// Returns `ok(some(v))` with the value `v` that was found, `ok(none)` if no value was - /// found, or `err(e)` indicating the error `e` occurred. - await-lookup: func( - handle: pending-lookup, - ) -> result, kv-error>; - - /// Wait on the async insert of a value in the KV Store. - /// - /// Returns `ok` if the `insert` succeeded, or an error code on failure. - await-insert: func( - handle: pending-insert, - ) -> result<_, kv-error>; - - /// Wait on the async delete of a value in the KV Store. - /// - /// Returns `ok(true)` if a value was successfully deleted, `ok(false)` if no value was - /// found, or `err(e)` indicating the error `e` occurred. - await-delete: func( - handle: pending-delete, - ) -> result; - - /// Wait on the async list of keys in the KV Store. - /// - /// Returns `ok(b)` with the body `b` on success, or `err(e)` indicating the error `e` - /// occurred. - await-list: func( - handle: pending-list, - ) -> result; - - /// A response from a KV Store Lookup operation. - /// - /// This type holds the `body`, metadata, and generation of found key. - resource entry { - /// Take and return the body from this `entry`, if it has one; otherwise return `none`. - /// - /// After calling this method, this entry will no longer have a body. - take-body: func() -> option; - - /// Read the metadata of the KV Store item, if present. - metadata: func(max-len: u64) -> result, error>; - - /// Read the current generation of the KV Store item. - generation: func() -> u64; - } - - /// Selects the behavior for an insert when the new key matches an existing key. - /// - /// A KV store maintains the property that its keys are unique from each other. If an insert - /// has a key that doesn't match any key already in the store, then the pair of the key and the - /// new value is inserted into the store. However, if the insert's key does match a key already - /// in the store, then no new key-value pair is inserted, and the insert's `insert-mode.mode` - /// determines what it does instead. - enum insert-mode { - /// Updates the existing key's value by overwriting it with the new value. - /// - /// This is the default mode. - overwrite, - - /// Fails, leaving the existing key's value unmodified. - /// - /// With this mode, the insert fails with a code of `kv-error.precondition-failed`, and - /// does not modify the existing value. Inserts with this mode will only “add” new key-value - /// pairs; they are prevented from modifying any existing ones. - add, - - /// Updates the existing key's value by appending the new value to it. - append, - - /// Updates the existing key's value by prepending the new value to it. - prepend, - } - - /// Options for configuring the behavior of the `insert` function. - record insert-options { - /// If set, allows fetching from the origin to occur in the background, enabling a faster - /// response with stale content. The cache will be updated with fresh content after the request - /// is completed. - background-fetch: bool, - - /// Requests for keys will return a “generation” header specific to the version of a key. The - /// generation header is a unique, non-serial 64-bit unsigned integer that can be used for - /// testing against a specific KV store value. - if-generation-match: option, - - /// Sets an arbitrary data field which can contain up to 2000B of data. - metadata: option, - - /// Sets a time for the key to expire. Deletion will take place up to 24 hours after the ttl - /// reaches 0. - time-to-live-sec: option, - - /// Select the behavior in the case when the new key matches an existing key. - mode: insert-mode, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `insert-options` - resource extra-insert-options {} - - /// Modes of KV Store list operations. - /// - /// This type serves to facilitate alternative methods of cache interactions with list operations. - enum list-mode { - /// Performs an un-cached list on every invocation. - /// - /// This is the default method of listing. - strong, - - /// Returns a cached list response to improve performance. - /// - /// The data may be slightly out of sync with the store, but repeated calls are faster. - /// - /// The word “eventual” here refers to eventual consistency. - eventual, - } - - record list-options { - mode: list-mode, - cursor: option, - limit: option, - prefix: option, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `list-options` - resource extra-list-options {} -} - -/// [Secret Store] API. -/// -/// [Secret Store]: https://www.fastly.com/documentation/reference/api/services/resources/secret-store/ -interface secret-store { - use types.{error, open-error}; - - /// An individual secret. - resource secret { - /// Creates a new “secret” from the given memory. - /// - /// This is *not* the suggested way to create `secret`s; instead, we suggest using `get`. - /// This secret will *NOT* be shared with other sessions. - /// - /// This method can be used for data that should be secret, but is being obtained by - /// some other means than the secret store. New “secrets” created this way use plaintext - /// only, and live in the session's memory unencrypted for much longer than secrets - /// generated by `get`. They should thus only be used in situations in which an API requires - /// a `secret`, but you cannot (for whatever reason) use a `store` to store them. - /// - /// As the early note says, this `secret` will be local to the current session, and - /// will not be shared with other sessions of this service. - from-bytes: static func(bytes: list) -> result; - - /// Returns the plaintext value of this secret. - plaintext: func( - max-len: u64 - ) -> result, error>; - } - - /// A Secret Store. - resource store { - /// Opens the Secret Store with the given name. - open: static func(name: string) -> result; - - /// Tries to look up a Secret by name in this secret store. - /// - /// If successful, this method returns `ok(some(s))` containing the found secret `s` if the - /// secret is found, or `ok(none)` if the secret was not found. - get: func( - key: string, - ) -> result, error>; - } -} - -/// Blocklists using [Access Control Lists] (ACLs) -/// -/// [Access Control Lists]: https://www.fastly.com/documentation/reference/api/acls/ -interface acl { - use types.{error, open-error, ip-address}; - use http-body.{body}; - - /// An ACL. - resource acl { - /// Opens an ACL linked to the current service with the given link name. - open: static func(name: string) -> result; - - /// Performs a lookup of the given IP address in the ACL. - /// - /// If no matches are found, then `ok(none)` is returned. This corresponds - /// to an HTTP error code of 204, “No Content”. - lookup: func( - ip-addr: ip-address, - ) -> result, acl-error>; - } - - /// Errors returned on ACL lookup failure. - enum acl-error { - /// Too many requests have been made. - /// - /// This corresponds to an HTTP error code of 429, “Too Many Requests”. - too-many-requests, - - /// Generic error value. - /// - /// This means that some unexpected error occurred. - generic-error, - } -} - -/// [Backends] API. -/// -/// A backend represents a service that the application can send requests to, potentially -/// caching the responses received. -/// -/// Backends come in one of two flavors: -/// * **Static Backends**: These backends are created using the Fastly UI or API, -/// and are predefined by the user. Static backends typically have short names that are -/// usable across every session of a service. -/// * **Dynamic Backends**: These backends are created programmatically using the -/// `register-dynamic-backend` API. They are defined at runtime, and may or may not -/// be shared across sessions depending on how they are configured. -/// -/// To use a backend, pass it to a `send*` function. -/// -/// Future versions of this function may return an error if your service does not have a backend -/// with this name. -/// -/// [Backends]: https://www.fastly.com/documentation/guides/integrations/non-fastly-services/developer-guide-backends/ -interface backend { - use types.{error}; - use http-types.{tls-version}; - use secret-store.{secret}; - - /// Creates a new dynamic backend. - /// - /// The arguments are the name of the new backend to use, along with a string describing the - /// backend host. The latter can be of the form: - /// - /// - "" - /// - "" - /// - ":" - /// - ":" - /// - /// The name can be whatever you would like, as long as it does not match the name of any of the - /// static service backends nor match any other dynamic backends built during this session. - /// (Names can overlap between different sessions of the same service—they will be treated as - /// completely separate entities and will not be pooled—but you cannot, for example, declare - /// a dynamic backend named “dynamic-backend” twice in the same session.) - /// - /// Dynamic backends must be enabled for the Compute service. You can determine whether or not - /// dynamic backends have been allowed for the current service by checking for the - /// `error.unsupported` error result. This error only arises when attempting to use dynamic - /// backends with a service that has not had dynamic backends enabled, or dynamic backends have - /// been administratively prohibited for the node in response to an ongoing incident. - register-dynamic-backend: func( - prefix: string, - target: string, - options: dynamic-backend-options, - ) -> result<_, error>; - - /// Options for `register-dynamic-backend`. - resource dynamic-backend-options { - /// Constructs an options resource with default values for all other possible fields for the - /// backend, which can be overridden using the other methods provided. - constructor(); - - /// Sets a host header override when contacting this backend. - /// - /// This will force the value of the “Host” header to the given string when sending out the - /// origin request. If this is not set and no header already exists, the “Host” header will - /// default to the target. - /// - /// For more information, see [the Fastly documentation on override hosts]. - /// - /// [the Fastly documentation on override hosts]: https://docs.fastly.com/en/guides/specifying-an-override-host> - override-host: func(value: string); - - /// Sets the connection timeout, in milliseconds, for this backend. - /// - /// Defaults to 1,000ms (1s). - connect-timeout: func(value: u32); - - /// Sets a timeout, in milliseconds, that applies between the time of connection and the time we - /// get the first byte back. - /// - /// Defaults to 15,000ms (15s). - first-byte-timeout: func(value: u32); - - /// Sets a timeout, in milliseconds, that applies between any two bytes we receive across the - /// wire. - /// - /// Defaults to 10,000ms (10s). - between-bytes-timeout: func(value: u32); - - /// Enables or disables TLS to connect to the backend. - /// - /// When using TLS, Fastly checks the validity of the backend’s certificate, and fails the - /// connection if the certificate is invalid. This check is not optional: an invalid - /// certificate will cause the backend connection to fail (but read on). - /// - /// By default, the validity check does not require that the certificate hostname matches the - /// hostname of your request. You can use check_certificate to request a check of the - /// certificate hostname. - /// - /// By default, certificate validity uses a set of public certificate authorities. You can - /// specify an alternative CA using ca_certificate. - use-tls: func(value: bool); - - /// Sets the minimum TLS version for connecting to the backend. - /// - /// Setting this will enable TLS for the connection as a side effect. - tls-min-version: func(value: tls-version); - - /// Sets the maximum TLS version for connecting to the backend. - /// - /// Setting this will enable TLS for the connection as a side effect. ( - tls-max-version: func(value: tls-version); - - /// Defines the hostname that the server certificate should declare, and turn on validation - /// during backend connections. - /// - /// You should enable this if you are using TLS, and setting this will enable TLS for the - /// connection as a side effect. - /// - /// If `check-certificate` is not provided (default), the server certificate’s hostname may - /// have any value. - cert-hostname: func(value: string); - - /// Sets the CA certificate to use when checking the validity of the backend. - /// - /// Setting this will enable TLS for the connection as a side effect. - /// - /// If `ca-certificate` is not provided (default), the backends’s certificate is validated - /// using a set of public root CAs. - ca-certificate: func(value: string); - - /// Sets the acceptable cipher suites to use for TLS 1.0 - 1.2 connections. - /// - /// Setting this will enable TLS for the connection as a side effect. - tls-ciphers: func(value: string); - - /// Sets the SNI hostname for the backend connection. - /// - /// Setting this will enable TLS for the connection as a side effect. - sni-hostname: func(value: string); - - /// Provides the given client certificate to the server as part of the TLS handshake. - /// - /// Setting this will enable TLS for the connection as a side effect. Both the certificate and - /// the key to use should be in standard PEM format; providing the information in another - /// format will lead to an error. We suggest that (at least the) key should be held in - /// something like the Fastly secret store for security, with the handle passed to this - /// function without unpacking it via Secret::plaintext; the certificate can be held in a less - /// secure medium. - /// - /// (If it is absolutely necessary to get the key from another source, we suggest the use of - /// `secret.from-bytes`. - client-cert: func(client-cert: string, key: borrow); - - /// Configures up to how long to allow HTTP keepalive connections to remain idle in the - /// connection pool. - http-keepalive-time-ms: func(value: u32); - - /// Configures whether or not to use TCP keepalive on the connection to the backend. - tcp-keepalive-enable: func(value: u32); - - /// Configures how long to wait in between each TCP keepalive probe sent to the backend. - tcp-keepalive-interval-secs: func(value: u32); - - /// Configures up to how many TCP keepalive probes to send to the backend before the connection - /// is considered dead. - tcp-keepalive-probes: func(value: u32); - - /// Configures how long to wait after the last sent data over the TCP connection before starting - /// to send TCP keepalive probes. - tcp-keepalive-time-secs: func(value: u32); - - /// Determines whether or not connections to the same backend should be pooled across different - /// sessions. - /// - /// Fastly considers two backends “the same” if they’re registered with the same name and - /// the exact same settings. In those cases, when pooling is enabled, if Session 1 opens a - /// connection to this backend it will be left open, and can be re-used by Session 2. This can - /// help improve backend latency, by removing the need for the initial - /// network / TLS handshake(s). - /// - /// By default, pooling is enabled for dynamic backends. - pooling: func(value: bool); - - /// Sets whether or not this backend will be used for gRPC traffic. - /// - /// Warning: Setting this for backends that will not be used with gRPC may have unpredictable - /// effects. Fastly only currently guarantees that this connection will work for gRPC traffic. - grpc: func(value: bool); - } - - type timeout-ms = u32; - type timeout-secs = u32; - type probe-count = u32; - - /// Returns `true` if a backend with this name exists. - exists: func(backend: string) -> result; - - enum backend-health { - unknown, - healthy, - unhealthy, - } - - /// Return the health of the backend if configured and currently known. - /// - /// For backends without a configured healthcheck, this will always return - /// `backend-health.unknown`. - is-healthy: func(backend: string) -> result; - - /// Returns `true` if the backend is a “dynamic” backend. - is-dynamic: func(backend: string) -> result; - - /// Gets the host of this backend. - get-host: func(backend: string, max-len: u64) -> result; - - /// Gets the “override host” for this backend. - /// - /// This is used to change the `Host` header sent to the backend. See - /// [the Fastly documentation on override hosts]. - /// - /// [the Fastly documentation on override hosts]: https://docs.fastly.com/en/guides/specifying-an-override-host> - get-override-host: func( - backend: string, - max-len: u64, - ) -> result>, error>; - - /// Gets the remote TCP port of the backend connection for the request. - get-port: func(backend: string) -> result; - - /// Gets the connection timeout of the backend. - get-connect-timeout-ms: func(backend: string) -> result; - - /// Gets the first byte timeout of the backend. - /// - /// This timeout applies between the time of connection and the time we get the first byte back. - get-first-byte-timeout-ms: func(backend: string) -> result; - - /// Gets the between byte timeout of the backend. - /// - /// This timeout applies between any two bytes we receive across the wire. - get-between-bytes-timeout-ms: func(backend: string) -> result; - - /// Returns `true` if the backend is configured to use TLS. - is-tls: func(backend: string) -> result; - - /// Gets the minimum TLS version this backend will use. - get-tls-min-version: func(backend: string) -> result, error>; - - /// Gets the maximum TLS version this backend will use. - get-tls-max-version: func(backend: string) -> result, error>; - - /// Returns the time for this backend to hold onto an idle HTTP keepalive connection - /// after it was last used before closing it. - get-http-keepalive-time: func( - backend: string, - ) -> result; - - /// Returns `true` if TCP keepalives have been enabled for this backend. - get-tcp-keepalive-enable: func( - backend: string, - ) -> result; - - /// Returns the time to wait in between sending each TCP keepalive probe to this backend. - get-tcp-keepalive-interval: func( - backend: string, - ) -> result; - - /// Returns the time to wait after the last data was sent before starting to send TCP keepalive - /// probes to this backend. - get-tcp-keepalive-probes: func( - backend: string, - ) -> result; - - /// Returns the time to wait after the last data was sent before starting to send TCP keepalive - /// probes to this backend. - get-tcp-keepalive-time: func( - backend: string, - ) -> result; -} - -/// Async IO support. -/// -/// This module provides several utilities for performing I/O asynchronously. -/// See the documentation for `async-io.pollable` for a description of the kinds -/// of events it supports. -/// -/// In the future, this interface is expected to be replaced by -/// [integrated async features]. -/// -/// [integrated async features]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Async.md#-async-explainer -interface async-io { - /// An object supporting generic async operations. - /// - /// Can be a `http-body.body`, `http-req.pending-response`, `http-req.pending-request`, - /// `cache.pending-entry`. `kv-store.pending-lookup`, `kv-store.pending-insert`, - /// `kv-store.pending-delete`, or `kv-store.pending-list`. - /// - /// Each async item has an associated I/O action: - /// - /// * Pending requests: awaiting the response headers / `response` object - /// * Normal bodies: reading bytes from the body - /// * Streaming bodies: writing bytes to the body - /// - /// For writing bytes, there is a large buffer associated with the handle that bytes - /// can eagerly be written into, even before the origin itself consumes that data. - resource pollable { - /// Make a nonblocking attempt to complete the I/O operation. - /// - /// Returns `true` if the given async item is “ready” for its associated I/O action, `false` - /// otherwise. - /// - /// If an object is ready, the I/O action is guaranteed to complete without blocking. - /// - /// Valid object handles includes bodies and pending requests. See the `async-io.pollable` - /// definition for more details, including what I/O actions are associated with each handle - /// type. - is-ready: func() -> bool; - - /// Create a new trivial `pollable` which reports being immediately ready. - new-ready: static func() -> pollable; - } - - /// Blocks until one of the given objects is ready for I/O. - /// - /// If an object is ready, the I/O action is guaranteed to complete without blocking. - /// - /// Valid object handles includes bodies and pending requests. See the `async-io.pollable` - /// definition for more details, including what I/O actions are associated with each handle - /// type. - /// - /// Returns the *index* (not handle!) of the first object that is ready. - /// - /// Traps if the list is empty. - select: func(handles: list>) -> u32; - - /// Blocks until one of the given objects is ready for I/O, or the timeout expires. - /// - /// If an object is ready, the I/O action is guaranteed to complete without blocking. - /// - /// Valid object handles includes bodies and pending requests. See the `async-io.pollable` - /// definition for more details, including what I/O actions are associated with each handle - /// type. - /// - /// The timeout is specified in milliseconds. - /// - /// Returns the *index* (not handle!) of the first object that is ready, or `none` if the - /// timeout expires before any objects are ready for I/O. - select-with-timeout: func(handles: list>, timeout-ms: u32) -> option; -} - -/// [Cache Purging] API. -/// -/// [Cache Purging]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/ -interface purge { - - use types.{error}; - - record purge-options { - /// Perform a [soft purge] instead of a hard purge. - /// - /// [soft purge]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/#soft-vs-hard-purging - soft-purge: bool, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `purge-options` - resource extra-purge-options {} - - /// Purge a surrogate key for the current service. - /// - /// A surrogate key can be a max of 1024 characters. - /// A surrogate key must contain only printable ASCII characters (those between `0x21` and `0x7E`, - /// inclusive). - /// - /// Returns a [JSON purge response]. - /// - /// [JSON purge response]: https://developer.fastly.com/reference/api/purging/#purge-tag - purge-surrogate-key: func( - surrogate-keys: string, - purge-options: purge-options, - ) -> result<_, error>; - - /// Purge a surrogate key for the current service, and return the purge id. - /// - /// This is similar to `purge-surrogate-key`, but on success, returns an - /// ASCII alphanumeric string identifying a purging. - purge-surrogate-key-verbose: func( - surrogate-keys: string, - purge-options: purge-options, - max-len: u64, - ) -> result; -} - -/// [Core Cache] API -/// -/// [Core Cache]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/#core-cache -interface cache { - - use types.{error}; - use http-body.{body}; - use http-req.{request}; - - /// The outcome of a cache lookup (either bare or as part of a cache transaction) - resource entry { - /// Performs a non-request-collapsing cache lookup. - /// - /// Returns a result without waiting for any request collapsing that may be ongoing. - lookup: static func( - key: list, - options: lookup-options, - ) -> result; - - /// The entrypoint to the request-collapsing cache transaction API. - /// - /// This operation always participates in request collapsing and may return stale objects. To - /// bypass request collapsing, use `lookup` and `insert` instead. - transaction-lookup: static func( - key: list, - options: lookup-options, - ) -> result; - - /// The entrypoint to the request-collapsing cache transaction API, returning instead of waiting - /// on busy. - /// - /// This operation always participates in request collapsing and may return stale objects. To - /// bypass request collapsing, use `lookup` and `insert` instead. - transaction-lookup-async: static func( - key: list, - options: lookup-options, - ) -> result; - - /// Insert an object into the cache with the given metadata. - /// - /// Can only be used in if the cache handle state includes the `must-insert-or-update` flag. - /// - /// The returned handle is to a streaming body that is used for writing the object into - /// the cache. - transaction-insert: func( - options: write-options, - ) -> result; - - /// Insert an object into the cache with the given metadata, and return a readable stream of the - /// bytes as they are stored. - /// - /// This helps avoid the “slow reader” problem on a teed stream, for example when a program - /// wishes to store a backend request in the cache while simultaneously streaming to a client - /// in an HTTP response. - /// - /// The returned body handle is to a streaming body that is used for writing the object *into* - /// the cache. The returned cache handle provides a separate transaction for reading out the - /// newly cached object to send elsewhere. - transaction-insert-and-stream-back: func( - options: write-options, - ) -> result, error>; - - /// Update the metadata of an object in the cache without changing its data. - /// - /// Can only be used in if the cache handle state includes both of the flags: - /// - `found` - /// - `must-insert-or-update` - transaction-update: func( - options: write-options, - ) -> result<_, error>; - - get-state: func() -> result; - - /// Gets the user metadata of the found object, returning `ok(none)` if no object - /// was found. - get-user-metadata: func(max-len: u64) -> result>, error>; - - /// Gets a range of the found object body, returning `ok(none)` if there - /// was no found object. - /// - /// The returned `body` must be closed before calling this function again on the same - /// `entry`. - /// - /// Note: until the CacheD protocol is adjusted to fully support this functionality, - /// the body of objects that are past the stale-while-revalidate period will not - /// be available, even when other metadata is. - get-body: func( - options: get-body-options, - ) -> result; - - /// Gets the content length of the found object, returning `ok(none)` if - /// there was no found object, or no content length was provided. - get-length: func() -> result, error>; - - /// Gets the configured max age of the found object, returning `ok(none)` - /// if there was no found object. - get-max-age-ns: func() -> result, error>; - - /// Gets the configured stale-while-revalidate period of the found object, returning `ok(none)` - /// if there was no found object. - get-stale-while-revalidate-ns: func() -> result, error>; - - /// Gets the age of the found object, returning `ok(none)` if there - /// was no found object. - get-age-ns: func() -> result, error>; - - /// Gets the number of cache hits for the found object, returning `ok(none)` - /// if there was no found object. - get-hits: func() -> result, error>; - - /// Cancel an obligation to provide an object to the cache. - /// - /// Useful if there is an error before streaming is possible, for example if a backend is - /// unreachable. - transaction-cancel: func() -> result<_, error>; - } - /// Handle that can be used to check whether or not a cache lookup is waiting on another client. - use async-io.{pollable as pending-entry}; - - /// A replace operation. - type replace-entry = entry; - - /// The entrypoint to the replace API. - /// - /// This operation always participates in request collapsing and may return stale objects. - replace: func( - key: list, - options: replace-options, - ) -> result; - - /// Replace an object in the cache with the given metadata - /// - /// The returned handle is to a streaming body that is used for writing the object into - /// the cache. - replace-insert: func( - handle: borrow, - options: write-options, - ) -> result; - - /// Gets the age of the existing object during replace, returning - /// `ok(none)` if there was no object. - replace-get-age-ns: func( - handle: borrow, - ) -> result, error>; - - /// Gets a range of the existing object body, returning `ok(none)` if there - /// was no existing object. - /// - /// The returned `body` must be closed before calling this function - /// again on the same `replace-entry`. - replace-get-body: func( - handle: borrow, - options: get-body-options, - ) -> result, error>; - - /// Gets the number of cache hits for the existing object during replace, - /// returning `ok(none)` if there was no object. - replace-get-hits: func( - handle: borrow, - ) -> result, error>; - - /// Gets the content length of the existing object during replace, - /// returning `ok(none)` if there was no object, or no content - /// length was provided. - replace-get-length: func( - handle: borrow, - ) -> result, error>; - - /// Gets the configured max age of the existing object during replace, - /// returning `ok(none)` if there was no object. - replace-get-max-age-ns: func( - handle: borrow, - ) -> result, error>; - - /// Gets the configured stale-while-revalidate period of the existing - /// object during replace, returning `ok(none)` if there was no - /// object. - replace-get-stale-while-revalidate-ns: func( - handle: borrow, - ) -> result, error>; - - /// Gets the lookup state of the existing object during replace, returning - /// `ok(none)` if there was no object. - replace-get-state: func( - handle: borrow, - ) -> result, error>; - - /// Gets the user metadata of the existing object during replace, returning - /// `ok(none)` if there was no object. - replace-get-user-metadata: func( - handle: borrow, - max-len: u64, - ) -> result>, error>; - - type object-length = u64; - type duration-ns = u64; - type cache-hit-count = u64; - - /// Options for cache lookup operations; currently used for both `lookup` and - /// `transaction-lookup`. - record lookup-options { - /// A full request handle, but used only for its headers - /// - /// May be `none` if the `request-headers` option isn't enabled. - /// - request-headers: option>, - - always-use-requested-range: bool, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `lookup-options` - resource extra-lookup-options { - constructor(); - } - - /// Configuration for several functions that write to the cache: - /// - `insert` - /// - `transaction-insert` - /// - `transaction-insert-and-stream-back` - /// - `transaction-update` - /// - /// Some options are only allowed for certain of these hostcalls; see the comments - /// on the fields. - record write-options { - /// this is a required field - max-age-ns: duration-ns, - /// a full request handle, but used only for its headers - /// - /// Only allowed for non-transactional `insert` - request-headers: option>, - /// a list of header names separated by spaces - vary-rule: option, - /// The initial age of the object in nanoseconds (default: 0). - /// - /// This age is used to determine the freshness lifetime of the object as well as to - /// prioritize which variant to return if a subsequent lookup matches more than one vary rule - initial-age-ns: option, - stale-while-revalidate-ns: option, - /// a list of surrogate keys separated by spaces - surrogate-keys: option, - length: option, - user-metadata: option>, - edge-max-age-ns: option, - sensitive-data: bool, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `write-options` - resource extra-write-options { - constructor(); - } - - record get-body-options { - %from: option, - to: option, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `get-body-options` - resource extra-get-body-options {} - - /// The status of this lookup (and potential transaction) - flags lookup-state { - /// a cached object was found - found, - /// the cached object is valid to use (implies found) - usable, - /// the cached object is stale (but may or may not be valid to use) - stale, - /// this client is requested to insert or revalidate an object - must-insert-or-update, - } - - /// Performs a non-request-collapsing cache insertion (or update). - /// - /// The returned handle is to a streaming body that is used for writing the object into - /// the cache. - insert: func( - key: list, - options: write-options, - ) -> result; - - /// Continues the lookup transaction from which the given busy handle was returned, - /// waiting for the leader transaction if request collapsed, and returns a cache handle. - await-entry: func( - handle: pending-entry, - ) -> result; - - /// Closes an interaction with the cache that has not yet finished request collapsing. - close-pending-entry: func(handle: pending-entry) -> result<_, error>; - - /// Closes an ongoing interaction with the cache. - /// - /// If the cache handle state includes the `must-insert-or-update` (and hence no insert or - /// update has been performed), closing the handle cancels any request collapsing, potentially - /// choosing a new waiter to perform the insertion/update. - /// - /// This may be passed either an `entry` or a `replace-entry`. - close-entry: func(handle: entry) -> result<_, error>; - - /// Options for cache replace operations - record replace-options { - /// a full request handle, but used only for its headers - request-headers: option>, - replace-strategy: option, - always-use-requested-range: bool, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `replace-options` - resource extra-replace-options { - constructor(); - } - - enum replace-strategy { - /// Immediately start the replace and do not wait for any other pending requests for the same - /// object, including insert requests. - /// - /// With this strategy a replace will race all other pending requests to update the object. - /// - /// The existing object will be accessible until this replace finishes providing the replacement - /// object. - /// - /// This is the default replace strategy. - immediate, - - /// Immediate, but remove the existing object immediately - /// - /// Requests for the same object that arrive after this replace starts will wait until this - /// replace starts providing the replacement object. - immediate-force-miss, - - /// Join the wait list behind other pending requests before starting this request. - /// - /// With this strategy this replace request will wait for an in-progress replace or insert - /// request before starting. - /// - /// This strategy allows implementing a counter, but may cause timeouts if too many requests - /// are waiting for in-progress and waiting updates to complete. - wait, - } -} - -/// [HTTP Cache] API. -/// -/// Overall, this should look very familiar to users of the Core Cache API. The primary differences -/// are: -/// -/// - HTTP `request`s and `response`s are used rather than relying on the user to -/// encode headers, status codes, etc in `user-metadata`. -/// -/// - Convenience functions specific to HTTP semantics are provided, such as `is-request-cacheable`, -/// `get-suggested-backend-request`, `get-suggested-write-options`, and -/// `transaction-record-not-cacheable`. -/// -/// The HTTP-specific behavior of these functions is intended to support applications that match the -/// normative guidance in [RFC 9111]. For example, `is-request-cacheable` returns `false` for `POST` -/// requests. However, this answer along with those of many of these functions explicitly provide -/// *suggestions*; they do not necessarily need to be followed if custom behavior is required, such -/// as caching `POST` responses when the application author knows that to be safe. -/// -/// The starting points for this API are `lookup` (no request collapsing) and `transaction-lookup` -/// (request collapsing). -/// -/// [HTTP Cache]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/cache-freshness/ -/// [RFC 9111]: https://www.rfc-editor.org/rfc/rfc9111.html -interface http-cache { - use types.{error}; - use http-body.{body}; - use http-req.{request}; - use http-resp.{response, response-with-body}; - use cache.{lookup-state, object-length, duration-ns, cache-hit-count}; - - /// An HTTP Cache transaction. - resource entry { - /// Performs a cache lookup based on the given request. - /// - /// This operation always participates in request collapsing and may return an obligation to - /// insert or update responses, and/or stale responses. To bypass request collapsing, use - /// `lookup` instead. - /// - /// The request is not consumed. - transaction-lookup: static func( - req-handle: borrow, - options: lookup-options, - ) -> result; - - /// Inserts a response into the cache with the given options, returning a streaming body handle - /// that is ready for writing or appending. - /// - /// Can only be used if the cache handle state includes the `must-insert-or-update` flag. - /// - /// The response is consumed. - transaction-insert: func( - resp-handle: response, - options: write-options, - ) -> result; - - /// Inserts a response into the cache with the given options, and return a fresh cache handle - /// that can be used to retrieve and stream the response while it's being inserted. - /// - /// This helps avoid the “slow reader” problem on a teed stream, for example when a program - /// wishes to store a backend request in the cache while simultaneously streaming to a client - /// in an HTTP response. - /// - /// The response is consumed. - transaction-insert-and-stream-back: func( - resp-handle: response, - options: write-options, - ) -> result, error>; - - /// Updates freshness lifetime, response headers, and caching settings without updating the - /// response body. - /// - /// Can only be used in if the cache handle state includes both of the flags: - /// - `found` - /// - `must-insert-or-update` - /// - /// The response is consumed. - transaction-update: func( - resp-handle: response, - options: write-options, - ) -> result<_, error>; - - /// Updates freshness lifetime, response headers, and caching settings without updating the - /// response body, and return a fresh cache handle that can be used to retrieve and stream the - /// stored response. - /// - /// Can only be used in if the cache handle state includes both of the flags: - /// - `found` - /// - `must-insert-or-update` - /// - /// The response is consumed. - transaction-update-and-return-fresh: func( - resp-handle: response, - options: write-options, - ) -> result; - - /// Disables request collapsing and response caching for this cache entry. - /// - /// In Varnish terms, this function stores a hit-for-pass object. - /// - /// Only the max age and, optionally, the vary rule are read from the `options` - /// for this function. - transaction-record-not-cacheable: func( - options: write-options, - ) -> result<_, error>; - - /// Prepares a suggested request to make to a backend to satisfy the looked-up request. - /// - /// If there is a stored, stale response, this suggested request may be for revalidation. If the - /// looked-up request is ranged, the suggested request will be unranged in order to try caching - /// the entire response. - get-suggested-backend-request: func() -> result; - - /// Prepares a suggested set of cache write options for a given request and response pair. - /// - /// The response is not consumed. - get-suggested-write-options: func( - response: borrow, - ) -> result; - - /// Adjusts a response into the appropriate form for storage and provides a storage action - /// recommendation. - /// - /// For example, if the looked-up request contains conditional headers, this function will - /// interpret a `304 Not Modified` response for revalidation by updating headers. - /// - /// In addition to the updated response, this function returns the recommended storage action. - prepare-response-for-storage: func( - response: borrow, - ) -> result, error>; - - /// Retrieves a stored response from the cache, returning `ok(none)` if - /// there was no response found. - /// - /// If `transform-for-client` is set, the response will be adjusted according to the looked-up - /// request. For example, a response retrieved for a range request may be transformed into a - /// `206 Partial Content` response with an appropriate `content-range` header. - get-found-response: func( - transform-for-client: u32, - ) -> result, error>; - - /// Gets the state of a cache transaction. - /// - /// Primarily useful after performing the lookup to determine what subsequent operations are - /// possible and whether any insertion or update obligations exist. - get-state: func( - ) -> result; - - /// Gets the length of the found response, returning `ok(none)` if there - /// was no response found or no length was provided. - get-length: func() -> result, error>; - - /// Gets the configured max age of the found response in nanoseconds, returning `ok(none)` - /// if there was no response found. - get-max-age-ns: func() -> result, error>; - - /// Gets the configured stale-while-revalidate period of the found response in nanoseconds, - /// returning `ok(none)` if there was no response found. - get-stale-while-revalidate-ns: func( - ) -> result, error>; - - /// Gets the age of the found response in nanoseconds, returning `ok(none)` - /// if there was no response found. - get-age-ns: func() -> result, error>; - - /// Gets the number of cache hits for the found response, returning `ok(none)` - /// if there was no response found. - /// - /// This figure only reflects hits for a stored response in a particular cache server - /// or cluster, not the entire Fastly network. - get-hits: func() -> result, error>; - - /// Gets whether a found response is marked as containing sensitive data, returning `ok(none)` - /// if there was no response found. - get-sensitive-data: func() -> result, error>; - - /// Gets the surrogate keys of the found response, returning `ok(none)` if - /// there was no response found. - /// - /// The output is a list of surrogate keys separated by spaces. - /// - /// If the full list requires more than `max-len` bytes, an `error.buffer-len` - /// error is returned containing the required size. - get-surrogate-keys: func( - max-len: u64, - ) -> result, error>; - - /// Gets the vary rule of the found response, returning `ok(none)` if there - /// was no response found. - /// - /// The output is a list of header names separated by spaces. - /// - /// If the full list requires more than `max-len` bytes, an `error.buffer-len` - /// error is returned containing the required size. - get-vary-rule: func( - max-len: u64, - ) -> result, error>; - - /// Abandons an obligation to provide a response to the cache. - /// - /// Useful if there is an error before streaming is possible, for example if a backend is - /// unreachable. - /// - /// If there are other requests collapsed on this transaction, one of those other requests will - /// be awoken and given the obligation to provide a response. If subsequent requests - /// are unlikely to yield cacheable responses, this may lead to undesired serialization of - /// requests. Consider using `transaction-record-not-cacheable` to make lookups for this request - /// bypass the cache. - transaction-abandon: func() -> result<_, error>; - } - - /// The suggested action to take for spec-recommended behavior following - /// `prepare-response-for-storage`. - enum storage-action { - /// Insert the response into cache (for `transaction-insert` and - /// `transaction-insert-and-stream-back`). - insert, - /// Update the stale response in cache (for `transaction-update` and - /// `transaction-update-and-return-fresh`). - update, - /// Do not store this response. - do-not-store, - /// Do not store this response, and furthermore record its non-cacheability for other pending - /// requests (`transaction-record-not-cacheable`). - record-uncacheable, - } - - /// Non-required options for cache lookups. - record lookup-options { - /// Cache key to use in lieu of the automatically-generated cache key based on the request's - /// properties. - override-key: option>, - /// Backend name that will be used for the eventual request. - backend-name: option, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `lookup-options` - resource extra-lookup-options {} - - /// Options for cache insertions and updates. - record write-options { - /// The maximum age of the response before it is considered stale, in nanoseconds. - /// - /// This field is required. - max-age-ns: duration-ns, - - /// A list of header names to use when calculating variants for this response. - /// - /// The format is a string containing header names separated by spaces. - vary-rule: option, - - /// The initial age of the response in nanoseconds. - /// - /// If this field is not set, the default value is zero. - /// - /// This age is used to determine the freshness lifetime of the response as well as to - /// prioritize which variant to return if a subsequent lookup matches more than one vary rule - initial-age-ns: option, - - /// The maximum duration after `max-age` during which the response may be delivered stale - /// while being revalidated, in nanoseconds. - /// - /// If this field is not set, the default value is zero. - stale-while-revalidate-ns: option, - - /// A list of surrogate keys that may be used to purge this response. - /// - /// The format is a string containing [valid surrogate keys] separated by spaces. - /// - /// If this field is not set, no surrogate keys will be associated with the response. This - /// means that the response cannot be purged except via a purge-all operation. - /// - /// [valid surrogate keys]: https://www.fastly.com/documentation/reference/http/http-headers/Surrogate-Key/ - surrogate-keys: option, - - /// The length of the response body. - /// - /// If this field is not set, the length of the body is treated as unknown. - /// - /// When possible, this field should be set so that other clients waiting to retrieve the - /// body have enough information to synthesize a `content-length` even before the complete - /// body is inserted to the cache. - length: option, - - /// Enable or disable PCI/HIPAA-compliant non-volatile caching. - /// - /// See the [Fastly PCI-Compliant Caching and Delivery documentation] for details. - /// - /// [Fastly PCI-Compliant Caching and Delivery documentation]: https://docs.fastly.com/products/pci-compliant-caching-and-delivery - sensitive-data: bool, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `write-options` - resource extra-write-options {} - - /// Determines whether a request is cacheable per conservative [RFC 9111] semantics. - /// - /// In particular, this function checks whether the request method is `GET` or `HEAD`, and - /// considers requests with other methods uncacheable. Applications where it is safe to cache - /// responses to other methods should consider using their own cacheability check instead of - /// this function. - /// - /// [RFC 9111]: https://www.rfc-editor.org/rfc/rfc9111.html - is-request-cacheable: func(request: borrow) -> result; - - /// Retrieves the default cache key for the request. - /// - /// If the full key requires more than `max-len` bytes, an `error.buffer-len` - /// error is returned containing the required size. - /// - /// At the moment, HTTP cache keys must always be 32 bytes. - get-suggested-cache-key: func( - request: borrow, - max-len: u64, - ) -> result, error>; - - /// Closes an ongoing interaction with the cache. - /// - /// If the cache handle state includes `must-insert-or-update` (and hence no insert or update - /// has been performed), closing the handle cancels any request collapsing, potentially choosing - /// a new waiter to perform the insertion/update. - close-entry: func( - handle: entry, - ) -> result<_, error>; - - /// The methods in this resource return values that correspond to the fields in a - /// `write-options`. This type is used when a `write-options` value would - /// be returned, so that it can use `max-len` parameters when returning - /// dynamically-sized data, and so that it excludes the `extra` field, since borrowed - /// handles cannot be returned from functions. - resource suggested-write-options { - /// Returns the suggested value for the `write-options.max-age-ns` field. - get-max-age-ns: func() -> duration-ns; - /// Returns the suggested value for the `write-options.vary-rule` field. - get-vary-rule: func(max-len: u64) -> result; - /// Returns the suggested value for the `write-options.initial-age-ns` field. - get-initial-age-ns: func() -> duration-ns; - /// Returns the suggested value for the `write-options.stale-while-revalidate-ns` field. - get-stale-while-revalidate-ns: func() -> duration-ns; - /// Returns the suggested value for the `write-options.surrogate-keys` field. - get-surrogate-keys: func(max-len: u64) -> result; - /// Returns the suggested value for the `write-options.length` field. - get-length: func() -> option; - /// Returns the suggested value for the `write-options.sensitive-data` field. - get-sensitive-data: func() -> bool; - } -} - -/// [Config Store] API. -/// -/// [Config Store]: https://www.fastly.com/documentation/guides/concepts/edge-state/dynamic-config/#config-stores -interface config-store { - use types.{error, open-error}; - - /// A Config Store. - resource store { - /// Attempts to open the named config store. - /// - /// Names are case sensitive. - open: static func(name: string) -> result; - - /// Fetches a value from the config store, returning `ok(none)` if it doesn't exist. - get: func( - key: string, - max-len: u64, - ) -> result, error>; - } -} - -/// [Shielding] API. -/// -/// [Shielding]: https://www.fastly.com/documentation/guides/concepts/shielding/ -interface shielding { - use types.{error}; - - shield-info: func( - name: string, - max-len: u64, - ) -> result; - - /// Extensibility for `shield-backend-options` - resource shield-backend-options { - constructor(); - - set-cache-key: func(cache-key: string); - set-first-byte-timeout: func(timeout-ms: u32); - } - - backend-for-shield: func( - name: string, - options: option>, - max-len: u64, - ) -> result; -} - -/// [Image Optimizer] API. -/// -/// [Image Optimizer]: https://www.fastly.com/documentation/guides/full-site-delivery/image-optimization/about-fastly-image-optimizer/ -interface image-optimizer { - - use http-body.{body}; - use http-req.{request}; - use http-resp.{response-with-body}; - use types.{error}; - - record image-optimizer-transform-options { - /// Contains any Image Optimizer API parameters that were set - /// as well as the Image Optimizer region the request is meant for. - sdk-claims-opts: option, - - /// Additional options may be added in the future via this resource type. - extra: option>, - } - - /// Extensibility for `image-optimizer-transform-options` - resource extra-image-optimizer-transform-options {} - - transform-image-optimizer-request: func( - origin-image-request: borrow, - origin-image-request-body: option, - origin-image-request-backend: string, - io-transform-options: image-optimizer-transform-options, - ) -> result; -} - -/// The exported interface. -/// -/// The `handle` function serves as the main entrypoint to applications. Unlike the -/// rest of the interfaces in this package, this `http-incoming` interface is exported by -/// applications rather than imported, which means that this is a function defined -/// by the application and called from the outside, rather than a function called -/// by the application into the outside. -interface http-incoming { - use http-body.{body}; - use http-req.{request}; - - /// Handle the given request. - /// - /// Conceptually, `send` returns a response to the given request, however this isn't - /// modeled as a literal return value in this API. Instead, the `send-downstream` - /// function is used to send the response. This allows for the option of streaming the - /// response body, since that requires the program to continue executing after the - /// response has been initiated. - handle: func(request: request, body: body) -> result; -} - -/// Features for interacting with the Compute runtime. -interface compute-runtime { - /// A timestamp in milliseconds. - type vcpu-ms = u64; - - /// Gets the amount of vCPU time that has passed since this session was started, in milliseconds. - /// - /// This function returns only time spent running on a vCPU, and does not include time spent - /// performing any I/O operations. However, it is based on clock time passing, and so will include - /// time spent executing hostcalls, is heavily affected by what core of what CPU is running the - /// code, and can even be influenced by the state of the CPU. - /// - /// As a result, this function *should not be used in benchmarking across runs*. It can be used, - /// with caution, to compare the runtime of different operations within the same session. - get-vcpu-ms: func() -> vcpu-ms; - - /// A UUID generated by Fastly for each session. - /// - /// This is often a useful value to include in log messages, and also to send to upstream - /// servers as an additional custom HTTP header, allowing for straightforward correlation of - /// which WebAssembly session processed a request to requests later processed by an origin - /// server. If a session is used to process multiple downstream requests, then you may wish to - /// use the per-request UUID associated with each individual request handle instead of this - /// field. - /// - /// Equivalent to the "FASTLY_TRACE_ID" environment variable. - get-session-id: func() -> string; - - /// The hostname of the Fastly cache server which is executing the current session, for - /// example, `cache-jfk1034`. - /// - /// Equivalent to the "FASTLY_HOSTNAME" environment variable and to [`server.hostname`] in VCL. - /// - /// [`server.hostname`]: https://www.fastly.com/documentation/reference/vcl/variables/server/server-hostname/ - get-hostname: func() -> string; - - /// The three-character identifying code of the [Fastly POP] in which the current session is - /// running. - /// - /// Equivalent to the "FASTLY_POP" environment variable and to [`server.datacenter`] in VCL. - /// - /// [Fastly POP]: https://www.fastly.com/documentation/guides/concepts/pop/ - /// [`server.datacenter`]: https://www.fastly.com/documentation/reference/vcl/variables/server/server-datacenter/ - get-pop: func() -> string; - - /// A code representing the general geographic region in which the [Fastly POP] processing the - /// current Compute session resides. - /// - /// Equivalent to the "FASTLY_REGION" environment variable and to [`server.region`] in VCL, and - /// has the same possible values. - /// - /// [`server.region`]: https://www.fastly.com/documentation/reference/vcl/variables/server/server-region/ - /// [Fastly POP]: https://www.fastly.com/documentation/guides/concepts/pop/ - get-region: func() -> string; - - /// The current cache generation value for this Fastly service. - /// - /// The cache generation value is incremented by [purge-all operations]. - /// - /// Equivalent to the "FASTLY_CACHE_GENERATION" environment variable and to - /// [`req.vcl.generation`] in VCL. - /// - /// [purge-all operations]: https://www.fastly.com/documentation/guides/concepts/edge-state/cache/purging/ - /// [`req.vcl.generation`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-vcl-generation/ - get-cache-generation: func() -> u64; - - /// The customer ID of the Fastly customer account to which the currently executing Fastly - /// service belongs. - /// - /// Equivalent to the "FASTLY_CUSTOMER_ID" environment variable and to [`req.customer_id`] in VCL. - /// - /// [`req.customer_id`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-customer-id/ - get-customer-id: func() -> string; - - /// Whether the request is running in the Fastly service's [staging environment]. - /// - /// `false` for production or `true` for staging. - /// - /// Equivalent to the "FASTLY_IS_STAGING" environment variable and to [`fastly.is_staging`] in VCL. - /// - /// [`fastly.is_staging`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/fastly-is-staging/ - /// [staging environment]: https://docs.fastly.com/products/staging - get-is-staging: func() -> bool; - - /// The identifier for the Fastly service that is processing the current request. - /// - /// Equivalent to the "FASTLY_SERVICE_ID" environment variable and to [`req.service_id`] in VCL. - /// - /// [`req.service_id`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-service-id/ - get-service-id: func() -> string; - - /// The version number for the Fastly service that is processing the current request. - /// - /// Equivalent to the "FASTLY_SERVICE_VERSION" environment variable and to [`req.vcl.version`] - /// in VCL. - /// - /// [`req.vcl.version`]: https://www.fastly.com/documentation/reference/vcl/variables/miscellaneous/req-vcl-version/ - get-service-version: func() -> u64; - - /// This function is not suitable for general-purpose use. - get-namespace-id: func() -> string; -} - -/// Interfaces that a Fastly Compute service may import. -/// -/// This contains the imports used in the `service` world, factored out into a -/// separate world so that it can be used by library components. Library components -/// are components that do not export anything themselves. -world service-imports { - import wasi:clocks/wall-clock@0.2.6; - import wasi:clocks/monotonic-clock@0.2.6; - import wasi:io/error@0.2.6; - import wasi:io/streams@0.2.6; - import wasi:io/poll@0.2.6; - import wasi:random/random@0.2.6; - import wasi:cli/environment@0.2.6; - import wasi:cli/exit@0.2.6; - import wasi:cli/stdout@0.2.6; - import wasi:cli/stderr@0.2.6; - import wasi:cli/stdin@0.2.6; - - import acl; - import async-io; - import backend; - import cache; - import compute-runtime; - import config-store; - import dictionary; - import geo; - import device-detection; - import erl; - import http-body; - import http-cache; - import http-downstream; - import http-req; - import http-resp; - import image-optimizer; - import log; - import kv-store; - import purge; - import secret-store; - import security; - import shielding; -} - -/// A Fastly Compute service. -/// -/// This defines the set of interfaces available to, and expected of, -/// Fastly Compute service applications. -/// -/// This `service` world includes all the `service-imports` imports, and adds the -/// `http-incoming` exports. -world service { - include service-imports; - - // Export the `http-incoming` interface. - export http-incoming; -} From 970bd61c20fa078c5081c91ffdd7344754c65bb2 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Tue, 14 Oct 2025 12:52:34 -0400 Subject: [PATCH 41/50] Move all `wasi:` packages over to a `wasiless:` namespace. This lets us substitute wasiless items in for WASI ones without `wac` having errors about conflicting resource types. (`resource` directives actually create resource-type singletons, and `wac` does not unify them. Thus, we have to give unique package paths to what would otherwise be conflicting ones.) --- src/bindings.rs | 2 +- wit/deps/cli/command.wit | 2 +- wit/deps/cli/imports.wit | 12 +++---- wit/deps/cli/stdio.wit | 6 ++-- wit/deps/clocks/monotonic-clock.wit | 4 +-- wit/deps/clocks/timezone.wit | 2 +- wit/deps/clocks/wall-clock.wit | 2 +- wit/deps/clocks/world.wit | 2 +- wit/deps/filesystem/preopens.wit | 2 +- wit/deps/filesystem/types.wit | 6 ++-- wit/deps/filesystem/world.wit | 2 +- wit/deps/http/proxy.wit | 14 ++++---- wit/deps/http/types.wit | 8 ++--- wit/deps/io/error.wit | 2 +- wit/deps/io/poll.wit | 2 +- wit/deps/io/streams.wit | 2 +- wit/deps/io/world.wit | 2 +- wit/deps/random/insecure-seed.wit | 2 +- wit/deps/random/insecure.wit | 2 +- wit/deps/random/random.wit | 2 +- wit/deps/random/world.wit | 2 +- wit/deps/sockets/ip-name-lookup.wit | 2 +- wit/deps/sockets/network.wit | 2 +- wit/deps/sockets/tcp.wit | 6 ++-- wit/deps/sockets/udp.wit | 2 +- wit/deps/sockets/world.wit | 2 +- wit/wasiless.wit | 54 ++++++++++++++--------------- 27 files changed, 74 insertions(+), 74 deletions(-) diff --git a/src/bindings.rs b/src/bindings.rs index 4655185..df68422 100644 --- a/src/bindings.rs +++ b/src/bindings.rs @@ -4,4 +4,4 @@ wit_bindgen::generate!({ generate_all, }); -pub use exports::wasi; +pub use exports::wasiless as wasi; diff --git a/wit/deps/cli/command.wit b/wit/deps/cli/command.wit index 6d3cc83..22b8857 100644 --- a/wit/deps/cli/command.wit +++ b/wit/deps/cli/command.wit @@ -1,4 +1,4 @@ -package wasi:cli@0.2.6; +package wasiless:cli@0.2.6; @since(version = 0.2.0) world command { diff --git a/wit/deps/cli/imports.wit b/wit/deps/cli/imports.wit index d9fd017..0af101b 100644 --- a/wit/deps/cli/imports.wit +++ b/wit/deps/cli/imports.wit @@ -1,17 +1,17 @@ -package wasi:cli@0.2.6; +package wasiless:cli@0.2.6; @since(version = 0.2.0) world imports { @since(version = 0.2.0) - include wasi:clocks/imports@0.2.6; + include wasiless:clocks/imports@0.2.6; @since(version = 0.2.0) - include wasi:filesystem/imports@0.2.6; + include wasiless:filesystem/imports@0.2.6; @since(version = 0.2.0) - include wasi:sockets/imports@0.2.6; + include wasiless:sockets/imports@0.2.6; @since(version = 0.2.0) - include wasi:random/imports@0.2.6; + include wasiless:random/imports@0.2.6; @since(version = 0.2.0) - include wasi:io/imports@0.2.6; + include wasiless:io/imports@0.2.6; @since(version = 0.2.0) import environment; diff --git a/wit/deps/cli/stdio.wit b/wit/deps/cli/stdio.wit index cb8aea2..000660b 100644 --- a/wit/deps/cli/stdio.wit +++ b/wit/deps/cli/stdio.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface stdin { @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream}; + use wasiless:io/streams@0.2.6.{input-stream}; @since(version = 0.2.0) get-stdin: func() -> input-stream; @@ -10,7 +10,7 @@ interface stdin { @since(version = 0.2.0) interface stdout { @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{output-stream}; + use wasiless:io/streams@0.2.6.{output-stream}; @since(version = 0.2.0) get-stdout: func() -> output-stream; @@ -19,7 +19,7 @@ interface stdout { @since(version = 0.2.0) interface stderr { @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{output-stream}; + use wasiless:io/streams@0.2.6.{output-stream}; @since(version = 0.2.0) get-stderr: func() -> output-stream; diff --git a/wit/deps/clocks/monotonic-clock.wit b/wit/deps/clocks/monotonic-clock.wit index f3bc839..cb87049 100644 --- a/wit/deps/clocks/monotonic-clock.wit +++ b/wit/deps/clocks/monotonic-clock.wit @@ -1,4 +1,4 @@ -package wasi:clocks@0.2.6; +package wasiless:clocks@0.2.6; /// WASI Monotonic Clock is a clock API intended to let users measure elapsed /// time. /// @@ -10,7 +10,7 @@ package wasi:clocks@0.2.6; @since(version = 0.2.0) interface monotonic-clock { @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; + use wasiless:io/poll@0.2.6.{pollable}; /// An instant in time, in nanoseconds. An instant is relative to an /// unspecified initial value, and can only be compared to instances from diff --git a/wit/deps/clocks/timezone.wit b/wit/deps/clocks/timezone.wit index ca98ad1..f4414e4 100644 --- a/wit/deps/clocks/timezone.wit +++ b/wit/deps/clocks/timezone.wit @@ -1,4 +1,4 @@ -package wasi:clocks@0.2.6; +package wasiless:clocks@0.2.6; @unstable(feature = clocks-timezone) interface timezone { diff --git a/wit/deps/clocks/wall-clock.wit b/wit/deps/clocks/wall-clock.wit index 76636a0..1f24147 100644 --- a/wit/deps/clocks/wall-clock.wit +++ b/wit/deps/clocks/wall-clock.wit @@ -1,4 +1,4 @@ -package wasi:clocks@0.2.6; +package wasiless:clocks@0.2.6; /// 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. diff --git a/wit/deps/clocks/world.wit b/wit/deps/clocks/world.wit index 5c53c51..7d1f7c1 100644 --- a/wit/deps/clocks/world.wit +++ b/wit/deps/clocks/world.wit @@ -1,4 +1,4 @@ -package wasi:clocks@0.2.6; +package wasiless:clocks@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/filesystem/preopens.wit b/wit/deps/filesystem/preopens.wit index f228479..245d18c 100644 --- a/wit/deps/filesystem/preopens.wit +++ b/wit/deps/filesystem/preopens.wit @@ -1,4 +1,4 @@ -package wasi:filesystem@0.2.6; +package wasiless:filesystem@0.2.6; @since(version = 0.2.0) interface preopens { diff --git a/wit/deps/filesystem/types.wit b/wit/deps/filesystem/types.wit index 75c1904..58f9c78 100644 --- a/wit/deps/filesystem/types.wit +++ b/wit/deps/filesystem/types.wit @@ -1,4 +1,4 @@ -package wasi:filesystem@0.2.6; +package wasiless:filesystem@0.2.6; /// 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. @@ -26,9 +26,9 @@ package wasi:filesystem@0.2.6; @since(version = 0.2.0) interface types { @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream, output-stream, error}; + use wasiless:io/streams@0.2.6.{input-stream, output-stream, error}; @since(version = 0.2.0) - use wasi:clocks/wall-clock@0.2.6.{datetime}; + use wasiless:clocks/wall-clock@0.2.6.{datetime}; /// File size or length of a region within a file. @since(version = 0.2.0) diff --git a/wit/deps/filesystem/world.wit b/wit/deps/filesystem/world.wit index 65597f9..c1fc096 100644 --- a/wit/deps/filesystem/world.wit +++ b/wit/deps/filesystem/world.wit @@ -1,4 +1,4 @@ -package wasi:filesystem@0.2.6; +package wasiless:filesystem@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/http/proxy.wit b/wit/deps/http/proxy.wit index 5bd9f99..fe49f09 100644 --- a/wit/deps/http/proxy.wit +++ b/wit/deps/http/proxy.wit @@ -1,4 +1,4 @@ -package wasi:http@0.2.6; +package wasiless:http@0.2.6; /// The `wasi:http/imports` world imports all the APIs for HTTP proxies. /// It is intended to be `include`d in other worlds. @@ -6,25 +6,25 @@ package wasi:http@0.2.6; world imports { /// HTTP proxies have access to time and randomness. @since(version = 0.2.0) - import wasi:clocks/monotonic-clock@0.2.6; + import wasiless:clocks/monotonic-clock@0.2.6; @since(version = 0.2.0) - import wasi:clocks/wall-clock@0.2.6; + import wasiless:clocks/wall-clock@0.2.6; @since(version = 0.2.0) - import wasi:random/random@0.2.6; + import wasiless:random/random@0.2.6; /// Proxies have standard output and error streams which are expected to /// terminate in a developer-facing console provided by the host. @since(version = 0.2.0) - import wasi:cli/stdout@0.2.6; + import wasiless:cli/stdout@0.2.6; @since(version = 0.2.0) - import wasi:cli/stderr@0.2.6; + import wasiless:cli/stderr@0.2.6; /// 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. @since(version = 0.2.0) - import wasi:cli/stdin@0.2.6; + import wasiless:cli/stdin@0.2.6; /// This is the default handler to use when user code simply wants to make an /// HTTP request (e.g., via `fetch()`). diff --git a/wit/deps/http/types.wit b/wit/deps/http/types.wit index c9f3cc4..e72ee0a 100644 --- a/wit/deps/http/types.wit +++ b/wit/deps/http/types.wit @@ -4,13 +4,13 @@ @since(version = 0.2.0) interface types { @since(version = 0.2.0) - use wasi:clocks/monotonic-clock@0.2.6.{duration}; + use wasiless:clocks/monotonic-clock@0.2.6.{duration}; @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream, output-stream}; + use wasiless:io/streams@0.2.6.{input-stream, output-stream}; @since(version = 0.2.0) - use wasi:io/error@0.2.6.{error as io-error}; + use wasiless:io/error@0.2.6.{error as io-error}; @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; + use wasiless:io/poll@0.2.6.{pollable}; /// This type corresponds to HTTP standard Methods. @since(version = 0.2.0) diff --git a/wit/deps/io/error.wit b/wit/deps/io/error.wit index 784f74a..53cdcec 100644 --- a/wit/deps/io/error.wit +++ b/wit/deps/io/error.wit @@ -1,4 +1,4 @@ -package wasi:io@0.2.6; +package wasiless:io@0.2.6; @since(version = 0.2.0) interface error { diff --git a/wit/deps/io/poll.wit b/wit/deps/io/poll.wit index 7f71183..37f064b 100644 --- a/wit/deps/io/poll.wit +++ b/wit/deps/io/poll.wit @@ -1,4 +1,4 @@ -package wasi:io@0.2.6; +package wasiless:io@0.2.6; /// A poll API intended to let users wait for I/O events on multiple handles /// at once. diff --git a/wit/deps/io/streams.wit b/wit/deps/io/streams.wit index c5da38c..2e4f44f 100644 --- a/wit/deps/io/streams.wit +++ b/wit/deps/io/streams.wit @@ -1,4 +1,4 @@ -package wasi:io@0.2.6; +package wasiless:io@0.2.6; /// WASI I/O is an I/O abstraction API which is currently focused on providing /// stream types. diff --git a/wit/deps/io/world.wit b/wit/deps/io/world.wit index 84c85c0..db72eba 100644 --- a/wit/deps/io/world.wit +++ b/wit/deps/io/world.wit @@ -1,4 +1,4 @@ -package wasi:io@0.2.6; +package wasiless:io@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/random/insecure-seed.wit b/wit/deps/random/insecure-seed.wit index d3dc03a..0a7552b 100644 --- a/wit/deps/random/insecure-seed.wit +++ b/wit/deps/random/insecure-seed.wit @@ -1,4 +1,4 @@ -package wasi:random@0.2.6; +package wasiless:random@0.2.6; /// The insecure-seed interface for seeding hash-map DoS resistance. /// /// It is intended to be portable at least between Unix-family platforms and diff --git a/wit/deps/random/insecure.wit b/wit/deps/random/insecure.wit index d4d0284..3b58ad7 100644 --- a/wit/deps/random/insecure.wit +++ b/wit/deps/random/insecure.wit @@ -1,4 +1,4 @@ -package wasi:random@0.2.6; +package wasiless:random@0.2.6; /// The insecure interface for insecure pseudo-random numbers. /// /// It is intended to be portable at least between Unix-family platforms and diff --git a/wit/deps/random/random.wit b/wit/deps/random/random.wit index a0ff956..b652ee0 100644 --- a/wit/deps/random/random.wit +++ b/wit/deps/random/random.wit @@ -1,4 +1,4 @@ -package wasi:random@0.2.6; +package wasiless:random@0.2.6; /// WASI Random is a random data API. /// /// It is intended to be portable at least between Unix-family platforms and diff --git a/wit/deps/random/world.wit b/wit/deps/random/world.wit index 099f47b..f00234b 100644 --- a/wit/deps/random/world.wit +++ b/wit/deps/random/world.wit @@ -1,4 +1,4 @@ -package wasi:random@0.2.6; +package wasiless:random@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/sockets/ip-name-lookup.wit b/wit/deps/sockets/ip-name-lookup.wit index ee6419e..341130c 100644 --- a/wit/deps/sockets/ip-name-lookup.wit +++ b/wit/deps/sockets/ip-name-lookup.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface ip-name-lookup { @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; + use wasiless:io/poll@0.2.6.{pollable}; @since(version = 0.2.0) use network.{network, error-code, ip-address}; diff --git a/wit/deps/sockets/network.wit b/wit/deps/sockets/network.wit index 6ca98b6..a092487 100644 --- a/wit/deps/sockets/network.wit +++ b/wit/deps/sockets/network.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface network { @unstable(feature = network-error-code) - use wasi:io/error@0.2.6.{error}; + use wasiless:io/error@0.2.6.{error}; /// An opaque resource that represents access to (a subset of) the network. /// This enables context-based security for networking. diff --git a/wit/deps/sockets/tcp.wit b/wit/deps/sockets/tcp.wit index beefd7b..581dd61 100644 --- a/wit/deps/sockets/tcp.wit +++ b/wit/deps/sockets/tcp.wit @@ -1,11 +1,11 @@ @since(version = 0.2.0) interface tcp { @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream, output-stream}; + use wasiless:io/streams@0.2.6.{input-stream, output-stream}; @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; + use wasiless:io/poll@0.2.6.{pollable}; @since(version = 0.2.0) - use wasi:clocks/monotonic-clock@0.2.6.{duration}; + use wasiless:clocks/monotonic-clock@0.2.6.{duration}; @since(version = 0.2.0) use network.{network, error-code, ip-socket-address, ip-address-family}; diff --git a/wit/deps/sockets/udp.wit b/wit/deps/sockets/udp.wit index 9dbe693..2bf057d 100644 --- a/wit/deps/sockets/udp.wit +++ b/wit/deps/sockets/udp.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface udp { @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; + use wasiless:io/poll@0.2.6.{pollable}; @since(version = 0.2.0) use network.{network, error-code, ip-socket-address, ip-address-family}; diff --git a/wit/deps/sockets/world.wit b/wit/deps/sockets/world.wit index e86f02c..0361421 100644 --- a/wit/deps/sockets/world.wit +++ b/wit/deps/sockets/world.wit @@ -1,4 +1,4 @@ -package wasi:sockets@0.2.6; +package wasiless:sockets@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 01906dd..b81a2ea 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -1,32 +1,32 @@ package fastly:wasiless; world wasiless { - export wasi:cli/terminal-input@0.2.6; - export wasi:cli/terminal-output@0.2.6; - export wasi:cli/terminal-stdin@0.2.6; - export wasi:cli/terminal-stdout@0.2.6; - export wasi:cli/terminal-stderr@0.2.6; - export wasi:io/error@0.2.6; - export wasi:io/poll@0.2.6; - export wasi:io/streams@0.2.6; - export wasi:clocks/wall-clock@0.2.6; - export wasi:filesystem/types@0.2.6; - export wasi:filesystem/preopens@0.2.6; - export wasi:sockets/network@0.2.6; - export wasi:sockets/instance-network@0.2.6; - export wasi:sockets/udp@0.2.6; - export wasi:sockets/udp-create-socket@0.2.6; - export wasi:clocks/monotonic-clock@0.2.6; - export wasi:sockets/tcp@0.2.6; - export wasi:sockets/tcp-create-socket@0.2.6; - export wasi:sockets/ip-name-lookup@0.2.6; - export wasi:random/insecure@0.2.6; - export wasi:random/insecure-seed@0.2.6; - export wasi:random/random@0.2.6; - export wasi:cli/environment@0.2.6; - export wasi:cli/exit@0.2.6; - export wasi:cli/stdout@0.2.6; - export wasi:cli/stderr@0.2.6; - export wasi:cli/stdin@0.2.6; + export wasiless:cli/terminal-input@0.2.6; + export wasiless:cli/terminal-output@0.2.6; + export wasiless:cli/terminal-stdin@0.2.6; + export wasiless:cli/terminal-stdout@0.2.6; + export wasiless:cli/terminal-stderr@0.2.6; + export wasiless:io/error@0.2.6; + export wasiless:io/poll@0.2.6; + export wasiless:io/streams@0.2.6; + export wasiless:clocks/wall-clock@0.2.6; + export wasiless:filesystem/types@0.2.6; + export wasiless:filesystem/preopens@0.2.6; + export wasiless:sockets/network@0.2.6; + export wasiless:sockets/instance-network@0.2.6; + export wasiless:sockets/udp@0.2.6; + export wasiless:sockets/udp-create-socket@0.2.6; + export wasiless:clocks/monotonic-clock@0.2.6; + export wasiless:sockets/tcp@0.2.6; + export wasiless:sockets/tcp-create-socket@0.2.6; + export wasiless:sockets/ip-name-lookup@0.2.6; + export wasiless:random/insecure@0.2.6; + export wasiless:random/insecure-seed@0.2.6; + export wasiless:random/random@0.2.6; + export wasiless:cli/environment@0.2.6; + export wasiless:cli/exit@0.2.6; + export wasiless:cli/stdout@0.2.6; + export wasiless:cli/stderr@0.2.6; + export wasiless:cli/stdin@0.2.6; } // Version numbers are fairly arbitrary. \ No newline at end of file From d644f9a5096061db12efa8a9a447d884d2217de3 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Wed, 15 Oct 2025 11:39:13 -0400 Subject: [PATCH 42/50] Revert "Move all `wasi:` packages over to a `wasiless:` namespace." This reverts commit 970bd61c20fa078c5081c91ffdd7344754c65bb2. This gambit didn't work. We were with the same error upon `wac`: ``` error: the encoding of the graph failed validation Caused by: type mismatch for import `wasi:filesystem/types@0.2.0` type mismatch in instance export `input-stream` resource types are not the same (ResourceId { globally_unique_id: 2, contextually_unique_id: 124 } vs. ResourceId { globally_unique_id: 2, contextually_unique_id: 6 }) (at offset 0x291a051) ``` --- src/bindings.rs | 2 +- wit/deps/cli/command.wit | 2 +- wit/deps/cli/imports.wit | 12 +++---- wit/deps/cli/stdio.wit | 6 ++-- wit/deps/clocks/monotonic-clock.wit | 4 +-- wit/deps/clocks/timezone.wit | 2 +- wit/deps/clocks/wall-clock.wit | 2 +- wit/deps/clocks/world.wit | 2 +- wit/deps/filesystem/preopens.wit | 2 +- wit/deps/filesystem/types.wit | 6 ++-- wit/deps/filesystem/world.wit | 2 +- wit/deps/http/proxy.wit | 14 ++++---- wit/deps/http/types.wit | 8 ++--- wit/deps/io/error.wit | 2 +- wit/deps/io/poll.wit | 2 +- wit/deps/io/streams.wit | 2 +- wit/deps/io/world.wit | 2 +- wit/deps/random/insecure-seed.wit | 2 +- wit/deps/random/insecure.wit | 2 +- wit/deps/random/random.wit | 2 +- wit/deps/random/world.wit | 2 +- wit/deps/sockets/ip-name-lookup.wit | 2 +- wit/deps/sockets/network.wit | 2 +- wit/deps/sockets/tcp.wit | 6 ++-- wit/deps/sockets/udp.wit | 2 +- wit/deps/sockets/world.wit | 2 +- wit/wasiless.wit | 54 ++++++++++++++--------------- 27 files changed, 74 insertions(+), 74 deletions(-) diff --git a/src/bindings.rs b/src/bindings.rs index df68422..4655185 100644 --- a/src/bindings.rs +++ b/src/bindings.rs @@ -4,4 +4,4 @@ wit_bindgen::generate!({ generate_all, }); -pub use exports::wasiless as wasi; +pub use exports::wasi; diff --git a/wit/deps/cli/command.wit b/wit/deps/cli/command.wit index 22b8857..6d3cc83 100644 --- a/wit/deps/cli/command.wit +++ b/wit/deps/cli/command.wit @@ -1,4 +1,4 @@ -package wasiless:cli@0.2.6; +package wasi:cli@0.2.6; @since(version = 0.2.0) world command { diff --git a/wit/deps/cli/imports.wit b/wit/deps/cli/imports.wit index 0af101b..d9fd017 100644 --- a/wit/deps/cli/imports.wit +++ b/wit/deps/cli/imports.wit @@ -1,17 +1,17 @@ -package wasiless:cli@0.2.6; +package wasi:cli@0.2.6; @since(version = 0.2.0) world imports { @since(version = 0.2.0) - include wasiless:clocks/imports@0.2.6; + include wasi:clocks/imports@0.2.6; @since(version = 0.2.0) - include wasiless:filesystem/imports@0.2.6; + include wasi:filesystem/imports@0.2.6; @since(version = 0.2.0) - include wasiless:sockets/imports@0.2.6; + include wasi:sockets/imports@0.2.6; @since(version = 0.2.0) - include wasiless:random/imports@0.2.6; + include wasi:random/imports@0.2.6; @since(version = 0.2.0) - include wasiless:io/imports@0.2.6; + include wasi:io/imports@0.2.6; @since(version = 0.2.0) import environment; diff --git a/wit/deps/cli/stdio.wit b/wit/deps/cli/stdio.wit index 000660b..cb8aea2 100644 --- a/wit/deps/cli/stdio.wit +++ b/wit/deps/cli/stdio.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface stdin { @since(version = 0.2.0) - use wasiless:io/streams@0.2.6.{input-stream}; + use wasi:io/streams@0.2.6.{input-stream}; @since(version = 0.2.0) get-stdin: func() -> input-stream; @@ -10,7 +10,7 @@ interface stdin { @since(version = 0.2.0) interface stdout { @since(version = 0.2.0) - use wasiless:io/streams@0.2.6.{output-stream}; + use wasi:io/streams@0.2.6.{output-stream}; @since(version = 0.2.0) get-stdout: func() -> output-stream; @@ -19,7 +19,7 @@ interface stdout { @since(version = 0.2.0) interface stderr { @since(version = 0.2.0) - use wasiless:io/streams@0.2.6.{output-stream}; + use wasi:io/streams@0.2.6.{output-stream}; @since(version = 0.2.0) get-stderr: func() -> output-stream; diff --git a/wit/deps/clocks/monotonic-clock.wit b/wit/deps/clocks/monotonic-clock.wit index cb87049..f3bc839 100644 --- a/wit/deps/clocks/monotonic-clock.wit +++ b/wit/deps/clocks/monotonic-clock.wit @@ -1,4 +1,4 @@ -package wasiless:clocks@0.2.6; +package wasi:clocks@0.2.6; /// WASI Monotonic Clock is a clock API intended to let users measure elapsed /// time. /// @@ -10,7 +10,7 @@ package wasiless:clocks@0.2.6; @since(version = 0.2.0) interface monotonic-clock { @since(version = 0.2.0) - use wasiless:io/poll@0.2.6.{pollable}; + use wasi:io/poll@0.2.6.{pollable}; /// An instant in time, in nanoseconds. An instant is relative to an /// unspecified initial value, and can only be compared to instances from diff --git a/wit/deps/clocks/timezone.wit b/wit/deps/clocks/timezone.wit index f4414e4..ca98ad1 100644 --- a/wit/deps/clocks/timezone.wit +++ b/wit/deps/clocks/timezone.wit @@ -1,4 +1,4 @@ -package wasiless:clocks@0.2.6; +package wasi:clocks@0.2.6; @unstable(feature = clocks-timezone) interface timezone { diff --git a/wit/deps/clocks/wall-clock.wit b/wit/deps/clocks/wall-clock.wit index 1f24147..76636a0 100644 --- a/wit/deps/clocks/wall-clock.wit +++ b/wit/deps/clocks/wall-clock.wit @@ -1,4 +1,4 @@ -package wasiless:clocks@0.2.6; +package wasi:clocks@0.2.6; /// 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. diff --git a/wit/deps/clocks/world.wit b/wit/deps/clocks/world.wit index 7d1f7c1..5c53c51 100644 --- a/wit/deps/clocks/world.wit +++ b/wit/deps/clocks/world.wit @@ -1,4 +1,4 @@ -package wasiless:clocks@0.2.6; +package wasi:clocks@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/filesystem/preopens.wit b/wit/deps/filesystem/preopens.wit index 245d18c..f228479 100644 --- a/wit/deps/filesystem/preopens.wit +++ b/wit/deps/filesystem/preopens.wit @@ -1,4 +1,4 @@ -package wasiless:filesystem@0.2.6; +package wasi:filesystem@0.2.6; @since(version = 0.2.0) interface preopens { diff --git a/wit/deps/filesystem/types.wit b/wit/deps/filesystem/types.wit index 58f9c78..75c1904 100644 --- a/wit/deps/filesystem/types.wit +++ b/wit/deps/filesystem/types.wit @@ -1,4 +1,4 @@ -package wasiless:filesystem@0.2.6; +package wasi:filesystem@0.2.6; /// 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. @@ -26,9 +26,9 @@ package wasiless:filesystem@0.2.6; @since(version = 0.2.0) interface types { @since(version = 0.2.0) - use wasiless:io/streams@0.2.6.{input-stream, output-stream, error}; + use wasi:io/streams@0.2.6.{input-stream, output-stream, error}; @since(version = 0.2.0) - use wasiless:clocks/wall-clock@0.2.6.{datetime}; + use wasi:clocks/wall-clock@0.2.6.{datetime}; /// File size or length of a region within a file. @since(version = 0.2.0) diff --git a/wit/deps/filesystem/world.wit b/wit/deps/filesystem/world.wit index c1fc096..65597f9 100644 --- a/wit/deps/filesystem/world.wit +++ b/wit/deps/filesystem/world.wit @@ -1,4 +1,4 @@ -package wasiless:filesystem@0.2.6; +package wasi:filesystem@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/http/proxy.wit b/wit/deps/http/proxy.wit index fe49f09..5bd9f99 100644 --- a/wit/deps/http/proxy.wit +++ b/wit/deps/http/proxy.wit @@ -1,4 +1,4 @@ -package wasiless:http@0.2.6; +package wasi:http@0.2.6; /// The `wasi:http/imports` world imports all the APIs for HTTP proxies. /// It is intended to be `include`d in other worlds. @@ -6,25 +6,25 @@ package wasiless:http@0.2.6; world imports { /// HTTP proxies have access to time and randomness. @since(version = 0.2.0) - import wasiless:clocks/monotonic-clock@0.2.6; + import wasi:clocks/monotonic-clock@0.2.6; @since(version = 0.2.0) - import wasiless:clocks/wall-clock@0.2.6; + import wasi:clocks/wall-clock@0.2.6; @since(version = 0.2.0) - import wasiless:random/random@0.2.6; + import wasi:random/random@0.2.6; /// Proxies have standard output and error streams which are expected to /// terminate in a developer-facing console provided by the host. @since(version = 0.2.0) - import wasiless:cli/stdout@0.2.6; + import wasi:cli/stdout@0.2.6; @since(version = 0.2.0) - import wasiless:cli/stderr@0.2.6; + import wasi:cli/stderr@0.2.6; /// 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. @since(version = 0.2.0) - import wasiless:cli/stdin@0.2.6; + import wasi:cli/stdin@0.2.6; /// This is the default handler to use when user code simply wants to make an /// HTTP request (e.g., via `fetch()`). diff --git a/wit/deps/http/types.wit b/wit/deps/http/types.wit index e72ee0a..c9f3cc4 100644 --- a/wit/deps/http/types.wit +++ b/wit/deps/http/types.wit @@ -4,13 +4,13 @@ @since(version = 0.2.0) interface types { @since(version = 0.2.0) - use wasiless:clocks/monotonic-clock@0.2.6.{duration}; + use wasi:clocks/monotonic-clock@0.2.6.{duration}; @since(version = 0.2.0) - use wasiless:io/streams@0.2.6.{input-stream, output-stream}; + use wasi:io/streams@0.2.6.{input-stream, output-stream}; @since(version = 0.2.0) - use wasiless:io/error@0.2.6.{error as io-error}; + use wasi:io/error@0.2.6.{error as io-error}; @since(version = 0.2.0) - use wasiless:io/poll@0.2.6.{pollable}; + use wasi:io/poll@0.2.6.{pollable}; /// This type corresponds to HTTP standard Methods. @since(version = 0.2.0) diff --git a/wit/deps/io/error.wit b/wit/deps/io/error.wit index 53cdcec..784f74a 100644 --- a/wit/deps/io/error.wit +++ b/wit/deps/io/error.wit @@ -1,4 +1,4 @@ -package wasiless:io@0.2.6; +package wasi:io@0.2.6; @since(version = 0.2.0) interface error { diff --git a/wit/deps/io/poll.wit b/wit/deps/io/poll.wit index 37f064b..7f71183 100644 --- a/wit/deps/io/poll.wit +++ b/wit/deps/io/poll.wit @@ -1,4 +1,4 @@ -package wasiless:io@0.2.6; +package wasi:io@0.2.6; /// A poll API intended to let users wait for I/O events on multiple handles /// at once. diff --git a/wit/deps/io/streams.wit b/wit/deps/io/streams.wit index 2e4f44f..c5da38c 100644 --- a/wit/deps/io/streams.wit +++ b/wit/deps/io/streams.wit @@ -1,4 +1,4 @@ -package wasiless:io@0.2.6; +package wasi:io@0.2.6; /// WASI I/O is an I/O abstraction API which is currently focused on providing /// stream types. diff --git a/wit/deps/io/world.wit b/wit/deps/io/world.wit index db72eba..84c85c0 100644 --- a/wit/deps/io/world.wit +++ b/wit/deps/io/world.wit @@ -1,4 +1,4 @@ -package wasiless:io@0.2.6; +package wasi:io@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/random/insecure-seed.wit b/wit/deps/random/insecure-seed.wit index 0a7552b..d3dc03a 100644 --- a/wit/deps/random/insecure-seed.wit +++ b/wit/deps/random/insecure-seed.wit @@ -1,4 +1,4 @@ -package wasiless:random@0.2.6; +package wasi:random@0.2.6; /// The insecure-seed interface for seeding hash-map DoS resistance. /// /// It is intended to be portable at least between Unix-family platforms and diff --git a/wit/deps/random/insecure.wit b/wit/deps/random/insecure.wit index 3b58ad7..d4d0284 100644 --- a/wit/deps/random/insecure.wit +++ b/wit/deps/random/insecure.wit @@ -1,4 +1,4 @@ -package wasiless:random@0.2.6; +package wasi:random@0.2.6; /// The insecure interface for insecure pseudo-random numbers. /// /// It is intended to be portable at least between Unix-family platforms and diff --git a/wit/deps/random/random.wit b/wit/deps/random/random.wit index b652ee0..a0ff956 100644 --- a/wit/deps/random/random.wit +++ b/wit/deps/random/random.wit @@ -1,4 +1,4 @@ -package wasiless:random@0.2.6; +package wasi:random@0.2.6; /// WASI Random is a random data API. /// /// It is intended to be portable at least between Unix-family platforms and diff --git a/wit/deps/random/world.wit b/wit/deps/random/world.wit index f00234b..099f47b 100644 --- a/wit/deps/random/world.wit +++ b/wit/deps/random/world.wit @@ -1,4 +1,4 @@ -package wasiless:random@0.2.6; +package wasi:random@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/deps/sockets/ip-name-lookup.wit b/wit/deps/sockets/ip-name-lookup.wit index 341130c..ee6419e 100644 --- a/wit/deps/sockets/ip-name-lookup.wit +++ b/wit/deps/sockets/ip-name-lookup.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface ip-name-lookup { @since(version = 0.2.0) - use wasiless:io/poll@0.2.6.{pollable}; + use wasi:io/poll@0.2.6.{pollable}; @since(version = 0.2.0) use network.{network, error-code, ip-address}; diff --git a/wit/deps/sockets/network.wit b/wit/deps/sockets/network.wit index a092487..6ca98b6 100644 --- a/wit/deps/sockets/network.wit +++ b/wit/deps/sockets/network.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface network { @unstable(feature = network-error-code) - use wasiless:io/error@0.2.6.{error}; + use wasi:io/error@0.2.6.{error}; /// An opaque resource that represents access to (a subset of) the network. /// This enables context-based security for networking. diff --git a/wit/deps/sockets/tcp.wit b/wit/deps/sockets/tcp.wit index 581dd61..beefd7b 100644 --- a/wit/deps/sockets/tcp.wit +++ b/wit/deps/sockets/tcp.wit @@ -1,11 +1,11 @@ @since(version = 0.2.0) interface tcp { @since(version = 0.2.0) - use wasiless:io/streams@0.2.6.{input-stream, output-stream}; + use wasi:io/streams@0.2.6.{input-stream, output-stream}; @since(version = 0.2.0) - use wasiless:io/poll@0.2.6.{pollable}; + use wasi:io/poll@0.2.6.{pollable}; @since(version = 0.2.0) - use wasiless:clocks/monotonic-clock@0.2.6.{duration}; + use wasi:clocks/monotonic-clock@0.2.6.{duration}; @since(version = 0.2.0) use network.{network, error-code, ip-socket-address, ip-address-family}; diff --git a/wit/deps/sockets/udp.wit b/wit/deps/sockets/udp.wit index 2bf057d..9dbe693 100644 --- a/wit/deps/sockets/udp.wit +++ b/wit/deps/sockets/udp.wit @@ -1,7 +1,7 @@ @since(version = 0.2.0) interface udp { @since(version = 0.2.0) - use wasiless:io/poll@0.2.6.{pollable}; + use wasi:io/poll@0.2.6.{pollable}; @since(version = 0.2.0) use network.{network, error-code, ip-socket-address, ip-address-family}; diff --git a/wit/deps/sockets/world.wit b/wit/deps/sockets/world.wit index 0361421..e86f02c 100644 --- a/wit/deps/sockets/world.wit +++ b/wit/deps/sockets/world.wit @@ -1,4 +1,4 @@ -package wasiless:sockets@0.2.6; +package wasi:sockets@0.2.6; @since(version = 0.2.0) world imports { diff --git a/wit/wasiless.wit b/wit/wasiless.wit index b81a2ea..01906dd 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -1,32 +1,32 @@ package fastly:wasiless; world wasiless { - export wasiless:cli/terminal-input@0.2.6; - export wasiless:cli/terminal-output@0.2.6; - export wasiless:cli/terminal-stdin@0.2.6; - export wasiless:cli/terminal-stdout@0.2.6; - export wasiless:cli/terminal-stderr@0.2.6; - export wasiless:io/error@0.2.6; - export wasiless:io/poll@0.2.6; - export wasiless:io/streams@0.2.6; - export wasiless:clocks/wall-clock@0.2.6; - export wasiless:filesystem/types@0.2.6; - export wasiless:filesystem/preopens@0.2.6; - export wasiless:sockets/network@0.2.6; - export wasiless:sockets/instance-network@0.2.6; - export wasiless:sockets/udp@0.2.6; - export wasiless:sockets/udp-create-socket@0.2.6; - export wasiless:clocks/monotonic-clock@0.2.6; - export wasiless:sockets/tcp@0.2.6; - export wasiless:sockets/tcp-create-socket@0.2.6; - export wasiless:sockets/ip-name-lookup@0.2.6; - export wasiless:random/insecure@0.2.6; - export wasiless:random/insecure-seed@0.2.6; - export wasiless:random/random@0.2.6; - export wasiless:cli/environment@0.2.6; - export wasiless:cli/exit@0.2.6; - export wasiless:cli/stdout@0.2.6; - export wasiless:cli/stderr@0.2.6; - export wasiless:cli/stdin@0.2.6; + export wasi:cli/terminal-input@0.2.6; + export wasi:cli/terminal-output@0.2.6; + export wasi:cli/terminal-stdin@0.2.6; + export wasi:cli/terminal-stdout@0.2.6; + export wasi:cli/terminal-stderr@0.2.6; + export wasi:io/error@0.2.6; + export wasi:io/poll@0.2.6; + export wasi:io/streams@0.2.6; + export wasi:clocks/wall-clock@0.2.6; + export wasi:filesystem/types@0.2.6; + export wasi:filesystem/preopens@0.2.6; + export wasi:sockets/network@0.2.6; + export wasi:sockets/instance-network@0.2.6; + export wasi:sockets/udp@0.2.6; + export wasi:sockets/udp-create-socket@0.2.6; + export wasi:clocks/monotonic-clock@0.2.6; + export wasi:sockets/tcp@0.2.6; + export wasi:sockets/tcp-create-socket@0.2.6; + export wasi:sockets/ip-name-lookup@0.2.6; + export wasi:random/insecure@0.2.6; + export wasi:random/insecure-seed@0.2.6; + export wasi:random/random@0.2.6; + export wasi:cli/environment@0.2.6; + export wasi:cli/exit@0.2.6; + export wasi:cli/stdout@0.2.6; + export wasi:cli/stderr@0.2.6; + export wasi:cli/stdin@0.2.6; } // Version numbers are fairly arbitrary. \ No newline at end of file From 7cb83670d72618eca4ea3204bea2400377824dbd Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Wed, 15 Oct 2025 16:44:52 -0400 Subject: [PATCH 43/50] Mate up Yan's work on getting composition to work with my fake routine implementations. * Export (in the `wasiless` world) only things used by Python but not provided by the Fastly Compute runtime. * Remove implementations of things we don't need for Python (or that are covered by Compute). * Flatten out contents of `wit` dir. These WITs are extracted from the Python+app component and are a little non-canonical, doing things like importing 0.2.6 interfaces into `filesystem/types@0.2.0`. Let's stick with this for now, since it works. --- build.sh | 12 + compose.wac | 29 ++ src/bindings.rs | 2 - src/cli.rs | 53 +- src/clocks.rs | 38 -- src/filesystem.rs | 6 +- src/io.rs | 124 ----- src/lib.rs | 2 - src/random.rs | 16 +- src/sockets.rs | 16 +- wit/deps/cli.wit | 28 + wit/deps/cli/command.wit | 10 - wit/deps/cli/environment.wit | 22 - wit/deps/cli/exit.wit | 17 - wit/deps/cli/imports.wit | 36 -- wit/deps/cli/run.wit | 6 - wit/deps/cli/stdio.wit | 26 - wit/deps/cli/terminal.wit | 62 --- wit/deps/clocks.wit | 29 ++ wit/deps/clocks/monotonic-clock.wit | 50 -- wit/deps/clocks/timezone.wit | 55 -- wit/deps/clocks/wall-clock.wit | 46 -- wit/deps/clocks/world.wit | 11 - wit/deps/filesystem.wit | 159 ++++++ wit/deps/filesystem/preopens.wit | 11 - wit/deps/filesystem/types.wit | 676 ------------------------ wit/deps/filesystem/world.wit | 9 - wit/deps/http/handler.wit | 49 -- wit/deps/http/proxy.wit | 50 -- wit/deps/http/types.wit | 688 ------------------------- wit/deps/io.wit | 48 ++ wit/deps/io/error.wit | 34 -- wit/deps/io/poll.wit | 47 -- wit/deps/io/streams.wit | 290 ----------- wit/deps/io/world.wit | 10 - wit/deps/random.wit | 12 + wit/deps/random/insecure-seed.wit | 27 - wit/deps/random/insecure.wit | 25 - wit/deps/random/random.wit | 29 -- wit/deps/random/world.wit | 13 - wit/deps/sockets.wit | 183 +++++++ wit/deps/sockets/instance-network.wit | 11 - wit/deps/sockets/ip-name-lookup.wit | 56 -- wit/deps/sockets/network.wit | 169 ------ wit/deps/sockets/tcp-create-socket.wit | 30 -- wit/deps/sockets/tcp.wit | 387 -------------- wit/deps/sockets/udp-create-socket.wit | 30 -- wit/deps/sockets/udp.wit | 288 ----------- wit/deps/sockets/world.wit | 19 - wit/wasiless.wit | 46 +- 50 files changed, 536 insertions(+), 3556 deletions(-) create mode 100755 build.sh create mode 100644 compose.wac delete mode 100644 src/clocks.rs delete mode 100644 src/io.rs create mode 100644 wit/deps/cli.wit delete mode 100644 wit/deps/cli/command.wit delete mode 100644 wit/deps/cli/environment.wit delete mode 100644 wit/deps/cli/exit.wit delete mode 100644 wit/deps/cli/imports.wit delete mode 100644 wit/deps/cli/run.wit delete mode 100644 wit/deps/cli/stdio.wit delete mode 100644 wit/deps/cli/terminal.wit create mode 100644 wit/deps/clocks.wit delete mode 100644 wit/deps/clocks/monotonic-clock.wit delete mode 100644 wit/deps/clocks/timezone.wit delete mode 100644 wit/deps/clocks/wall-clock.wit delete mode 100644 wit/deps/clocks/world.wit create mode 100644 wit/deps/filesystem.wit delete mode 100644 wit/deps/filesystem/preopens.wit delete mode 100644 wit/deps/filesystem/types.wit delete mode 100644 wit/deps/filesystem/world.wit delete mode 100644 wit/deps/http/handler.wit delete mode 100644 wit/deps/http/proxy.wit delete mode 100644 wit/deps/http/types.wit create mode 100644 wit/deps/io.wit delete mode 100644 wit/deps/io/error.wit delete mode 100644 wit/deps/io/poll.wit delete mode 100644 wit/deps/io/streams.wit delete mode 100644 wit/deps/io/world.wit create mode 100644 wit/deps/random.wit delete mode 100644 wit/deps/random/insecure-seed.wit delete mode 100644 wit/deps/random/insecure.wit delete mode 100644 wit/deps/random/random.wit delete mode 100644 wit/deps/random/world.wit create mode 100644 wit/deps/sockets.wit delete mode 100644 wit/deps/sockets/instance-network.wit delete mode 100644 wit/deps/sockets/ip-name-lookup.wit delete mode 100644 wit/deps/sockets/network.wit delete mode 100644 wit/deps/sockets/tcp-create-socket.wit delete mode 100644 wit/deps/sockets/tcp.wit delete mode 100644 wit/deps/sockets/udp-create-socket.wit delete mode 100644 wit/deps/sockets/udp.wit delete mode 100644 wit/deps/sockets/world.wit diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..bf59e11 --- /dev/null +++ b/build.sh @@ -0,0 +1,12 @@ +set -x + +# generate wit directory +# wasm-tools component wit $1 --out-dir wit + +#wit-bindgen rust --stubs wit --generate-all --world wasiless +#cp wasiless.rs src/lib.rs +cargo build --target=wasm32-unknown-unknown +cp target/wasm32-unknown-unknown/debug/wasiless.wasm . +wasm-tools component new wasiless.wasm -o wasiless.wasm +wac compose --dep fastly:wasiless=wasiless.wasm --dep app:component=$1 -o composed.wasm compose.wac + diff --git a/compose.wac b/compose.wac new file mode 100644 index 0000000..23ca911 --- /dev/null +++ b/compose.wac @@ -0,0 +1,29 @@ +package fastly:python-wasiless; + +// Instantiate wasiless, minimal or crashing implementations of irrelevant WASI interfaces: +let wasiless = new fastly:wasiless { ... }; + +// Instantiate the Python component. Pass in the 0.2.6 routines from wasiless, +// even when Python wants a different version: +/*let app = new app:component { + "wasi:cli/terminal-input@0.2.0": wasiless["wasi:cli/terminal-input@0.2.6"], + "wasi:cli/terminal-output@0.2.0": wasiless["wasi:cli/terminal-output@0.2.6"], + "wasi:cli/terminal-stdin@0.2.0": wasiless["wasi:cli/terminal-stdin@0.2.6"], + "wasi:cli/terminal-stdout@0.2.0": wasiless["wasi:cli/terminal-stdout@0.2.6"], + "wasi:cli/terminal-stderr@0.2.0": wasiless["wasi:cli/terminal-stderr@0.2.6"], + "wasi:filesystem/types@0.2.0": wasiless["wasi:filesystem/types@0.2.6"], + "wasi:filesystem/preopens@0.2.0": wasiless["wasi:filesystem/preopens@0.2.6"], + "wasi:sockets/network@0.2.0": wasiless["wasi:sockets/network@0.2.6"], + "wasi:sockets/instance-network@0.2.0": wasiless["wasi:sockets/instance-network@0.2.6"], + "wasi:sockets/udp@0.2.0": wasiless["wasi:sockets/udp@0.2.6"], + "wasi:sockets/udp-create-socket@0.2.0": wasiless["wasi:sockets/udp-create-socket@0.2.6"], + "wasi:sockets/tcp@0.2.0": wasiless["wasi:sockets/tcp@0.2.6"], + "wasi:sockets/tcp-create-socket@0.2.0": wasiless["wasi:sockets/tcp-create-socket@0.2.6"], + "wasi:sockets/ip-name-lookup@0.2.0": wasiless["wasi:sockets/ip-name-lookup@0.2.6"], + "wasi:random/insecure@0.2.0": wasiless["wasi:random/insecure@0.2.6"], + "wasi:random/insecure-seed@0.2.0": wasiless["wasi:random/insecure-seed@0.2.6"], + ... +};*/ +let app = new app:component { ...wasiless, ... }; +export app...; + diff --git a/src/bindings.rs b/src/bindings.rs index 4655185..5f79300 100644 --- a/src/bindings.rs +++ b/src/bindings.rs @@ -3,5 +3,3 @@ wit_bindgen::generate!({ path: "wit", generate_all, }); - -pub use exports::wasi; diff --git a/src/cli.rs b/src/cli.rs index 80ce2b6..d1e8919 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,9 +1,11 @@ use crate::Wasiless; -use crate::bindings::wasi::cli::terminal_input::{self, GuestTerminalInput, TerminalInput}; -use crate::bindings::wasi::cli::terminal_output::{self, GuestTerminalOutput, TerminalOutput}; -use crate::bindings::wasi::cli::{ - environment, exit, stderr, stdin, stdout, terminal_stderr, terminal_stdin, terminal_stdout, +use crate::bindings::exports::wasi::cli::terminal_input::{ + self, GuestTerminalInput, TerminalInput, }; +use crate::bindings::exports::wasi::cli::terminal_output::{ + self, GuestTerminalOutput, TerminalOutput, +}; +use crate::bindings::exports::wasi::cli::{terminal_stderr, terminal_stdin, terminal_stdout}; impl GuestTerminalInput for TerminalInput {} @@ -34,46 +36,3 @@ impl terminal_stderr::Guest for Wasiless { None } } - -impl environment::Guest for Wasiless { - #[allow(unused_variables)] - fn get_environment() -> Vec<(String, String)> { - Vec::new() - } - #[allow(unused_variables)] - fn get_arguments() -> Vec { - Vec::new() - } - #[allow(unused_variables)] - fn initial_cwd() -> Option { - unreachable!() - } -} - -impl exit::Guest for Wasiless { - #[allow(unused_variables)] - fn exit(status: Result<(), ()>) -> () { - unreachable!() - } -} - -impl stdout::Guest for Wasiless { - #[allow(unused_variables)] - fn get_stdout() -> stdout::OutputStream { - unreachable!() - } -} - -impl stderr::Guest for Wasiless { - #[allow(unused_variables)] - fn get_stderr() -> stderr::OutputStream { - unreachable!() - } -} - -impl stdin::Guest for Wasiless { - #[allow(unused_variables)] - fn get_stdin() -> stdin::InputStream { - unreachable!() - } -} diff --git a/src/clocks.rs b/src/clocks.rs deleted file mode 100644 index 44f0be4..0000000 --- a/src/clocks.rs +++ /dev/null @@ -1,38 +0,0 @@ -use crate::Wasiless; -use crate::bindings::wasi::clocks::monotonic_clock::{self, Duration, Instant}; -use crate::bindings::wasi::clocks::wall_clock::{self, Datetime}; -use crate::bindings::wasi::io::poll::Pollable; - -impl wall_clock::Guest for Wasiless { - fn now() -> Datetime { - Datetime { - seconds: 0, - nanoseconds: 0, - } - } - - fn resolution() -> Datetime { - Datetime { - seconds: 0, - nanoseconds: 0, - } - } -} - -impl monotonic_clock::Guest for Wasiless { - fn now() -> Instant { - 0 - } - - fn resolution() -> Duration { - 1 // A little less absurd than 0 - } - - fn subscribe_instant(_when: Instant) -> Pollable { - unreachable!() - } - - fn subscribe_duration(_when: Duration) -> Pollable { - unreachable!() - } -} diff --git a/src/filesystem.rs b/src/filesystem.rs index d19985a..1fb0d87 100644 --- a/src/filesystem.rs +++ b/src/filesystem.rs @@ -1,9 +1,9 @@ use crate::Wasiless; -use crate::bindings::wasi::filesystem::{ +use crate::bindings::exports::wasi::filesystem::{ self, types::{ Advice, Descriptor, DescriptorBorrow, DescriptorFlags, DescriptorStat, DescriptorType, - DirectoryEntry, DirectoryEntryStream, ErrorBorrow, ErrorCode, Filesize, GuestDescriptor, + DirectoryEntry, DirectoryEntryStream, Error, ErrorCode, Filesize, GuestDescriptor, GuestDirectoryEntryStream, MetadataHashValue, NewTimestamp, OpenFlags, PathFlags, }, }; @@ -164,7 +164,7 @@ impl GuestDirectoryEntryStream for DirectoryEntryStream { impl filesystem::types::Guest for Wasiless { type Descriptor = Descriptor; type DirectoryEntryStream = DirectoryEntryStream; - fn filesystem_error_code(_err: ErrorBorrow) -> Option { + fn filesystem_error_code(_err: &Error) -> Option { None } } diff --git a/src/io.rs b/src/io.rs deleted file mode 100644 index bd4beaa..0000000 --- a/src/io.rs +++ /dev/null @@ -1,124 +0,0 @@ -use crate::Wasiless; -use crate::bindings::wasi::io::error::{self, Error, GuestError}; -use crate::bindings::wasi::io::poll::Pollable; -use crate::bindings::wasi::io::poll::{self, GuestPollable, PollableBorrow}; -use crate::bindings::wasi::io::streams::{ - self, GuestInputStream, GuestOutputStream, InputStream, InputStreamBorrow, OutputStream, - StreamError, -}; - -impl GuestError for Error { - fn to_debug_string(&self) -> String { - "".to_owned() - } -} - -impl error::Guest for Wasiless { - type Error = Error; -} - -impl GuestPollable for Pollable { - /// Returns true for consistency with the fact that our block() doesn't block. - fn ready(&self) -> bool { - true - } - - /// Never blocks, lest we block forever. - fn block(&self) -> () { - () - } -} - -impl poll::Guest for Wasiless { - type Pollable = Pollable; - - /// This is a real implementation, in an attempt to present a consistent - /// picture of our fake reality to callers and thus avoid provoking crashes - /// unnecessarily. - fn poll(pollables: Vec) -> Vec { - if pollables.len() > (u32::MAX as usize) { - panic!("list of pollables too long to be indexed with a u32") - } - pollables - .iter() - .enumerate() - .filter_map(|(i, p)| { - if p.get::().ready() { - Some(i as u32) - } else { - None - } - }) - .collect() - } -} - -impl GuestInputStream for InputStream { - fn read(&self, _len: u64) -> Result, StreamError> { - Ok(Vec::new()) - } - - fn blocking_read(&self, _len: u64) -> Result, StreamError> { - Ok(Vec::new()) - } - - fn skip(&self, _len: u64) -> Result { - Ok(0) - } - - fn blocking_skip(&self, _len: u64) -> Result { - Ok(0) - } - - fn subscribe(&self) -> Pollable { - unreachable!() - } -} - -/// Writes appear to go through without error but also report back that they wrote 0 bytes. -impl GuestOutputStream for OutputStream { - fn check_write(&self) -> Result { - Ok(4096) // TODO: Make this interlock with subscribe(). - } - - fn write(&self, _contents: Vec) -> Result<(), StreamError> { - Ok(()) - } - - fn blocking_write_and_flush(&self, _contents: Vec) -> Result<(), StreamError> { - Ok(()) - } - - fn flush(&self) -> Result<(), StreamError> { - Ok(()) - } - - fn blocking_flush(&self) -> Result<(), StreamError> { - Ok(()) - } - - fn subscribe(&self) -> Pollable { - unreachable!() - } - - fn write_zeroes(&self, _len: u64) -> Result<(), StreamError> { - Ok(()) - } - - fn blocking_write_zeroes_and_flush(&self, _len: u64) -> Result<(), StreamError> { - Ok(()) - } - - fn splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { - Ok(0) - } - - fn blocking_splice(&self, _src: InputStreamBorrow, _len: u64) -> Result { - Ok(0) - } -} - -impl streams::Guest for Wasiless { - type InputStream = InputStream; - type OutputStream = OutputStream; -} diff --git a/src/lib.rs b/src/lib.rs index b458398..ba1b19d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,9 +8,7 @@ mod bindings; mod cli; -mod clocks; mod filesystem; -mod io; mod random; mod sockets; diff --git a/src/random.rs b/src/random.rs index dcaef59..678b537 100644 --- a/src/random.rs +++ b/src/random.rs @@ -1,5 +1,5 @@ use crate::Wasiless; -use crate::bindings::wasi::random; +use crate::bindings::exports::wasi::random; impl random::insecure::Guest for Wasiless { #[allow(unused_variables)] @@ -18,17 +18,3 @@ impl random::insecure_seed::Guest for Wasiless { unreachable!() } } - -impl random::random::Guest for Wasiless { - #[allow(unused_variables)] - fn get_random_bytes(len: u64) -> Vec { - // TODO: This isn't random at all, let alone cryptographically so. As - // such, it violates the WASI spec, which stipulates this must be left - // out if it can't be random. - Vec::with_capacity(len as usize) - } - #[allow(unused_variables)] - fn get_random_u64() -> u64 { - unreachable!() - } -} diff --git a/src/sockets.rs b/src/sockets.rs index 2ace13d..802b66a 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -1,17 +1,17 @@ use crate::Wasiless; -use crate::bindings::wasi::io::poll::Pollable; -use crate::bindings::wasi::sockets::instance_network; -use crate::bindings::wasi::sockets::ip_name_lookup; -use crate::bindings::wasi::sockets::network::{ +use crate::bindings::exports::wasi::sockets::instance_network; +use crate::bindings::exports::wasi::sockets::ip_name_lookup; +use crate::bindings::exports::wasi::sockets::network::{ self, ErrorCode, GuestNetwork, IpAddressFamily, IpSocketAddress, Network, NetworkBorrow, }; -use crate::bindings::wasi::sockets::tcp::{self, GuestTcpSocket, TcpSocket}; -use crate::bindings::wasi::sockets::tcp_create_socket; -use crate::bindings::wasi::sockets::udp::{ +use crate::bindings::exports::wasi::sockets::tcp::{self, GuestTcpSocket, TcpSocket}; +use crate::bindings::exports::wasi::sockets::tcp_create_socket; +use crate::bindings::exports::wasi::sockets::udp::{ self, GuestIncomingDatagramStream, GuestOutgoingDatagramStream, GuestUdpSocket, IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream, UdpSocket, }; -use crate::bindings::wasi::sockets::udp_create_socket; +use crate::bindings::exports::wasi::sockets::udp_create_socket; +use crate::bindings::wasi::io::poll::Pollable; impl GuestNetwork for Network {} diff --git a/wit/deps/cli.wit b/wit/deps/cli.wit new file mode 100644 index 0000000..5f1811b --- /dev/null +++ b/wit/deps/cli.wit @@ -0,0 +1,28 @@ +package wasi:cli@0.2.0; + +interface terminal-input { + resource terminal-input; +} + +interface terminal-output { + resource terminal-output; +} + +interface terminal-stdin { + use terminal-input.{terminal-input}; + + get-terminal-stdin: func() -> option; +} + +interface terminal-stdout { + use terminal-output.{terminal-output}; + + get-terminal-stdout: func() -> option; +} + +interface terminal-stderr { + use terminal-output.{terminal-output}; + + get-terminal-stderr: func() -> option; +} + diff --git a/wit/deps/cli/command.wit b/wit/deps/cli/command.wit deleted file mode 100644 index 6d3cc83..0000000 --- a/wit/deps/cli/command.wit +++ /dev/null @@ -1,10 +0,0 @@ -package wasi:cli@0.2.6; - -@since(version = 0.2.0) -world command { - @since(version = 0.2.0) - include imports; - - @since(version = 0.2.0) - export run; -} diff --git a/wit/deps/cli/environment.wit b/wit/deps/cli/environment.wit deleted file mode 100644 index 2f449bd..0000000 --- a/wit/deps/cli/environment.wit +++ /dev/null @@ -1,22 +0,0 @@ -@since(version = 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. - @since(version = 0.2.0) - get-environment: func() -> list>; - - /// Get the POSIX-style arguments to the program. - @since(version = 0.2.0) - get-arguments: func() -> list; - - /// Return a path that programs should use as their initial current working - /// directory, interpreting `.` as shorthand for this. - @since(version = 0.2.0) - initial-cwd: func() -> option; -} diff --git a/wit/deps/cli/exit.wit b/wit/deps/cli/exit.wit deleted file mode 100644 index 427935c..0000000 --- a/wit/deps/cli/exit.wit +++ /dev/null @@ -1,17 +0,0 @@ -@since(version = 0.2.0) -interface exit { - /// Exit the current instance and any linked instances. - @since(version = 0.2.0) - exit: func(status: result); - - /// Exit the current instance and any linked instances, reporting the - /// specified status code to the host. - /// - /// The meaning of the code depends on the context, with 0 usually meaning - /// "success", and other values indicating various types of failure. - /// - /// This function does not return; the effect is analogous to a trap, but - /// without the connotation that something bad has happened. - @unstable(feature = cli-exit-with-code) - exit-with-code: func(status-code: u8); -} diff --git a/wit/deps/cli/imports.wit b/wit/deps/cli/imports.wit deleted file mode 100644 index d9fd017..0000000 --- a/wit/deps/cli/imports.wit +++ /dev/null @@ -1,36 +0,0 @@ -package wasi:cli@0.2.6; - -@since(version = 0.2.0) -world imports { - @since(version = 0.2.0) - include wasi:clocks/imports@0.2.6; - @since(version = 0.2.0) - include wasi:filesystem/imports@0.2.6; - @since(version = 0.2.0) - include wasi:sockets/imports@0.2.6; - @since(version = 0.2.0) - include wasi:random/imports@0.2.6; - @since(version = 0.2.0) - include wasi:io/imports@0.2.6; - - @since(version = 0.2.0) - import environment; - @since(version = 0.2.0) - import exit; - @since(version = 0.2.0) - import stdin; - @since(version = 0.2.0) - import stdout; - @since(version = 0.2.0) - import stderr; - @since(version = 0.2.0) - import terminal-input; - @since(version = 0.2.0) - import terminal-output; - @since(version = 0.2.0) - import terminal-stdin; - @since(version = 0.2.0) - import terminal-stdout; - @since(version = 0.2.0) - import terminal-stderr; -} diff --git a/wit/deps/cli/run.wit b/wit/deps/cli/run.wit deleted file mode 100644 index 655346e..0000000 --- a/wit/deps/cli/run.wit +++ /dev/null @@ -1,6 +0,0 @@ -@since(version = 0.2.0) -interface run { - /// Run the program. - @since(version = 0.2.0) - run: func() -> result; -} diff --git a/wit/deps/cli/stdio.wit b/wit/deps/cli/stdio.wit deleted file mode 100644 index cb8aea2..0000000 --- a/wit/deps/cli/stdio.wit +++ /dev/null @@ -1,26 +0,0 @@ -@since(version = 0.2.0) -interface stdin { - @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream}; - - @since(version = 0.2.0) - get-stdin: func() -> input-stream; -} - -@since(version = 0.2.0) -interface stdout { - @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{output-stream}; - - @since(version = 0.2.0) - get-stdout: func() -> output-stream; -} - -@since(version = 0.2.0) -interface stderr { - @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{output-stream}; - - @since(version = 0.2.0) - get-stderr: func() -> output-stream; -} diff --git a/wit/deps/cli/terminal.wit b/wit/deps/cli/terminal.wit deleted file mode 100644 index d305498..0000000 --- a/wit/deps/cli/terminal.wit +++ /dev/null @@ -1,62 +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. -@since(version = 0.2.0) -interface terminal-input { - /// The input side of a terminal. - @since(version = 0.2.0) - 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. -@since(version = 0.2.0) -interface terminal-output { - /// The output side of a terminal. - @since(version = 0.2.0) - resource terminal-output; -} - -/// An interface providing an optional `terminal-input` for stdin as a -/// link-time authority. -@since(version = 0.2.0) -interface terminal-stdin { - @since(version = 0.2.0) - use terminal-input.{terminal-input}; - - /// If stdin is connected to a terminal, return a `terminal-input` handle - /// allowing further interaction with it. - @since(version = 0.2.0) - get-terminal-stdin: func() -> option; -} - -/// An interface providing an optional `terminal-output` for stdout as a -/// link-time authority. -@since(version = 0.2.0) -interface terminal-stdout { - @since(version = 0.2.0) - use terminal-output.{terminal-output}; - - /// If stdout is connected to a terminal, return a `terminal-output` handle - /// allowing further interaction with it. - @since(version = 0.2.0) - get-terminal-stdout: func() -> option; -} - -/// An interface providing an optional `terminal-output` for stderr as a -/// link-time authority. -@since(version = 0.2.0) -interface terminal-stderr { - @since(version = 0.2.0) - use terminal-output.{terminal-output}; - - /// If stderr is connected to a terminal, return a `terminal-output` handle - /// allowing further interaction with it. - @since(version = 0.2.0) - get-terminal-stderr: func() -> option; -} diff --git a/wit/deps/clocks.wit b/wit/deps/clocks.wit new file mode 100644 index 0000000..7fb41eb --- /dev/null +++ b/wit/deps/clocks.wit @@ -0,0 +1,29 @@ +package wasi:clocks@0.2.6; + +interface wall-clock { + record datetime { + seconds: u64, + nanoseconds: u32, + } + + now: func() -> datetime; + + resolution: func() -> datetime; +} + +interface monotonic-clock { + use wasi:io/poll@0.2.6.{pollable}; + + type instant = u64; + + type duration = u64; + + now: func() -> instant; + + resolution: func() -> duration; + + subscribe-instant: func(when: instant) -> pollable; + + subscribe-duration: func(when: duration) -> pollable; +} + diff --git a/wit/deps/clocks/monotonic-clock.wit b/wit/deps/clocks/monotonic-clock.wit deleted file mode 100644 index f3bc839..0000000 --- a/wit/deps/clocks/monotonic-clock.wit +++ /dev/null @@ -1,50 +0,0 @@ -package wasi:clocks@0.2.6; -/// 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. -@since(version = 0.2.0) -interface monotonic-clock { - @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{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. - @since(version = 0.2.0) - type instant = u64; - - /// A duration of time, in nanoseconds. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - now: func() -> instant; - - /// Query the resolution of the clock. Returns the duration of time - /// corresponding to a clock tick. - @since(version = 0.2.0) - resolution: func() -> duration; - - /// Create a `pollable` which will resolve once the specified instant - /// has occurred. - @since(version = 0.2.0) - subscribe-instant: func( - when: instant, - ) -> pollable; - - /// Create a `pollable` that will resolve after the specified duration has - /// elapsed from the time this function is invoked. - @since(version = 0.2.0) - subscribe-duration: func( - when: duration, - ) -> pollable; -} diff --git a/wit/deps/clocks/timezone.wit b/wit/deps/clocks/timezone.wit deleted file mode 100644 index ca98ad1..0000000 --- a/wit/deps/clocks/timezone.wit +++ /dev/null @@ -1,55 +0,0 @@ -package wasi:clocks@0.2.6; - -@unstable(feature = clocks-timezone) -interface timezone { - @unstable(feature = clocks-timezone) - use wall-clock.{datetime}; - - /// Return information needed to display the given `datetime`. This includes - /// the UTC offset, the time zone name, and a flag indicating whether - /// daylight saving time is active. - /// - /// If the timezone cannot be determined for the given `datetime`, return a - /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight - /// saving time. - @unstable(feature = clocks-timezone) - display: func(when: datetime) -> timezone-display; - - /// The same as `display`, but only return the UTC offset. - @unstable(feature = clocks-timezone) - utc-offset: func(when: datetime) -> s32; - - /// Information useful for displaying the timezone of a specific `datetime`. - /// - /// This information may vary within a single `timezone` to reflect daylight - /// saving time adjustments. - @unstable(feature = clocks-timezone) - record timezone-display { - /// The number of seconds difference between UTC time and the local - /// time of the timezone. - /// - /// The returned value will always be less than 86400 which is the - /// number of seconds in a day (24*60*60). - /// - /// In implementations that do not expose an actual time zone, this - /// should return 0. - utc-offset: s32, - - /// The abbreviated name of the timezone to display to a user. The name - /// `UTC` indicates Coordinated Universal Time. Otherwise, this should - /// reference local standards for the name of the time zone. - /// - /// In implementations that do not expose an actual time zone, this - /// should be the string `UTC`. - /// - /// In time zones that do not have an applicable name, a formatted - /// representation of the UTC offset may be returned, such as `-04:00`. - name: string, - - /// Whether daylight saving time is active. - /// - /// In implementations that do not expose an actual time zone, this - /// should return false. - in-daylight-saving-time: bool, - } -} diff --git a/wit/deps/clocks/wall-clock.wit b/wit/deps/clocks/wall-clock.wit deleted file mode 100644 index 76636a0..0000000 --- a/wit/deps/clocks/wall-clock.wit +++ /dev/null @@ -1,46 +0,0 @@ -package wasi:clocks@0.2.6; -/// 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. -@since(version = 0.2.0) -interface wall-clock { - /// A time and date in seconds plus nanoseconds. - @since(version = 0.2.0) - 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 - @since(version = 0.2.0) - now: func() -> datetime; - - /// Query the resolution of the clock. - /// - /// The nanoseconds field of the output is always less than 1000000000. - @since(version = 0.2.0) - resolution: func() -> datetime; -} diff --git a/wit/deps/clocks/world.wit b/wit/deps/clocks/world.wit deleted file mode 100644 index 5c53c51..0000000 --- a/wit/deps/clocks/world.wit +++ /dev/null @@ -1,11 +0,0 @@ -package wasi:clocks@0.2.6; - -@since(version = 0.2.0) -world imports { - @since(version = 0.2.0) - import monotonic-clock; - @since(version = 0.2.0) - import wall-clock; - @unstable(feature = clocks-timezone) - import timezone; -} diff --git a/wit/deps/filesystem.wit b/wit/deps/filesystem.wit new file mode 100644 index 0000000..9a2f885 --- /dev/null +++ b/wit/deps/filesystem.wit @@ -0,0 +1,159 @@ +package wasi:filesystem@0.2.0; + +interface types { + use wasi:io/streams@0.2.6.{input-stream, output-stream}; + use wasi:clocks/wall-clock@0.2.6.{datetime}; + use wasi:io/streams@0.2.6.{error}; + + resource descriptor { + read-via-stream: func(offset: filesize) -> result; + write-via-stream: func(offset: filesize) -> result; + append-via-stream: func() -> result; + advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; + sync-data: func() -> result<_, error-code>; + get-flags: func() -> result; + get-type: func() -> result; + set-size: func(size: filesize) -> result<_, error-code>; + set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + read: func(length: filesize, offset: filesize) -> result, bool>, error-code>; + write: func(buffer: list, offset: filesize) -> result; + read-directory: func() -> result; + sync: func() -> result<_, error-code>; + create-directory-at: func(path: string) -> result<_, error-code>; + stat: func() -> result; + stat-at: func(path-flags: path-flags, path: string) -> result; + set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; + readlink-at: func(path: string) -> result; + remove-directory-at: func(path: string) -> result<_, error-code>; + rename-at: func(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + symlink-at: func(old-path: string, new-path: string) -> result<_, error-code>; + unlink-file-at: func(path: string) -> result<_, error-code>; + is-same-object: func(other: borrow) -> bool; + metadata-hash: func() -> result; + metadata-hash-at: func(path-flags: path-flags, path: string) -> result; + } + + type filesize = u64; + + 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, + } + + enum advice { + normal, + sequential, + random, + will-need, + dont-need, + no-reuse, + } + + flags descriptor-flags { + read, + write, + file-integrity-sync, + data-integrity-sync, + requested-write-sync, + mutate-directory, + } + + enum descriptor-type { + unknown, + block-device, + character-device, + directory, + fifo, + symbolic-link, + regular-file, + socket, + } + + variant new-timestamp { + no-change, + now, + timestamp(datetime), + } + + resource directory-entry-stream { + read-directory-entry: func() -> result, error-code>; + } + + type link-count = u64; + + record descriptor-stat { + %type: descriptor-type, + link-count: link-count, + size: filesize, + data-access-timestamp: option, + data-modification-timestamp: option, + status-change-timestamp: option, + } + + flags path-flags { + symlink-follow, + } + + flags open-flags { + create, + directory, + exclusive, + truncate, + } + + record metadata-hash-value { + lower: u64, + upper: u64, + } + + record directory-entry { + %type: descriptor-type, + name: string, + } + + filesystem-error-code: func(err: borrow) -> option; +} + +interface preopens { + use types.{descriptor}; + + get-directories: func() -> list>; +} + diff --git a/wit/deps/filesystem/preopens.wit b/wit/deps/filesystem/preopens.wit deleted file mode 100644 index f228479..0000000 --- a/wit/deps/filesystem/preopens.wit +++ /dev/null @@ -1,11 +0,0 @@ -package wasi:filesystem@0.2.6; - -@since(version = 0.2.0) -interface preopens { - @since(version = 0.2.0) - use types.{descriptor}; - - /// Return the set of preopened directories, and their paths. - @since(version = 0.2.0) - get-directories: func() -> list>; -} diff --git a/wit/deps/filesystem/types.wit b/wit/deps/filesystem/types.wit deleted file mode 100644 index 75c1904..0000000 --- a/wit/deps/filesystem/types.wit +++ /dev/null @@ -1,676 +0,0 @@ -package wasi:filesystem@0.2.6; -/// 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 -@since(version = 0.2.0) -interface types { - @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream, output-stream, error}; - @since(version = 0.2.0) - use wasi:clocks/wall-clock@0.2.6.{datetime}; - - /// File size or length of a region within a file. - @since(version = 0.2.0) - type filesize = u64; - - /// The type of a filesystem object referenced by a descriptor. - /// - /// Note: This was called `filetype` in earlier versions of WASI. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 integrity - /// 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - type link-count = u64; - - /// When setting a timestamp, this gives the value to set it to. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 POSIX. - @since(version = 0.2.0) - append-via-stream: func() -> result; - - /// Provide file advisory information on a descriptor. - /// - /// This is similar to `posix_fadvise` in POSIX. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - sync: func() -> result<_, error-code>; - - /// Create a directory. - /// - /// Note: This is similar to `mkdirat` in POSIX. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - /// - /// Fails with `error-code::no-entry` if the old path does not exist, - /// with `error-code::exist` if the new path already exists, and - /// `error-code::not-permitted` if the old path is not a file. - /// - /// Note: This is similar to `linkat` in POSIX. - @since(version = 0.2.0) - 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. - /// - /// 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 encouraged 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. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - resource directory-entry-stream { - /// Read a single directory entry from a `directory-entry-stream`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - filesystem-error-code: func(err: borrow) -> option; -} diff --git a/wit/deps/filesystem/world.wit b/wit/deps/filesystem/world.wit deleted file mode 100644 index 65597f9..0000000 --- a/wit/deps/filesystem/world.wit +++ /dev/null @@ -1,9 +0,0 @@ -package wasi:filesystem@0.2.6; - -@since(version = 0.2.0) -world imports { - @since(version = 0.2.0) - import types; - @since(version = 0.2.0) - import preopens; -} diff --git a/wit/deps/http/handler.wit b/wit/deps/http/handler.wit deleted file mode 100644 index 6a6c629..0000000 --- a/wit/deps/http/handler.wit +++ /dev/null @@ -1,49 +0,0 @@ -/// This interface defines a handler of incoming HTTP Requests. It should -/// be exported by components which can respond to HTTP Requests. -@since(version = 0.2.0) -interface incoming-handler { - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. -@since(version = 0.2.0) -interface outgoing-handler { - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - handle: func( - request: outgoing-request, - options: option - ) -> result; -} diff --git a/wit/deps/http/proxy.wit b/wit/deps/http/proxy.wit deleted file mode 100644 index 5bd9f99..0000000 --- a/wit/deps/http/proxy.wit +++ /dev/null @@ -1,50 +0,0 @@ -package wasi:http@0.2.6; - -/// The `wasi:http/imports` world imports all the APIs for HTTP proxies. -/// It is intended to be `include`d in other worlds. -@since(version = 0.2.0) -world imports { - /// HTTP proxies have access to time and randomness. - @since(version = 0.2.0) - import wasi:clocks/monotonic-clock@0.2.6; - @since(version = 0.2.0) - import wasi:clocks/wall-clock@0.2.6; - @since(version = 0.2.0) - import wasi:random/random@0.2.6; - - /// Proxies have standard output and error streams which are expected to - /// terminate in a developer-facing console provided by the host. - @since(version = 0.2.0) - import wasi:cli/stdout@0.2.6; - @since(version = 0.2.0) - import wasi:cli/stderr@0.2.6; - - /// 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. - @since(version = 0.2.0) - import wasi:cli/stdin@0.2.6; - - /// This is the default handler to use when user code simply wants to make an - /// HTTP request (e.g., via `fetch()`). - @since(version = 0.2.0) - import outgoing-handler; -} - -/// 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. -@since(version = 0.2.0) -world proxy { - @since(version = 0.2.0) - include imports; - - /// 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`. - @since(version = 0.2.0) - export incoming-handler; -} diff --git a/wit/deps/http/types.wit b/wit/deps/http/types.wit deleted file mode 100644 index c9f3cc4..0000000 --- a/wit/deps/http/types.wit +++ /dev/null @@ -1,688 +0,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. -@since(version = 0.2.0) -interface types { - @since(version = 0.2.0) - use wasi:clocks/monotonic-clock@0.2.6.{duration}; - @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream, output-stream}; - @since(version = 0.2.0) - use wasi:io/error@0.2.6.{error as io-error}; - @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; - - /// This type corresponds to HTTP standard Methods. - @since(version = 0.2.0) - variant method { - get, - head, - post, - put, - delete, - connect, - options, - trace, - patch, - other(string) - } - - /// This type corresponds to HTTP standard Related Schemes. - @since(version = 0.2.0) - variant scheme { - HTTP, - HTTPS, - other(string) - } - - /// These cases are inspired by the IANA HTTP Proxy Error Types: - /// - @since(version = 0.2.0) - 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: - @since(version = 0.2.0) - record DNS-error-payload { - rcode: option, - info-code: option - } - - /// Defines the case payload type for `TLS-alert-received` above: - @since(version = 0.2.0) - record TLS-alert-received-payload { - alert-id: option, - alert-message: option - } - - /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - variant header-error { - /// This error indicates that a `field-name` 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-name` 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 names are always strings. - /// - /// Field names should always be treated as case insensitive by the `fields` - /// resource for the purposes of equality checking. - @since(version = 0.2.1) - type field-name = field-key; - - /// Field keys are always strings. - /// - /// Field keys should always be treated as case insensitive by the `fields` - /// resource for the purposes of equality checking. - /// - /// # Deprecation - /// - /// This type has been deprecated in favor of the `field-name` type. - @since(version = 0.2.0) - @deprecated(version = 0.2.2) - 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. - @since(version = 0.2.0) - 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 - /// immutable. In an immutable fields, the `set`, `append`, and `delete` - /// operations will fail with `header-error.immutable`. - @since(version = 0.2.0) - resource fields { - - /// Construct an empty HTTP Fields. - /// - /// The resulting `fields` is mutable. - @since(version = 0.2.0) - constructor(); - - /// Construct an HTTP Fields. - /// - /// The resulting `fields` is mutable. - /// - /// The list represents each name-value pair in the Fields. Names - /// which have multiple values are represented by multiple entries in this - /// list with the same name. - /// - /// The tuple is a pair of the field name, represented as a string, and - /// Value, represented as a list of bytes. - /// - /// An error result will be returned if any `field-name` or `field-value` is - /// syntactically invalid, or if a field is forbidden. - @since(version = 0.2.0) - from-list: static func( - entries: list> - ) -> result; - - /// Get all of the values corresponding to a name. If the name is not present - /// in this `fields` or is syntactically invalid, an empty list is returned. - /// However, if the name is present but empty, this is represented by a list - /// with one or more empty field-values present. - @since(version = 0.2.0) - get: func(name: field-name) -> list; - - /// Returns `true` when the name is present in this `fields`. If the name is - /// syntactically invalid, `false` is returned. - @since(version = 0.2.0) - has: func(name: field-name) -> bool; - - /// Set all of the values for a name. Clears any existing values for that - /// name, if they have been set. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-name` or any of - /// the `field-value`s are syntactically invalid. - @since(version = 0.2.0) - set: func(name: field-name, value: list) -> result<_, header-error>; - - /// Delete all values for a name. Does nothing if no values for the name - /// exist. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-name` is - /// syntactically invalid. - @since(version = 0.2.0) - delete: func(name: field-name) -> result<_, header-error>; - - /// Append a value for a name. Does not change or delete any existing - /// values for that name. - /// - /// Fails with `header-error.immutable` if the `fields` are immutable. - /// - /// Fails with `header-error.invalid-syntax` if the `field-name` or - /// `field-value` are syntactically invalid. - @since(version = 0.2.0) - append: func(name: field-name, value: field-value) -> result<_, header-error>; - - /// Retrieve the full set of names and values in the Fields. Like the - /// constructor, the list represents each name-value pair. - /// - /// The outer list represents each name-value pair in the Fields. Names - /// which have multiple values are represented by multiple entries in this - /// list with the same name. - /// - /// The names and values are always returned in the original casing and in - /// the order in which they will be serialized for transport. - @since(version = 0.2.0) - entries: func() -> list>; - - /// Make a deep copy of the Fields. Equivalent in behavior to calling the - /// `fields` constructor on the return value of `entries`. The resulting - /// `fields` is mutable. - @since(version = 0.2.0) - clone: func() -> fields; - } - - /// Headers is an alias for Fields. - @since(version = 0.2.0) - type headers = fields; - - /// Trailers is an alias for Fields. - @since(version = 0.2.0) - type trailers = fields; - - /// Represents an incoming HTTP Request. - @since(version = 0.2.0) - resource incoming-request { - - /// Returns the method of the incoming request. - @since(version = 0.2.0) - method: func() -> method; - - /// Returns the path with query parameters from the request, as a string. - @since(version = 0.2.0) - path-with-query: func() -> option; - - /// Returns the protocol scheme from the request. - @since(version = 0.2.0) - scheme: func() -> option; - - /// Returns the authority of the Request's target URI, if present. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - headers: func() -> headers; - - /// Gives the `incoming-body` associated with this request. Will only - /// return success at most once, and subsequent calls will return error. - @since(version = 0.2.0) - consume: func() -> result; - } - - /// Represents an outgoing HTTP Request. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - body: func() -> result; - - /// Get the Method for the Request. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - set-scheme: func(scheme: option) -> result; - - /// Get the authority of the Request's target URI. 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. - @since(version = 0.2.0) - authority: func() -> option; - /// Set the authority of the Request's target URI. 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. - @since(version = 0.2.0) - 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 transferred to - /// another component by e.g. `outgoing-handler.handle`. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - resource request-options { - /// Construct a default `request-options` value. - @since(version = 0.2.0) - constructor(); - - /// The timeout for the initial connect to the HTTP Server. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - set-connect-timeout: func(duration: option) -> result; - - /// The timeout for receiving the first byte of the Response body. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - set-first-byte-timeout: func(duration: option) -> result; - - /// The timeout for receiving subsequent chunks of bytes in the Response - /// body stream. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - resource response-outparam { - /// Send an HTTP 1xx response. - /// - /// Unlike `response-outparam.set`, this does not consume the - /// `response-outparam`, allowing the guest to send an arbitrary number of - /// informational responses before sending the final response using - /// `response-outparam.set`. - /// - /// This will return an `HTTP-protocol-error` if `status` is not in the - /// range [100-199], or an `internal-error` if the implementation does not - /// support informational responses. - @unstable(feature = informational-outbound-responses) - send-informational: func( - status: u16, - headers: headers - ) -> result<_, error-code>; - - /// 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. - @since(version = 0.2.0) - set: static func( - param: response-outparam, - response: result, - ); - } - - /// This type corresponds to the HTTP standard Status Code. - @since(version = 0.2.0) - type status-code = u16; - - /// Represents an incoming HTTP Response. - @since(version = 0.2.0) - resource incoming-response { - - /// Returns the status code from the incoming response. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - headers: func() -> headers; - - /// Returns the incoming body. May be called at most once. Returns error - /// if called additional times. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - %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. - @since(version = 0.2.0) - finish: static func(this: incoming-body) -> future-trailers; - } - - /// Represents a future which may eventually 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. - @since(version = 0.2.0) - resource future-trailers { - - /// Returns a pollable which becomes ready when either the trailers have - /// been received, or an error has occurred. When this pollable is ready, - /// the `get` method will return `some`. - @since(version = 0.2.0) - subscribe: func() -> pollable; - - /// Returns the contents of the trailers, or an error which occurred, - /// 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 occurred 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. - @since(version = 0.2.0) - get: func() -> option, error-code>>>; - } - - /// Represents an outgoing HTTP Response. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - constructor(headers: headers); - - /// Get the HTTP Status Code for the Response. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 transferred to - /// another component by e.g. `outgoing-handler.handle`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 occurred. The implementation should propagate 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - finish: static func( - this: outgoing-body, - trailers: option - ) -> result<_, error-code>; - } - - /// Represents a future which may eventually 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. - @since(version = 0.2.0) - resource future-incoming-response { - /// Returns a pollable which becomes ready when either the Response has - /// been received, or an error has occurred. When this pollable is ready, - /// the `get` method will return `some`. - @since(version = 0.2.0) - 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 received successfully, or that an error - /// occurred. Errors may also occur while consuming the response body, - /// but those will be reported by the `incoming-body` and its - /// `output-stream` child. - @since(version = 0.2.0) - get: func() -> option>>; - } -} diff --git a/wit/deps/io.wit b/wit/deps/io.wit new file mode 100644 index 0000000..11b7a7f --- /dev/null +++ b/wit/deps/io.wit @@ -0,0 +1,48 @@ +package wasi:io@0.2.6; + +interface error { + resource error { + to-debug-string: func() -> string; + } +} + +interface poll { + resource pollable { + ready: func() -> bool; + block: func(); + } + + poll: func(in: list>) -> list; +} + +interface streams { + use error.{error}; + use poll.{pollable}; + + resource input-stream { + read: func(len: u64) -> result, stream-error>; + blocking-read: func(len: u64) -> result, stream-error>; + skip: func(len: u64) -> result; + blocking-skip: func(len: u64) -> result; + subscribe: func() -> pollable; + } + + variant stream-error { + last-operation-failed(error), + closed, + } + + resource output-stream { + check-write: func() -> result; + write: func(contents: list) -> result<_, stream-error>; + blocking-write-and-flush: func(contents: list) -> result<_, stream-error>; + flush: func() -> result<_, stream-error>; + blocking-flush: func() -> result<_, stream-error>; + subscribe: func() -> pollable; + write-zeroes: func(len: u64) -> result<_, stream-error>; + blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; + splice: func(src: borrow, len: u64) -> result; + blocking-splice: func(src: borrow, len: u64) -> result; + } +} + diff --git a/wit/deps/io/error.wit b/wit/deps/io/error.wit deleted file mode 100644 index 784f74a..0000000 --- a/wit/deps/io/error.wit +++ /dev/null @@ -1,34 +0,0 @@ -package wasi:io@0.2.6; - -@since(version = 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 - /// offer functions to "downcast" this error into more specific types. For example, - /// errors returned from streams derived from filesystem types can be described using - /// the filesystem's own error-code type. This is done using the function - /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` - /// parameter and returns an `option`. - /// - /// The set of functions which can "downcast" an `error` into a more - /// concrete type is open. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - to-debug-string: func() -> string; - } -} diff --git a/wit/deps/io/poll.wit b/wit/deps/io/poll.wit deleted file mode 100644 index 7f71183..0000000 --- a/wit/deps/io/poll.wit +++ /dev/null @@ -1,47 +0,0 @@ -package wasi:io@0.2.6; - -/// A poll API intended to let users wait for I/O events on multiple handles -/// at once. -@since(version = 0.2.0) -interface poll { - /// `pollable` represents a single I/O event which may be ready, or not. - @since(version = 0.2.0) - resource pollable { - - /// Return the readiness of a pollable. This function never blocks. - /// - /// Returns `true` when the pollable is ready, and `false` otherwise. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - /// - /// This function traps if either: - /// - the list is empty, or: - /// - the list contains more elements than can be indexed with a `u32` value. - /// - /// 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 ready for I/O. - @since(version = 0.2.0) - poll: func(in: list>) -> list; -} diff --git a/wit/deps/io/streams.wit b/wit/deps/io/streams.wit deleted file mode 100644 index c5da38c..0000000 --- a/wit/deps/io/streams.wit +++ /dev/null @@ -1,290 +0,0 @@ -package wasi:io@0.2.6; - -/// 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. -@since(version = 0.2.0) -interface streams { - @since(version = 0.2.0) - use error.{error}; - @since(version = 0.2.0) - use poll.{pollable}; - - /// An error for input-stream and output-stream operations. - @since(version = 0.2.0) - variant stream-error { - /// The last operation (a write or flush) failed before completion. - /// - /// More information is available in the `error` payload. - /// - /// After this, the stream will be closed. All future operations return - /// `stream-error::closed`. - 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`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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`. - /// - /// Dropping an `output-stream` while there's still an active write in - /// progress may result in the data being lost. Before dropping the stream, - /// be sure to fully flush your writes. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 - /// ``` - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - flush: func() -> result<_, stream-error>; - - /// Request to flush buffered output, and block until flush completes - /// and stream is ready for writing again. - @since(version = 0.2.0) - 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 occurred. 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 - /// ``` - @since(version = 0.2.0) - 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 equivalent 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`. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - blocking-splice: func( - /// The stream to read from - src: borrow, - /// The number of bytes to splice - len: u64, - ) -> result; - } -} diff --git a/wit/deps/io/world.wit b/wit/deps/io/world.wit deleted file mode 100644 index 84c85c0..0000000 --- a/wit/deps/io/world.wit +++ /dev/null @@ -1,10 +0,0 @@ -package wasi:io@0.2.6; - -@since(version = 0.2.0) -world imports { - @since(version = 0.2.0) - import streams; - - @since(version = 0.2.0) - import poll; -} diff --git a/wit/deps/random.wit b/wit/deps/random.wit new file mode 100644 index 0000000..eb3d27d --- /dev/null +++ b/wit/deps/random.wit @@ -0,0 +1,12 @@ +package wasi:random@0.2.0; + +interface insecure { + get-insecure-random-bytes: func(len: u64) -> list; + + get-insecure-random-u64: func() -> u64; +} + +interface insecure-seed { + insecure-seed: func() -> tuple; +} + diff --git a/wit/deps/random/insecure-seed.wit b/wit/deps/random/insecure-seed.wit deleted file mode 100644 index d3dc03a..0000000 --- a/wit/deps/random/insecure-seed.wit +++ /dev/null @@ -1,27 +0,0 @@ -package wasi:random@0.2.6; -/// The insecure-seed interface for seeding hash-map DoS resistance. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -@since(version = 0.2.0) -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. - @since(version = 0.2.0) - insecure-seed: func() -> tuple; -} diff --git a/wit/deps/random/insecure.wit b/wit/deps/random/insecure.wit deleted file mode 100644 index d4d0284..0000000 --- a/wit/deps/random/insecure.wit +++ /dev/null @@ -1,25 +0,0 @@ -package wasi:random@0.2.6; -/// The insecure interface for insecure pseudo-random numbers. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -@since(version = 0.2.0) -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. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - get-insecure-random-u64: func() -> u64; -} diff --git a/wit/deps/random/random.wit b/wit/deps/random/random.wit deleted file mode 100644 index a0ff956..0000000 --- a/wit/deps/random/random.wit +++ /dev/null @@ -1,29 +0,0 @@ -package wasi:random@0.2.6; -/// WASI Random is a random data API. -/// -/// It is intended to be portable at least between Unix-family platforms and -/// Windows. -@since(version = 0.2.0) -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. - @since(version = 0.2.0) - 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`. - @since(version = 0.2.0) - get-random-u64: func() -> u64; -} diff --git a/wit/deps/random/world.wit b/wit/deps/random/world.wit deleted file mode 100644 index 099f47b..0000000 --- a/wit/deps/random/world.wit +++ /dev/null @@ -1,13 +0,0 @@ -package wasi:random@0.2.6; - -@since(version = 0.2.0) -world imports { - @since(version = 0.2.0) - import random; - - @since(version = 0.2.0) - import insecure; - - @since(version = 0.2.0) - import insecure-seed; -} diff --git a/wit/deps/sockets.wit b/wit/deps/sockets.wit new file mode 100644 index 0000000..fc71f10 --- /dev/null +++ b/wit/deps/sockets.wit @@ -0,0 +1,183 @@ +package wasi:sockets@0.2.0; + +interface network { + resource network; + + type ipv4-address = tuple; + + record ipv4-socket-address { + port: u16, + address: ipv4-address, + } + + type ipv6-address = tuple; + + record ipv6-socket-address { + port: u16, + flow-info: u32, + address: ipv6-address, + scope-id: u32, + } + + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + + 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, + } + + enum ip-address-family { + ipv4, + ipv6, + } + + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } +} + +interface instance-network { + use network.{network}; + + instance-network: func() -> network; +} + +interface udp { + use network.{network, ip-socket-address, error-code, ip-address-family}; + use wasi:io/poll@0.2.6.{pollable}; + + resource udp-socket { + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + %stream: func(remote-address: option) -> result, error-code>; + local-address: func() -> result; + remote-address: func() -> result; + address-family: func() -> ip-address-family; + unicast-hop-limit: func() -> result; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + 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>; + subscribe: func() -> pollable; + } + + resource incoming-datagram-stream { + receive: func(max-results: u64) -> result, error-code>; + subscribe: func() -> pollable; + } + + resource outgoing-datagram-stream { + check-send: func() -> result; + send: func(datagrams: list) -> result; + subscribe: func() -> pollable; + } + + record incoming-datagram { + data: list, + remote-address: ip-socket-address, + } + + record outgoing-datagram { + data: list, + remote-address: option, + } +} + +interface udp-create-socket { + use network.{ip-address-family}; + use udp.{udp-socket}; + use network.{error-code}; + + create-udp-socket: func(address-family: ip-address-family) -> result; +} + +interface tcp { + use network.{network, ip-socket-address, error-code}; + use wasi:io/streams@0.2.6.{input-stream, output-stream}; + use network.{ip-address-family}; + use wasi:clocks/monotonic-clock@0.2.6.{duration}; + use wasi:io/poll@0.2.6.{pollable}; + + resource tcp-socket { + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + start-listen: func() -> result<_, error-code>; + finish-listen: func() -> result<_, error-code>; + accept: func() -> result, error-code>; + local-address: func() -> result; + remote-address: func() -> result; + is-listening: func() -> bool; + address-family: func() -> ip-address-family; + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + keep-alive-enabled: func() -> result; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + keep-alive-idle-time: func() -> result; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + keep-alive-interval: func() -> result; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + keep-alive-count: func() -> result; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + hop-limit: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + 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>; + subscribe: func() -> pollable; + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } + + enum shutdown-type { + receive, + send, + both, + } +} + +interface tcp-create-socket { + use network.{ip-address-family}; + use tcp.{tcp-socket}; + use network.{error-code}; + + create-tcp-socket: func(address-family: ip-address-family) -> result; +} + +interface ip-name-lookup { + use network.{ip-address, error-code}; + use wasi:io/poll@0.2.6.{pollable}; + use network.{network}; + + resource resolve-address-stream { + resolve-next-address: func() -> result, error-code>; + subscribe: func() -> pollable; + } + + resolve-addresses: func(network: borrow, name: string) -> result; +} + diff --git a/wit/deps/sockets/instance-network.wit b/wit/deps/sockets/instance-network.wit deleted file mode 100644 index 5f6e6c1..0000000 --- a/wit/deps/sockets/instance-network.wit +++ /dev/null @@ -1,11 +0,0 @@ - -/// This interface provides a value-export of the default network handle.. -@since(version = 0.2.0) -interface instance-network { - @since(version = 0.2.0) - use network.{network}; - - /// Get a handle to the default network. - @since(version = 0.2.0) - instance-network: func() -> network; -} diff --git a/wit/deps/sockets/ip-name-lookup.wit b/wit/deps/sockets/ip-name-lookup.wit deleted file mode 100644 index ee6419e..0000000 --- a/wit/deps/sockets/ip-name-lookup.wit +++ /dev/null @@ -1,56 +0,0 @@ -@since(version = 0.2.0) -interface ip-name-lookup { - @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; - @since(version = 0.2.0) - 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: - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - resolve-addresses: func(network: borrow, name: string) -> result; - - @since(version = 0.2.0) - 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) - @since(version = 0.2.0) - 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 0.2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - @since(version = 0.2.0) - subscribe: func() -> pollable; - } -} diff --git a/wit/deps/sockets/network.wit b/wit/deps/sockets/network.wit deleted file mode 100644 index 6ca98b6..0000000 --- a/wit/deps/sockets/network.wit +++ /dev/null @@ -1,169 +0,0 @@ -@since(version = 0.2.0) -interface network { - @unstable(feature = network-error-code) - use wasi:io/error@0.2.6.{error}; - - /// 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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, - } - - /// Attempts to extract a network-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 - /// network-related information about the error to return. - /// - /// Note that this function is fallible because not all stream-related - /// errors are network-related errors. - @unstable(feature = network-error-code) - network-error-code: func(err: borrow) -> option; - - @since(version = 0.2.0) - enum ip-address-family { - /// Similar to `AF_INET` in POSIX. - ipv4, - - /// Similar to `AF_INET6` in POSIX. - ipv6, - } - - @since(version = 0.2.0) - type ipv4-address = tuple; - @since(version = 0.2.0) - type ipv6-address = tuple; - - @since(version = 0.2.0) - variant ip-address { - ipv4(ipv4-address), - ipv6(ipv6-address), - } - - @since(version = 0.2.0) - record ipv4-socket-address { - /// sin_port - port: u16, - /// sin_addr - address: ipv4-address, - } - - @since(version = 0.2.0) - record ipv6-socket-address { - /// sin6_port - port: u16, - /// sin6_flowinfo - flow-info: u32, - /// sin6_addr - address: ipv6-address, - /// sin6_scope_id - scope-id: u32, - } - - @since(version = 0.2.0) - variant ip-socket-address { - ipv4(ipv4-socket-address), - ipv6(ipv6-socket-address), - } -} diff --git a/wit/deps/sockets/tcp-create-socket.wit b/wit/deps/sockets/tcp-create-socket.wit deleted file mode 100644 index eedbd30..0000000 --- a/wit/deps/sockets/tcp-create-socket.wit +++ /dev/null @@ -1,30 +0,0 @@ -@since(version = 0.2.0) -interface tcp-create-socket { - @since(version = 0.2.0) - use network.{network, error-code, ip-address-family}; - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - create-tcp-socket: func(address-family: ip-address-family) -> result; -} diff --git a/wit/deps/sockets/tcp.wit b/wit/deps/sockets/tcp.wit deleted file mode 100644 index beefd7b..0000000 --- a/wit/deps/sockets/tcp.wit +++ /dev/null @@ -1,387 +0,0 @@ -@since(version = 0.2.0) -interface tcp { - @since(version = 0.2.0) - use wasi:io/streams@0.2.6.{input-stream, output-stream}; - @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; - @since(version = 0.2.0) - use wasi:clocks/monotonic-clock@0.2.6.{duration}; - @since(version = 0.2.0) - use network.{network, error-code, ip-socket-address, ip-address-family}; - - @since(version = 0.2.0) - 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 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. - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - @since(version = 0.2.0) - finish-bind: func() -> result<_, error-code>; - - /// Connect to a remote endpoint. - /// - /// On success: - /// - the socket is transitioned into the `connected` 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - start-listen: func() -> result<_, error-code>; - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - local-address: func() -> result; - - /// Get the remote address. - /// - /// # Typical errors - /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) - /// - /// # References - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - remote-address: func() -> result; - - /// Whether the socket is in the `listening` state. - /// - /// Equivalent to the SO_ACCEPTCONN socket option. - @since(version = 0.2.0) - is-listening: func() -> bool; - - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - keep-alive-enabled: func() -> result; - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - keep-alive-idle-time: func() -> result; - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - keep-alive-interval: func() -> result; - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - keep-alive-count: func() -> result; - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - hop-limit: func() -> result; - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - receive-buffer-size: func() -> result; - @since(version = 0.2.0) - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - @since(version = 0.2.0) - send-buffer-size: func() -> result; - @since(version = 0.2.0) - 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 more information. - /// - /// Note: this function is here for WASI 0.2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - @since(version = 0.2.0) - 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 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; - } -} diff --git a/wit/deps/sockets/udp-create-socket.wit b/wit/deps/sockets/udp-create-socket.wit deleted file mode 100644 index e8eeacb..0000000 --- a/wit/deps/sockets/udp-create-socket.wit +++ /dev/null @@ -1,30 +0,0 @@ -@since(version = 0.2.0) -interface udp-create-socket { - @since(version = 0.2.0) - use network.{network, error-code, ip-address-family}; - @since(version = 0.2.0) - 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: - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - create-udp-socket: func(address-family: ip-address-family) -> result; -} diff --git a/wit/deps/sockets/udp.wit b/wit/deps/sockets/udp.wit deleted file mode 100644 index 9dbe693..0000000 --- a/wit/deps/sockets/udp.wit +++ /dev/null @@ -1,288 +0,0 @@ -@since(version = 0.2.0) -interface udp { - @since(version = 0.2.0) - use wasi:io/poll@0.2.6.{pollable}; - @since(version = 0.2.0) - use network.{network, error-code, ip-socket-address, ip-address-family}; - - /// A received datagram. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - %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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - remote-address: func() -> result; - - /// Whether this is a IPv4 or IPv6 socket. - /// - /// Equivalent to the SO_DOMAIN socket option. - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - unicast-hop-limit: func() -> result; - @since(version = 0.2.0) - 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. - @since(version = 0.2.0) - receive-buffer-size: func() -> result; - @since(version = 0.2.0) - set-receive-buffer-size: func(value: u64) -> result<_, error-code>; - @since(version = 0.2.0) - send-buffer-size: func() -> result; - @since(version = 0.2.0) - 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 0.2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - @since(version = 0.2.0) - subscribe: func() -> pollable; - } - - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - 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 0.2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - @since(version = 0.2.0) - subscribe: func() -> pollable; - } - - @since(version = 0.2.0) - 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 - /// - - /// - - /// - - /// - - /// - - /// - - /// - - /// - - @since(version = 0.2.0) - 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 0.2 only. - /// It's planned to be removed when `future` is natively supported in Preview3. - @since(version = 0.2.0) - subscribe: func() -> pollable; - } -} diff --git a/wit/deps/sockets/world.wit b/wit/deps/sockets/world.wit deleted file mode 100644 index e86f02c..0000000 --- a/wit/deps/sockets/world.wit +++ /dev/null @@ -1,19 +0,0 @@ -package wasi:sockets@0.2.6; - -@since(version = 0.2.0) -world imports { - @since(version = 0.2.0) - import instance-network; - @since(version = 0.2.0) - import network; - @since(version = 0.2.0) - import udp; - @since(version = 0.2.0) - import udp-create-socket; - @since(version = 0.2.0) - import tcp; - @since(version = 0.2.0) - import tcp-create-socket; - @since(version = 0.2.0) - import ip-name-lookup; -} diff --git a/wit/wasiless.wit b/wit/wasiless.wit index 01906dd..2731b11 100644 --- a/wit/wasiless.wit +++ b/wit/wasiless.wit @@ -1,32 +1,22 @@ package fastly:wasiless; +// Interfaces that are imported by the Python+app component but are not provided +// by Viceroy (ignoring versions): world wasiless { - export wasi:cli/terminal-input@0.2.6; - export wasi:cli/terminal-output@0.2.6; - export wasi:cli/terminal-stdin@0.2.6; - export wasi:cli/terminal-stdout@0.2.6; - export wasi:cli/terminal-stderr@0.2.6; - export wasi:io/error@0.2.6; - export wasi:io/poll@0.2.6; - export wasi:io/streams@0.2.6; - export wasi:clocks/wall-clock@0.2.6; - export wasi:filesystem/types@0.2.6; - export wasi:filesystem/preopens@0.2.6; - export wasi:sockets/network@0.2.6; - export wasi:sockets/instance-network@0.2.6; - export wasi:sockets/udp@0.2.6; - export wasi:sockets/udp-create-socket@0.2.6; - export wasi:clocks/monotonic-clock@0.2.6; - export wasi:sockets/tcp@0.2.6; - export wasi:sockets/tcp-create-socket@0.2.6; - export wasi:sockets/ip-name-lookup@0.2.6; - export wasi:random/insecure@0.2.6; - export wasi:random/insecure-seed@0.2.6; - export wasi:random/random@0.2.6; - export wasi:cli/environment@0.2.6; - export wasi:cli/exit@0.2.6; - export wasi:cli/stdout@0.2.6; - export wasi:cli/stderr@0.2.6; - export wasi:cli/stdin@0.2.6; + export wasi:cli/terminal-input@0.2.0; + export wasi:cli/terminal-output@0.2.0; + export wasi:cli/terminal-stdin@0.2.0; + export wasi:cli/terminal-stdout@0.2.0; + export wasi:cli/terminal-stderr@0.2.0; + export wasi:filesystem/types@0.2.0; + export wasi:filesystem/preopens@0.2.0; + export wasi:sockets/network@0.2.0; + export wasi:sockets/instance-network@0.2.0; + export wasi:sockets/udp@0.2.0; + export wasi:sockets/udp-create-socket@0.2.0; + export wasi:sockets/tcp@0.2.0; + export wasi:sockets/tcp-create-socket@0.2.0; + export wasi:sockets/ip-name-lookup@0.2.0; + export wasi:random/insecure@0.2.0; + export wasi:random/insecure-seed@0.2.0; } -// Version numbers are fairly arbitrary. \ No newline at end of file From 4c9ac507bae44e7964c0f689cb67c0f505e210a7 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Thu, 16 Oct 2025 12:17:23 -0400 Subject: [PATCH 44/50] Wrap build process (including componentization) in a makefile. Ready us to move composition to the compute-sdk-python repo. --- .gitignore | 3 ++- Makefile | 9 +++++++++ build.sh | 12 ------------ compose.wac | 29 ----------------------------- 4 files changed, 11 insertions(+), 42 deletions(-) create mode 100755 Makefile delete mode 100755 build.sh delete mode 100644 compose.wac diff --git a/.gitignore b/.gitignore index 2f1c24c..c7b9bef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target -/wasiless.rs \ No newline at end of file +/wasiless.rs +/wasiless.wasm diff --git a/Makefile b/Makefile new file mode 100755 index 0000000..3d15366 --- /dev/null +++ b/Makefile @@ -0,0 +1,9 @@ +wasiless.wasm: target/wasm32-unknown-unknown/debug/wasiless.wasm + wasm-tools component new target/wasm32-unknown-unknown/debug/wasiless.wasm -o wasiless.wasm + +target/wasm32-unknown-unknown/debug/wasiless.wasm: $(shell find src -name '*.rs') + cargo build + +# `wasm-tools component wit some_componentize_py_output.wasm --out-dir wit` +# handily extracts the wit for a new version of Python/componentize-py into this +# tree. \ No newline at end of file diff --git a/build.sh b/build.sh deleted file mode 100755 index bf59e11..0000000 --- a/build.sh +++ /dev/null @@ -1,12 +0,0 @@ -set -x - -# generate wit directory -# wasm-tools component wit $1 --out-dir wit - -#wit-bindgen rust --stubs wit --generate-all --world wasiless -#cp wasiless.rs src/lib.rs -cargo build --target=wasm32-unknown-unknown -cp target/wasm32-unknown-unknown/debug/wasiless.wasm . -wasm-tools component new wasiless.wasm -o wasiless.wasm -wac compose --dep fastly:wasiless=wasiless.wasm --dep app:component=$1 -o composed.wasm compose.wac - diff --git a/compose.wac b/compose.wac deleted file mode 100644 index 23ca911..0000000 --- a/compose.wac +++ /dev/null @@ -1,29 +0,0 @@ -package fastly:python-wasiless; - -// Instantiate wasiless, minimal or crashing implementations of irrelevant WASI interfaces: -let wasiless = new fastly:wasiless { ... }; - -// Instantiate the Python component. Pass in the 0.2.6 routines from wasiless, -// even when Python wants a different version: -/*let app = new app:component { - "wasi:cli/terminal-input@0.2.0": wasiless["wasi:cli/terminal-input@0.2.6"], - "wasi:cli/terminal-output@0.2.0": wasiless["wasi:cli/terminal-output@0.2.6"], - "wasi:cli/terminal-stdin@0.2.0": wasiless["wasi:cli/terminal-stdin@0.2.6"], - "wasi:cli/terminal-stdout@0.2.0": wasiless["wasi:cli/terminal-stdout@0.2.6"], - "wasi:cli/terminal-stderr@0.2.0": wasiless["wasi:cli/terminal-stderr@0.2.6"], - "wasi:filesystem/types@0.2.0": wasiless["wasi:filesystem/types@0.2.6"], - "wasi:filesystem/preopens@0.2.0": wasiless["wasi:filesystem/preopens@0.2.6"], - "wasi:sockets/network@0.2.0": wasiless["wasi:sockets/network@0.2.6"], - "wasi:sockets/instance-network@0.2.0": wasiless["wasi:sockets/instance-network@0.2.6"], - "wasi:sockets/udp@0.2.0": wasiless["wasi:sockets/udp@0.2.6"], - "wasi:sockets/udp-create-socket@0.2.0": wasiless["wasi:sockets/udp-create-socket@0.2.6"], - "wasi:sockets/tcp@0.2.0": wasiless["wasi:sockets/tcp@0.2.6"], - "wasi:sockets/tcp-create-socket@0.2.0": wasiless["wasi:sockets/tcp-create-socket@0.2.6"], - "wasi:sockets/ip-name-lookup@0.2.0": wasiless["wasi:sockets/ip-name-lookup@0.2.6"], - "wasi:random/insecure@0.2.0": wasiless["wasi:random/insecure@0.2.6"], - "wasi:random/insecure-seed@0.2.0": wasiless["wasi:random/insecure-seed@0.2.6"], - ... -};*/ -let app = new app:component { ...wasiless, ... }; -export app...; - From 5ef2e47e0787412a868f6c825d5463ba4a79a0f7 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Thu, 16 Oct 2025 16:48:39 -0400 Subject: [PATCH 45/50] Fix some inconsistent whitespace. --- src/sockets.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sockets.rs b/src/sockets.rs index 802b66a..acd2b25 100644 --- a/src/sockets.rs +++ b/src/sockets.rs @@ -268,6 +268,7 @@ impl ip_name_lookup::GuestResolveAddressStream for Wasiless { unreachable!() } } + impl ip_name_lookup::Guest for Wasiless { type ResolveAddressStream = Wasiless; #[allow(unused_variables)] From 32df0b40fcb7fcc3b89f7f8292ca4abcf7b5ba61 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 20 Oct 2025 16:28:53 -0400 Subject: [PATCH 46/50] Switch to a release build. It's 71K instead of 3MB. --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 3d15366..5ed2069 100755 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ wasiless.wasm: target/wasm32-unknown-unknown/debug/wasiless.wasm - wasm-tools component new target/wasm32-unknown-unknown/debug/wasiless.wasm -o wasiless.wasm + wasm-tools component new target/wasm32-unknown-unknown/release/wasiless.wasm -o wasiless.wasm target/wasm32-unknown-unknown/debug/wasiless.wasm: $(shell find src -name '*.rs') - cargo build + cargo build --release # `wasm-tools component wit some_componentize_py_output.wasm --out-dir wit` # handily extracts the wit for a new version of Python/componentize-py into this From c1cc36fb2821f2c8bfc6b96494e3aee965e9bcc7 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 20 Oct 2025 16:29:06 -0400 Subject: [PATCH 47/50] Bring readme up to date. --- README.md | 42 ++++++++---------------------------------- 1 file changed, 8 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 26a6bd8..2d7e9e9 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,7 @@ Wasiless is a WebAssembly component that provides minimal or trapping implementa ## Build -Build wasiless as a WASIp2 component as follows: - -``` shell -cargo build --release -wasm-tools component new target/wasm32-unknown-unknown/debug/wasiless.wasm -o componentized.wasm -``` +Build wasiless as a WASIp2 component using `make`. ## Use @@ -18,34 +13,13 @@ Here is an example composition of wasiless and a Python component (built using c ``` package fastly:python-wasiless; -// Instantiate wasiless, minimal or crashing implementations of irrelevant WASI interfaces: -let wasiless = new fastly:wasiless { - ... -}; - -// Instantiate the Python component. Pass in the 0.2.6 routines from wasiless, -// even when Python wants a different version: -let app = new app:component { - "wasi:cli/terminal-input@0.2.0": wasiless["wasi:cli/terminal-input@0.2.6"], - "wasi:cli/terminal-output@0.2.0": wasiless["wasi:cli/terminal-output@0.2.6"], - "wasi:cli/terminal-stdin@0.2.0": wasiless["wasi:cli/terminal-stdin@0.2.6"], - "wasi:cli/terminal-stdout@0.2.0": wasiless["wasi:cli/terminal-stdout@0.2.6"], - "wasi:cli/terminal-stderr@0.2.0": wasiless["wasi:cli/terminal-stderr@0.2.6"], - "wasi:filesystem/types@0.2.0": wasiless["wasi:filesystem/types@0.2.6"], - "wasi:filesystem/preopens@0.2.0": wasiless["wasi:filesystem/preopens@0.2.6"], - "wasi:sockets/network@0.2.0": wasiless["wasi:sockets/network@0.2.6"], - "wasi:sockets/instance-network@0.2.0": wasiless["wasi:sockets/instance-network@0.2.6"], - "wasi:sockets/udp@0.2.0": wasiless["wasi:sockets/udp@0.2.6"], - "wasi:sockets/udp-create-socket@0.2.0": wasiless["wasi:sockets/udp-create-socket@0.2.6"], - "wasi:sockets/tcp@0.2.0": wasiless["wasi:sockets/tcp@0.2.6"], - "wasi:sockets/tcp-create-socket@0.2.0": wasiless["wasi:sockets/tcp-create-socket@0.2.6"], - "wasi:sockets/ip-name-lookup@0.2.0": wasiless["wasi:sockets/ip-name-lookup@0.2.6"], - "wasi:random/insecure@0.2.0": wasiless["wasi:random/insecure@0.2.6"], - "wasi:random/insecure-seed@0.2.0": wasiless["wasi:random/insecure-seed@0.2.6"], - ... -}; - -export app.exports; +// Instantiate wasiless to satisfy irrelevant WASI interfaces: +let wasiless = new fastly:wasiless { ... }; + +// Instantiate the Python component: +let app = new app:component { ...wasiless, ... }; + +// Export only the HTTP handler, not the extraneous `exports` bundle: export app["fastly:compute/http-incoming"]; ``` From 3e472664af5536748b9445c0bdfe18f61556e97c Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Mon, 20 Oct 2025 16:56:50 -0400 Subject: [PATCH 48/50] =?UTF-8?q?Add=20a=20CI=20job=20to=20make=20sure=20t?= =?UTF-8?q?he=20build=20isn=E2=80=99t=20broken.=20(#3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/build.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..4f7c558 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,35 @@ +name: Make sure the build isn't broken + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + build: + runs-on: forge-amd64-medium + steps: + - uses: actions/checkout@v4 + - name: Set up Rust + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + toolchain: '1.86.0' + target: wasm32-unknown-unknown + components: rustfmt + - name: Check formatting + run: cargo fmt --all -- --check + - name: Cache wasm-tools + id: cache-cargo + uses: actions/cache@v4 + with: + key: tests-cargo-bin + path: | + ~/.cargo/bin/ + - name: Install wasm-tools + if: steps.cache-cargo.outputs.cache-hit != 'true' + run: cargo install wasm-tools + - name: Make sure it builds + run: make From 1dee009783d7b1c688a69d19ed081eb84eaf5f66 Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Wed, 1 Apr 2026 17:39:32 -0400 Subject: [PATCH 49/50] Remove wasiless submodule. --- .gitmodules | 4 +--- crates/wasiless | 1 - 2 files changed, 1 insertion(+), 4 deletions(-) delete mode 160000 crates/wasiless diff --git a/.gitmodules b/.gitmodules index 233453b..8b13789 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1 @@ -[submodule "crates/wasiless"] - path = crates/wasiless - url = git@github.com:fastly/wasiless.git + diff --git a/crates/wasiless b/crates/wasiless deleted file mode 160000 index 4c9ac50..0000000 --- a/crates/wasiless +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4c9ac507bae44e7964c0f689cb67c0f505e210a7 From 7c2285acf3de1143a0e0b37e6603781ca623d5ba Mon Sep 17 00:00:00 2001 From: Erik Rose Date: Wed, 1 Apr 2026 17:35:43 -0400 Subject: [PATCH 50/50] Move everything into crates/wasiless/ in prep for merging into the compute-sdk-python repo. --- {.cargo => crates/wasiless/.cargo}/config.toml | 0 .gitignore => crates/wasiless/.gitignore | 0 Cargo.lock => crates/wasiless/Cargo.lock | 0 Cargo.toml => crates/wasiless/Cargo.toml | 0 Makefile => crates/wasiless/Makefile | 0 README.md => crates/wasiless/README.md | 0 {src => crates/wasiless/src}/bindings.rs | 0 {src => crates/wasiless/src}/cli.rs | 0 {src => crates/wasiless/src}/filesystem.rs | 0 {src => crates/wasiless/src}/lib.rs | 0 {src => crates/wasiless/src}/random.rs | 0 {src => crates/wasiless/src}/sockets.rs | 0 {wit => crates/wasiless/wit}/deps/cli.wit | 0 {wit => crates/wasiless/wit}/deps/clocks.wit | 0 {wit => crates/wasiless/wit}/deps/filesystem.wit | 0 {wit => crates/wasiless/wit}/deps/io.wit | 0 {wit => crates/wasiless/wit}/deps/random.wit | 0 {wit => crates/wasiless/wit}/deps/sockets.wit | 0 {wit => crates/wasiless/wit}/wasiless.wit | 0 19 files changed, 0 insertions(+), 0 deletions(-) rename {.cargo => crates/wasiless/.cargo}/config.toml (100%) rename .gitignore => crates/wasiless/.gitignore (100%) rename Cargo.lock => crates/wasiless/Cargo.lock (100%) rename Cargo.toml => crates/wasiless/Cargo.toml (100%) rename Makefile => crates/wasiless/Makefile (100%) rename README.md => crates/wasiless/README.md (100%) rename {src => crates/wasiless/src}/bindings.rs (100%) rename {src => crates/wasiless/src}/cli.rs (100%) rename {src => crates/wasiless/src}/filesystem.rs (100%) rename {src => crates/wasiless/src}/lib.rs (100%) rename {src => crates/wasiless/src}/random.rs (100%) rename {src => crates/wasiless/src}/sockets.rs (100%) rename {wit => crates/wasiless/wit}/deps/cli.wit (100%) rename {wit => crates/wasiless/wit}/deps/clocks.wit (100%) rename {wit => crates/wasiless/wit}/deps/filesystem.wit (100%) rename {wit => crates/wasiless/wit}/deps/io.wit (100%) rename {wit => crates/wasiless/wit}/deps/random.wit (100%) rename {wit => crates/wasiless/wit}/deps/sockets.wit (100%) rename {wit => crates/wasiless/wit}/wasiless.wit (100%) diff --git a/.cargo/config.toml b/crates/wasiless/.cargo/config.toml similarity index 100% rename from .cargo/config.toml rename to crates/wasiless/.cargo/config.toml diff --git a/.gitignore b/crates/wasiless/.gitignore similarity index 100% rename from .gitignore rename to crates/wasiless/.gitignore diff --git a/Cargo.lock b/crates/wasiless/Cargo.lock similarity index 100% rename from Cargo.lock rename to crates/wasiless/Cargo.lock diff --git a/Cargo.toml b/crates/wasiless/Cargo.toml similarity index 100% rename from Cargo.toml rename to crates/wasiless/Cargo.toml diff --git a/Makefile b/crates/wasiless/Makefile similarity index 100% rename from Makefile rename to crates/wasiless/Makefile diff --git a/README.md b/crates/wasiless/README.md similarity index 100% rename from README.md rename to crates/wasiless/README.md diff --git a/src/bindings.rs b/crates/wasiless/src/bindings.rs similarity index 100% rename from src/bindings.rs rename to crates/wasiless/src/bindings.rs diff --git a/src/cli.rs b/crates/wasiless/src/cli.rs similarity index 100% rename from src/cli.rs rename to crates/wasiless/src/cli.rs diff --git a/src/filesystem.rs b/crates/wasiless/src/filesystem.rs similarity index 100% rename from src/filesystem.rs rename to crates/wasiless/src/filesystem.rs diff --git a/src/lib.rs b/crates/wasiless/src/lib.rs similarity index 100% rename from src/lib.rs rename to crates/wasiless/src/lib.rs diff --git a/src/random.rs b/crates/wasiless/src/random.rs similarity index 100% rename from src/random.rs rename to crates/wasiless/src/random.rs diff --git a/src/sockets.rs b/crates/wasiless/src/sockets.rs similarity index 100% rename from src/sockets.rs rename to crates/wasiless/src/sockets.rs diff --git a/wit/deps/cli.wit b/crates/wasiless/wit/deps/cli.wit similarity index 100% rename from wit/deps/cli.wit rename to crates/wasiless/wit/deps/cli.wit diff --git a/wit/deps/clocks.wit b/crates/wasiless/wit/deps/clocks.wit similarity index 100% rename from wit/deps/clocks.wit rename to crates/wasiless/wit/deps/clocks.wit diff --git a/wit/deps/filesystem.wit b/crates/wasiless/wit/deps/filesystem.wit similarity index 100% rename from wit/deps/filesystem.wit rename to crates/wasiless/wit/deps/filesystem.wit diff --git a/wit/deps/io.wit b/crates/wasiless/wit/deps/io.wit similarity index 100% rename from wit/deps/io.wit rename to crates/wasiless/wit/deps/io.wit diff --git a/wit/deps/random.wit b/crates/wasiless/wit/deps/random.wit similarity index 100% rename from wit/deps/random.wit rename to crates/wasiless/wit/deps/random.wit diff --git a/wit/deps/sockets.wit b/crates/wasiless/wit/deps/sockets.wit similarity index 100% rename from wit/deps/sockets.wit rename to crates/wasiless/wit/deps/sockets.wit diff --git a/wit/wasiless.wit b/crates/wasiless/wit/wasiless.wit similarity index 100% rename from wit/wasiless.wit rename to crates/wasiless/wit/wasiless.wit