From 1f4d01aad7eefb740b9bff6d1bb94239a2bf9155 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 23:40:18 +0000 Subject: [PATCH 1/4] Build Python components from prepared runtime assets --- Cargo.lock | 223 +++ Cargo.toml | 4 + Makefile.toml | 16 + golem-python-assembler/Cargo.toml | 27 + golem-python-assembler/src/lib.rs | 218 +++ golem-python-assembler/tests/assemble.rs | 192 +++ sdks/python/README.md | 41 + sdks/python/src/golem/__init__.py | 1 + sdks/python/src/golem/_bootstrap.py | 20 + sdks/python/src/golem/_guest.py | 61 + sdks/python/src/golem/_registry.py | 21 + sdks/python/wit/deps/blobstore/blobstore.wit | 29 + sdks/python/wit/deps/blobstore/container.wit | 51 + sdks/python/wit/deps/blobstore/types.wit | 70 + sdks/python/wit/deps/blobstore/world.wit | 5 + sdks/python/wit/deps/cli-0.2.6/cli.wit | 261 ++++ sdks/python/wit/deps/cli/cli.wit | 256 ++++ sdks/python/wit/deps/clocks-0.2.6/clocks.wit | 157 ++ sdks/python/wit/deps/clocks/clocks.wit | 161 ++ sdks/python/wit/deps/config/store.wit | 30 + sdks/python/wit/deps/config/world.wit | 6 + .../wit/deps/filesystem-0.2.6/filesystem.wit | 587 +++++++ .../python/wit/deps/filesystem/filesystem.wit | 575 +++++++ .../wit/deps/golem-1.x/golem-context.wit | 93 ++ sdks/python/wit/deps/golem-1.x/golem-host.wit | 289 ++++ .../deps/golem-1.x/golem-oplog-processor.wit | 27 + .../python/wit/deps/golem-1.x/golem-oplog.wit | 1359 +++++++++++++++++ .../python/wit/deps/golem-1.x/golem-retry.wit | 203 +++ sdks/python/wit/deps/golem-agent/common.wit | 272 ++++ .../wit/deps/golem-agent/durable-streams.wit | 112 ++ sdks/python/wit/deps/golem-agent/guest.wit | 40 + sdks/python/wit/deps/golem-agent/host.wit | 208 +++ .../deps/golem-agent/invocation-context.wit | 17 + .../wit/deps/golem-core-v2/golem-core-v2.wit | 713 +++++++++ sdks/python/wit/deps/golem-core-v2/http.wit | 83 + .../golem-durability/golem-durability.wit | 111 ++ sdks/python/wit/deps/golem-network/dns.wit | 121 ++ .../wit/deps/golem-permissions/derive.wit | 54 + .../wit/deps/golem-permissions/inspect.wit | 14 + .../kernel-introspection.wit | 20 + .../wit/deps/golem-permissions/revoke.wit | 15 + .../wit/deps/golem-permissions/types.wit | 98 ++ .../wit/deps/golem-permissions/wallet.wit | 29 + sdks/python/wit/deps/golem-quota/types.wit | 76 + sdks/python/wit/deps/golem-rdbms/ignite.wit | 84 + sdks/python/wit/deps/golem-rdbms/mysql.wit | 141 ++ sdks/python/wit/deps/golem-rdbms/postgres.wit | 296 ++++ sdks/python/wit/deps/golem-rdbms/types.wit | 47 + sdks/python/wit/deps/golem-rdbms/world.wit | 7 + sdks/python/wit/deps/golem-secrets/reveal.wit | 31 + sdks/python/wit/deps/golem-secrets/types.wit | 73 + sdks/python/wit/deps/golem-tool/common.wit | 415 +++++ sdks/python/wit/deps/golem-tool/guest.wit | 67 + sdks/python/wit/deps/golem-tool/host.wit | 154 ++ .../python/wit/deps/golem-tool/middleware.wit | 84 + sdks/python/wit/deps/golem-tool/streams.wit | 36 + .../wit/deps/golem-websocket/websocket.wit | 65 + sdks/python/wit/deps/http-0.2.6/http.wit | 733 +++++++++ sdks/python/wit/deps/http/http.wit | 509 ++++++ sdks/python/wit/deps/io-0.2.6/io.wit | 331 ++++ sdks/python/wit/deps/keyvalue/caching.wit | 87 ++ sdks/python/wit/deps/keyvalue/error.wit | 20 + .../wit/deps/keyvalue/eventual-batch.wit | 81 + sdks/python/wit/deps/keyvalue/eventual.wit | 56 + .../python/wit/deps/keyvalue/handle-watch.wit | 17 + sdks/python/wit/deps/keyvalue/types.wit | 67 + sdks/python/wit/deps/keyvalue/world.wit | 21 + sdks/python/wit/deps/logging/logging.wit | 37 + sdks/python/wit/deps/random-0.2.6/random.wit | 92 ++ sdks/python/wit/deps/random/random.wit | 107 ++ .../python/wit/deps/sockets-0.2.6/sockets.wit | 949 ++++++++++++ sdks/python/wit/deps/sockets/sockets.wit | 839 ++++++++++ sdks/python/wit/main.wit | 45 + 73 files changed, 12457 insertions(+) create mode 100644 golem-python-assembler/Cargo.toml create mode 100644 golem-python-assembler/src/lib.rs create mode 100644 golem-python-assembler/tests/assemble.rs create mode 100644 sdks/python/README.md create mode 100644 sdks/python/src/golem/__init__.py create mode 100644 sdks/python/src/golem/_bootstrap.py create mode 100644 sdks/python/src/golem/_guest.py create mode 100644 sdks/python/src/golem/_registry.py create mode 100644 sdks/python/wit/deps/blobstore/blobstore.wit create mode 100644 sdks/python/wit/deps/blobstore/container.wit create mode 100644 sdks/python/wit/deps/blobstore/types.wit create mode 100644 sdks/python/wit/deps/blobstore/world.wit create mode 100644 sdks/python/wit/deps/cli-0.2.6/cli.wit create mode 100644 sdks/python/wit/deps/cli/cli.wit create mode 100644 sdks/python/wit/deps/clocks-0.2.6/clocks.wit create mode 100644 sdks/python/wit/deps/clocks/clocks.wit create mode 100644 sdks/python/wit/deps/config/store.wit create mode 100644 sdks/python/wit/deps/config/world.wit create mode 100644 sdks/python/wit/deps/filesystem-0.2.6/filesystem.wit create mode 100644 sdks/python/wit/deps/filesystem/filesystem.wit create mode 100644 sdks/python/wit/deps/golem-1.x/golem-context.wit create mode 100644 sdks/python/wit/deps/golem-1.x/golem-host.wit create mode 100644 sdks/python/wit/deps/golem-1.x/golem-oplog-processor.wit create mode 100644 sdks/python/wit/deps/golem-1.x/golem-oplog.wit create mode 100644 sdks/python/wit/deps/golem-1.x/golem-retry.wit create mode 100644 sdks/python/wit/deps/golem-agent/common.wit create mode 100644 sdks/python/wit/deps/golem-agent/durable-streams.wit create mode 100644 sdks/python/wit/deps/golem-agent/guest.wit create mode 100644 sdks/python/wit/deps/golem-agent/host.wit create mode 100644 sdks/python/wit/deps/golem-agent/invocation-context.wit create mode 100644 sdks/python/wit/deps/golem-core-v2/golem-core-v2.wit create mode 100644 sdks/python/wit/deps/golem-core-v2/http.wit create mode 100644 sdks/python/wit/deps/golem-durability/golem-durability.wit create mode 100644 sdks/python/wit/deps/golem-network/dns.wit create mode 100644 sdks/python/wit/deps/golem-permissions/derive.wit create mode 100644 sdks/python/wit/deps/golem-permissions/inspect.wit create mode 100644 sdks/python/wit/deps/golem-permissions/kernel-introspection.wit create mode 100644 sdks/python/wit/deps/golem-permissions/revoke.wit create mode 100644 sdks/python/wit/deps/golem-permissions/types.wit create mode 100644 sdks/python/wit/deps/golem-permissions/wallet.wit create mode 100644 sdks/python/wit/deps/golem-quota/types.wit create mode 100644 sdks/python/wit/deps/golem-rdbms/ignite.wit create mode 100644 sdks/python/wit/deps/golem-rdbms/mysql.wit create mode 100644 sdks/python/wit/deps/golem-rdbms/postgres.wit create mode 100644 sdks/python/wit/deps/golem-rdbms/types.wit create mode 100644 sdks/python/wit/deps/golem-rdbms/world.wit create mode 100644 sdks/python/wit/deps/golem-secrets/reveal.wit create mode 100644 sdks/python/wit/deps/golem-secrets/types.wit create mode 100644 sdks/python/wit/deps/golem-tool/common.wit create mode 100644 sdks/python/wit/deps/golem-tool/guest.wit create mode 100644 sdks/python/wit/deps/golem-tool/host.wit create mode 100644 sdks/python/wit/deps/golem-tool/middleware.wit create mode 100644 sdks/python/wit/deps/golem-tool/streams.wit create mode 100644 sdks/python/wit/deps/golem-websocket/websocket.wit create mode 100644 sdks/python/wit/deps/http-0.2.6/http.wit create mode 100644 sdks/python/wit/deps/http/http.wit create mode 100644 sdks/python/wit/deps/io-0.2.6/io.wit create mode 100644 sdks/python/wit/deps/keyvalue/caching.wit create mode 100644 sdks/python/wit/deps/keyvalue/error.wit create mode 100644 sdks/python/wit/deps/keyvalue/eventual-batch.wit create mode 100644 sdks/python/wit/deps/keyvalue/eventual.wit create mode 100644 sdks/python/wit/deps/keyvalue/handle-watch.wit create mode 100644 sdks/python/wit/deps/keyvalue/types.wit create mode 100644 sdks/python/wit/deps/keyvalue/world.wit create mode 100644 sdks/python/wit/deps/logging/logging.wit create mode 100644 sdks/python/wit/deps/random-0.2.6/random.wit create mode 100644 sdks/python/wit/deps/random/random.wit create mode 100644 sdks/python/wit/deps/sockets-0.2.6/sockets.wit create mode 100644 sdks/python/wit/deps/sockets/sockets.wit create mode 100644 sdks/python/wit/main.wit diff --git a/Cargo.lock b/Cargo.lock index 6f1eb31433..ea8aef3775 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -110,6 +110,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -1439,6 +1454,27 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bs58" version = "0.5.1" @@ -1902,15 +1938,72 @@ dependencies = [ "unicode-width 0.2.2", ] +[[package]] +name = "component-init-transform" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3e4bafc7af4899d058acd5568dc6105bd3e46f42b5650d38453a264e8f1db38" +dependencies = [ + "anyhow", + "async-trait", + "futures", + "wasm-encoder 0.257.1", + "wasm-metadata 0.257.1", + "wasmparser 0.257.1", +] + +[[package]] +name = "componentize-py" +version = "0.25.0" +source = "git+https://github.com/golemcloud/componentize-py?rev=189e903b00ca43500f95e2d32eaf44496a7a3640#189e903b00ca43500f95e2d32eaf44496a7a3640" +dependencies = [ + "anyhow", + "async-trait", + "bytes", + "component-init-transform", + "componentize-py-test-generator", + "filetime", + "flate2", + "futures", + "hex", + "indexmap 2.14.0", + "reqwest 0.12.28", + "serde", + "serde_json", + "sha2 0.10.9", + "tar", + "tempfile", + "toml 0.8.23", + "wasm-encoder 0.258.3", + "wasmparser 0.258.3", + "wasmtime", + "wit-component 0.258.3", + "zstd", +] + +[[package]] +name = "componentize-py-test-generator" +version = "0.25.0" +source = "git+https://github.com/golemcloud/componentize-py?rev=189e903b00ca43500f95e2d32eaf44496a7a3640#189e903b00ca43500f95e2d32eaf44496a7a3640" +dependencies = [ + "anyhow", + "getrandom 0.2.17", + "hex", + "proptest", +] + [[package]] name = "compression-codecs" version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf" dependencies = [ + "brotli", "compression-core", "flate2", "memchr", + "zstd", + "zstd-safe", ] [[package]] @@ -4442,6 +4535,20 @@ dependencies = [ "tokio", ] +[[package]] +name = "golem-python-assembler" +version = "0.0.0" +dependencies = [ + "anyhow", + "componentize-py", + "golem-common", + "tempfile", + "test-r", + "tokio", + "wasmtime", + "wasmtime-wasi", +] + [[package]] name = "golem-registry-service" version = "0.0.0" @@ -9149,7 +9256,9 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", + "futures-channel", "futures-core", + "futures-util", "http 1.5.0", "http-body 1.1.0", "http-body-util", @@ -12377,6 +12486,26 @@ dependencies = [ "wasmparser 0.251.0", ] +[[package]] +name = "wasm-encoder" +version = "0.257.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8ad9f0a39050867bda22e6486c316e2e52d20a42154d5bc433934bf738d085" +dependencies = [ + "leb128fmt", + "wasmparser 0.257.1", +] + +[[package]] +name = "wasm-encoder" +version = "0.258.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f64765e43c000fae008a48db8b288e175e237fc9ce20a26586836878c1bee89f" +dependencies = [ + "leb128fmt", + "wasmparser 0.258.3", +] + [[package]] name = "wasm-encoder" version = "0.261.0" @@ -12416,6 +12545,37 @@ dependencies = [ "wasmparser 0.251.0", ] +[[package]] +name = "wasm-metadata" +version = "0.257.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57460ad9bce753e8a80d47a445cb87c8724ea57f463d9c906a947c41032ce1ac" +dependencies = [ + "anyhow", + "auditable-serde", + "flate2", + "indexmap 2.14.0", + "serde", + "serde_derive", + "serde_json", + "spdx", + "url", + "wasm-encoder 0.257.1", + "wasmparser 0.257.1", +] + +[[package]] +name = "wasm-metadata" +version = "0.258.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e10808eb27efde692f1b1706089fe19296728bf872291f5b4e0d50fba88f2f" +dependencies = [ + "anyhow", + "indexmap 2.14.0", + "wasm-encoder 0.258.3", + "wasmparser 0.258.3", +] + [[package]] name = "wasm-metadata" version = "0.261.0" @@ -12539,6 +12699,32 @@ dependencies = [ "serde", ] +[[package]] +name = "wasmparser" +version = "0.257.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92fc335fb6d48f46bda1d8b26b69e28320c15ac3272208333833d6e217e2b4a" +dependencies = [ + "bitflags 2.13.1", + "hashbrown 0.17.1", + "indexmap 2.14.0", + "semver", + "serde", +] + +[[package]] +name = "wasmparser" +version = "0.258.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe9269dd817e0e7021bf534ccd9761bc2d64778b6708e41228b8439d75eaa0b1" +dependencies = [ + "bitflags 2.13.1", + "hashbrown 0.17.1", + "indexmap 2.14.0", + "semver", + "serde", +] + [[package]] name = "wasmparser" version = "0.261.0" @@ -13581,6 +13767,24 @@ dependencies = [ "wit-parser 0.251.0", ] +[[package]] +name = "wit-component" +version = "0.258.3" +source = "git+https://github.com/golemcloud/componentize-py?rev=189e903b00ca43500f95e2d32eaf44496a7a3640#189e903b00ca43500f95e2d32eaf44496a7a3640" +dependencies = [ + "anyhow", + "bitflags 2.13.1", + "indexmap 2.14.0", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder 0.258.3", + "wasm-metadata 0.258.3", + "wasmparser 0.258.3", + "wit-parser 0.258.3", +] + [[package]] name = "wit-component" version = "0.261.0" @@ -13651,6 +13855,25 @@ dependencies = [ "wasmparser 0.251.0", ] +[[package]] +name = "wit-parser" +version = "0.258.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a2127663dcf3ee16614fb0e3c33d5c6c66fec9dad317a8b0fdd3869487a533" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "id-arena", + "indexmap 2.14.0", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser 0.258.3", +] + [[package]] name = "wit-parser" version = "0.261.0" diff --git a/Cargo.toml b/Cargo.toml index 90935d7136..552bef81c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ members = [ "cli/golem", "cli/golem-cli", "golem-openapi-client-generator", + "golem-python-assembler", ] exclude = [ @@ -47,6 +48,7 @@ print_stderr = "deny" license-file = "LICENSE" [workspace.dependencies] +componentize-py = { git = "https://github.com/golemcloud/componentize-py", rev = "189e903b00ca43500f95e2d32eaf44496a7a3640", default-features = false } golem-api-grpc = { version = "=0.0.0", path = "golem-api-grpc" } golem-cli = { version = "=0.0.0", path = "cli/golem-cli" } golem-client = { version = "=0.0.0", path = "golem-client" } @@ -374,6 +376,8 @@ wasmtime = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem wasmtime-wasi = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } wasmtime-wasi-http = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } wasmtime-wizer = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } +# wit-component 0.258.3 with the dlopen symbol-table fix that componentize-py links with. +wit-component = { git = "https://github.com/golemcloud/componentize-py", rev = "189e903b00ca43500f95e2d32eaf44496a7a3640" } # The head of the branch `golem-rustic_core-v0.13.0` of the fork. rustic_core = { git = "https://github.com/golemcloud/rustic_core", rev = "2269cbb0b2b89dc55cd4dca0172ead894b7b43fd" } diff --git a/Makefile.toml b/Makefile.toml index 1c72ee7859..cd6079dcfd 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -132,6 +132,7 @@ args = [ "--src", "wit/deps", "--dst", "sdks/scala/wit/deps", "--src", "wit/deps", "--dst", "sdks/moonbit/golem_sdk/wit/deps", "--src", "wit/deps", "--dst", "sdks/go/golem/wit/deps", + "--src", "wit/deps", "--dst", "sdks/python/wit/deps", ] [tasks.wit-golem-cli] @@ -3316,3 +3317,18 @@ if ${failed} trigger_error "Cleanup finished with failures; see the errors above" end ''' + +# Prepares the Python SDK's runtime and bindings for `golem-python-assembler`. +# Installs componentize-py from the fork revision that the workspace's +# `componentize-py` dependency pins; keep the two revisions equal. Building it +# compiles CPython for WASI and needs `WASI_SDK_PATH`. +[tasks.python-sdk-prepare] +description = "Prepares the Python SDK runtime and bindings in sdks/python/target/prepared" +script_runner = "@duckscript" +script = ''' +rev = set 189e903b00ca43500f95e2d32eaf44496a7a3640 +tools = set sdks/python/target/tools +exec --fail-on-error cargo install --locked --git https://github.com/golemcloud/componentize-py --rev ${rev} --root ${tools} componentize-py +rm -r sdks/python/target/prepared +exec --fail-on-error ${tools}/bin/componentize-py -d sdks/python/wit -w agent-guest prepare sdks/python/target/prepared +''' diff --git a/golem-python-assembler/Cargo.toml b/golem-python-assembler/Cargo.toml new file mode 100644 index 0000000000..162dc6fdc3 --- /dev/null +++ b/golem-python-assembler/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "golem-python-assembler" +version = "0.0.0" +edition = "2024" +license = "Apache-2.0" +homepage = "https://golem.cloud" +repository = "https://github.com/golemcloud/golem" +description = "Builds Golem components from prepared Python assets" + +[lib] +harness = false + +[dependencies] +anyhow = { workspace = true } +componentize-py = { workspace = true } +golem-common = { workspace = true, default-features = true } +wasmtime = { workspace = true } +wasmtime-wasi = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } +test-r = { workspace = true } +tokio = { workspace = true } + +[[test]] +name = "assemble" +harness = false diff --git a/golem-python-assembler/src/lib.rs b/golem-python-assembler/src/lib.rs new file mode 100644 index 0000000000..75357a8e68 --- /dev/null +++ b/golem-python-assembler/src/lib.rs @@ -0,0 +1,218 @@ +//! Builds Golem components from prepared Python assets. +//! +//! The prepared assets carry the CPython runtime and the bindings for the +//! Python SDK's WIT world; see `componentize_py::prepared`. An application +//! build links them with the SDK sources and the application sources, then +//! pre-initializes the result on Golem's shared Wasmtime engine. The build +//! does not process WIT, generate code or compile CPython. + +use std::{ + path::Path, + sync::atomic::{AtomicU64, Ordering}, + time::Duration, +}; + +use anyhow::{Context, Result, ensure}; +use componentize_py::prepared::{Assembler, Prepared}; +use wasmtime::{ + Engine, Store, + component::{Linker, ResourceTable}, +}; +use wasmtime_wasi::{ + Deterministic, FsPerms, IoCtx, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, + p2::pipe::MemoryOutputPipe, +}; + +#[cfg(test)] +test_r::enable!(); + +/// The SDK module that pre-initialization imports. +pub const BOOTSTRAP_MODULE: &str = "golem._bootstrap"; + +/// The environment variable that passes the entry modules to the bootstrap. +pub const ENTRY_MODULES_VAR: &str = "GOLEM_PYTHON_ENTRY_MODULES"; + +/// The size of the linear-memory C stack. +/// +/// CPython raises `RecursionError` when this stack is nearly full, but it does +/// not see the engine's call stack, which the shared engine limits to 1 MiB. +/// With 96 KiB, deep `repr`, `json`, `pickle` and `__repr__` recursion raises +/// `RecursionError` instead of exhausting the engine's call stack. +pub const STACK_SIZE: u32 = 96 * 1024; + +/// The capacity of each of the stdout and stderr buffers of +/// pre-initialization. Writing more fails the build. +pub const OUTPUT_CAPACITY: usize = 64 * 1024; + +/// The guest mount names of the SDK and the application sources. +const SDK_MOUNT: &str = "sdk"; +const APP_MOUNT: &str = "app"; + +/// An application to build. +pub struct Application<'a> { + /// The directory that contains the SDK's `golem` package. + pub sdk_dir: &'a Path, + /// The directory that contains the application's modules. + pub source_dir: &'a Path, + /// The modules that declare the application's agents, imported in order. + pub entry_modules: &'a [&'a str], +} + +struct Host { + ctx: WasiCtx, + io: IoCtx, + table: ResourceTable, +} + +impl WasiView for Host { + fn ctx(&mut self) -> WasiCtxView<'_> { + WasiCtxView { + ctx: &mut self.ctx, + table: &mut self.table, + io_ctx: &mut self.io, + } + } +} + +/// The clock seen during pre-initialization. It starts at the Unix epoch and +/// advances one microsecond each time it is read, so nothing the application +/// saves depends on when it was built. +#[derive(Default)] +struct BuildClock(AtomicU64); + +impl BuildClock { + fn tick(&self) -> u64 { + self.0.fetch_add(1000, Ordering::Relaxed) + } +} + +impl wasmtime_wasi::HostWallClock for BuildClock { + fn resolution(&self) -> Duration { + Duration::from_micros(1) + } + + fn now(&self) -> Duration { + Duration::from_nanos(self.tick()) + } +} + +impl wasmtime_wasi::HostMonotonicClock for BuildClock { + fn resolution(&self) -> u64 { + 1000 + } + + fn now(&self) -> u64 { + self.tick() + } +} + +fn validate_entry_module(module: &str) -> Result<()> { + ensure!( + !module.is_empty() + && module.split('.').all(|part| { + let mut chars = part.chars(); + chars + .next() + .is_some_and(|c| c == '_' || c.is_ascii_alphabetic()) + && chars.all(|c| c == '_' || c.is_ascii_alphanumeric()) + }), + "`{module}` is not a Python module name" + ); + Ok(()) +} + +/// Reads and verifies prepared assets. +pub fn read_prepared(dir: &Path) -> Result { + Prepared::read(dir) +} + +/// Builds the component for `app` and returns its bytes. +/// +/// Fails before any application code runs when the entry modules are invalid. +/// An exception that an entry module raises during import fails the build, +/// and the error contains its traceback and the output of pre-initialization. +pub async fn build(prepared: &Prepared, app: &Application<'_>) -> Result> { + ensure!( + !app.entry_modules.is_empty(), + "the application has no entry modules" + ); + for module in app.entry_modules { + validate_entry_module(module)?; + } + + let python_path = [(SDK_MOUNT, app.sdk_dir), (APP_MOUNT, app.source_dir)]; + let assembly = Assembler { + prepared, + app_name: BOOTSTRAP_MODULE, + python_path: &python_path, + stack_size: Some(STACK_SIZE), + } + .assemble()?; + + let plan = &assembly.plan; + let stdout = MemoryOutputPipe::new(OUTPUT_CAPACITY); + let stderr = MemoryOutputPipe::new(OUTPUT_CAPACITY); + let mut wasi = WasiCtxBuilder::new(); + wasi.stdout(stdout.clone()).stderr(stderr.clone()); + wasi.secure_random(Deterministic::new(plan.entropy.random_bytes.clone())) + .insecure_random(Deterministic::new(plan.entropy.random_bytes.clone())) + .insecure_random_seed(plan.entropy.insecure_seed) + .wall_clock(BuildClock::default()) + .monotonic_clock(BuildClock::default()) + .env(ENTRY_MODULES_VAR, app.entry_modules.join(",")); + for (key, value) in &plan.env { + wasi.env(key, value); + } + for preopen in &plan.preopens { + wasi.preopened_dir(&preopen.host, &preopen.guest, FsPerms::ReadWrite) + .map_err(|error| { + anyhow::Error::from(error).context(preopen.host.display().to_string()) + })?; + } + let (ctx, io) = wasi.build(); + + let engine = + Engine::new(&golem_common::wasmtime_config::create_wasmtime_config_without_fs_cache())?; + let mut linker = Linker::::new(&engine); + wasmtime_wasi::p2::add_to_linker_async(&mut linker)?; + componentize_py::add_trapping_stubs(&mut linker, &plan.stubs)?; + + let mut store = Store::new( + &engine, + Host { + ctx, + io, + table: ResourceTable::new(), + }, + ); + // The shared engine meters fuel and interrupts on epochs; initialization + // runs to completion. + store.set_fuel(u64::MAX)?; + store.set_epoch_deadline(u64::MAX); + + // The runtime prints the traceback of an exception that fails + // initialization to stderr; the error itself names only the exception. + assembly.initialize(store, linker).await.with_context(|| { + format!( + "Python pre-initialization failed\n{}{}", + String::from_utf8_lossy(&stdout.contents()), + String::from_utf8_lossy(&stderr.contents()) + ) + }) +} + +#[cfg(test)] +mod tests { + use super::validate_entry_module; + use test_r::test; + + #[test] + fn entry_module_names() { + for valid in ["app", "my_app.agents", "_private", "a1.b2"] { + assert!(validate_entry_module(valid).is_ok(), "{valid}"); + } + for invalid in ["", "1app", "app.", ".app", "a,b", "a-b", "a..b", "รค"] { + assert!(validate_entry_module(invalid).is_err(), "{invalid}"); + } + } +} diff --git a/golem-python-assembler/tests/assemble.rs b/golem-python-assembler/tests/assemble.rs new file mode 100644 index 0000000000..9809e3d408 --- /dev/null +++ b/golem-python-assembler/tests/assemble.rs @@ -0,0 +1,192 @@ +//! Builds Python applications from the prepared SDK assets and runs them on +//! the shared engine. +//! +//! The prepared assets are a build output; `cargo make python-sdk-prepare` +//! writes them to `sdks/python/target/prepared`. + +use std::{fs, path::PathBuf}; + +use anyhow::{Context, Result}; +use golem_python_assembler::{Application, build, read_prepared}; +use test_r::test; +use wasmtime::{ + Engine, Store, + component::{Component, Linker, ResourceTable, Val}, +}; +use wasmtime_wasi::{IoCtx, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView}; + +test_r::enable!(); + +struct Host { + ctx: WasiCtx, + io: IoCtx, + table: ResourceTable, +} + +impl WasiView for Host { + fn ctx(&mut self) -> WasiCtxView<'_> { + WasiCtxView { + ctx: &mut self.ctx, + table: &mut self.table, + io_ctx: &mut self.io, + } + } +} + +fn python_sdk() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../sdks/python") +} + +fn prepared() -> Result { + let dir = python_sdk().join("target/prepared"); + read_prepared(&dir).with_context(|| { + format!( + "run `cargo make python-sdk-prepare` to write the prepared assets to {}", + dir.display() + ) + }) +} + +fn write_app(dir: &std::path::Path, module: &str, source: &str) -> Result<()> { + fs::write(dir.join(format!("{module}.py")), source)?; + Ok(()) +} + +async fn discover_agent_types(component: &[u8]) -> Result { + let engine = + Engine::new(&golem_common::wasmtime_config::create_wasmtime_config_without_fs_cache())?; + let component = Component::new(&engine, component)?; + let mut linker = Linker::::new(&engine); + wasmtime_wasi::p2::add_to_linker_async(&mut linker)?; + linker.define_unknown_imports_as_traps(&component)?; + let (ctx, io) = WasiCtxBuilder::new().build(); + let mut store = Store::new( + &engine, + Host { + ctx, + io, + table: ResourceTable::new(), + }, + ); + store.set_fuel(u64::MAX)?; + store.set_epoch_deadline(u64::MAX); + let instance = linker.instantiate_async(&mut store, &component).await?; + let guest = instance + .get_export_index(&mut store, None, "golem:agent/guest@2.0.0") + .context("guest export")?; + let discover = instance + .get_export_index(&mut store, Some(&guest), "discover-agent-types") + .context("discover-agent-types export")?; + let func = instance + .get_func(&mut store, discover) + .context("discover-agent-types function")?; + let mut results = [Val::Bool(false)]; + func.call_async(&mut store, &[], &mut results).await?; + Ok(results[0].clone()) +} + +#[test] +async fn builds_unrelated_apps_from_the_same_prepared_assets() -> Result<()> { + let prepared = prepared()?; + let sdk = python_sdk().join("src"); + + for (module, source) in [ + ("first_app", "VALUE = 1\n"), + ( + "second_app", + "import json\n\nVALUE = json.dumps({'a': [1, 2]})\n", + ), + ] { + let dir = tempfile::tempdir()?; + write_app(dir.path(), module, source)?; + let component = build( + &prepared, + &Application { + sdk_dir: &sdk, + source_dir: dir.path(), + entry_modules: &[module], + }, + ) + .await?; + + assert_eq!( + discover_agent_types(&component).await?, + Val::Result(Ok(Some(Box::new(Val::List(vec![]))))), + "{module} declares no agents" + ); + } + Ok(()) +} + +#[test] +async fn import_errors_keep_the_original_traceback() -> Result<()> { + let prepared = prepared()?; + let dir = tempfile::tempdir()?; + write_app( + dir.path(), + "broken", + "def load():\n raise ValueError('cannot load settings')\n\nload()\n", + )?; + + let error = build( + &prepared, + &Application { + sdk_dir: &python_sdk().join("src"), + source_dir: dir.path(), + entry_modules: &["broken"], + }, + ) + .await + .expect_err("an entry module that raises fails the build"); + + let message = format!("{error:#}"); + assert!( + message.contains("ValueError: cannot load settings"), + "{message}" + ); + assert!( + message.contains("broken.py\", line 2, in load"), + "{message}" + ); + Ok(()) +} + +#[test] +async fn invalid_entry_modules_fail_before_imports() -> Result<()> { + let prepared = prepared()?; + let dir = tempfile::tempdir()?; + // Importing `marker` writes a file into the application directory. + write_app(dir.path(), "marker", "open('/app/imported', 'w').close()\n")?; + let sdk = python_sdk().join("src"); + + let error = build( + &prepared, + &Application { + sdk_dir: &sdk, + source_dir: dir.path(), + entry_modules: &["marker", "not a module"], + }, + ) + .await + .expect_err("an invalid entry module fails the build"); + assert!( + format!("{error:#}").contains("`not a module` is not a Python module name"), + "{error:#}" + ); + assert!(!dir.path().join("imported").exists()); + + build( + &prepared, + &Application { + sdk_dir: &sdk, + source_dir: dir.path(), + entry_modules: &["marker"], + }, + ) + .await?; + assert!( + dir.path().join("imported").exists(), + "a valid build imports the entry module" + ); + Ok(()) +} diff --git a/sdks/python/README.md b/sdks/python/README.md new file mode 100644 index 0000000000..da02064c47 --- /dev/null +++ b/sdks/python/README.md @@ -0,0 +1,41 @@ +# Golem Python SDK + +Work in progress. This directory holds the Python SDK and the inputs of its +prepared runtime: + +- `wit/main.wit`: the guest world, `golem:python/agent-guest`. `wit/deps` is a + mirror of the top-level `wit/deps` (`cargo make wit`). +- `src/golem`: the `golem` package. `golem._bootstrap` is the module that + pre-initialization imports. It registers the component's exports, imports + the application's entry modules and finalizes the agent registry. + Discovery constructs no agents. + +## Prepared assets + +`cargo make python-sdk-prepare` installs componentize-py from the +[golemcloud fork](https://github.com/golemcloud/componentize-py) at the +revision that the workspace pins. It then prepares the runtime and bindings for +`wit/main.wit` in `target/prepared`. Building componentize-py compiles CPython +3.14.10 for WASI and needs `WASI_SDK_PATH`. + +`golem-python-assembler` links the prepared assets with the SDK and an +application and pre-initializes the result on Golem's shared Wasmtime engine. +It does not process WIT, generate bindings or compile CPython. Its tests read +`target/prepared`: + +```shell +cargo make python-sdk-prepare +cargo test -p golem-python-assembler +``` + +## Current limits + +- Applications declare no agents yet. Discovery returns an empty list. +- Third-party packages and native extensions in applications are not + supported. +- Pre-initialization output is limited to 64 KiB each for stdout and stderr. + More output fails the build. +- The C stack is 96 KiB. Deep recursion in `repr`, `json`, `pickle` and + `__repr__` raises `RecursionError` at a lower depth than in native CPython. +- Two builds of the same input can differ in a few bytes. The difference + comes from host file metadata that pre-initialization records. diff --git a/sdks/python/src/golem/__init__.py b/sdks/python/src/golem/__init__.py new file mode 100644 index 0000000000..64a830b706 --- /dev/null +++ b/sdks/python/src/golem/__init__.py @@ -0,0 +1 @@ +"""The Golem Python SDK.""" diff --git a/sdks/python/src/golem/_bootstrap.py b/sdks/python/src/golem/_bootstrap.py new file mode 100644 index 0000000000..f9dffe7946 --- /dev/null +++ b/sdks/python/src/golem/_bootstrap.py @@ -0,0 +1,20 @@ +"""The module that pre-initialization imports. + +The assembler passes the application's entry modules, in order, in the +`GOLEM_PYTHON_ENTRY_MODULES` environment variable, separated by commas. The +bootstrap registers the component's exports, imports each entry module, +finalizes the agent registry and removes the variable, so that the saved +component does not keep it. +""" + +import importlib +import os + +from golem import _guest, _registry # noqa: F401 (registers the exports) + +_ENTRY_MODULES = "GOLEM_PYTHON_ENTRY_MODULES" + +for _module in os.environ.pop(_ENTRY_MODULES).split(","): + importlib.import_module(_module) + +_registry.finalize() diff --git a/sdks/python/src/golem/_guest.py b/sdks/python/src/golem/_guest.py new file mode 100644 index 0000000000..20059d1faa --- /dev/null +++ b/sdks/python/src/golem/_guest.py @@ -0,0 +1,61 @@ +"""Implementations of the component's exports. + +Importing this module registers them; the bootstrap imports it before the +application's entry modules. +""" + +from componentize_py_types import Err +from wit.exports.golem.agent_v2 import Guest as AgentGuest +from wit.exports.golem.agent_v2.guest import guest as agent_guest +from wit.exports.golem.tool_v0_1 import Guest as ToolGuest, ToolMiddlewareGuest +from wit.exports.golem.tool_v0_1.guest import guest as tool_guest +from wit.exports.golem.tool_v0_1.tool_middleware_guest import ( + guest as tool_middleware_guest, +) +from wit.imports.golem.agent_v2.common import AgentError_InvalidType +from wit.imports.golem.core_v2.types import ToolError_InvalidToolName + +from golem import _registry + + +def _unknown_agent_type(name: str) -> Err: + return Err(AgentError_InvalidType(f"this component defines no agent type `{name}`")) + + +@agent_guest +class Agent(AgentGuest): + async def initialize(self, agent_type, input): + raise _unknown_agent_type(agent_type) + + async def invoke(self, method_name, input): + raise Err(AgentError_InvalidType("the agent is not initialized")) + + def get_definition(self): + raise RuntimeError("the agent is not initialized") + + def discover_agent_types(self): + return _registry.agent_types() + + +@tool_guest +class Tools(ToolGuest): + def discover_tools(self): + return [] + + def get_tool(self, name): + raise Err(ToolError_InvalidToolName(name)) + + async def invoke(self, tool_name, command_path, input, stdin): + raise Err(ToolError_InvalidToolName(tool_name)) + + +@tool_middleware_guest +class ToolMiddleware(ToolMiddlewareGuest): + def discover_tool_middlewares(self): + return [] + + def get_tool_middleware(self, name): + raise Err(ToolError_InvalidToolName(name)) + + async def invoke_tool_middleware(self, middleware_name, *args): + raise Err(ToolError_InvalidToolName(middleware_name)) diff --git a/sdks/python/src/golem/_registry.py b/sdks/python/src/golem/_registry.py new file mode 100644 index 0000000000..a7577e18e8 --- /dev/null +++ b/sdks/python/src/golem/_registry.py @@ -0,0 +1,21 @@ +"""Agent types that the application's entry modules declare. + +The bootstrap finalizes the registry once, after it imports every entry +module and before pre-initialization saves the component. Discovery reads +the finalized registry; it constructs no agents. +""" + +_finalized = False + + +def finalize() -> None: + global _finalized + if _finalized: + raise RuntimeError("the agent registry is already finalized") + _finalized = True + + +def agent_types() -> list: + if not _finalized: + raise RuntimeError("the agent registry is not finalized") + return [] diff --git a/sdks/python/wit/deps/blobstore/blobstore.wit b/sdks/python/wit/deps/blobstore/blobstore.wit new file mode 100644 index 0000000000..cc52516a57 --- /dev/null +++ b/sdks/python/wit/deps/blobstore/blobstore.wit @@ -0,0 +1,29 @@ +package wasi:blobstore; + +// wasi-cloud Blobstore service definition +interface blobstore { + use container.{container}; + use types.{error, container-name, object-id}; + + // creates a new empty container + create-container: func(name: container-name) -> result; + + // retrieves a container by name + get-container: func(name: container-name) -> result; + + // deletes a container and all objects within it + delete-container: func(name: container-name) -> result<_, error>; + + // returns true if the container exists + container-exists: func(name: container-name) -> result; + + // copies (duplicates) an object, to the same or a different container. + // returns an error if the target container does not exist. + // overwrites destination object if it already existed. + copy-object: func(src: object-id, dest: object-id) -> result<_, error>; + + // moves or renames an object, to the same or a different container + // returns an error if the destination container does not exist. + // overwrites destination object if it already existed. + move-object: func(src:object-id, dest: object-id) -> result<_, error>; +} \ No newline at end of file diff --git a/sdks/python/wit/deps/blobstore/container.wit b/sdks/python/wit/deps/blobstore/container.wit new file mode 100644 index 0000000000..a814738526 --- /dev/null +++ b/sdks/python/wit/deps/blobstore/container.wit @@ -0,0 +1,51 @@ +package wasi:blobstore; + +// a Container is a collection of objects +interface container { + use types.{ + container-metadata, + error, + incoming-value, + object-metadata, + object-name, + outgoing-value, + }; + + // this defines the `container` resource + resource container { + // returns container name + name: func() -> result; + + // returns container metadata + info: func() -> result; + + // retrieves an object or portion of an object, as a resource. + // Start and end offsets are inclusive. + // Once a data-blob resource has been created, the underlying bytes are held by the blobstore service for the lifetime + // of the data-blob resource, even if the object they came from is later deleted. + get-data: func(name: object-name, start: u64, end: u64) -> result; + + // creates or replaces an object with the data blob. + write-data: func(name: object-name, data: borrow) -> result<_, error>; + + // returns list of objects in the container. Order is undefined. + list-objects: func() -> result, error>; + + // deletes object. + // does not return error if object did not exist. + delete-object: func(name: object-name) -> result<_, error>; + + // deletes multiple objects in the container + delete-objects: func(names: list) -> result<_, error>; + + // returns true if the object exists in this container + has-object: func(name: object-name) -> result; + + // returns metadata for the object + object-info: func(name: object-name) -> result; + + // removes all objects within the container, leaving the container empty. + clear: func() -> result<_, error>; + } + +} diff --git a/sdks/python/wit/deps/blobstore/types.wit b/sdks/python/wit/deps/blobstore/types.wit new file mode 100644 index 0000000000..66454f8f9c --- /dev/null +++ b/sdks/python/wit/deps/blobstore/types.wit @@ -0,0 +1,70 @@ +package wasi:blobstore; + +// Types used by blobstore +interface types { + // name of a container, a collection of objects. + // The container name may be any valid UTF-8 string. + type container-name = string; + + // name of an object within a container + // The object name may be any valid UTF-8 string. + type object-name = string; + + // TODO: define timestamp to include seconds since + // Unix epoch and nanoseconds + // https://github.com/WebAssembly/wasi-blob-store/issues/7 + type timestamp = u64; + + // size of an object, in bytes + type object-size = u64; + + type error = string; + + // information about a container + record container-metadata { + // the container's name + name: container-name, + // date and time container was created + created-at: timestamp, + } + + // information about an object + record object-metadata { + // the object's name + name: object-name, + // the object's parent container + container: container-name, + // date and time the object was created + created-at: timestamp, + // size of the object, in bytes + size: object-size, + } + + // identifier for an object that includes its container name + record object-id { + container: container-name, + object: object-name + } + + /// A data blob value. The value can be of any type that can be represented + /// in a byte array. + // Soon: switch to `resource value { ... }` + resource outgoing-value { + new-outgoing-value: static func() -> outgoing-value; + outgoing-value-write-body: func(data: stream) -> result; + } + + /// A incoming-value is a wrapper around a value. + /// + /// The incoming-value provides two ways to consume the value: + /// 1. `incoming-value-consume-sync` consumes the value synchronously and returns the + /// value as a list of bytes. + /// 2. `incoming-value-consume-async` consumes the value asynchronously and returns the + /// value as a `stream`. + // Soon: switch to `resource incoming-value { ... }` + resource incoming-value { + incoming-value-consume-sync: func() -> result, error>; + incoming-value-consume-async: func() -> result, error>; + size: func() -> u64; + } +} diff --git a/sdks/python/wit/deps/blobstore/world.wit b/sdks/python/wit/deps/blobstore/world.wit new file mode 100644 index 0000000000..4391d68b87 --- /dev/null +++ b/sdks/python/wit/deps/blobstore/world.wit @@ -0,0 +1,5 @@ +package wasi:blobstore; + +world blob-store { + import blobstore; +} \ No newline at end of file diff --git a/sdks/python/wit/deps/cli-0.2.6/cli.wit b/sdks/python/wit/deps/cli-0.2.6/cli.wit new file mode 100644 index 0000000000..d7a3ca4d2c --- /dev/null +++ b/sdks/python/wit/deps/cli-0.2.6/cli.wit @@ -0,0 +1,261 @@ +package wasi:cli@0.2.6; + +@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; +} + +@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); +} + +@since(version = 0.2.0) +interface run { + /// Run the program. + @since(version = 0.2.0) + run: func() -> result; +} + +@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; +} + +/// 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; +} + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import wasi:io/error@0.2.6; + @since(version = 0.2.0) + import wasi:io/poll@0.2.6; + @since(version = 0.2.0) + import wasi:io/streams@0.2.6; + @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; + @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; + @unstable(feature = clocks-timezone) + import wasi:clocks/timezone@0.2.6; + @since(version = 0.2.0) + import wasi:filesystem/types@0.2.6; + @since(version = 0.2.0) + import wasi:filesystem/preopens@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/network@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/instance-network@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/udp@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/udp-create-socket@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/tcp@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/tcp-create-socket@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/ip-name-lookup@0.2.6; + @since(version = 0.2.0) + import wasi:random/random@0.2.6; + @since(version = 0.2.0) + import wasi:random/insecure@0.2.6; + @since(version = 0.2.0) + import wasi:random/insecure-seed@0.2.6; +} +@since(version = 0.2.0) +world command { + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import wasi:io/error@0.2.6; + @since(version = 0.2.0) + import wasi:io/poll@0.2.6; + @since(version = 0.2.0) + import wasi:io/streams@0.2.6; + @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; + @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; + @unstable(feature = clocks-timezone) + import wasi:clocks/timezone@0.2.6; + @since(version = 0.2.0) + import wasi:filesystem/types@0.2.6; + @since(version = 0.2.0) + import wasi:filesystem/preopens@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/network@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/instance-network@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/udp@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/udp-create-socket@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/tcp@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/tcp-create-socket@0.2.6; + @since(version = 0.2.0) + import wasi:sockets/ip-name-lookup@0.2.6; + @since(version = 0.2.0) + import wasi:random/random@0.2.6; + @since(version = 0.2.0) + import wasi:random/insecure@0.2.6; + @since(version = 0.2.0) + import wasi:random/insecure-seed@0.2.6; + + @since(version = 0.2.0) + export run; +} diff --git a/sdks/python/wit/deps/cli/cli.wit b/sdks/python/wit/deps/cli/cli.wit new file mode 100644 index 0000000000..7aae56c17e --- /dev/null +++ b/sdks/python/wit/deps/cli/cli.wit @@ -0,0 +1,256 @@ +package wasi:cli@0.3.0; + +@since(version = 0.3.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.3.0) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.3.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.3.0) + get-initial-cwd: func() -> option; +} + +@since(version = 0.3.0) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.3.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. + @since(version = 0.3.0) + exit-with-code: func(status-code: u8); +} + +@since(version = 0.3.0) +interface run { + /// Run the program. + @since(version = 0.3.0) + run: async func() -> result; +} + +@since(version = 0.3.0) +interface types { + @since(version = 0.3.0) + enum error-code { + /// Input/output error + io, + /// Invalid or incomplete multibyte or wide character + illegal-byte-sequence, + /// Broken pipe + pipe, + } +} + +@since(version = 0.3.0) +interface stdin { + use types.{error-code}; + + /// Return a stream for reading from stdin. + /// + /// This function returns a stream which provides data read from stdin, + /// and a future to signal read results. + /// + /// If the stream's readable end is dropped the future will resolve to success. + /// + /// If the stream's writable end is dropped the future will either resolve to + /// success if stdin was closed by the writer or to an error-code if reading + /// failed for some other reason. + /// + /// Multiple streams may be active at the same time. The behavior of concurrent + /// reads is implementation-specific. + @since(version = 0.3.0) + read-via-stream: func() -> tuple, future>>; +} + +@since(version = 0.3.0) +interface stdout { + use types.{error-code}; + + /// Write the given stream to stdout. + /// + /// If the stream's writable end is dropped this function will either return + /// success once the entire contents of the stream have been written or an + /// error-code representing a failure. + /// + /// Otherwise if there is an error the readable end of the stream will be + /// dropped and this function will return an error-code. + @since(version = 0.3.0) + write-via-stream: func(data: stream) -> future>; +} + +@since(version = 0.3.0) +interface stderr { + use types.{error-code}; + + /// Write the given stream to stderr. + /// + /// If the stream's writable end is dropped this function will either return + /// success once the entire contents of the stream have been written or an + /// error-code representing a failure. + /// + /// Otherwise if there is an error the readable end of the stream will be + /// dropped and this function will return an error-code. + @since(version = 0.3.0) + write-via-stream: func(data: stream) -> future>; +} + +/// 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.3.0) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.3.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.3.0) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.3.0) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.3.0) +interface terminal-stdin { + @since(version = 0.3.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.3.0) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.3.0) +interface terminal-stdout { + @since(version = 0.3.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.3.0) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.3.0) +interface terminal-stderr { + @since(version = 0.3.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.3.0) + get-terminal-stderr: func() -> option; +} + +@since(version = 0.3.0) +world imports { + @since(version = 0.3.0) + import environment; + @since(version = 0.3.0) + import exit; + @since(version = 0.3.0) + import types; + @since(version = 0.3.0) + import stdin; + @since(version = 0.3.0) + import stdout; + @since(version = 0.3.0) + import stderr; + @since(version = 0.3.0) + import terminal-input; + @since(version = 0.3.0) + import terminal-output; + @since(version = 0.3.0) + import terminal-stdin; + @since(version = 0.3.0) + import terminal-stdout; + @since(version = 0.3.0) + import terminal-stderr; + import wasi:clocks/types@0.3.0; + import wasi:clocks/monotonic-clock@0.3.0; + import wasi:clocks/system-clock@0.3.0; + @unstable(feature = clocks-timezone) + import wasi:clocks/timezone@0.3.0; + import wasi:filesystem/types@0.3.0; + import wasi:filesystem/preopens@0.3.0; + import wasi:sockets/types@0.3.0; + import wasi:sockets/ip-name-lookup@0.3.0; + import wasi:random/random@0.3.0; + import wasi:random/insecure@0.3.0; + import wasi:random/insecure-seed@0.3.0; +} +@since(version = 0.3.0) +world command { + @since(version = 0.3.0) + import environment; + @since(version = 0.3.0) + import exit; + @since(version = 0.3.0) + import types; + @since(version = 0.3.0) + import stdin; + @since(version = 0.3.0) + import stdout; + @since(version = 0.3.0) + import stderr; + @since(version = 0.3.0) + import terminal-input; + @since(version = 0.3.0) + import terminal-output; + @since(version = 0.3.0) + import terminal-stdin; + @since(version = 0.3.0) + import terminal-stdout; + @since(version = 0.3.0) + import terminal-stderr; + import wasi:clocks/types@0.3.0; + import wasi:clocks/monotonic-clock@0.3.0; + import wasi:clocks/system-clock@0.3.0; + @unstable(feature = clocks-timezone) + import wasi:clocks/timezone@0.3.0; + import wasi:filesystem/types@0.3.0; + import wasi:filesystem/preopens@0.3.0; + import wasi:sockets/types@0.3.0; + import wasi:sockets/ip-name-lookup@0.3.0; + import wasi:random/random@0.3.0; + import wasi:random/insecure@0.3.0; + import wasi:random/insecure-seed@0.3.0; + + @since(version = 0.3.0) + export run; +} diff --git a/sdks/python/wit/deps/clocks-0.2.6/clocks.wit b/sdks/python/wit/deps/clocks-0.2.6/clocks.wit new file mode 100644 index 0000000000..d638f1a40f --- /dev/null +++ b/sdks/python/wit/deps/clocks-0.2.6/clocks.wit @@ -0,0 +1,157 @@ +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; +} + +/// 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; +} + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// 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, + } + + /// 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; +} + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import wasi:io/poll@0.2.6; + @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/sdks/python/wit/deps/clocks/clocks.wit b/sdks/python/wit/deps/clocks/clocks.wit new file mode 100644 index 0000000000..d8b8cfe4e3 --- /dev/null +++ b/sdks/python/wit/deps/clocks/clocks.wit @@ -0,0 +1,161 @@ +package wasi:clocks@0.3.0; + +/// This interface common types used throughout wasi:clocks. +@since(version = 0.3.0) +interface types { + /// A duration of time, in nanoseconds. + @since(version = 0.3.0) + type duration = u64; +} + +/// 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.3.0) +interface monotonic-clock { + use types.{duration}; + + /// A mark on a monotonic clock is a number of nanoseconds since an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + @since(version = 0.3.0) + type mark = 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. + /// + /// For completeness, this function traps if it's not possible to represent + /// the value of the clock in a `mark`. Consequently, implementations + /// should ensure that the starting time is low enough to avoid the + /// possibility of overflow in practice. + @since(version = 0.3.0) + now: func() -> mark; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.3.0) + get-resolution: func() -> duration; + + /// Wait until the specified mark has occurred. + @since(version = 0.3.0) + wait-until: async func(when: mark); + + /// Wait for the specified duration to elapse. + @since(version = 0.3.0) + wait-for: async func(how-long: duration); +} + +/// WASI System Clock is a clock API intended to let users query the current +/// time. The clock is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// 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.3.0) +interface system-clock { + use types.{duration}; + + /// An "instant", or "exact time", is a point in time without regard to any + /// time zone: just the time since a particular external reference point, + /// often called an "epoch". + /// + /// Here, the epoch is 1970-01-01T00:00:00Z, also known as + /// [POSIX's Seconds Since the Epoch], also known as [Unix Time]. + /// + /// Note that even if the seconds field is negative, incrementing + /// nanoseconds always represents moving forwards in time. + /// For example, `{ -1 seconds, 999999999 nanoseconds }` represents the + /// instant one nanosecond before the epoch. + /// For more on various different ways to represent time, see + /// https://tc39.es/proposal-temporal/docs/timezone.html + /// + /// [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.3.0) + record instant { + seconds: s64, + 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 nanoseconds field of the output is always less than 1000000000. + @since(version = 0.3.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the smallest duration of time + /// that the implementation permits distinguishing. + @since(version = 0.3.0) + get-resolution: func() -> duration; +} + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use system-clock.{instant}; + + /// Return the IANA identifier of the currently configured timezone. This + /// should be an identifier from the IANA Time Zone Database. + /// + /// For displaying to a user, the identifier should be converted into a + /// localized name by means of an internationalization API. + /// + /// If the implementation does not expose an actual timezone, or is unable + /// to provide mappings from times to deltas between the configured timezone + /// and UTC, or determining the current timezone fails, or the timezone does + /// not have an IANA identifier, this returns nothing. + @unstable(feature = clocks-timezone) + iana-id: func() -> option; + + /// The number of nanoseconds difference between UTC time and the local + /// time of the currently configured timezone, at the exact time of + /// `instant`. + /// + /// The magnitude of the returned value will always be less than + /// 86,400,000,000,000 which is the number of nanoseconds in a day + /// (24*60*60*1e9). + /// + /// If the implementation does not expose an actual timezone, or is unable + /// to provide mappings from times to deltas between the configured timezone + /// and UTC, or determining the current timezone fails, this returns + /// nothing. + @unstable(feature = clocks-timezone) + utc-offset: func(when: instant) -> option; + + /// Returns a string that is suitable to assist humans in debugging whether + /// any timezone is available, and if so, which. This may be the same string + /// as `iana-id`, or a formatted representation of the UTC offset such as + /// `-04:00`, or something else. + /// + /// 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. + @unstable(feature = clocks-timezone) + to-debug-string: func() -> string; +} + +@since(version = 0.3.0) +world imports { + @since(version = 0.3.0) + import types; + @since(version = 0.3.0) + import monotonic-clock; + @since(version = 0.3.0) + import system-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/sdks/python/wit/deps/config/store.wit b/sdks/python/wit/deps/config/store.wit new file mode 100644 index 0000000000..794379a754 --- /dev/null +++ b/sdks/python/wit/deps/config/store.wit @@ -0,0 +1,30 @@ +interface store { + /// An error type that encapsulates the different errors that can occur fetching configuration values. + variant error { + /// This indicates an error from an "upstream" config source. + /// As this could be almost _anything_ (such as Vault, Kubernetes ConfigMaps, KeyValue buckets, etc), + /// the error message is a string. + upstream(string), + /// This indicates an error from an I/O operation. + /// As this could be almost _anything_ (such as a file read, network connection, etc), + /// the error message is a string. + /// Depending on how this ends up being consumed, + /// we may consider moving this to use the `wasi:io/error` type instead. + /// For simplicity right now in supporting multiple implementations, it is being left as a string. + io(string), + } + + /// Gets a configuration value of type `string` associated with the `key`. + /// + /// The value is returned as an `option`. If the key is not found, + /// `Ok(none)` is returned. If an error occurs, an `Err(error)` is returned. + get: func( + /// A string key to fetch + key: string + ) -> result, error>; + + /// Gets a list of configuration key-value pairs of type `string`. + /// + /// If an error occurs, an `Err(error)` is returned. + get-all: func() -> result>, error>; +} diff --git a/sdks/python/wit/deps/config/world.wit b/sdks/python/wit/deps/config/world.wit new file mode 100644 index 0000000000..f92f080a57 --- /dev/null +++ b/sdks/python/wit/deps/config/world.wit @@ -0,0 +1,6 @@ +package wasi:config@0.2.0-draft; + +world imports { + /// The interface for wasi:config/store + import store; +} \ No newline at end of file diff --git a/sdks/python/wit/deps/filesystem-0.2.6/filesystem.wit b/sdks/python/wit/deps/filesystem-0.2.6/filesystem.wit new file mode 100644 index 0000000000..9f4a8288b4 --- /dev/null +++ b/sdks/python/wit/deps/filesystem-0.2.6/filesystem.wit @@ -0,0 +1,587 @@ +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, + } + + /// 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; + + /// 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, + } + + /// 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(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(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(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + @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(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.2.0) + read: func(length: filesize, offset: filesize) -> result, bool>, error-code>; + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.2.0) + write: func(buffer: list, offset: filesize) -> result; + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + @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(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(path-flags: path-flags, path: string) -> result; + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + @since(version = 0.2.0) + set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + /// Create a hard link. + /// + /// 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(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, 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(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + @since(version = 0.2.0) + readlink-at: func(path: string) -> result; + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + @since(version = 0.2.0) + remove-directory-at: func(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(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + @since(version = 0.2.0) + symlink-at: func(old-path: string, new-path: string) -> result<_, error-code>; + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + @since(version = 0.2.0) + unlink-file-at: func(path: string) -> result<_, error-code>; + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + @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(path-flags: path-flags, 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; +} + +@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>; +} + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import wasi:io/error@0.2.6; + @since(version = 0.2.0) + import wasi:io/poll@0.2.6; + @since(version = 0.2.0) + import wasi:io/streams@0.2.6; + @since(version = 0.2.0) + import wasi:clocks/wall-clock@0.2.6; + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/sdks/python/wit/deps/filesystem/filesystem.wit b/sdks/python/wit/deps/filesystem/filesystem.wit new file mode 100644 index 0000000000..e4a778f3d2 --- /dev/null +++ b/sdks/python/wit/deps/filesystem/filesystem.wit @@ -0,0 +1,575 @@ +package wasi:filesystem@0.3.0; + +/// WASI filesystem is a filesystem API primarily intended to let users run WASI +/// programs that access their files on their existing filesystems, without +/// significant overhead. +/// +/// 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]. +/// +/// Though this package presents a portable interface modelled on POSIX, it +/// prioritizes compatibility over portability: allowing users to access their +/// files on their machine is more important than exposing a single semantics +/// across all platforms. Notably, depending on the underlying operating system +/// and file system: +/// * Paths may be case-folded or not. +/// * Deleting (unlinking) a file may fail if there are other file descriptors +/// open. +/// * Durability and atomicity of changes to underlying files when there are +/// concurrent writers. +/// +/// Users that need well-defined, portable semantics should use a key-value +/// store or a database instead. +/// +/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +@since(version = 0.3.0) +interface types { + @since(version = 0.3.0) + use wasi:clocks/system-clock@0.3.0.{instant}; + + /// File size or length of a region within a file. + @since(version = 0.3.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.3.0) + variant descriptor-type { + /// 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, + /// The type of the descriptor or file is different from any of the + /// other types specified. + other(option), + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + @since(version = 0.3.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, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.3.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.3.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.3.0) + type link-count = u64; + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.3.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, + } + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.3.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(instant), + } + + /// A directory entry. + @since(version = 0.3.0) + 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. + @since(version = 0.3.0) + variant error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// 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, + /// A catch-all for errors not captured by the existing variants. + /// Implementations can use this to extend the error type without + /// breaking existing code. + other(option), + } + + /// File or memory access pattern advisory information. + @since(version = 0.3.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.3.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.3.0) + resource descriptor { + /// Return a stream for reading from a file. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// This function returns a `stream` which provides the data received from the + /// file, and a `future` providing additional error information in case an + /// error is encountered. + /// + /// If no error is encountered, `stream.read` on the `stream` will return + /// `read-status::closed` with no `error-context` and the future resolves to + /// the value `ok`. If an error is encountered, `stream.read` on the + /// `stream` returns `read-status::closed` with an `error-context` and the future + /// resolves to `err` with an `error-code`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.3.0) + read-via-stream: func(offset: filesize) -> tuple, future>>; + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// 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. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.3.0) + write-via-stream: func(data: stream, offset: filesize) -> future>; + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// This function returns once either full contents of the stream are + /// written or an error is encountered. + /// + /// Note: This is similar to `write` with `O_APPEND` in POSIX. + @since(version = 0.3.0) + append-via-stream: func(data: stream) -> future>; + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.3.0) + advise: async func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code>; + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + @since(version = 0.3.0) + sync-data: async 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.3.0) + get-flags: async 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.3.0) + get-type: async 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.3.0) + set-size: async 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.3.0) + set-times: async func(data-access-timestamp: new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code>; + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + /// + /// This function returns a future, which will resolve to an error code if + /// reading full contents of the directory fails. + @since(version = 0.3.0) + read-directory: func() -> tuple, future>>; + /// 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.3.0) + sync: async func() -> result<_, error-code>; + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.3.0) + create-directory-at: async func(path: string) -> result<_, error-code>; + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + @since(version = 0.3.0) + stat: async 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.3.0) + stat-at: async func(path-flags: path-flags, path: string) -> result; + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + @since(version = 0.3.0) + set-times-at: async func(path-flags: path-flags, path: string, data-access-timestamp: new-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.3.0) + link-at: async func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, 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.3.0) + open-at: async func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: descriptor-flags) -> result; + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + @since(version = 0.3.0) + readlink-at: async func(path: string) -> result; + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + @since(version = 0.3.0) + remove-directory-at: async func(path: string) -> result<_, error-code>; + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.3.0) + rename-at: async func(old-path: string, new-descriptor: borrow, new-path: string) -> result<_, error-code>; + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + @since(version = 0.3.0) + symlink-at: async func(old-path: string, new-path: string) -> result<_, error-code>; + /// Unlink a filesystem object that is not a directory. + /// + /// This is similar to `unlinkat(fd, path, 0)` in POSIX. + /// + /// Error returns are as specified by POSIX. + /// + /// If the filesystem object is a directory, `error-code::access` or + /// `error-code::is-directory` may be returned instead of the + /// POSIX-specified `error-code::not-permitted`. + @since(version = 0.3.0) + unlink-file-at: async func(path: string) -> result<_, error-code>; + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + @since(version = 0.3.0) + is-same-object: async 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.3.0) + metadata-hash: async 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.3.0) + metadata-hash-at: async func(path-flags: path-flags, path: string) -> result; + } +} + +@since(version = 0.3.0) +interface preopens { + @since(version = 0.3.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.3.0) + get-directories: func() -> list>; +} + +@since(version = 0.3.0) +world imports { + @since(version = 0.3.0) + import wasi:clocks/types@0.3.0; + @since(version = 0.3.0) + import wasi:clocks/system-clock@0.3.0; + @since(version = 0.3.0) + import types; + @since(version = 0.3.0) + import preopens; +} diff --git a/sdks/python/wit/deps/golem-1.x/golem-context.wit b/sdks/python/wit/deps/golem-1.x/golem-context.wit new file mode 100644 index 0000000000..aa3252a487 --- /dev/null +++ b/sdks/python/wit/deps/golem-1.x/golem-context.wit @@ -0,0 +1,93 @@ +package golem:api@1.5.0; + +/// Invocation context support +interface context { + use wasi:clocks/system-clock@0.3.0.{instant as datetime}; + + /// Starts a new `span` with the given name, as a child of the current invocation context + start-span: func(name: string) -> span; + + /// Gets the current invocation context + /// + /// The function call captures the current context; if new spans are started, the returned `invocation-context` instance will not + /// reflect that. + current-context: func() -> invocation-context; + + /// Allows or disallows forwarding of trace context headers in outgoing HTTP requests + /// + /// Returns the previous value of the setting + allow-forwarding-trace-context-headers: func(allow: bool) -> bool; + + /// Represents a unit of work or operation + resource span { + /// Gets the starting time of the span + started-at: func() -> datetime; + + /// Set an attribute on the span + set-attribute: func(name: string, value: attribute-value); + + /// Set multiple attributes on the span + set-attributes: func(attributes: list); + + /// Early finishes the span; otherwise it will be finished when the resource is dropped + finish: func(); + } + + /// Represents an invocation context wich allows querying the stack of attributes + /// created by automatic and user-defined spans. + resource invocation-context { + /// Gets the current trace id + trace-id: func() -> trace-id; + + /// Gets the current span id + span-id: func() -> span-id; + + /// Gets the parent context, if any; allows recursive processing of the invocation context. + /// + /// Alternatively, the attribute query methods can return inherited values without having to + /// traverse the stack manually. + parent: func() -> option; + + /// Gets the value of an attribute `key`. If `inherited` is true, the value is searched in the stack of spans, + /// otherwise only in the current span. + get-attribute: func(key: string, inherited: bool) -> option; + + /// Gets all attributes of the current invocation context. If `inherited` is true, it returns the merged set of attributes, each + /// key associated with the latest value found in the stack of spans. + get-attributes: func(inherited: bool) -> list; + + /// Gets the chain of attribute values associated with the given `key`. If the key does not exist in any of the + /// spans in the invocation context, the list is empty. The chain's first element contains the most recent (innermost) value. + get-attribute-chain: func(key: string) -> list; + + /// Gets all values of all attributes of the current invocation context. + get-attribute-chains: func() -> list; + + /// Gets the W3C Trace Context headers associated with the current invocation context + trace-context-headers: func() -> list>; + } + + /// An attribute of a span + record attribute { + key: string, + value: attribute-value + } + + /// A chain of attribute values, the first element representing the most recent value + record attribute-chain { + key: string, + values: list + } + + /// Possible span attribute value types + variant attribute-value { + /// A string value + %string(string) + } + + /// The trace represented by a 16 bytes hexadecimal string + type trace-id = string; + + /// The span represented by a 8 bytes hexadecimal string + type span-id = string; +} diff --git a/sdks/python/wit/deps/golem-1.x/golem-host.wit b/sdks/python/wit/deps/golem-1.x/golem-host.wit new file mode 100644 index 0000000000..96595830bb --- /dev/null +++ b/sdks/python/wit/deps/golem-1.x/golem-host.wit @@ -0,0 +1,289 @@ +package golem:api@1.5.0; + +/// The Golem host API provides low level access to Golem specific features such as promises and control over +/// the durability and transactional guarantees the executor provides. +interface host { + use golem:core/types@2.0.0.{component-id, uuid, agent-id, promise-id, oplog-index}; + /// Represents a Golem component's version + type component-revision = u64; + + /// Represents a Golem environment + record environment-id { + uuid: uuid, + } + + /// Describes how to update an agent to a different component version + enum update-mode { + /// Automatic update tries to recover the agent using the new component version + /// and may fail if there is a divergence. + automatic, + + /// Manual, snapshot-based update uses a user-defined implementation of the `save-snapshot` interface + /// to store the agent's state, and a user-defined implementation of the `load-snapshot` interface to + /// load it into the new version. + snapshot-based + } + + /// Operators used in filtering enumerated agents + enum filter-comparator { + equal, + not-equal, + greater-equal, + greater, + less-equal, + less + } + + /// Operators used on strings in filtering enumerated agents + enum string-filter-comparator { + equal, + not-equal, + like, + not-like, + starts-with + } + + /// The current status of an agent + enum agent-status { + /// The agent is running an invoked function + running, + /// The agent is ready to run an invoked function + idle, + /// An invocation is active but waiting for something (sleeping, waiting for a promise) + suspended, + /// The last invocation was interrupted but will be resumed + interrupted, + /// The last invocation failed and a retry was scheduled + retrying, + /// The last invocation failed and the agent can no longer be used + failed, + /// The agent exited after a successful invocation and can no longer be invoked + exited, + /// The agent is a never-live sandbox: it replays its history and never runs live + sandboxed, + } + + /// Describes a filter condition on the canonical key of keyed agents when enumerating + /// agents. An agent without a key never matches it. + record agent-key-filter { + comparator: string-filter-comparator, + value: string + } + + /// Describes a filter condition on the agent status when enumerating agents + record agent-status-filter { + comparator: filter-comparator, + value: agent-status + } + + /// Describes a filter condition on the component version when enumerating agents + record agent-version-filter { + comparator: filter-comparator, + value: u64 + } + + /// Describes a filter condition on the agent's creation time when enumerating agents + record agent-created-at-filter { + comparator: filter-comparator, + value: u64 + } + + /// Describes a filter condition on the agent's environment variables when enumerating agents + record agent-env-filter { + name: string, + comparator: string-filter-comparator, + value: string + } + + /// Describes a filter condition on the agent's configuration variables when enumerating agents + record agent-config-vars-filter { + name: string, + comparator: string-filter-comparator, + value: string + } + + /// Describes one filter condition for enumerating agents + variant agent-property-filter { + key(agent-key-filter), + status(agent-status-filter), + version(agent-version-filter), + created-at(agent-created-at-filter), + env(agent-env-filter), + config(agent-config-vars-filter) + } + + /// Combines multiple filter conditions with an `AND` relationship for enumerating agents + record agent-all-filter { + filters: list + } + + /// Combines multiple groups of filter conditions with an `OR` relationship for enumerating agents + record agent-any-filter { + filters: list + } + + /// Metadata about an agent + record agent-metadata { + /// The agent ID + agent-id: agent-id, + /// The name of the agent's type. Owners without an agent type have none. + agent-type-name: option, + /// The incarnation of the agent: a deleted and re-created agent keeps its ID but + /// gets a new fingerprint + fingerprint: uuid, + /// Command line arguments seen by the agent + args: list, + /// Environment variables seen by the agent + env: list>, + /// Configuration variables seen by the agent + config: list>, + /// The current agent status + status: agent-status, + /// The component version the agent is running with + component-revision: u64, + /// The agent's current retry count + retry-count: u64, + /// The environment the agent belongs to + environment-id: environment-id + } + + /// Creates an agent enumeration + resource get-agents { + /// Creates an agent enumeration request. It is going to enumerate the agents of `agent-type-name` + /// in the current environment, filtered by the conditions given by `filter`. If `precise` is true, + /// the server will calculate the most recent state of all the returned agents, otherwise the returned + /// metadata will be not guaranteed to be up-to-date. + constructor(agent-type-name: string, filter: option, precise: bool); + + /// Retrieves the next batch of agent metadata. + get-next: func() -> result>, agent-operation-error>; + } + + /// Target parameter for the `revert-agent` operation + variant revert-agent-target { + /// Revert to a specific oplog index. The given index will be the last one to be kept. + revert-to-oplog-index(oplog-index), + /// Revert the last N invocations. + revert-last-invocations(u64) + } + + /// Error returned by an operation targeting another agent. + variant agent-operation-error { + permission-denied, + backend-error(string), + } + + /// Details about the fork result + record fork-details { + forked-agent-id: agent-id, + } + + /// Indicates which agent the code is running on after `fork`. + /// The parameter contains details about the fork result, such as the ID of the newly + /// created agent. + variant fork-result { + /// The original agent that called `fork` + original(fork-details), + /// The new agent + forked(fork-details) + } + + resource get-promise-result { + /// Awaits the result of the promise. + get: async func() -> list; + } + + /// Create a new promise + create-promise: func() -> promise-id; + + /// Gets a handle to the result of the promise. Can only be called in the same agent that orignally created the promise. + get-promise: func(promise-id: promise-id) -> get-promise-result; + + /// Completes the given promise with the given payload. Returns true if the promise was completed, false + /// if the promise was already completed. The payload is passed to the agent that is awaiting the promise. + complete-promise: func(promise-id: promise-id, data: list) -> bool; + + /// Blocks the execution until the oplog has been written to at least the specified number of replicas, + /// or the maximum number of replicas if the requested number is higher. + oplog-commit: func(replicas: u8); + + /// Unconditionally traps the current invocation with the given reason. + /// + /// This call never returns: it surfaces as an uncatchable wasm trap on the host side + /// and fails the invocation. Recoverable failures must be handled by guest code. + trap: func(reason: string); + + /// Generates an idempotency key. This operation will never be replayed โ€” + /// i.e. not only is this key generated, but it is persisted and committed, such that the key can be used in third-party systems (e.g. payment processing) + /// to introduce idempotence. + generate-idempotency-key: func() -> uuid; + + /// Initiates an update attempt for the given agent. The function returns immediately once the request has been processed, + /// not waiting for the agent to get updated. + update-agent: func(agent-id: agent-id, target-revision: component-revision, mode: update-mode) -> result<_, agent-operation-error>; + + /// Get the current agent's metadata + get-self-metadata: func() -> result; + + /// Get agent metadata + get-agent-metadata: func(agent-id: agent-id) -> option; + + /// Forks an agent at a given oplog index into a new agent of the same type, and returns + /// the ID that Golem issued for the new agent. The new agent has no key. + fork-agent: func(source-agent-id: agent-id, oplog-idx-cut-off: oplog-index) -> result; + + /// Revert an agent to a previous state + revert-agent: func(agent-id: agent-id, revert-target: revert-agent-target) -> result<_, agent-operation-error>; + + /// Get the component-id for a given component reference. + /// Returns none when no component with the specified reference exists. + /// The syntax of the component reference is implementation dependent. + /// + /// Golem OSS: "{component_name}" + /// Golem Cloud: + /// 1: "{component_name}" -> will resolve in current account and project + /// 2: "{project_name}/{component_name}" -> will resolve in current account + /// 3: "{account_id}/{project_name}/{component_name}" + resolve-component-id: func(component-reference: string) -> option; + + /// Forks the current agent at the current execution point. The new agent has the same type, a new + /// ID that Golem issues and no key. The ID of the forked agent is returned in `fork-result` on + /// both sides. The newly created agent continues running from the same point, but the return value is + /// going to be different in this agent and the forked agent. + fork: func() -> result; + + /// Snapshot payload + record snapshot { + payload: list, + mime-type: string + } +} + +/// Interface providing user-defined snapshotting capability. This can be used to perform manual update of agents +/// when the new component incompatible with the old one. +interface save-snapshot { + use host.{snapshot}; + + /// Saves the component's state into a user-defined snapshot + save: async func() -> snapshot; +} + +/// Interface providing user-defined snapshotting capability. This can be used to perform manual update of agents +/// when the new component incompatible with the old one. +interface load-snapshot { + use golem:core/types@2.0.0.{schema-value-tree}; + use host.{snapshot}; + + /// Tries to load a user-defined snapshot, setting up the agent's state based on it. + /// The function can return with a failure to indicate that the update is not possible. + /// + /// `constructor` is a value tree whose root encodes the agent's constructor parameter + /// list, in the same form `initialize` received it when the agent was created. + load: async func(snapshot: snapshot, %constructor: schema-value-tree) -> result<_, string>; +} + +world golem-host { + import host; + import save-snapshot; + import load-snapshot; +} diff --git a/sdks/python/wit/deps/golem-1.x/golem-oplog-processor.wit b/sdks/python/wit/deps/golem-1.x/golem-oplog-processor.wit new file mode 100644 index 0000000000..b54514bf9d --- /dev/null +++ b/sdks/python/wit/deps/golem-1.x/golem-oplog-processor.wit @@ -0,0 +1,27 @@ +package golem:api@1.5.0; + +interface oplog-processor { + use wasi:clocks/system-clock@0.3.0.{instant as datetime}; + use golem:core/types@2.0.0.{account-id, agent-id}; + + use host.{oplog-index, agent-metadata}; + use oplog.{oplog-entry}; + + record account-info { + account-id: account-id + } + + /// Called when one of the agents the plugin is activated on has written new entries to its oplog. + /// + /// There are no guarantees for the number of processors running at the same time, and different entries from the same agent + /// may be sent to different processor instances. + /// + /// The `account-info` parameters contains details of the account the installation belongs to. + /// The `config` parameter contains the configuration parameters for the plugin, as specified in the plugin installation + /// The `agent-id` parameter identifies the agent. + /// The `metadata` parameter contains the agent metadata captured when the batch was prepared. + /// Retries of that batch retain the same metadata. + /// The `first-entry-index` parameter contains the index of the first entry in the list of `entries`. + /// The `entries` parameter always contains at least one element. + process: async func(account-info: account-info, config: list>, agent-id: agent-id, metadata: agent-metadata, first-entry-index: oplog-index, entries: list) -> result<_, string>; +} diff --git a/sdks/python/wit/deps/golem-1.x/golem-oplog.wit b/sdks/python/wit/deps/golem-1.x/golem-oplog.wit new file mode 100644 index 0000000000..2e1aa583d5 --- /dev/null +++ b/sdks/python/wit/deps/golem-1.x/golem-oplog.wit @@ -0,0 +1,1359 @@ +package golem:api@1.5.0; + +/// Host interface for enumerating and searching for agent oplogs +interface oplog { + use wasi:clocks/system-clock@0.3.0.{instant as datetime}; + use golem:core/types@2.0.0.{account-id, card-id, schema-value-tree, typed-schema-value, tool-rpc-error}; + + use host.{component-revision, oplog-index, environment-id, uuid, agent-id}; + use wasi:clocks/types@0.3.0.{duration}; + + /// Whether an agent is durable (persistent oplog) or ephemeral. + /// This mirrors the agent-mode enum in golem:agent/common@1.5.0; it is duplicated here to avoid + /// a circular WIT package dependency between golem:api and golem:agent. + enum agent-mode { + durable, + ephemeral + } + + use context.{attribute, attribute-value, span-id, trace-id}; + use retry.{retry-predicate, retry-policy, named-retry-policy}; + + /// Index into a retry-policy-state's node list + type state-node-index = s32; + + /// Persistent state of a retry policy across retry attempts. + /// Root is nodes[0]. Children referenced by state-node-index. + record retry-policy-state { + nodes: list, + } + + variant state-node { + /// Counter-based state (e.g. periodic, exponential, fibonacci). + counter(u32), + /// Terminal state โ€” policy has given up. + terminal, + /// Wrapper state delegating to an inner policy state. + wrapper(state-node-index), + /// Count-box state with attempt tracking. + count-box(count-box-state), + /// And-then sequential composition state. + and-then(and-then-state), + /// Pair state for union/intersect composition. + pair(pair-state), + } + + record count-box-state { + attempts: u32, + inner: state-node-index, + } + + record and-then-state { + left: state-node-index, + right: state-node-index, + on-right: bool, + } + + record pair-state { + left: state-node-index, + right: state-node-index, + } + + record environment-plugin-grant-id { + uuid: uuid, + } + + variant wrapped-function-type { + /// The side-effect reads from the agent's local state (for example local file system, + /// random generator, etc.) + read-local, + /// The side-effect writes to the agent's local state (for example local file system) + write-local, + /// The side-effect reads from external state (for example a key-value store) + read-remote, + /// The side-effect manipulates external state (for example an RPC call) + write-remote, + } + + record plugin-installation-description { + environment-plugin-grant-id: environment-plugin-grant-id, + plugin-priority: s32, + plugin-name: string, + plugin-version: string, + parameters: list> + } + + record raw-local-agent-config-entry { + path: list, + value: schema-value-tree + } + + record local-agent-config-entry { + path: list, + value: typed-schema-value + } + + record create-parameters { + timestamp: datetime, + agent-id: agent-id, + /// The name of the agent's type. Owners without an agent type have none. + agent-type-name: option, + owner-kind: owner-kind, + agent-mode: agent-mode, + component-revision: component-revision, + env: list>, + created-by: account-id, + environment-id: environment-id, + parent: option, + component-size: u64, + initial-total-linear-memory-size: u64, + initial-active-plugins: list, + local-agent-config: list, + instance-id: uuid, + /// Whether the agent is a never-live sandbox. A marked agent reports the + /// `sandboxed` status. + never-live: bool + } + + enum owner-kind { + component-agent, + ephemeral-external-tool, + oplog-processor, + } + + /// Identifies a durable call by its place in a call order. + /// + /// `anchor` is the oplog index of the record that numbers the call: the agent invocation, the + /// entity invocation or the parent custom durable invocation that made it. `ordinal` is the + /// place of the call among the calls numbered under `anchor`, starting at 0. + record durable-invocation-id { + anchor: oplog-index, + ordinal: u64, + } + + /// Parameters of an enriched durable host-call `start` entry. + /// + /// The recorded `request` payload of every durable host call โ€” including + /// durable P3 async calls such as HTTP send/consume-body, sockets, keyvalue, + /// and blobstore operations โ€” surfaces as a generic `typed-schema-value` + /// tree, identified by `function-name`; there are no per-interface named WIT + /// variants for the payload shapes. + /// + /// `denial` is the reason the host denied the call before it ran. A denied + /// call never runs its operation, and its `end` holds the denied response. + record start-parameters { + timestamp: datetime, + parent-start-index: option, + function-name: string, + invocation-id: option, + observational-owner: option, + request: option, + durable-function-type: wrapped-function-type, + span-started: option, + denial: option, + } + + /// Parameters of an enriched durable host-call `end` entry. Like the + /// `start` `request`, the recorded `response` payload surfaces as a generic + /// `typed-schema-value` tree (no per-interface named WIT variants). + record end-parameters { + timestamp: datetime, + start-index: oplog-index, + response: option, + forced-commit: bool, + span-finished: option, + span-attributes: option, + } + + /// Parameters of an enriched durable host-call `cancelled` entry. Like the + /// `start` `request`, the optional recorded `partial` result surfaces as a + /// generic `typed-schema-value` tree (no per-interface named WIT variants). + record cancelled-parameters { + timestamp: datetime, + start-index: oplog-index, + partial: option, + span-finished: option, + } + + enum span-kind { + internal, + client, + server, + } + + enum span-outcome { + completed, + failed, + cancelled, + abandoned, + denied, + } + + record span-link { + trace-id: trace-id, + span-id: span-id, + trace-states: list, + } + + /// The span name remains in the `name` attribute. An embedded opening must + /// be explicitly closed; invocation boundaries do not close it automatically. + record span-started { + span-id: span-id, + trace-id: trace-id, + trace-states: list, + parent-span-id: option, + links: list, + started-at: datetime, + attributes: list, + kind: span-kind, + } + + /// A compact close records the outcome but no error-message payload. Consumers + /// must not decode the opaque host request to manufacture one. + record span-finished { + span-id: span-id, + finished-at: datetime, + outcome: span-outcome, + } + + /// Attributes applied by `end` before the span is closed. + record span-attributes { + span-id: span-id, + attributes: list, + } + + /// Parameters of a `completion-discarded` entry: the durable host call started at + /// `start-index` completed successfully (its `end` entry was persisted) but the response + /// was never delivered to the agent, because the agent dropped the call's completion + /// future after the `end` was already recorded. + record completion-discarded-parameters { + timestamp: datetime, + start-index: oplog-index, + } + + /// Parameters of a `completion-delivered` entry: the successful result of the durable host + /// call started at `start-index` was handed to the agent at this point in the recorded + /// execution. Replay may prepare the recorded host result earlier, but does not hand it to the + /// agent until this marker and prevents later oplog entries from advancing until that handoff. + record completion-delivered-parameters { + timestamp: datetime, + start-index: oplog-index, + } + + record local-span-data { + span-id: span-id, + start: datetime, + parent: option, + /// Optionally an index of the invocation-context field within agent-invocation + linked-context: option, + attributes: list, + inherited: bool + } + + record external-span-data { + span-id: span-id + } + + variant span-data { + local-span(local-span-data), + external-span(external-span-data) + } + + record wallet-version-token { + wallet-id-hash: list, + generation: u64, + } + + record public-invocation-wallet-pin { + wallet-token: wallet-version-token, + scope-card-id: option, + } + + record raw-invocation-wallet-pin { + wallet-token: wallet-version-token, + pinned-card-ids: list, + scope-card-id: option, + } + + record agent-invocation-started-parameters { + timestamp: datetime, + invocation: agent-invocation, + wallet-pin: public-invocation-wallet-pin, + } + + record agent-invocation-finished-parameters { + timestamp: datetime, + invocation-id: uuid, + %result: agent-invocation-result, + method-name: option, + consumed-fuel: s64, + component-revision: u64, + } + + record agent-invocation-failed-parameters { + timestamp: datetime, + invocation-id: uuid, + error: string, + start-index: oplog-index, + } + + enum oplog-error-kind { + invocation, + recovery + } + + record error-parameters { + timestamp: datetime, + kind: oplog-error-kind, + /// The invocation whose work failed; absent for a `recovery` error, and for an `invocation` error recorded while no invocation runs. + invocation-id: option, + error: string, + retry-from: oplog-index, + /// Persistent retry policy state, if a semantic retry policy is active. + retry-policy-state: option, + /// When the failed host call retries, for an in-function retry. + retry-at: option, + /// The start of the host call that waits until `retry-at`. + retrying-start-index: option, + } + + record oplog-region { + start: oplog-index, + end: oplog-index + } + + record jump-parameters { + timestamp: datetime, + jump: oplog-region + } + + /// Parameters for a set-retry-policy oplog entry. + record set-retry-policy-parameters { + timestamp: datetime, + policy: named-retry-policy, + } + + /// Parameters for a remove-retry-policy oplog entry. + record remove-retry-policy-parameters { + timestamp: datetime, + name: string, + } + + record queued-card-event-install { + card-id: card-id, + } + + record queued-card-event-revoke { + card-id: card-id, + } + + variant queued-card-event { + install(queued-card-event-install), + revoke(queued-card-event-revoke), + } + + /// Parameters for a card-event-queued oplog entry. + record card-event-queued-parameters { + timestamp: datetime, + event: queued-card-event, + } + + /// Parameters for a card-installed oplog entry. + record card-installed-parameters { + timestamp: datetime, + queued-event-index: option, + card-id: card-id, + wallet-generation: u64, + } + + /// Raw parameters for a card-installed oplog entry. + record raw-card-installed-parameters { + timestamp: datetime, + queued-event-index: option, + card: list, + wallet-generation: u64, + } + + enum card-install-failure { + card-revoked, + not-found, + recipient-mismatch, + not-permitted, + } + + /// Parameters for a card-install-failed oplog entry. + record card-install-failed-parameters { + timestamp: datetime, + queued-event-index: oplog-index, + card-id: card-id, + reason: card-install-failure, + } + + /// Parameters for a card-revoked oplog entry. + record card-revoked-parameters { + timestamp: datetime, + queued-event-index: oplog-index, + card-id: card-id, + wallet-generation: u64, + } + + /// Parameters for a card-expired oplog entry. + record card-expired-parameters { + timestamp: datetime, + card-id: card-id, + wallet-generation: u64, + } + + /// Identifies which host-owned stream a host-stream-frame oplog entry belongs to. + /// The kind determines how the entry's payload is interpreted. + enum host-stream-kind { + /// A frame of the outgoing request body of a P3 HTTP client send. + p3-http-request-body, + } + + /// Parameters for a host-stream-frame oplog entry: a durably recorded frame of a + /// host-owned stream (e.g. the outgoing request body of a P3 HTTP client send), + /// attached to the durable host call identified by its start entry's index. + record host-stream-frame-parameters { + timestamp: datetime, + parent-start-index: oplog-index, + kind: host-stream-kind, + payload: typed-schema-value, + } + + /// A consumed attachment read with inline observation metadata. + record tool-attachment-read-parameters { + timestamp: datetime, + observation: typed-schema-value, + payload: option>, + } + + /// An effective attachment control transition without a byte payload. + record tool-attachment-control-parameters { + timestamp: datetime, + attachment: typed-schema-value, + transition: typed-schema-value, + } + + /// A public durable-stream producer record rendered as a typed schema value. + record durable-stream-record-parameters { + timestamp: datetime, + %record: typed-schema-value, + } + + record agent-initialization-parameters { + invocation-id: uuid, + constructor-parameters: typed-schema-value, + trace-id: string, + trace-states: list, + invocation-context: list>, + } + + record agent-method-invocation-parameters { + invocation-id: uuid, + method-name: string, + function-input: typed-schema-value, + trace-id: string, + trace-states: list, + invocation-context: list>, + } + + record load-snapshot-parameters { + snapshot: snapshot-data, + } + + record process-oplog-entries-parameters { + invocation-id: uuid, + } + + record manual-update-parameters { + target-revision: component-revision, + } + + record external-tool-invocation-parameters { + invocation-id: uuid, + tool-name: string, + command-path: list, + input: typed-schema-value, + trace-id: string, + trace-states: list, + invocation-context: list>, + } + + variant agent-invocation { + agent-initialization(agent-initialization-parameters), + agent-method-invocation(agent-method-invocation-parameters), + external-tool(external-tool-invocation-parameters), + save-snapshot, + load-snapshot(load-snapshot-parameters), + process-oplog-entries(process-oplog-entries-parameters), + manual-update(manual-update-parameters), + } + + variant agent-invocation-result { + agent-initialization(agent-invocation-output-parameters), + agent-method(agent-invocation-output-parameters), + external-tool(external-tool-result-parameters), + manual-update, + load-snapshot(fallible-result-parameters), + save-snapshot(save-snapshot-result-parameters), + process-oplog-entries(fallible-result-parameters), + } + + record external-tool-result-parameters { + %result: result, + } + + record tool-invocation-result { + %result: option, + } + + record agent-invocation-output-parameters { + output: typed-schema-value, + } + + record fallible-result-parameters { + error: option, + } + + record save-snapshot-result-parameters { + snapshot: snapshot-data, + } + + record pending-agent-invocation-parameters { + timestamp: datetime, + invocation: agent-invocation, + not-before: option, + } + + variant update-description { + /// Automatic update by replaying the oplog on the new version + auto-update, + /// Automatic update assisted by the latest eligible periodic snapshot + snapshot-assisted-automatic, + /// Custom update by loading a given snapshot on the new version + snapshot-based(snapshot-based-update-parameters) + } + + record snapshot-based-update-parameters { + payload: list, + mime-type: string, + /// The filesystem snapshot taken with the application snapshot, if any + filesystem-snapshot: option, + } + + record pending-update-parameters { + timestamp: datetime, + target-revision: component-revision, + description: update-description, + update-attempt-index: oplog-index, + } + + record successful-update-parameters { + timestamp: datetime, + target-revision: component-revision, + new-component-size: u64, + new-active-plugins: list, + snapshot-assisted-details: option, + /// The entries of the durable calls that the target revision's initializer made, if any + bootstrap: option, + } + + record snapshot-assisted-update-details { + pending-update-index: oplog-index, + source-component-revision: component-revision, + source-revision-start-index: oplog-index, + snapshot-index: oplog-index, + } + + record failed-update-parameters { + timestamp: datetime, + target-revision: component-revision, + details: option, + snapshot-assisted-details: option, + update-attempt-index: option, + /// Why the update failed + failure-class: update-failure-class, + /// The first divergence from the recorded history, when the replay of the target diverged + /// at a recorded entry + divergence: option, + } + + /// Why an update failed + enum update-failure-class { + /// The history did not replay on the target + divergence, + /// The target code trapped, panicked or returned an agent error on recorded inputs + target-trap, + /// Replaying needs a peer effect + not-replayable, + /// The target revision was missing, refused or unsupported, or changes the agent's mode + target-rejected, + /// The replay was interrupted + interrupted, + /// An operational failure, such as storage, load or quota + operational, + /// Snapshot, restore and other failures + other, + } + + /// The first entry at which a replay did not reproduce the recorded execution + record replay-divergence { + /// The oplog index of the first divergence + oplog-index: oplog-index, + /// What the oplog holds at the index + expected: replay-step, + /// What the replay did at the index + actual: replay-step, + /// The identity fields on which the two steps differ; empty when the steps differ in kind + mismatched: list, + } + + /// One step of a replay + variant replay-step { + /// A host call + host-call(replay-host-call), + /// The end of an invocation + invocation-end, + /// The end of the recorded history + end-of-history, + /// Another step, which the text describes + other(string), + } + + /// The identity of a recorded `Start`, or of the call that a replay made in its place + record replay-host-call { + function-name: string, + durable-function-type: wrapped-function-type, + parent-start-index: option, + invocation-id: option, + observational-owner: option, + /// Whether the call carries a request: true for a durable call, false for a durable scope + carries-request: bool, + /// The request of the call, when it is known + request: option, + } + + /// An identity field of a recorded `Start`, which a replayed host call must match + enum start-identity-field { + function-name, + function-type, + invocation-id, + observational-owner, + request-presence, + parent, + } + + record failed-snapshot-assisted-update-details { + pending-update-index: oplog-index, + source-component-revision: component-revision, + source-revision-start-index: oplog-index, + snapshot-index: oplog-index, + } + + record grow-memory-parameters { + timestamp: datetime, + delta: u64 + } + + record memory-size-reconciled-parameters { + timestamp: datetime, + bytes: u64 + } + + type agent-resource-id = u64; + + record create-resource-parameters { + timestamp: datetime, + id: agent-resource-id, + name: string, + owner: string + } + + record drop-resource-parameters { + timestamp: datetime, + id: agent-resource-id, + name: string, + owner: string + } + + enum log-level { + stdout, + stderr, + trace, + debug, + info, + warn, + error, + critical + } + + record log-parameters { + timestamp: datetime, + level: log-level, + context: string, + message: string, + trace-context: option, + } + + record log-trace-context { + trace-id: trace-id, + span-id: span-id, + } + + record activate-plugin-parameters { + timestamp: datetime, + plugin: plugin-installation-description + } + + record deactivate-plugin-parameters { + timestamp: datetime, + plugin: plugin-installation-description + } + + record revert-parameters { + timestamp: datetime, + dropped-region: oplog-region + } + + record cancel-pending-invocation-parameters { + timestamp: datetime, + invocation-id: uuid + } + + record begin-remote-transaction-parameters { + timestamp: datetime, + transaction-id: string + } + + record remote-transaction-parameters { + timestamp: datetime, + begin-index: oplog-index + } + + record snapshot-data { + data: list, + mime-type: string, + } + + record snapshot-parameters { + timestamp: datetime, + data: snapshot-data, + /// The filesystem snapshot taken with the application snapshot, if any + filesystem-snapshot: option, + /// The entries of the durable calls that the running revision's initializer made, if any + bootstrap: option, + } + + /// The store holds the named filesystem snapshot from this point + record snapshot-confirmed-parameters { + timestamp: datetime, + filesystem-snapshot: string, + } + + /// The agent released a host resource whose only durable content is its span, and the + /// span closed. `resource-start-index` is the `start` that opened the span. + record span-closed-parameters { + timestamp: datetime, + resource-start-index: option, + span-finished: span-finished, + } + + record oplog-processor-checkpoint-parameters { + timestamp: datetime, + plugin: plugin-installation-description, + source-component-revision: component-revision, + target-agent-id: agent-id, + confirmed-up-to: oplog-index, + sending-up-to: oplog-index, + last-batch-start: oplog-index, + } + + record timestamp { + timestamp: datetime + } + + /// Opaque oplog payload, which can either be serialized inline or stored externally + variant oplog-payload { + inline(list), + external(oplog-external-payload) + } + + record oplog-external-payload { + payload-id: uuid, + md5-hash: list + } + + record agent-terminated-by-quota-error { + environment-id: environment-id, + resource-name: string + } + + record ephemeral-sleep-too-long { + requested-nanos: u64, + max-nanos: u64 + } + + record ephemeral-fuel-exhausted { + overdraft-limit: u64 + } + + record ephemeral-cannot-suspend { + reason: string + } + + record read-only-violation { + method: string, + host-function: string + } + + /// Describes the error that occurred in the agent + variant worker-error { + unknown(string), + invalid-request(string), + stack-overflow, + out-of-memory, + exceeded-memory-limit, + internal-error(string), + deterministic-trap(string), + transient-error(string), + permanent-error(string), + exceeded-table-limit, + exceeded-http-call-limit, + exceeded-rpc-call-limit, + agent-terminated-by-quota(agent-terminated-by-quota-error), + ephemeral-sleep-too-long(ephemeral-sleep-too-long), + ephemeral-fuel-exhausted(ephemeral-fuel-exhausted), + ephemeral-cannot-suspend(ephemeral-cannot-suspend), + read-only-violation(read-only-violation) + } + + record raw-create-parameters { + timestamp: datetime, + agent-id: agent-id, + /// The name of the agent's type. Owners without an agent type have none. + agent-type-name: option, + owner-kind: owner-kind, + agent-mode: agent-mode, + component-revision: component-revision, + env: list>, + environment-id: environment-id, + created-by: account-id, + parent: option, + component-size: u64, + initial-total-linear-memory-size: u64, + initial-active-plugins: list, + local-agent-config: list, + instance-id: uuid, + /// Whether the agent is a never-live sandbox. A marked agent reports the + /// `sandboxed` status. + never-live: bool + } + + record raw-start-parameters { + timestamp: datetime, + parent-start-index: option, + function-name: string, + invocation-id: option, + observational-owner: option, + request: option, + durable-function-type: wrapped-function-type, + span-started: option, + denial: option, + } + + record raw-end-parameters { + timestamp: datetime, + start-index: oplog-index, + response: option, + forced-commit: bool, + span-finished: option, + span-attributes: option, + } + + record raw-cancelled-parameters { + timestamp: datetime, + start-index: oplog-index, + partial: option, + span-finished: option, + } + + record raw-completion-discarded-parameters { + timestamp: datetime, + start-index: oplog-index, + } + + record raw-completion-delivered-parameters { + timestamp: datetime, + start-index: oplog-index, + } + + /// Parameters for a host-stream-frame oplog entry, with the frame payload in raw + /// (possibly externally stored) form. + record raw-host-stream-frame-parameters { + timestamp: datetime, + parent-start-index: oplog-index, + kind: host-stream-kind, + payload: oplog-payload, + } + + /// A consumed attachment read; only original data observations own payloads. + record raw-tool-attachment-read-parameters { + timestamp: datetime, + entity-parent-start-index: option, + observation: typed-schema-value, + payload: option, + } + + /// A released host resource whose span closed, attributed to the entity scope it ran in. + record raw-span-closed-parameters { + timestamp: datetime, + entity-parent-start-index: option, + resource-start-index: option, + span-finished: span-finished, + } + + /// An effective attachment control transition without a byte payload. + record raw-tool-attachment-control-parameters { + timestamp: datetime, + entity-parent-start-index: option, + attachment: typed-schema-value, + transition: typed-schema-value, + } + + /// A raw durable-stream producer record, stored inline or in external payload storage. + record raw-durable-stream-record-parameters { + timestamp: datetime, + %record: oplog-payload, + summary: option, + } + + enum durable-stream-outcome { + success, + error, + } + + enum durable-stream-terminal-outcome { + finished, + failed, + consumer-cancelled, + } + + enum stream-terminal-origin { + source, + control, + } + + record durable-stream-terminal-summary { + outcome: durable-stream-terminal-outcome, + origin: stream-terminal-origin, + } + + variant durable-stream-event-summary { + registered, + items(u64), + terminal(durable-stream-terminal-summary), + session-result, + session-finished(durable-stream-outcome), + session-cancellation, + session-expired, + } + + record raw-agent-invocation-started-parameters { + timestamp: datetime, + invocation-id: uuid, + payload: oplog-payload, + trace-id: string, + trace-states: list, + invocation-context: list, + wallet-pin: raw-invocation-wallet-pin, + } + + record raw-agent-invocation-finished-parameters { + timestamp: datetime, + invocation-id: uuid, + %result: oplog-payload, + method-name: option, + consumed-fuel: s64, + component-revision: u64, + } + + record raw-agent-invocation-failed-parameters { + timestamp: datetime, + invocation-id: uuid, + error: worker-error, + start-index: oplog-index, + } + + record raw-error-parameters { + timestamp: datetime, + kind: oplog-error-kind, + /// The invocation whose work failed; absent for a `recovery` error, and for an `invocation` error recorded while no invocation runs. + invocation-id: option, + error: worker-error, + retry-from: oplog-index, + /// Persistent retry policy state, if a semantic retry policy is active. + retry-policy-state: option, + /// When the failed host call retries, for an in-function retry. + retry-at: option, + /// The start of the host call that waits until `retry-at`. + retrying-start-index: option, + } + + record raw-pending-agent-invocation-parameters { + timestamp: datetime, + not-before: option, + invocation-id: uuid, + payload: oplog-payload, + trace-id: string, + trace-states: list, + invocation-context: list, + } + + /// Raw update description used in oplog entries + variant raw-update-description { + /// Automatic update by replaying the oplog on the new version + automatic(component-revision), + /// Automatic update assisted by the latest eligible periodic snapshot + snapshot-assisted-automatic(raw-snapshot-assisted-automatic-update), + /// Custom update by loading a given snapshot on the new version + snapshot-based(raw-snapshot-based-update) + } + + record raw-snapshot-assisted-automatic-update { + target-revision: component-revision, + source-component-revision: component-revision, + source-revision-start-index: oplog-index, + snapshot-index: oplog-index, + snapshot-revision: component-revision, + /// The filesystem snapshot of the selected record, if it has one + filesystem-snapshot: option, + /// The bootstrap range of the selected record, if it has one + snapshot-bootstrap: option, + } + + record raw-snapshot-based-update { + target-revision: component-revision, + payload: oplog-payload, + mime-type: string, + filesystem-snapshot: option, + } + + record raw-pending-update-parameters { + timestamp: datetime, + description: raw-update-description, + update-attempt-index: option, + } + + record raw-successful-update-parameters { + timestamp: datetime, + target-revision: component-revision, + new-component-size: u64, + new-active-plugins: list, + snapshot-assisted-details: option, + /// The entries of the durable calls that the target revision's initializer made, if any + bootstrap: option, + } + + record resource-type-id { + name: string, + owner: string, + } + + record raw-create-resource-parameters { + timestamp: datetime, + id: agent-resource-id, + resource-type-id: resource-type-id, + } + + record raw-drop-resource-parameters { + timestamp: datetime, + id: agent-resource-id, + resource-type-id: resource-type-id, + } + + record raw-activate-plugin-parameters { + timestamp: datetime, + plugin-grant-id: environment-plugin-grant-id + } + + record raw-deactivate-plugin-parameters { + timestamp: datetime, + plugin-grant-id: environment-plugin-grant-id + } + + record raw-begin-remote-transaction-parameters { + timestamp: datetime, + transaction-id: string, + original-begin-index: oplog-index + } + + record raw-snapshot-parameters { + timestamp: datetime, + data: oplog-payload, + mime-type: string, + active-cards: list>, + wallet-generation: u64, + filesystem-snapshot: option, + /// The entries of the durable calls that the running revision's initializer made, if any + bootstrap: option, + } + + record raw-oplog-processor-checkpoint-parameters { + timestamp: datetime, + plugin-grant-id: environment-plugin-grant-id, + source-component-revision: component-revision, + target-agent-id: agent-id, + confirmed-up-to: oplog-index, + sending-up-to: oplog-index, + last-batch-start: oplog-index, + delivery: option>, + } + + variant oplog-entry { + /// The initial agent oplog entry + create(raw-create-parameters), + /// Marks the start of a durable host call (or scope such as a batched-write). + start(raw-start-parameters), + /// Marks the successful completion of a durable host call (or scope) started by a matching `Start`. + end(raw-end-parameters), + /// Marks that a durable host call started by a matching `Start` was cancelled + /// (e.g. dropped from a `select!`) before producing a final response. + cancelled(raw-cancelled-parameters), + /// The agent has been invoked + agent-invocation-started(raw-agent-invocation-started-parameters), + /// The agent has completed an invocation + agent-invocation-finished(raw-agent-invocation-finished-parameters), + agent-invocation-failed(raw-agent-invocation-failed-parameters), + /// Agent suspended + suspend(timestamp), + /// Agent failed + error(raw-error-parameters), + /// A previously failed startup or replay completed successfully. + recovery-succeeded(timestamp), + /// The agent needs to recover up to the given target oplog index and continue running from + /// the source oplog index from there + /// `jump` is an oplog region representing that from the end of that region we want to go back to the start and + /// ignore all recorded operations in between. + jump(jump-parameters), + /// Indicates that the agent has been interrupted at this point. + /// Only used to recompute the agent's (cached) status, has no effect on execution. + interrupted(timestamp), + /// Indicates that the agent has been exited using WASI's exit function. + exited(timestamp), + /// An invocation request arrived while the agent was busy + pending-agent-invocation(raw-pending-agent-invocation-parameters), + /// An update request arrived and will be applied as soon the agent restarts + pending-update(raw-pending-update-parameters), + /// An update was successfully applied + successful-update(raw-successful-update-parameters), + /// An update failed to be applied + failed-update(failed-update-parameters), + /// Increased total linear memory size + grow-memory(grow-memory-parameters), + memory-size-reconciled(memory-size-reconciled-parameters), + /// Created a resource instance + create-resource(raw-create-resource-parameters), + /// Dropped a resource instance + drop-resource(raw-drop-resource-parameters), + /// The agent emitted a log message + log(log-parameters), + /// The agent has been restarted, forgetting all its history + restart(timestamp), + /// An unfinished durable invocation was admitted to resume + resumed(timestamp), + /// Activates a plugin + activate-plugin(raw-activate-plugin-parameters), + /// Deactivates a plugin + deactivate-plugin(raw-deactivate-plugin-parameters), + /// Revert an agent to a previous state + revert(revert-parameters), + /// Cancel a pending invocation + cancel-pending-invocation(cancel-pending-invocation-parameters), + /// Begins a transaction operation + begin-remote-transaction(raw-begin-remote-transaction-parameters), + /// Pre-Commit of the transaction, indicating that the transaction will be committed + pre-commit-remote-transaction(remote-transaction-parameters), + /// Pre-Rollback of the transaction, indicating that the transaction will be rolled back + pre-rollback-remote-transaction(remote-transaction-parameters), + /// Committed transaction operation, indicating that the transaction was committed + committed-remote-transaction(remote-transaction-parameters), + /// Rolled back transaction operation, indicating that the transaction was rolled back + rolled-back-remote-transaction(remote-transaction-parameters), + /// A snapshot of the agent's state + snapshot(raw-snapshot-parameters), + /// Checkpoint for oplog processor plugin delivery tracking + oplog-processor-checkpoint(raw-oplog-processor-checkpoint-parameters), + /// Sets or overwrites a named retry policy + set-retry-policy(set-retry-policy-parameters), + /// Removes a named retry policy by name + remove-retry-policy(remove-retry-policy-parameters), + /// Durable queue entry for pending permission-card work + card-event-queued(card-event-queued-parameters), + /// Records successful installation of a permission card into the agent wallet + card-installed(raw-card-installed-parameters), + /// Records failed installation of a permission card into the agent wallet + card-install-failed(card-install-failed-parameters), + /// Records that a permission card used by the agent has been revoked + card-revoked(card-revoked-parameters), + /// Records that a permission card used by the agent has expired + card-expired(card-expired-parameters), + /// A durably recorded frame of a host-owned stream (e.g. an outgoing HTTP request body), + /// attached to the durable host call identified by its start entry's index + host-stream-frame(raw-host-stream-frame-parameters), + tool-attachment-read(raw-tool-attachment-read-parameters), + tool-attachment-control(raw-tool-attachment-control-parameters), + /// Registers a durable stream before exposing its handle + stream-registered(raw-durable-stream-record-parameters), + /// Records committed durable stream values or a packed-u8 batch + stream-items(raw-durable-stream-record-parameters), + /// Records the unique outcome or consumer cancellation of a durable stream + stream-terminal(raw-durable-stream-record-parameters), + /// Records durable Stream Session state and consumer-journal facts + stream-session(raw-durable-stream-record-parameters), + /// The successful completion of the durable host call started by the matching `start` + /// was persisted, but its response was never delivered to the agent (the agent dropped + /// the completion future after the `end` was recorded) + completion-discarded(raw-completion-discarded-parameters), + /// The successful completion of the durable host call started by the matching `start` + /// was delivered to the agent at this point in the recorded execution + completion-delivered(raw-completion-delivered-parameters), + /// The store holds the named filesystem snapshot; the `snapshot` entry with the same name is usable + snapshot-confirmed(snapshot-confirmed-parameters), + /// The agent released a host resource and its span closed; the release is not a durable call + span-closed(raw-span-closed-parameters) + } + + variant public-oplog-entry { + /// The initial agent oplog entry + create(create-parameters), + /// Marks the start of a durable host call (or scope such as a batched-write). + start(start-parameters), + /// Marks the successful completion of a durable host call (or scope) started by a matching `Start`. + end(end-parameters), + /// Marks that a durable host call started by a matching `Start` was cancelled + /// (e.g. dropped from a `select!`) before producing a final response. + cancelled(cancelled-parameters), + /// The agent has been invoked + agent-invocation-started(agent-invocation-started-parameters), + /// The agent has completed an invocation + agent-invocation-finished(agent-invocation-finished-parameters), + agent-invocation-failed(agent-invocation-failed-parameters), + /// Agent suspended + suspend(timestamp), + /// Agent failed + error(error-parameters), + /// A previously failed startup or replay completed successfully. + recovery-succeeded(timestamp), + /// The agent needs to recover up to the given target oplog index and continue running from + /// the source oplog index from there + /// `jump` is an oplog region representing that from the end of that region we want to go back to the start and + /// ignore all recorded operations in between. + jump(jump-parameters), + /// Indicates that the agent has been interrupted at this point. + /// Only used to recompute the agent's (cached) status, has no effect on execution. + interrupted(timestamp), + /// Indicates that the agent has been exited using WASI's exit function. + exited(timestamp), + /// An invocation request arrived while the agent was busy + pending-agent-invocation(pending-agent-invocation-parameters), + /// An update request arrived and will be applied as soon the agent restarts + pending-update(pending-update-parameters), + /// An update was successfully applied + successful-update(successful-update-parameters), + /// An update failed to be applied + failed-update(failed-update-parameters), + /// Increased total linear memory size + grow-memory(grow-memory-parameters), + memory-size-reconciled(memory-size-reconciled-parameters), + /// Created a resource instance + create-resource(create-resource-parameters), + /// Dropped a resource instance + drop-resource(drop-resource-parameters), + /// The agent emitted a log message + log(log-parameters), + /// The agent's has been restarted, forgetting all its history + restart(timestamp), + /// An unfinished durable invocation was admitted to resume + resumed(timestamp), + /// Activates a plugin + activate-plugin(activate-plugin-parameters), + /// Deactivates a plugin + deactivate-plugin(deactivate-plugin-parameters), + /// Revert an agent to a previous state + revert(revert-parameters), + /// Cancel a pending invocation + cancel-pending-invocation(cancel-pending-invocation-parameters), + /// Begins a transaction operation + begin-remote-transaction(begin-remote-transaction-parameters), + /// Pre-Commit of the transaction, indicating that the transaction will be committed + pre-commit-remote-transaction(remote-transaction-parameters), + /// Pre-Rollback of the transaction, indicating that the transaction will be rolled back + pre-rollback-remote-transaction(remote-transaction-parameters), + /// Committed transaction operation, indicating that the transaction was committed + committed-remote-transaction(remote-transaction-parameters), + /// Rolled back transaction operation, indicating that the transaction was rolled back + rolled-back-remote-transaction(remote-transaction-parameters), + /// A snapshot of the worker's state + snapshot(snapshot-parameters), + /// Checkpoint for oplog processor plugin delivery tracking + oplog-processor-checkpoint(oplog-processor-checkpoint-parameters), + /// Sets or overwrites a named retry policy + set-retry-policy(set-retry-policy-parameters), + /// Removes a named retry policy by name + remove-retry-policy(remove-retry-policy-parameters), + /// Durable queue entry for pending permission-card work + card-event-queued(card-event-queued-parameters), + /// Records successful installation of a permission card into the agent wallet + card-installed(card-installed-parameters), + /// Records failed installation of a permission card into the agent wallet + card-install-failed(card-install-failed-parameters), + /// Records that a permission card used by the agent has been revoked + card-revoked(card-revoked-parameters), + /// Records that a permission card used by the agent has expired + card-expired(card-expired-parameters), + /// A durably recorded frame of a host-owned stream (e.g. an outgoing HTTP request body), + /// attached to the durable host call identified by its start entry's index + host-stream-frame(host-stream-frame-parameters), + tool-attachment-read(tool-attachment-read-parameters), + tool-attachment-control(tool-attachment-control-parameters), + /// Registers a durable stream before exposing its handle + stream-registered(durable-stream-record-parameters), + /// Records committed durable stream values or a packed-u8 batch + stream-items(durable-stream-record-parameters), + /// Records the unique outcome or consumer cancellation of a durable stream + stream-terminal(durable-stream-record-parameters), + /// Records durable Stream Session state and consumer-journal facts + stream-session(durable-stream-record-parameters), + /// The successful completion of the durable host call started by the matching `start` + /// was persisted, but its response was never delivered to the agent (the agent dropped + /// the completion future after the `end` was recorded) + completion-discarded(completion-discarded-parameters), + /// The successful completion of the durable host call started by the matching `start` + /// was delivered to the agent at this point in the recorded execution + completion-delivered(completion-delivered-parameters), + /// The store holds the named filesystem snapshot; the `snapshot` entry with the same name is usable + snapshot-confirmed(snapshot-confirmed-parameters), + /// The agent released a host resource and its span closed; the release is not a durable call + span-closed(span-closed-parameters) + } + + /// Enriches raw oplog entries into public oplog entries by resolving oplog payloads + /// and augmenting entries with component metadata. + enrich-oplog-entries: func(environment-id: environment-id, agent-id: agent-id, entries: list>, component-revision: component-revision) -> result, string>; + + variant oplog-read-error { + permission-denied, + internal-error(string), + } + + resource get-oplog { + constructor(agent-id: agent-id, start: oplog-index); + get-next: func() -> result>, oplog-read-error>; + } + + resource search-oplog { + constructor(agent-id: agent-id, text: string); + get-next: func() -> result>>, oplog-read-error>; + } +} diff --git a/sdks/python/wit/deps/golem-1.x/golem-retry.wit b/sdks/python/wit/deps/golem-1.x/golem-retry.wit new file mode 100644 index 0000000000..45b26fddcf --- /dev/null +++ b/sdks/python/wit/deps/golem-1.x/golem-retry.wit @@ -0,0 +1,203 @@ +package golem:api@1.5.0; + +interface retry { + use wasi:clocks/types@0.3.0.{duration}; + + // โ”€โ”€ Predicate value โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /// Dynamic value for property comparisons in retry predicates + variant predicate-value { + text(string), + integer(s64), + boolean(bool), + } + + // โ”€โ”€ Predicate tree (flattened) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /// Index into a retry-predicate's node list + type predicate-node-index = s32; + + /// A composable predicate tree for matching retry contexts. + /// Root is nodes[0]. Children referenced by predicate-node-index. + record retry-predicate { + nodes: list, + } + + variant predicate-node { + prop-eq(property-comparison), + prop-neq(property-comparison), + prop-gt(property-comparison), + prop-gte(property-comparison), + prop-lt(property-comparison), + prop-lte(property-comparison), + prop-exists(string), + prop-in(property-set-check), + prop-matches(property-pattern), + prop-starts-with(property-pattern), + prop-contains(property-pattern), + pred-and(tuple), + pred-or(tuple), + pred-not(predicate-node-index), + pred-true, + pred-false, + } + + record property-comparison { + property-name: string, + value: predicate-value, + } + + record property-set-check { + property-name: string, + values: list, + } + + record property-pattern { + property-name: string, + pattern: string, + } + + // โ”€โ”€ Policy tree (flattened) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /// Index into a retry-policy's node list + type policy-node-index = s32; + + /// A composable retry policy tree. + /// Root is nodes[0]. Children referenced by policy-node-index. + record retry-policy { + nodes: list, + } + + variant policy-node { + periodic(duration), + exponential(exponential-config), + fibonacci(fibonacci-config), + immediate, + never, + count-box(count-box-config), + time-box(time-box-config), + clamp-delay(clamp-config), + add-delay(add-delay-config), + jitter(jitter-config), + filtered-on(filtered-config), + and-then(tuple), + policy-union(tuple), + policy-intersect(tuple), + } + + record exponential-config { + base-delay: duration, + factor: f64, + } + + record fibonacci-config { + first: duration, + second: duration, + } + + record count-box-config { + max-retries: u32, + inner: policy-node-index, + } + + record time-box-config { + limit: duration, + inner: policy-node-index, + } + + record clamp-config { + min-delay: duration, + max-delay: duration, + inner: policy-node-index, + } + + record add-delay-config { + delay: duration, + inner: policy-node-index, + } + + record jitter-config { + factor: f64, + inner: policy-node-index, + } + + /// filtered-config embeds a full retry-predicate inline (self-contained) + record filtered-config { + predicate: retry-predicate, + inner: policy-node-index, + } + + // โ”€โ”€ Named policy rule โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /// A named retry policy rule: predicate selects when it applies, + /// policy defines the retry strategy, priority controls evaluation order + /// (higher = checked first). + record named-retry-policy { + name: string, + priority: u32, + predicate: retry-predicate, + policy: retry-policy, + } + + // โ”€โ”€ Host functions โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /// Get all retry policies active for the calling task: the agent-wide policies, overridden + /// by the retry policy scopes open in the task + get-retry-policies: func() -> list; + + /// Get a specific retry policy by name, as `get-retry-policies` reports it + get-retry-policy-by-name: func(name: string) -> option; + + /// Resolve the matching retry policy for a given operation context. + /// Evaluates the policies of `get-retry-policies` in descending priority order; returns the + /// policy from the first rule whose predicate matches, or none. + /// Invalid predicates return an error without trapping the invocation. + resolve-retry-policy: func( + verb: string, + noun-uri: string, + properties: list>, + ) -> result, string>; + + record retry-decision { + /// Opaque continuation for this retry sequence. Pass it unchanged to the next decision. + state: list, + /// None means exhausted. A zero delay still permits another attempt. + delay: option, + } + + /// Advance the host's retry evaluator once after a failed, compensated attempt. + /// Empty state starts a sequence. None selects the configured default retry policy. + /// Elapsed includes work, compensation and durable waits since the first attempt. + /// The continuation binds the effective policy and retains elapsed high-water marks. + /// A changed policy or invalid continuation returns an error, never a reset budget. + /// The host records the decision, including jitter and errors, for deterministic replay. + next-retry-delay: func( + policy: option, + state: list, + elapsed: duration, + verb: string, + noun-uri: string, + properties: list>, + ) -> result; + + /// Add or overwrite a named retry policy (persisted to oplog). + /// If a policy with the same name exists, it is replaced. + set-retry-policy: func(policy: named-retry-policy); + + /// Remove a named retry policy by name (persisted to oplog). + remove-retry-policy: func(name: string); +} + +interface retry-scope { + use retry.{named-retry-policy}; + + /// A named retry policy that applies to the host calls of the task that created the scope, + /// until the scope is dropped or the task ends. A subtask that the task creates while the + /// scope is open, and a host call that it starts, keep the scope after the scope is dropped. + /// + /// The innermost open scope with a name overrides the agent-wide policy with that name. + /// Opening and dropping a scope changes no agent-wide state and records no oplog entry. + resource retry-policy-scope { + constructor(policy: named-retry-policy); + } +} diff --git a/sdks/python/wit/deps/golem-agent/common.wit b/sdks/python/wit/deps/golem-agent/common.wit new file mode 100644 index 0000000000..e7f4748e49 --- /dev/null +++ b/sdks/python/wit/deps/golem-agent/common.wit @@ -0,0 +1,272 @@ +package golem:agent@2.0.0; + +interface common { + use golem:core/types@2.0.0.{schema-graph, type-node-index, typed-schema-value, + metadata-envelope, agent-id, account-id, environment-id, uuid, datetime}; + use golem:core/http@2.0.0.{http-route-mode, durable-stream-route-options, + http-method as concrete-http-method, path-segment as neutral-path-segment, + header-variable, query-variable, file-mapping, file-response-header}; + use wasi:clocks/types@0.3.0.{duration}; + + enum agent-mode { + durable, + ephemeral + } + + /// Full agent type declaration. + /// + /// `schema` is the per-agent type-node pool. Constructor / method / config + /// schema roots below are `type-node-index` values into `schema`. The + /// `schema.root` field is a structurally-required placeholder and is not the + /// semantic root of the agent type. + record agent-type { + type-name: string, + kind: agent-type-kind, + description: string, + source-language: string, + schema: schema-graph, + %constructor: agent-constructor, + methods: list, + dependencies: list, + mode: agent-mode, + http-mount: option, + snapshotting: snapshotting, + config: list, + } + + enum agent-type-kind { + regular, + http-router, + } + + /// An agent type deployed in the current environment + record registered-agent-type { + agent-type: agent-type, + } + + /// Dependent agent type. All schema roots inside it resolve against its own + /// `schema`, not against the parent agent-type's graph. + record agent-dependency { + type-name: string, + description: option, + schema: schema-graph, + %constructor: agent-constructor, + methods: list, + } + + /// Ordered, named input parameters with per-field source annotation. + variant input-schema { + parameters(list), + } + + record named-field { + name: string, + source: field-source, + /// Index into the owning agent-type / dependency `schema` graph. + schema: type-node-index, + metadata: metadata-envelope, + } + + variant field-source { + user-supplied, + } + + /// Output is either unit (no value) or a single value of the given type. + variant output-schema { + unit, + /// Index into the owning agent-type / dependency `schema` graph. + single(type-node-index), + } + + record agent-method { + name: string, + description: string, + http-endpoint: list, + prompt-hint: option, + input-schema: input-schema, + output-schema: output-schema, + read-only: option, + } + + record read-only-config { + cache-policy: cache-policy, + } + + variant cache-policy { + no-cache, + until-write, + ttl(duration), + } + + record http-mount-details { + path-prefix: list, + auth-details: option, + phantom-agent: bool, + phantom-id-binding: option, + cors-options: cors-options, + webhook-suffix: list, + static-bindings: list, + filesystem-bindings: list, + /// Additional response headers for files served by static-bindings or filesystem-bindings. + file-response-headers: list, + /// The name of a parameterless router method that returns the OpenAPI document as a string. + openapi-provider-method: option, + } + + variant phantom-id-binding { + path(phantom-id-binding-details), + query(phantom-id-binding-details), + } + + record phantom-id-binding-details { + name: string, + optional: bool, + } + + record cors-options { + allowed-patterns: list, + } + + record http-endpoint-details { + http-method: http-method, + path-suffix: list, + header-vars: list, + query-vars: list, + auth-details: option, + cors-options: cors-options, + mode: option, + durable-streams: option, + } + + variant http-method { + method(concrete-http-method), + any, + } + + variant path-segment { + segment(neutral-path-segment), + system-variable(system-variable), + } + + enum system-variable { + agent-type, + agent-version + } + + record auth-details { + required: bool, + } + + /// The (issuer, subject) pair of one principal. A reference is data: holding one grants + /// nothing. Two references name the same principal exactly when both strings are equal, + /// byte for byte. + record principal-ref { + issuer: string, + subject: string, + } + + /// One identity, as Golem verified it. Every kind except anonymous has a pair. + variant principal { + user(user-principal), + account(account-principal), + agent(agent-principal), + tool(tool-principal), + anonymous, + } + + /// A user, authenticated by a sign-in provider: the provider's pair. + record user-principal { + pair: principal-ref, + /// The verified claims, as the JSON object that Golem received. + claims: string, + authenticated-at: datetime, + } + + enum account-authentication { + api-token, + bootstrap-token, + sign-in, + } + + /// An account: (Golem issuer, "account:"). + record account-principal { + pair: principal-ref, + account-id: account-id, + authentication: account-authentication, + } + + /// An agent: (Golem issuer, "agent:/"). + record agent-principal { + pair: principal-ref, + agent-id: agent-id, + agent-type: string, + environment-id: environment-id, + } + + /// A tool: (Golem issuer, "tool:/"). + record tool-principal { + pair: principal-ref, + environment-id: environment-id, + tool-name: string, + } + + /// A token that the request presented, and the reference of its maker. It never holds the + /// token's value. + record token-provenance { + id: uuid, + maker: option, + } + + /// The principals that caused an invocation, and the tokens presented at the entry point. + record caller { + /// The principal at the root of the call tree. + original: principal, + /// The principal that made this call. + immediate: principal, + tokens: list, + } + + record agent-constructor { + name: option, + description: string, + prompt-hint: option, + input-schema: input-schema, + } + + variant snapshotting { + disabled, + enabled(snapshotting-config) + } + + variant snapshotting-config { + default, // current default in the server + periodic(duration), + every-n-invocation(u16) + } + + enum agent-config-source { + local, + secret + } + + record agent-config-declaration { + source: agent-config-source, + path: list, + /// Index into the owning agent-type `schema` graph. + value-type: type-node-index, + } + + record typed-agent-config-value { + path: list, + value: typed-schema-value, + } + + /// Agent-level failures + variant agent-error { + invalid-input(string), + invalid-method(string), + invalid-type(string), + invalid-agent-id(string), + custom-error(typed-schema-value), + } +} diff --git a/sdks/python/wit/deps/golem-agent/durable-streams.wit b/sdks/python/wit/deps/golem-agent/durable-streams.wit new file mode 100644 index 0000000000..ea5701b0cc --- /dev/null +++ b/sdks/python/wit/deps/golem-agent/durable-streams.wit @@ -0,0 +1,112 @@ +package golem:agent@2.0.0; + +/// External Durable Streams descriptors are recorded when resources are created. +/// Callers own checkpoints, buffered items, producer progress and retries. +interface durable-streams { + use golem:core/types@2.0.0.{secret}; + + enum durable-stream-mode { json, bytes } + enum durable-stream-transport { catch-up, long-poll, sse } + + /// Both values are server-generated opaque tokens, not Golem stream offsets. + record durable-stream-checkpoint { + offset: string, + cursor: option, + } + + record durable-stream-reader-options { + url: string, + mode: durable-stream-mode, + /// Whole-attempt deadline, in milliseconds, from 1 through 300000. + timeout-ms: u64, + } + + record durable-stream-read-request { + checkpoint: durable-stream-checkpoint, + transport: durable-stream-transport, + /// Pin the original stream media type after the initial catch-up read. + /// Required for SSE, whose HTTP media type is text/event-stream. + content-type: option, + } + + /// A complete HTTP body or SSE data/control pair. Empty is not EOF unless closed. + record durable-stream-batch { + payload: list, + content-type: string, + next: durable-stream-checkpoint, + up-to-date: bool, + closed: bool, + } + + record durable-stream-writer-options { + url: string, + content-type: string, + producer-id: string, + producer-epoch: u64, + /// Whole-attempt deadline, in milliseconds, from 1 through 300000. + timeout-ms: u64, + } + + variant durable-stream-append-payload { + /// Individually encoded complete JSON values; the host frames the outer array. + json(list), + bytes(list), + } + + record durable-stream-append-request { + payload: durable-stream-append-payload, + sequence: u64, + close: bool, + } + + record durable-stream-append-receipt { + /// Duplicate acknowledgements may omit the offset. + next-offset: option, + epoch: u64, + sequence: u64, + closed: bool, + } + + enum durable-stream-error-kind { + invalid-request, + permission-denied, + not-found, + gone, + closed, + sequence-conflict, + fenced, + producer-diverged, + protocol-error, + payload-too-large, + timeout, + transport, + rate-limited, + unavailable, + } + + record durable-stream-error { + kind: durable-stream-error-kind, + message: string, + retry-after-ms: option, + producer-epoch: option, + expected-sequence: option, + } + + /// Immutable read descriptor. Construction records no HTTP effect and captures + /// the secret's pinned identity, not its plaintext or the borrowed handle. + resource durable-stream-reader { + constructor(options: durable-stream-reader-options, auth: option>); + + /// One protocol attempt. Replay returns the recorded batch without HTTP. + read: async func(request: durable-stream-read-request) -> result; + } + + /// Immutable writer descriptor. The caller owns sequence progress and pending + /// append state; retaining this resource does not advance either automatically. + resource durable-stream-writer { + constructor(options: durable-stream-writer-options, auth: option>); + + /// One protocol-idempotent attempt. Retry the identical sequence, body and close flag. + append: async func(request: durable-stream-append-request) -> result; + } +} diff --git a/sdks/python/wit/deps/golem-agent/guest.wit b/sdks/python/wit/deps/golem-agent/guest.wit new file mode 100644 index 0000000000..68628eb15d --- /dev/null +++ b/sdks/python/wit/deps/golem-agent/guest.wit @@ -0,0 +1,40 @@ +package golem:agent@2.0.0; + +interface guest { + use golem:core/types@2.0.0.{schema-value-tree}; + use common.{agent-error, agent-type}; + + /// Initializes the agent of a given type with the given constructor parameters. + /// If called a second time, it fails. + /// + /// `input` is a value tree whose root encodes the constructor's parameter + /// list (one record field per declared `named-field`, in declaration order). + /// The guest interprets it against its own constructor `input-schema`. + /// The creator's principal is available from `invocation-context.caller`. + initialize: async func(agent-type: string, input: schema-value-tree) -> result<_, agent-error>; + + /// Invokes an agent. If create was not called before, it fails. + /// + /// `input` is a value tree whose root encodes the method's parameter list. + /// Streams are represented recursively by `stream-value` nodes. The result + /// is `none` when the method's `output-schema` is `unit`, and `some(value)` + /// for a `single` output. The caller is available from `invocation-context.caller`. + invoke: async func(method-name: string, input: schema-value-tree) -> result, agent-error>; + + /// Gets the agent type. If create was not called before, it fails + get-definition: func() -> agent-type; + + /// Gets the agent types defined by this component + discover-agent-types: func() -> result, agent-error>; +} + +world agent-guest { + import golem:api/host@1.5.0; + import common; + import invocation-context; + export guest; +} + +world agent-host { + export host; +} diff --git a/sdks/python/wit/deps/golem-agent/host.wit b/sdks/python/wit/deps/golem-agent/host.wit new file mode 100644 index 0000000000..a84e32bb79 --- /dev/null +++ b/sdks/python/wit/deps/golem-agent/host.wit @@ -0,0 +1,208 @@ +package golem:agent@2.0.0; + +interface host { + use golem:core/types@2.0.0.{agent-id, promise-id, schema-graph, schema-value-tree, permission-card, invocation-id}; + use wasi:clocks/system-clock@0.3.0.{instant as datetime}; + use common.{agent-error, agent-type, registered-agent-type, typed-agent-config-value}; + + /// Gets all the registered agent types + get-all-agent-types: func() -> list; + + /// Get a specific registered agent type by name + get-agent-type: func(agent-type-name: string) -> option; + + /// Gets the deployed agent type that the type tag of an agent ID names. Returns `none` + /// when no deployed agent type has that tag. + get-agent-type-by-agent-id: func(agent-id: agent-id) -> option; + + /// Creates a webhook that can be used to integrate with webhook driven apis. + /// When the created url is called with a post request, the provided promise-id is completed with the body of the post request. + /// Note the following behaviours: + /// * Only agents whoose agent types are _currently_ deployed via an http api are allowed to create a webhook. Calling this function while the agent + /// is not deployed via an http api will trap. + /// * Only the agent type that created the promise is allowed to create a webhook for it. Using this host function + /// from a different agent type will trap. + variant webhook-error { + permission-denied, + internal-error(string), + } + + create-webhook: func(promise-id: promise-id) -> result; + + /// Possible failures of an RPC call + variant rpc-error { + /// Protocol level error + protocol-error(string), + /// Access denied + denied(string), + /// Target agent or function not found + not-found(string), + /// Internal error on the remote side + remote-internal-error(string), + /// The remote endpoint returned an agent-domain error + remote-agent-error(agent-error), + /// A keyed create found an agent that already has the key, or the agent at the ID + /// that a key derives has another key + conflict(string) + } + + /// Gets the ID of the keyed agent of the given type and constructor parameters, or + /// `none` when no such agent exists. Never creates the agent. + /// + /// `input` is a value tree whose root encodes the constructor's parameter list. + lookup-agent-id: func(agent-type-name: string, input: schema-value-tree) -> result, rpc-error>; + + /// Options of `wasm-rpc.create` + record create-options { + /// Creates the keyed agent of the constructor parameters, and fails with `conflict` + /// when it already exists. Otherwise the new agent has no key and a new ID. + keyed: bool, + /// Overrides of the agent type's local configuration values + agent-config: list, + /// Environment variables added to the ones the manifest defines + env: list>, + } + + /// An agent created by `wasm-rpc.create` + record created { + client: wasm-rpc, + agent-id: agent-id, + } + + /// Final identity allocated for one remote invocation. For an ephemeral + /// target, `agent-id` is the ID of the one-shot instance that ran it. + record invocation-metadata { + agent-id: agent-id, + invocation-id: invocation-id, + } + + /// Result of an awaited invocation together with its final identity. + record invocation-result-with-metadata { + metadata: invocation-metadata, + %result: option, + } + + /// Asynchronous invocation handle together with its final identity, when + /// preparation succeeded. Rejected calls report their error through the future. + record async-invocation-with-metadata { + metadata: option, + %future: future-invoke-result, + } + + /// Receipt returned when an invocation has been scheduled. + record scheduled-invocation-receipt { + metadata: invocation-metadata, + } + + /// Receipt for a scheduled invocation that can still be cancelled. + record cancelable-scheduled-invocation-receipt { + metadata: invocation-metadata, + cancellation-token: cancellation-token, + } + + /// An RPC client for invoking remote agents + resource wasm-rpc { + /// Creates an RPC client connecting to the keyed agent of the given type and + /// constructor parameters. + /// + /// For durable targets, creates the target if missing and returns after successful + /// initialization. An initialized target is reused without rerunning its constructor. + /// Use `bind-self` to schedule on self from inside an unfinished constructor. + /// For ephemeral targets, each invocation runs on a new one-shot instance. + /// + /// `constructor` is a value tree whose root encodes the target agent + /// constructor's parameter list. + upsert: static func(agent-type-name: string, %constructor: schema-value-tree) -> result; + + /// Creates an RPC client connecting to the existing agent with the given ID. Never + /// creates the agent. Fails with `not-found` when no agent of the given type has the ID. + get-by-id: static func(agent-type-name: string, agent-id: agent-id) -> result; + + /// Creates a durable agent of the given type, and returns after its successful + /// initialization. The creation is durable: replay returns the same agent. + /// + /// `constructor` is a value tree whose root encodes the target agent + /// constructor's parameter list. + create: static async func(agent-type-name: string, %constructor: schema-value-tree, options: create-options) -> result; + + /// The ID of the agent this client connects to. On a client of `upsert` it creates the + /// agent when it is missing, without invoking a method. + agent-id: async func() -> result; + + /// Binds the current durable agent incarnation without creating it or waiting + /// for its constructor to finish. + /// + /// Use this to schedule work on self from inside the constructor. The agent's + /// identity already exists then, but initialization is still in progress. + /// Normal RPC client construction reuses an initialized agent without running + /// its constructor again, but waits if initialization is still in progress. + /// Calling it on self from the constructor would therefore deadlock. + /// + /// Binding does not make awaited self-calls reentrant. Scheduled work runs + /// after construction finishes. Method calls still require method authority. + /// Typed clients must validate the returned agent type. The returned ID and + /// connection preserve the recorded incarnation during replay. + bind-self: static func() -> result, rpc-error>; + + /// Invokes a remote method with the given parameters, and awaits the result. + /// + /// `input` encodes the method's parameter list. The returned result is + /// `none` for a `unit` output and `some(value)` for a `single` output. + invoke-and-await: func(method-name: string, input: schema-value-tree, scope-card: option>) -> result; + + /// Triggers the invocation of a remote method with the given parameters, + /// and returns its final identity immediately. + /// Scope lending is not supported: `scope-card` must be `none`. + invoke: func(method-name: string, input: schema-value-tree, scope-card: option>) -> result; + + /// Invokes a remote method with the given parameters, and returns a `future-invoke-result` value which can + /// be polled for the result together with the final invocation identity. + /// + /// With this function it is possible to call multiple (different) agents simultaneously. + async-invoke-and-await: func(method-name: string, input: schema-value-tree, scope-card: option>) -> async-invocation-with-metadata; + + /// Schedules an invocation for later and returns its final identity. + /// Scope lending is not supported: `scope-card` must be `none`. + schedule-invocation: func(scheduled-time: datetime, method-name: string, input: schema-value-tree, scope-card: option>) -> result; + + /// Schedules an invocation for later and returns its final identity and + /// cancellation capability. Call cancel on the returned resource to + /// cancel the invocation before the scheduled time. + /// Scope lending is not supported: `scope-card` must be `none`. + schedule-cancelable-invocation: func(scheduled-time: datetime, method-name: string, input: schema-value-tree, scope-card: option>) -> result; + } + + /// Represents an asynchronous invocation result + resource future-invoke-result { + /// Awaits the result of the invocation. + get: async func() -> result, rpc-error>; + /// Best-effort attempt to cancel the remote invocation by idempotency key. + /// If the invocation has already started or completed, this is a no-op. + cancel: func(); + } + + /// Cancellation token for scheduled invocations + resource cancellation-token { + /// Cancel the scheduled invocation + cancel: func(); + } + + /// Get the current value of the config key. + /// + /// The expected schema is a hint to the host what type of value is expected by the guest and can be used + /// by the host to automatically migrate config values to fit the expected schema. + /// + /// Only keys that are declared by the agent-type are allowed to be accessed. Trying + /// to access an undeclared key will trap, unless the expected type is an option. In that case + /// none is returned. + /// + /// Getting a local key will get values defined as part of the current + /// component revision + overrides declared during agent creation. + /// + /// Getting a shared key will get the current value of the key in the environment. + variant config-value-error { + permission-denied, + } + + get-config-value: func(key: list, expected: schema-graph) -> result; +} diff --git a/sdks/python/wit/deps/golem-agent/invocation-context.wit b/sdks/python/wit/deps/golem-agent/invocation-context.wit new file mode 100644 index 0000000000..f1c148084b --- /dev/null +++ b/sdks/python/wit/deps/golem-agent/invocation-context.wit @@ -0,0 +1,17 @@ +package golem:agent@2.0.0; + +/// Describes the invocation that runs the calling code. Every function reads values recorded +/// with the start of the invocation, so no function is a durable call. +interface invocation-context { + use golem:core/types@2.0.0.{invocation-id as current-invocation-id}; + use common.{caller as invocation-caller}; + + /// Returns the ID of the running invocation. A nested tool call returns the ID of the + /// enclosing invocation. Returns none outside an invocation: during component initialization, + /// in snapshot save and load, and in oplog processing. + invocation-id: func() -> option; + + /// Returns the caller of the running invocation. Code that runs without a recorded caller + /// gets the agent itself in both roles. + caller: func() -> invocation-caller; +} diff --git a/sdks/python/wit/deps/golem-core-v2/golem-core-v2.wit b/sdks/python/wit/deps/golem-core-v2/golem-core-v2.wit new file mode 100644 index 0000000000..9ea621303a --- /dev/null +++ b/sdks/python/wit/deps/golem-core-v2/golem-core-v2.wit @@ -0,0 +1,713 @@ +// Language-independent value and type model used by Golem agents and the +// platform's typed I/O surfaces. +// +// Recursive schema types and values are represented flat-with-indices because +// WIT does not support recursive types. The matching in-memory forms in each +// SDK (e.g., a recursive `SchemaType` / `SchemaValue` / `SchemaGraph` in Rust) +// convert to and from this flat form mechanically. +// +// Design notes: +// - Graph-with-root: a `schema-graph` owns a `defs` list of named type +// definitions, a flat `type-nodes` list, and a root index. +// `schema-type-node::ref-type` references entries in `defs` by index. A +// `schema-graph` is always self-contained โ€” there is no implicit external +// registry that consumers must look up. +// - `quantity-value` is a fixed-point decimal `mantissa * 10^(-scale)` with +// a unit string; mantissa fits in `s64` and scale fits in `s32`. + +package golem:core@2.0.0; + +interface types { + // ============================================================ + // Carrier indices + // ============================================================ + + /// Index into a `schema-graph`'s `type-nodes` list. + type type-node-index = s32; + + /// Index into a `schema-value-tree`'s `value-nodes` list. + type value-node-index = s32; + + /// Index into a `schema-graph`'s `defs` list. + type def-index = s32; + + /// Stable, language-independent identifier for a named type definition. + /// Must be unique within the enclosing `schema-graph`. Conventional format + /// is a dot-separated namespace path (e.g., `"myapp.users.user"`). Each + /// SDK provides a default derivation rule (typically based on the local + /// language's type name); cross-language interop requires the same + /// `type-id` on every side, which users can pin via the SDK's `named` + /// attribute. + type type-id = string; + + // ============================================================ + // Common embedded value types + // ============================================================ + + record uuid { + high-bits: u64, + low-bits: u64, + } + + /// Parses a UUID from a string + parse-uuid: func(uuid: string) -> result; + + /// Converts a UUID to a string + uuid-to-string: func(uuid: uuid) -> string; + + record datetime { + /// Seconds since the Unix epoch (UTC). + seconds: s64, + /// Nanoseconds since `seconds`, in `[0, 1_000_000_000)`. + nanoseconds: u32, + } + + record environment-id { + uuid: uuid, + } + + // ============================================================ + // Platform identifiers + // ============================================================ + // + // Platform identifiers used by the schema-native surfaces. Keeping them + // here lets migrated interfaces depend on a single core version. + + /// Represents a Golem component + record component-id { + uuid: uuid, + } + + /// Represents a Golem agent: an RFC 9562 version 8 UUID that Golem issues. Its first + /// 32 bits are the agent type's type ID. It holds no component and no environment; + /// an agent ID names an agent within one environment. + record agent-id { + uuid: uuid, + } + + /// The owner whose oplog records an invocation + variant invocation-owner { + /// An agent. A tool invocation is owned by the agent of its external-tool owner. + agent(agent-id), + /// A tool. The runtime does not produce this case yet. + tool(string), + } + + /// Identifies one invocation. With an agent owner, its text form is `.`, where `` is the owner's agent ID as a UUID. + record invocation-id { + owner: invocation-owner, + id: uuid, + } + + /// Represents a Golem account + record account-id { + uuid: uuid, + } + + /// Represents a Golem permission card + record card-id { + uuid: uuid + } + + /// An index into the persistent log storing all performed operations of an agent + type oplog-index = u64; + + /// A promise ID is a value that can be passed to an external Golem API to + /// complete that promise from an arbitrary external source, while Golem + /// agents can await for this completion. + record promise-id { + agent-id: agent-id, + /// Fingerprint of the agent incarnation that created the promise. A deleted and + /// re-created agent keeps its agent ID but gets a new fingerprint, so the promise IDs + /// of the deleted incarnation do not reach the new one. + fingerprint: uuid, + oplog-idx: oplog-index, + } + + // ============================================================ + // Capability resources + // ============================================================ + + /// An unforgeable capability granting the right to consume a named + /// resource. The handle is opaque: a guest can only obtain one from the + /// host (e.g. via `golem:quota`) and can never inspect or fabricate its + /// internal state. When carried in a `schema-value-tree` (see + /// `schema-value-node::quota-token-handle`) the handle is transferred by + /// ownership; the host converts it to/from its internal trusted + /// representation at the boundary. + resource quota-token; + + /// An unforgeable handle to sensitive material held by the runtime. The + /// handle is opaque to guests: components can pass it through schema values + /// and reveal it only through capability-gated host interfaces. + resource secret; + + /// An affine wrapper around a native Component Model stream of schema + /// values. The indirection lets a stream occur anywhere in a recursive + /// `schema-value-tree` while preserving the native stream endpoint. + resource schema-value-stream { + /// Wraps items and their producer's explicit outcome for placement in a value tree. + /// Producers may supply only ok or failed. None means no explicit outcome: + /// body settlement supplies abandoned on normal return or trapped on a trap. + wrap: static async func(reader: stream, outcome: future>) -> own; + + /// Consumes the wrapper. Completion resolves only after the reader consumes EOF. + /// Readers must await completion at EOF; a failed outcome is not a clean end. + unwrap: static async func(value: own) -> tuple, future>; + } + + /// An unforgeable handle to a permission card held by the runtime. The + /// handle is opaque to guests: components can hold, pass, derive, install, + /// and revoke cards only through the `golem:permissions` interfaces. When + /// carried in a `schema-value-tree` (see + /// `schema-value-node::permission-card-handle`) the handle is transferred + /// by ownership; the host converts it to/from its internal trusted + /// card-store representation at the boundary. The wire form is the card-id + /// (UUID) alone โ€” no grants, parents, or metadata cross the wire as + /// authority. + resource permission-card; + + // ============================================================ + // Schema graph (self-contained type carrier) + // ============================================================ + + /// A self-contained schema graph. Anywhere a schema travels with a value + /// (typed pair, oplog `custom` payload, REST/RPC envelope, public oplog + /// rendering), the payload owns its own `schema-graph` โ€” there is no + /// implicit external registry that consumers must look up. + record schema-graph { + /// All schema-type nodes used in this graph. Reachable from `root` + /// directly (anonymous types) or transitively via `defs`. + type-nodes: list, + /// Named type definitions in this graph. Indices into this list are + /// the targets of `schema-type-node::ref-type`. Ordering is + /// deterministic (sorted by `id`). + defs: list, + /// Index into `type-nodes` of the root schema type. + root: type-node-index, + } + + /// A named type definition inside a `schema-graph`. + /// + /// The def itself does not carry metadata; metadata lives on the + /// referenced `schema-type-node` so there is one source of truth for + /// docs / aliases / examples / deprecation / role on each type. + record schema-type-def { + /// Stable identifier; unique within the enclosing graph. + id: type-id, + /// Optional human-readable qualified name (display only). + name: option, + /// Index into the enclosing graph's `type-nodes` for this def's body. + body: type-node-index, + } + + /// Typed metadata envelope. Holds non-validation, non-rendering-critical + /// information (docs, aliases, examples, deprecation, role). Per-scalar + /// validation constraints live on the relevant scalar's typed substructure, + /// not here. + record metadata-envelope { + doc: option, + aliases: list, + /// Canonical-encoded example values (JSON strings). Empty = no examples. + /// Kept as strings so metadata is self-contained on the type side and + /// does not have to cross-reference an accompanying value tree. + examples: list, + /// Deprecation message; `none` means not deprecated. + deprecated: option, + /// Optional role annotation tagging a type with a consumer-facing intent. + role: option, + } + + /// Open registry; unknown roles fall back to structural handling. + variant role { + /// `list>` whose elements are interchangeable modalities. + multimodal, + /// `variant { inline: text, url: url }` ergonomic unstructured-text wrapper. + unstructured-text, + /// `variant { inline: binary, url: url }` ergonomic unstructured-binary wrapper. + unstructured-binary, + /// Any other producer-defined role, preserved verbatim. + other(string), + } + + // ============================================================ + // Schema type + // ============================================================ + + /// One node in a `schema-graph`. Carries the type body and a per-node + /// metadata envelope (docs, aliases, examples, deprecation, role). + /// Recursive positions reference other nodes (or named definitions) by + /// index inside the body. + record schema-type-node { + body: schema-type-body, + metadata: metadata-envelope, + } + + /// The structural body of a `schema-type-node`. + /// + /// Closed sum types come in two shapes that differ by how the decoder + /// learns which branch a value belongs to: + /// + /// - `variant-type` is a **carried-tag** sum: the value explicitly + /// carries its case (`variant-value.case` index). Zero-inference + /// decoding. Natural mapping for language-level algebraic data types + /// (Rust `enum`, Scala `sealed trait`, WIT `variant`, etc.). + /// + /// - `union-type` is an **inferred-tag** sum: the value does not carry + /// its tag. Each branch declares a `discriminator-rule` (prefix / + /// suffix / contains / regex on string-shaped bodies, or + /// field-equals / field-absent on record-shaped bodies) and the + /// decoder picks the branch whose rule matches the raw value. + /// Natural mapping for inputs where the producer writes an unadorned + /// value (a URL whose scheme picks the handler, a JSON object whose + /// `"kind"` field picks the variant, an MCP content block whose + /// `"type"` field picks the part shape, โ€ฆ). + variant schema-type-body { + // --- Reference to a named definition in the same `schema-graph` --- + ref-type(def-index), + + // --- Primitives --- + bool-type, + s8-type(option), + s16-type(option), + s32-type(option), + s64-type(option), + u8-type(option), + u16-type(option), + u32-type(option), + u64-type(option), + f32-type(option), + f64-type(option), + char-type, + string-type, + + // --- Structural composites --- + record-type(list), + variant-type(list), + enum-type(list), + flags-type(list), + tuple-type(list), + list-type(type-node-index), + fixed-list-type(fixed-list-spec), + map-type(map-spec), + option-type(type-node-index), + result-type(result-spec), + + // --- Rich semantic types --- + text-type(text-restrictions), + binary-type(binary-restrictions), + path-type(path-spec), + url-type(url-restrictions), + uuid-type, + datetime-type, + duration-type, + quantity-type(quantity-spec), + + // --- Discriminated union (closed, inferred-tag) --- + union-type(union-spec), + + // --- Capability nodes --- + secret-type(secret-spec), + quota-token-type(quota-token-spec), + permission-card-type(permission-card-spec), + + // --- WASI P3 stubs (parseable only; no semantics yet) --- + future-type(option), + stream-type(option), + } + + record named-field-type { + name: string, + body: type-node-index, + metadata: metadata-envelope, + } + + record variant-case-type { + name: string, + payload: option, + metadata: metadata-envelope, + } + + record fixed-list-spec { + element: type-node-index, + length: u32, + } + + /// Map key types are restricted to primitives. Enforced at schema + /// construction time, not by the WIT type itself. + record map-spec { + key: type-node-index, + value: type-node-index, + } + + record result-spec { + ok: option, + err: option, + } + + // --- Numeric restrictions --- + + /// A numeric bound usable across every numeric representation. Float bounds + /// carry canonical IEEE-754 `f64` bits (NaN/inf rejected, -0.0 normalized); + /// comparisons decode the bits to `f64` and compare numerically. + variant numeric-bound { + signed(s64), + unsigned(u64), + float-bits(u64), + } + + /// Inline numeric refinement. `none` on a numeric type means unconstrained + /// (the common case). The empty restriction set is never encoded as `some`: + /// producers normalize it to `none`, decoders normalize a decoded empty to + /// `none`. `unit` is schema/help metadata only. + record numeric-restrictions { + min: option, + max: option, + unit: option, + } + + // --- Text / Binary restrictions --- + + record text-restrictions { + /// Optional set of allowed BCP-47 language codes. `none` = unrestricted. + languages: option>, + min-length: option, + max-length: option, + regex: option, + } + + record binary-restrictions { + /// Optional set of allowed MIME types. `none` = unrestricted. + mime-types: option>, + min-bytes: option, + max-bytes: option, + } + + // --- Path --- + + enum path-direction { + input, + output, + in-out, + } + + enum path-kind { + file, + directory, + any, + } + + record path-spec { + direction: path-direction, + kind: path-kind, + allowed-mime-types: option>, + allowed-extensions: option>, + } + + // --- URL --- + + record url-restrictions { + allowed-schemes: option>, + allowed-hosts: option>, + } + + // --- Quantity --- + + /// Fixed-point decimal value with unit: numeric value = `mantissa * 10^(-scale)`. + /// `unit` is a free-form string at the value level; the schema's + /// `quantity-spec` constrains the accepted set. + record quantity-value { + mantissa: s64, + scale: s32, + unit: string, + } + + record quantity-spec { + /// Canonical base unit (e.g., `"kg"`, `"m"`, `"s"`, `"B"`). + base-unit: string, + /// Suffixes accepted on input and rendered on output (e.g., `["kg","g","mg"]`). + allowed-suffixes: list, + /// Optional inclusive range, expressed in canonical fixed-point form. + min: option, + max: option, + } + + // --- Discriminated union --- + // + // Inferred-tag sum. Each branch declares a rule that the decoder uses to + // identify values belonging to that branch from the raw underlying value. + // + // Portable schema-construction contract: + // - branch `tag`s are unique within the union, + // - string-pattern discriminators (`prefix` / `suffix` / `contains` / + // `regex`) require a branch body whose canonical raw JSON + // representation is a string (`string-type`, `url-type`, `path-type`, + // or a `ref` resolving to one), + // - `field-equals` requires a record-shaped branch body that declares + // the referenced field; a literal additionally requires that field to + // have a canonical raw JSON string representation, + // - `field-absent` requires a record-shaped branch body that does not + // declare the referenced field, + // - byte-identical regex text is rejected first as duplicate syntax, + // without making a semantic claim about the regex language, + // - every remaining pair of discriminator rules is classified as + // overlapping, disjoint, or indeterminate. Overlapping pairs are rejected; + // disjoint and indeterminate pairs are accepted. Runtime decoders + // still reject a raw value that matches multiple accepted branches. + // + // The canonical pair classification is symmetric and based only on the + // raw discriminator rules; branch body schemas do not refine it: + // - two prefixes overlap exactly when either prefixes the other, + // - two suffixes overlap exactly when either suffixes the other, + // - every prefix/suffix, prefix/contains, suffix/contains, and + // contains/contains pair overlaps, + // - a string-pattern rule and a record-shaped rule are disjoint because + // a raw JSON value cannot be both a string and an object, + // - field-equals rules on different fields overlap; on the same field + // they are disjoint only when both literals are present and differ, + // - every pair of field-absent rules overlaps, + // - field-equals and field-absent are disjoint on the same field and + // overlap on different fields, + // - after the duplicate-syntax check above, every pair containing a + // regex and another string-pattern rule is indeterminate and accepted. + // No portable semantic regex-overlap analysis is attempted because SDK + // regex dialects differ. + + record union-spec { + branches: list, + } + + record union-branch { + /// Logical branch name. Carried in `union-value.tag` after the + /// decoder resolves the branch; used by renderers, codegen, docs. + tag: string, + /// Branch body type. Any schema type compatible with the + /// discriminator rule (see schema-construction validation above). + body: type-node-index, + /// Rule the decoder uses to pick this branch from a raw value. + discriminator: discriminator-rule, + metadata: metadata-envelope, + } + + /// How the decoder identifies that a value belongs to a given union branch. + variant discriminator-rule { + /// String value starts with this prefix (e.g. `"ssh://"`). + prefix(string), + /// String value ends with this suffix (e.g. `".tar.gz"`). + suffix(string), + /// String value contains this substring. + contains(string), + /// String value has a match for this regex in the implementation's + /// regex dialect. The pattern must include anchors when whole-string + /// matching is required. + regex(string), + /// Record-shaped value where the named field is present, and โ€” if + /// `literal` is set โ€” has the given literal string value. The common + /// JSON-discriminated-object case (`{"kind":"circle",โ€ฆ}`) is + /// `field-equals { field-name: "kind", literal: some("circle") }`. + field-equals(field-discriminator), + /// Record-shaped value where the named field is absent. + field-absent(string), + } + + record field-discriminator { + field-name: string, + /// Optional required literal value for the field. + literal: option, + } + + // --- Capability nodes --- + + record secret-spec { + /// Revealed payload type carried by this secret handle. + inner: type-node-index, + /// Optional categorisation (e.g., `"api-key"`, `"oauth-token"`). + category: option, + } + + record quota-token-spec { + /// Resource name this token covers (e.g., declared in the agent manifest). + /// `none` = any resource permitted. + resource-name: option, + } + + record permission-card-spec { + /// `true` = polymorphic (carries slot variables in owner / resource-id), + /// `false` = monomorphic. Structural metadata only; authority lives in + /// the card store, not in the schema spec. + polymorphic: bool, + } + + // ============================================================ + // Schema value (always paired with a schema-graph) + // ============================================================ + + /// A flat schema-value tree. Always travels paired with a `schema-graph` + /// (see `typed-schema-value`). Indices refer to entries in `value-nodes` + /// within this same tree. + /// + /// The value tree is structurally driven by the schema: record-value + /// payload order matches the schema's field order, variant-value carries a + /// case index, enum-value carries a case index, union-value carries the + /// discriminator's literal tag. The value side does not redundantly carry + /// field names, case names, or named-ref identifiers โ€” those come from the + /// schema. + record schema-value-tree { + value-nodes: list, + root: value-node-index, + } + + variant schema-value-node { + // Primitives + bool-value(bool), + s8-value(s8), + s16-value(s16), + s32-value(s32), + s64-value(s64), + u8-value(u8), + u16-value(u16), + u32-value(u32), + u64-value(u64), + f32-value(f32), + f64-value(f64), + char-value(char), + string-value(string), + + // Structural composites + record-value(list), + variant-value(variant-value-payload), + enum-value(u32), + flags-value(list), + tuple-value(list), + list-value(list), + fixed-list-value(list), + map-value(list), + option-value(option), + result-value(result-value-payload), + + // Rich semantic + text-value(text-value-payload), + binary-value(binary-value-payload), + path-value(string), + url-value(string), + uuid-value(uuid), + datetime-value(datetime), + duration-value(duration-value-payload), + quantity-value-node(quantity-value), + + // Discriminated union: tag is matched against schema branches. + union-value(union-value-payload), + + // Capability nodes + secret-value(own), + quota-token-handle(own), + permission-card-handle(own), + stream-value(own), + + // WASI P3 stubs (parseable only in the schema; no constructible values). + } + + record variant-value-payload { + case: u32, + payload: option, + } + + record map-entry { + key: value-node-index, + value: value-node-index, + } + + /// Result payload: exactly one of `ok-value` / `err-value` is set. Each + /// inner option allows `result<_, _>` cases whose ok/err type is unit (no + /// payload). + variant result-value-payload { + ok-value(option), + err-value(option), + } + + record text-value-payload { + text: string, + /// BCP-47 language tag, when known. + language: option, + } + + record binary-value-payload { + bytes: list, + mime-type: option, + } + + /// Signed duration as total nanoseconds. + record duration-value-payload { + nanoseconds: s64, + } + + record union-value-payload { + /// Tag of the branch the decoder resolved, matching one of the + /// `union-spec::branches[*].tag` values. Carried so receivers do not + /// have to re-run discriminator rules to know which branch was + /// matched; encoders must ensure it agrees with the body. + tag: string, + /// Underlying value. Its shape matches the resolved branch's body + /// type and (by construction) satisfies the branch's discriminator + /// rule. + body: value-node-index, + } + + // ============================================================ + // Wire carriers + // ============================================================ + + /// A typed value: a self-contained schema graph paired with a value tree + /// built against that schema. + record typed-schema-value { + graph: schema-graph, + value: schema-value-tree, + } + + /// The producer's failure, independent of a reader dropping its stream. + variant stream-error { + failed(typed-schema-value), + trapped(string), + /// An invocation cancellation request was recorded and honoured. + cancelled, + /// The producing invocation completed with its writer still open. + abandoned, + interrupted(string), + resource-exhausted(string), + } + + type stream-outcome = result<_, stream-error>; + + /// A declared tool failure shared by invocation and oplog interfaces. + record custom-tool-error { + /// The selected declared error-case name, independent of payload shape. + name: string, + /// Unit for a payloadless error; otherwise the declared payload type. + payload: typed-schema-value, + } + + variant tool-error { + invalid-tool-name(string), + invalid-command-path(list), + invalid-input(string), + constraint-violation(string), + /// The returned value does not match the body's declared result schema. + invalid-result(string), + /// Consumers preserve unfamiliar names and typed payloads when forwarding. + custom-error(custom-tool-error), + } + + variant tool-rpc-error { + protocol-error(string), + denied(string), + not-found(string), + remote-internal-error(string), + remote-tool-error(tool-error), + /// The operation's explicit cancellation won terminal arbitration. + cancelled, + /// A filesystem-capable input or output attachment exceeded the + /// configured per-direction retained-byte limit. + resource-exhausted(string), + } + +} diff --git a/sdks/python/wit/deps/golem-core-v2/http.wit b/sdks/python/wit/deps/golem-core-v2/http.wit new file mode 100644 index 0000000000..a1191a4b52 --- /dev/null +++ b/sdks/python/wit/deps/golem-core-v2/http.wit @@ -0,0 +1,83 @@ +interface http { + variant http-method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + custom(string), + } + + variant path-segment { + literal(string), + path-variable(path-variable), + // only allowed as the last segment + remaining-path-variable(path-variable), + } + + record path-variable { + variable-name: string, + } + + record header-variable { + header-name: string, + variable-name: string, + } + + record query-variable { + query-param-name: string, + variable-name: string, + } + + variant file-mapping { + exact(exact-file-mapping), + subtree(subtree-file-mapping), + } + + record exact-file-mapping { + public-path: list, + file-path: string, + } + + record subtree-file-mapping { + public-prefix: list, + filesystem-root: string, + } + + record file-response-header { + name: string, + value: string, + } + + enum http-route-mode { + durable-streams, + plain, + sse, + web-socket, + } + + record durable-stream-route-options { + slots: list, + load: option, + } + + record durable-stream-slot-options { + source: durable-stream-slot-source, + name: option, + content-type: option, + } + + variant durable-stream-slot-source { + input(string), + output(string), + } + + record durable-stream-route-load-options { + max-concurrent-readers-per-stream: option, + max-append-requests-per-second-per-stream: option, + } +} diff --git a/sdks/python/wit/deps/golem-durability/golem-durability.wit b/sdks/python/wit/deps/golem-durability/golem-durability.wit new file mode 100644 index 0000000000..d389b375bc --- /dev/null +++ b/sdks/python/wit/deps/golem-durability/golem-durability.wit @@ -0,0 +1,111 @@ +package golem:durability@1.6.0; + +interface durability { + use golem:api/oplog@1.5.0.{wrapped-function-type}; + use wasi:clocks/system-clock@0.3.0.{instant as datetime}; + use golem:core/types@2.0.0.{typed-schema-value}; + + type durable-function-type = wrapped-function-type; + + /// A resident snapshot of custom invocation attribution for the current invocation. + /// Dropping a snapshot does not close any live custom invocation. + resource custom-invocation-context; + + /// With no argument, captures the current context without changing it. With a snapshot, + /// consumes and installs it and returns the previous context. A snapshot can contain an + /// empty context. Snapshots cannot be installed in another invocation or after their + /// enclosing custom invocations have closed. This operation neither yields nor journals. + exchange-custom-invocation-context: func( + next: option, + ) -> custom-invocation-context; + + /// A live custom durable invocation. + /// + /// Attribution follows the guest-installed execution scope, not the resource's lifetime. + /// Synchronous begin and enter install the scope on the current task; exchange switches it. + /// Host effects initiated in that scope are replay-inert observational entries owned by + /// the invocation. Detached work and concurrent SDK continuations do not acquire the scope + /// automatically; the guest runtime must install it around execution and destruction. + /// Nested operations must finish or be dropped before their parent finishes. + /// Synchronous finish consumes the resource; asynchronous finish borrows it while persisting + /// the response. Dropping it without finishing leaves the invocation incomplete so normal + /// recovery re-executes it. + resource live-custom-durable-invocation { + /// Installs a live invocation returned by asynchronous admission on the current task. + enter: func(); + + /// Completes the invocation with its schema-carrying response. + finish: static func( + this: live-custom-durable-invocation, + response: typed-schema-value, + forced-commit: bool, + ); + + /// Completes an asynchronous invocation at a recorded guest result-delivery boundary. + /// The caller retains the resource until completion or cancellation, then drops it. + finish-async: static async func( + this: borrow, + response: typed-schema-value, + forced-commit: bool, + ); + } + + /// Represents the oplog entry version; this is for backward compatibility and most use cases should always use + /// (and expect) the latest version. + enum oplog-entry-version { + v1, + v2 + } + + /// Represents a persisted durable function invocation. The `response` field + /// contains a value and its schema graph together, making the user-defined payload observable by external tools. + record persisted-durable-function-invocation { + /// The timestamp of the invocation. + timestamp: datetime, + /// The invoked function's unique name + function-name: string, + /// Arbitrary structured value and schema graph describing the invocation's result + response: typed-schema-value, + /// Type of the durable function invocation + function-type: durable-function-type, + /// Oplog entry version + entry-version: oplog-entry-version + } + + /// The result of opening a custom durable invocation. + variant custom-durable-invocation { + /// Execute the operation body and finish the returned live invocation. + live(live-custom-durable-invocation), + /// Return the recorded response without executing the operation body. + replayed(persisted-durable-function-invocation), + } + + /// Observes a function call (produces logs and metrics) + observe-function-call: func(iface: string, function: string); + + /// Opens a custom durable invocation. + /// + /// The executor allocates a deterministic identity synchronously when the call begins. A fresh + /// or incomplete invocation returns an owned `live-custom-durable-invocation`. A completed + /// invocation returns `replayed` with its recorded response. + begin-custom-durable-invocation: func( + function-name: string, + request: typed-schema-value, + function-type: durable-function-type, + ) -> custom-durable-invocation; + + /// Admits an asynchronous operation without blocking sibling guest futures. Live admission + /// requires enter before executing the body. Completed replay waits for recorded delivery. + begin-custom-durable-invocation-async: async func( + function-name: string, + request: typed-schema-value, + function-type: durable-function-type, + ) -> custom-durable-invocation; + + // The p2 version of this interface had a `lazy-initialized-pollable` resource: a + // host-owned pollable that was ready while unattached (during replay) and could later + // be re-bound to a real pollable when execution went live. It has no p3 equivalent + // and none is needed: p3 `future`/`stream` handles are one-shot and guest-creatable, + // so durable stream wrappers express the replay-to-live transition by resolving + // replayed results immediately and directly awaiting the live source afterwards. +} diff --git a/sdks/python/wit/deps/golem-network/dns.wit b/sdks/python/wit/deps/golem-network/dns.wit new file mode 100644 index 0000000000..cfa9129e67 --- /dev/null +++ b/sdks/python/wit/deps/golem-network/dns.wit @@ -0,0 +1,121 @@ +package golem:network@0.1.0; + +/// DNS record lookups. +/// +/// `wasi:sockets/ip-name-lookup` resolves names to addresses only. This interface queries one +/// record type of one name and returns the typed records of the answer with their TTLs. +/// +/// Each call is one durable operation of the agent: the host records the answer, and a replay +/// returns the recorded answer, including a negative answer or an error, without a query. A +/// transient resolver failure retries under the agent's retry policy. A lookup needs the same +/// `network` grant on the name as an address lookup, and the operator must enable agent sockets. +/// The A and AAAA answers link their addresses to the queried name, so a grant on the name also +/// allows a socket connect to those addresses. +/// +/// The host uses the upstream servers of the executor configuration, by default the system +/// resolver configuration. It does not read the hosts file and does not cache answers. +interface dns { + /// The record type to query. + enum record-type { + a, + aaaa, + cname, + mx, + ns, + ptr, + srv, + txt, + caa, + soa, + naptr, + } + + type ipv4-address = tuple; + type ipv6-address = tuple; + + /// A mail exchange (RFC 1035). + record mx-record { + preference: u16, + exchange: string, + } + + /// A service location (RFC 2782). + record srv-record { + priority: u16, + weight: u16, + port: u16, + target: string, + } + + /// A certification authority authorization (RFC 8659). `issuer-critical` is the high bit of + /// the flags; `value` holds the raw value octets. + record caa-record { + issuer-critical: bool, + tag: string, + value: list, + } + + /// The start of a zone of authority (RFC 1035). + record soa-record { + mname: string, + rname: string, + serial: u32, + refresh: u32, + retry: u32, + expire: u32, + minimum: u32, + } + + /// A naming authority pointer (RFC 3403). + record naptr-record { + order: u16, + preference: u16, + naptr-flags: string, + services: string, + regexp: string, + replacement: string, + } + + /// The data of one record. Domain names are in ASCII presentation form without the final dot. + variant record-data { + a(ipv4-address), + aaaa(ipv6-address), + cname(string), + mx(mx-record), + ns(string), + ptr(string), + srv(srv-record), + /// The character strings of the record, as raw octets. + txt(list>), + caa(caa-record), + soa(soa-record), + naptr(naptr-record), + } + + /// One record of an answer, with its time to live in seconds as the answer gave it. + record dns-record { + ttl: u32, + data: record-data, + } + + variant dns-error { + /// No grant allows a lookup of the name. + access-denied, + /// The name is not a valid domain name. + invalid-name, + /// The name does not exist (`NXDOMAIN`). + name-not-found, + /// The name exists but has no records of the queried type. + no-data, + /// The lookup can succeed later: the servers timed out, were unreachable or answered + /// `SERVFAIL`. + temporary-resolver-failure, + /// The servers refused the query or failed in a way that a retry does not repair, or the + /// operator did not enable agent sockets. + permanent-resolver-failure, + } + + /// Queries the records of type `record-type` of `name`. The answer holds only records of that + /// type; the CNAME records of a followed alias chain are left out. + resolve: async func(name: string, record-type: record-type) -> result, dns-error>; +} diff --git a/sdks/python/wit/deps/golem-permissions/derive.wit b/sdks/python/wit/deps/golem-permissions/derive.wit new file mode 100644 index 0000000000..8572018224 --- /dev/null +++ b/sdks/python/wit/deps/golem-permissions/derive.wit @@ -0,0 +1,54 @@ +package golem:permissions@0.1.0; + +/// Derivation of new permission cards from an existing card or from the +/// caller's wallet. +/// +/// Derivation narrows authority: a child card's lattice is bounded by its +/// parent's lattice. The caller specifies which lower-positive and +/// upper-positive grants to retain and which lower-negative and +/// upper-negative grants to add, plus an optional lifespan. +/// +/// Persistent derivation returns a template if any requested grant contains +/// an owner slot variable (`?agent`, `?env`, ...), otherwise a concrete card. +/// Resource-ID slots are not supported and return `invalid-pattern`. Slots +/// name the eventual holder, not the caller. Every possible instantiation +/// must be bounded by the parent. A template parent in the caller's wallet +/// is resolved for the caller before validation. +interface derive { + use golem:core/types@2.0.0.{permission-card}; + use types.{pattern-grant, permission-error, duration, persistent-card}; + + /// Derive a child card from `parent`, narrowing the grant lattice. + /// + /// A template parent (one whose grants carry slot variables) must be in + /// the caller's wallet and is resolved against the caller's identity. + /// Only its grants addressed to the caller can be retained. + derive: func( + parent: borrow, + lower-positive-to-retain: list, + lower-negative-to-add: list, + upper-positive-to-retain: list, + upper-negative-to-add: list, + lifespan: option, + ) -> result; + + /// Derive a card directly from the caller's wallet. + derive-from-wallet: func( + lower-positive: list, + lower-negative: list, + upper-positive: list, + upper-negative: list, + lifespan: option, + ) -> result; + + /// Derive an invocation-local card from one or more persistent or scope + /// parents. Scope cards are attenuated in-memory and are never persisted. + /// Requested grants must be concrete; slots return `invalid-pattern`. + derive-scope: func( + parents: list>, + lower-positive: list, + lower-negative: list, + upper-positive: list, + upper-negative: list, + ) -> result; +} diff --git a/sdks/python/wit/deps/golem-permissions/inspect.wit b/sdks/python/wit/deps/golem-permissions/inspect.wit new file mode 100644 index 0000000000..34481974fd --- /dev/null +++ b/sdks/python/wit/deps/golem-permissions/inspect.wit @@ -0,0 +1,14 @@ +package golem:permissions@0.1.0; + +/// Read-only inspection of a permission card's full grant lattice. +/// +/// Returns the four quadrants of the card's bound lattice +/// (lower/upper ร— positive/negative) as a `card-view`. Importing this +/// interface grants no authority to mutate or derive cards. +interface inspect { + use golem:core/types@2.0.0.{permission-card}; + use types.{card-view, permission-error}; + + /// Return the card's complete grant lattice. + inspect-card: func(c: borrow) -> result; +} diff --git a/sdks/python/wit/deps/golem-permissions/kernel-introspection.wit b/sdks/python/wit/deps/golem-permissions/kernel-introspection.wit new file mode 100644 index 0000000000..d555454b01 --- /dev/null +++ b/sdks/python/wit/deps/golem-permissions/kernel-introspection.wit @@ -0,0 +1,20 @@ +package golem:permissions@0.1.0; + +/// Introspection of the permission kernel's registered resource classes and +/// verbs, and validation of individual grants against the kernel's schema. +interface kernel-introspection { + use types.{pattern-grant, permission-error}; + + record kernel-module { + class-name: string, + verbs: list, + } + + /// List every resource class the kernel knows about, with their + /// permitted verbs. + list-modules: func() -> list; + + /// Validate that `g` references a known class, owner, recipient, verb, + /// and resource-id pattern accepted by the kernel. + validate-grant: func(g: pattern-grant) -> result<_, permission-error>; +} diff --git a/sdks/python/wit/deps/golem-permissions/revoke.wit b/sdks/python/wit/deps/golem-permissions/revoke.wit new file mode 100644 index 0000000000..da2fb7975a --- /dev/null +++ b/sdks/python/wit/deps/golem-permissions/revoke.wit @@ -0,0 +1,15 @@ +package golem:permissions@0.1.0; + +/// Revocation of a permission card and its derivation DAG subtree. +/// +/// `revoke-card` consumes the owned handle (the receiving component's +/// resource-table entry is deleted); the stored card is walked via the card +/// store's DAG descendant index. Returns the cut-subtree size. +interface revoke { + use golem:core/types@2.0.0.{permission-card}; + use types.{permission-error}; + + /// Revoke `c` and every card transitively derived from it. + /// Consumes the owned handle. + revoke-card: func(c: permission-card) -> result; +} diff --git a/sdks/python/wit/deps/golem-permissions/types.wit b/sdks/python/wit/deps/golem-permissions/types.wit new file mode 100644 index 0000000000..79690970bf --- /dev/null +++ b/sdks/python/wit/deps/golem-permissions/types.wit @@ -0,0 +1,98 @@ +package golem:permissions@0.1.0; + +/// The permission-card resource's shared data model and inspection operations. +/// +/// The `permission-card` capability itself is defined as a bare resource in +/// `golem:core/types` so that it can travel inside a `schema-value-tree` as an +/// opaque, unforgeable handle. This interface exposes only safe inspection +/// operations over that handle plus the records and variants the other +/// permissions interfaces reference. Components that only need to *hold and +/// pass* cards โ€” most tools and middleware โ€” import only this interface. +interface types { + use golem:core/types@2.0.0.{permission-card, card-id, agent-id, uuid}; + + record timestamp { + seconds: s64, + nanoseconds: u32, + } + + /// ISO-8601 duration string (e.g. `"P30D"` for 30 days). + record duration { + iso-8601: string, + } + + variant holder { + account(uuid), + app(uuid), + agent(agent-id), + } + + record pattern-grant { + class: string, + owner: string, + recipient: string, + verb: string, + resource-id: string, + } + + record card-view { + lower-positive: list, + lower-negative: list, + upper-positive: list, + upper-negative: list, + } + + record wallet-version-token { + /// 32 bytes โ€” BLAKE3 of (holder-kind, holder-id). + wallet-id-hash: list, + generation: u64, + } + + variant permission-error { + not-permitted(string), + lower-bound-too-broad(string), + upper-bound-too-broad(string), + wallet-multi-source-required(string), + card-revoked(string), + card-expired(string), + install-recipient-mismatch(string), + unknown-resource-class(string), + invalid-pattern(string), + invalid-verb(string), + invalid-owner(string), + invalid-recipient(string), + } + + /// A persistent derivation result, labelled with its kind. + variant persistent-card { + concrete(permission-card), + template(permission-card), + } + + /// A card in the caller's wallet, labelled with its kind. + variant wallet-card { + /// A concrete card: every grant names concrete owners and resources. + concrete(permission-card), + /// A template card: its grants may contain slot variables (`?agent`, + /// `?env`, ...), which resolve for each holder. + template(permission-card), + /// The scope card lent to the current invocation. It can be inspected + /// and attached to awaited calls, and is retired at the end of the + /// invocation. + scope(permission-card), + } + + // --- Card inspection --- + // Free functions on a borrowed handle, because the resource itself is + // bare in core (matching secret/quota-token). + + /// Stable identifier of this card. + id: func(c: borrow) -> card-id; + + /// Parent card identifiers in the derivation DAG. + parents: func(c: borrow) -> list; + + /// Expiry timestamp, if the card has a bounded lifespan. For a scope card, + /// the earliest expiry of its root cards. + expires-at: func(c: borrow) -> option; +} diff --git a/sdks/python/wit/deps/golem-permissions/wallet.wit b/sdks/python/wit/deps/golem-permissions/wallet.wit new file mode 100644 index 0000000000..a14155c274 --- /dev/null +++ b/sdks/python/wit/deps/golem-permissions/wallet.wit @@ -0,0 +1,29 @@ +package golem:permissions@0.1.0; + +/// Wallet operations: enumerate the caller's installed cards, query the +/// wallet's version token, and install a card onto a target holder. +interface wallet { + use golem:core/types@2.0.0.{permission-card}; + use types.{permission-error, wallet-version-token, holder, wallet-card}; + + /// All permission cards currently installed in the caller's wallet, each + /// labelled with its kind. + /// + /// During an invocation that received a scope card, the list also + /// contains that scope card, as a `scope` entry, if the caller holds + /// `card:inspect`. Without `card:inspect` the scope card is sealed: it + /// still authorizes the invocation but is not listed. + self-wallet: func() -> list; + + /// Version token for the caller's wallet, changed whenever the set of + /// installed cards changes. + self-version: func() -> wallet-version-token; + + /// Install `card` onto `target`. Returns unit on success. + /// + /// Only agent targets are currently supported. Account and application + /// targets return `not-permitted("install-card currently supports only + /// agent targets")` before any wallet or oplog mutation. + install-card: func(card: permission-card, target: holder) + -> result<_, permission-error>; +} diff --git a/sdks/python/wit/deps/golem-quota/types.wit b/sdks/python/wit/deps/golem-quota/types.wit new file mode 100644 index 0000000000..a6acaec556 --- /dev/null +++ b/sdks/python/wit/deps/golem-quota/types.wit @@ -0,0 +1,76 @@ +package golem:quota@1.5.0; + +/// Host interface for the Golem quota system. +/// +/// Agents use quota-tokens to declare intent to consume a named resource and to +/// reserve / commit actual usage. +/// +/// The `quota-token` capability itself is defined in `golem:core/types` so that +/// it can travel inside a `schema-value-tree` as an opaque, unforgeable handle. +/// This interface only exposes the operations that act on such a handle. +interface types { + use golem:core/types@2.0.0.{quota-token}; + + /// Error returned when a reservation cannot be satisfied because the + /// resource's enforcement policy is `reject`. + /// + /// The inner value is an optional estimate in nanoseconds of how long + /// the caller would need to wait for capacity (only available for + /// rate-limited resources). + record failed-reservation { + estimated-wait-nanos: option, + } + + /// A short-lived capability that represents a pending or committed + /// resource consumption. Drop without committing is equivalent to + /// committing zero usage. + resource reservation { + /// Commit actual usage, consuming the reservation. + /// + /// If `used` < reserved โ€” unused capacity is returned to the pool. + /// If `used` > reserved โ€” the excess is deducted from the token's + /// remaining allocation as "debt". + commit: static func(this: reservation, used: u64); + } + + /// Request a quota capability for the given resource. + /// - `resource-name` : the resource name (as declared in the manifest). + /// - `expected-use` : expected units per reservation; used to derive + /// credit rate and max-credit for fair scheduling. + new-token: func( + resource-name: string, + expected-use: u64, + ) -> quota-token; + + /// Reserve `amount` units from the token's local allocation. + /// + /// Blocks internally until capacity is available or the resource's + /// enforcement action fires. Returns a `reservation` handle that + /// must be committed (or dropped) to release unused capacity. + reserve: func( + token: borrow, + amount: u64, + ) -> result; + + /// Split off a child token with `child-expected-use` units from `token`. + /// + /// The parent's `expected-use` is reduced by `child-expected-use`. + /// Credits are divided proportionally between parent and child. + /// + /// Traps if `child-expected-use` exceeds the parent's current `expected-use`. + split: func( + token: borrow, + child-expected-use: u64, + ) -> quota-token; + + /// Merge `other` back into `token`. + /// + /// The two tokens must refer to the same resource (same resource-name + /// and environment). `other` is consumed. + /// + /// Traps if the tokens refer to different resources. + merge: func( + token: borrow, + other: quota-token, + ); +} diff --git a/sdks/python/wit/deps/golem-rdbms/ignite.wit b/sdks/python/wit/deps/golem-rdbms/ignite.wit new file mode 100644 index 0000000000..bdaccfc13a --- /dev/null +++ b/sdks/python/wit/deps/golem-rdbms/ignite.wit @@ -0,0 +1,84 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Golem Source License v1.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://license.golem.cloud/LICENSE +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package golem:rdbms@1.5.0; + +interface ignite2 { + // โ”€โ”€ Error โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + variant error { + connection-failure(string), + query-parameter-failure(string), + query-execution-failure(string), + query-response-failure(string), + other(string), + /// The resident transaction or result stream cannot be resumed. Recorded results + /// remain valid; this does not prove that an earlier write failed. + resource-lost(string), + } + + // โ”€โ”€ Value types (maps 1-to-1 onto ignite_client::IgniteValue) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + variant db-value { + db-null, + db-boolean(bool), + db-byte(s8), + db-short(s16), + db-int(s32), + db-long(s64), + db-float(f32), + db-double(f64), + /// 16-bit Unicode code unit (Java char). + db-char(u16), + db-string(string), + db-uuid(tuple), + /// Milliseconds since Unix epoch (UTC). + db-date(s64), + /// (milliseconds since epoch, sub-millisecond nanoseconds 0..999_999). + db-timestamp(tuple), + /// Nanoseconds since midnight. + db-time(s64), + db-decimal(string), + db-byte-array(list), + } + + // โ”€โ”€ Metadata โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + record db-column { ordinal: u64, name: string } + record db-row { values: list } + record db-result { columns: list, rows: list } + + // โ”€โ”€ Resources โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + resource db-result-stream { + get-columns: func() -> result, error>; + get-next: func() -> result>, error>; + } + + resource db-transaction { + query: func(statement: string, params: list) -> result; + query-stream: func(statement: string, params: list) -> result; + execute: func(statement: string, params: list) -> result; + commit: func() -> result<_, error>; + rollback: func() -> result<_, error>; + } + + resource db-connection { + /// Open a connection to an Apache Ignite 2.x node. + /// + /// Address format: `ignite://[user:pass@]host:port[?pool_size=N&tls=true]` + /// Default port: 10800. + open: static func(address: string) -> result; + query: func(statement: string, params: list) -> result; + query-stream: func(statement: string, params: list) -> result; + execute: func(statement: string, params: list) -> result; + begin-transaction: func() -> result; + } +} diff --git a/sdks/python/wit/deps/golem-rdbms/mysql.wit b/sdks/python/wit/deps/golem-rdbms/mysql.wit new file mode 100644 index 0000000000..d6278a023a --- /dev/null +++ b/sdks/python/wit/deps/golem-rdbms/mysql.wit @@ -0,0 +1,141 @@ +package golem:rdbms@1.5.0; + +interface mysql { + use types.{date, time, timestamp}; + + variant error { + connection-failure(string), + query-parameter-failure(string), + query-execution-failure(string), + query-response-failure(string), + other(string), + /// The resident transaction or result stream cannot be resumed. Recorded results + /// remain valid; this does not prove that an earlier write failed. + resource-lost(string) + } + + variant db-column-type { + boolean, + tinyint, + smallint, + mediumint, + int, + bigint, + tinyint-unsigned, + smallint-unsigned, + mediumint-unsigned, + int-unsigned, + bigint-unsigned, + float, + double, + decimal, + date, + datetime, + timestamp, + time, + year, + fixchar, + varchar, + tinytext, + text, + mediumtext, + longtext, + binary, + varbinary, + tinyblob, + blob, + mediumblob, + longblob, + enumeration, + set, + bit, + json + } + + record db-column { + ordinal: u64, + name: string, + db-type: db-column-type, + db-type-name: string + } + + /// Value descriptor for a single database value + variant db-value { + boolean(bool), + tinyint(s8), + smallint(s16), + mediumint(s32), + int(s32), + bigint(s64), + tinyint-unsigned(u8), + smallint-unsigned(u16), + mediumint-unsigned(u32), + int-unsigned(u32), + bigint-unsigned(u64), + float(f32), + double(f64), + decimal(string), + date(date), + datetime(timestamp), + timestamp(timestamp), + time(time), + year(u16), + fixchar(string), + varchar(string), + tinytext(string), + text(string), + mediumtext(string), + longtext(string), + binary(list), + varbinary(list), + tinyblob(list), + blob(list), + mediumblob(list), + longblob(list), + enumeration(string), + set(string), + bit(list), + json(string), + null + } + + /// A single row of values + record db-row { + values: list + } + + record db-result { + columns: list, + rows: list + } + + /// A potentially very large and lazy stream of rows: + resource db-result-stream { + get-columns: func() -> result, error>; + get-next: func() -> result>, error>; + } + + resource db-connection { + open: static func(address: string) -> result; + + query: func(statement: string, params: list) -> result; + + query-stream: func(statement: string, params: list) -> result; + + execute: func(statement: string, params: list) -> result; + + begin-transaction: func() -> result; + } + + resource db-transaction { + query: func(statement: string, params: list) -> result; + + query-stream: func(statement: string, params: list) -> result; + + execute: func(statement: string, params: list) -> result; + + commit: func() -> result<_, error>; + + rollback: func() -> result<_, error>; + } +} diff --git a/sdks/python/wit/deps/golem-rdbms/postgres.wit b/sdks/python/wit/deps/golem-rdbms/postgres.wit new file mode 100644 index 0000000000..e68ca79c81 --- /dev/null +++ b/sdks/python/wit/deps/golem-rdbms/postgres.wit @@ -0,0 +1,296 @@ +package golem:rdbms@1.5.0; + +interface postgres { + use types.{date, time, timetz, timestamp, timestamptz, uuid, ip-address, mac-address}; + + variant error { + connection-failure(string), + query-parameter-failure(string), + query-execution-failure(string), + query-response-failure(string), + other(string), + /// The resident transaction or result stream cannot be resumed. Recorded results + /// remain valid; this does not prove that an earlier write failed. + resource-lost(string) + } + + record interval { + months: s32, + days: s32, + microseconds: s64 + } + + variant int4bound { + included(s32), + excluded(s32), + unbounded + } + + variant int8bound { + included(s64), + excluded(s64), + unbounded + } + + variant numbound { + included(string), + excluded(string), + unbounded + } + + variant tsbound { + included(timestamp), + excluded(timestamp), + unbounded + } + + variant tstzbound { + included(timestamptz), + excluded(timestamptz), + unbounded + } + + variant datebound { + included(date), + excluded(date), + unbounded + } + + record int4range { + start: int4bound, + end: int4bound + } + + record int8range { + start: int8bound, + end: int8bound + } + + record numrange { + start: numbound, + end: numbound + } + + record tsrange { + start: tsbound, + end: tsbound + } + + record tstzrange { + start: tstzbound, + end: tstzbound + } + + record daterange { + start: datebound, + end: datebound + } + + record enumeration-type { + name: string + } + + record enumeration { + name: string, + value: string + } + + record composite-type { + name: string, + attributes: list> + } + + record composite { + name: string, + values: list + } + + record domain-type { + name: string, + base-type: lazy-db-column-type + } + + record domain { + name: string, + value: lazy-db-value + } + + record range-type { + name: string, + base-type: lazy-db-column-type + } + + variant value-bound { + included(lazy-db-value), + excluded(lazy-db-value), + unbounded + } + + record values-range { + start: value-bound, + end: value-bound + } + + record range { + name: string, + value: values-range + } + + record sparse-vec { + dim: s32, + indices: list, + values: list + } + + variant db-column-type { + character, + int2, + int4, + int8, + float4, + float8, + numeric, + boolean, + text, + varchar, + bpchar, + timestamp, + timestamptz, + date, + time, + timetz, + interval, + bytea, + uuid, + xml, + json, + jsonb, + jsonpath, + inet, + cidr, + macaddr, + bit, + varbit, + int4range, + int8range, + numrange, + tsrange, + tstzrange, + daterange, + money, + oid, + enumeration(enumeration-type), + composite(composite-type), + domain(domain-type), + array(lazy-db-column-type), + range(range-type), + vector, + halfvec, + sparsevec + } + + variant db-value { + character(s8), + int2(s16), + int4(s32), + int8(s64), + float4(f32), + float8(f64), + numeric(string), + boolean(bool), + text(string), + varchar(string), + bpchar(string), + timestamp(timestamp), + timestamptz(timestamptz), + date(date), + time(time), + timetz(timetz), + interval(interval), + bytea(list), + json(string), + jsonb(string), + jsonpath(string), + xml(string), + uuid(uuid), + inet(ip-address), + cidr(ip-address), + macaddr(mac-address), + bit(list), + varbit(list), + int4range(int4range), + int8range(int8range), + numrange(numrange), + tsrange(tsrange), + tstzrange(tstzrange), + daterange(daterange), + money(s64), + oid(u32), + enumeration(enumeration), + composite(composite), + domain(domain), + array(list), + range(range), + null, + vector(list), + halfvec(list), + sparsevec(sparse-vec) + } + + resource lazy-db-value { + constructor(value: db-value); + get: func() -> db-value; + } + + resource lazy-db-column-type { + constructor(value: db-column-type); + get: func() -> db-column-type; + } + + record db-column { + ordinal: u64, + name: string, + db-type: db-column-type, + db-type-name: string + } + + /// A single row of values + record db-row { + values: list + } + + record db-result { + columns: list, + rows: list + } + + /// A potentially very large and lazy stream of rows: + resource db-result-stream { + get-columns: func() -> result, error>; + get-next: func() -> result>, error>; + } + + resource db-connection { + open: static func(address: string) -> result; + + query: func(statement: string, params: list) -> result; + + query-stream: func(statement: string, params: list) -> result; + + execute: func(statement: string, params: list) -> result; + + begin-transaction: func() -> result; + } + + resource db-transaction { + query: func(statement: string, params: list) -> result; + + query-stream: func(statement: string, params: list) -> result; + + execute: func(statement: string, params: list) -> result; + + commit: func() -> result<_, error>; + + rollback: func() -> result<_, error>; + } +} diff --git a/sdks/python/wit/deps/golem-rdbms/types.wit b/sdks/python/wit/deps/golem-rdbms/types.wit new file mode 100644 index 0000000000..36af8b1fde --- /dev/null +++ b/sdks/python/wit/deps/golem-rdbms/types.wit @@ -0,0 +1,47 @@ +package golem:rdbms@1.5.0; + +interface types { + + record uuid { + high-bits: u64, + low-bits: u64 + } + + variant ip-address { + ipv4(tuple), + ipv6(tuple), + } + + record mac-address { + octets: tuple + } + + record date { + year: s32, + month: u8, + day: u8 + } + + record time { + hour: u8, + minute: u8, + second: u8, + nanosecond: u32 + } + + record timestamp { + date: date, + time: time + } + + record timestamptz { + timestamp: timestamp, + offset: s32 + } + + record timetz { + time: time, + offset: s32 + } + +} diff --git a/sdks/python/wit/deps/golem-rdbms/world.wit b/sdks/python/wit/deps/golem-rdbms/world.wit new file mode 100644 index 0000000000..f8702cbf16 --- /dev/null +++ b/sdks/python/wit/deps/golem-rdbms/world.wit @@ -0,0 +1,7 @@ +package golem:rdbms@1.5.0; + +world imports { + import postgres; + import mysql; + import ignite2; +} diff --git a/sdks/python/wit/deps/golem-secrets/reveal.wit b/sdks/python/wit/deps/golem-secrets/reveal.wit new file mode 100644 index 0000000000..76a81735f6 --- /dev/null +++ b/sdks/python/wit/deps/golem-secrets/reveal.wit @@ -0,0 +1,31 @@ +package golem:secrets@0.1.0; + +/// Capability-gated escape hatch: convert a secret resource back +/// to plaintext. The capability is the import โ€” components that +/// do not import this interface cannot reveal secrets. v1 grants +/// reveal at the import-or-not level only; v2 introduces +/// per-(agent, tool, tool-middleware) manifest binding axes that narrow +/// reveal even when imported (ยง5.6). +/// +/// Every successful reveal is recorded in the calling agent's +/// oplog as `(calling-agent, secret-id, timestamp)`. The +/// plaintext bytes are not part of the audit record. +/// +/// Tools that consume secrets at the wire boundary (HTTP +/// authorization headers, signing operations, encryption) SHOULD +/// prefer host-mediated substitution over reveal โ€” host +/// capabilities accepting `borrow` directly let the +/// runtime substitute plaintext at the syscall boundary, never +/// crossing into guest linear memory at all. Reveal is the +/// fallback for genuinely custom protocols the host doesn't +/// natively support; its use is loud by design. +interface reveal { + use types.{secret-error}; + use golem:core/types@2.0.0.{secret, schema-graph, schema-value-tree}; + + /// Unpack a secret resource to its inner typed value. `expected` is the + /// guest's inner-type graph; the host validates it against the secret's + /// pinned inner type and returns the stored value as a schema-value-tree. + reveal: func(s: borrow, expected: schema-graph) + -> result; +} diff --git a/sdks/python/wit/deps/golem-secrets/types.wit b/sdks/python/wit/deps/golem-secrets/types.wit new file mode 100644 index 0000000000..1e10ce9e10 --- /dev/null +++ b/sdks/python/wit/deps/golem-secrets/types.wit @@ -0,0 +1,73 @@ +package golem:secrets@0.1.0; + +/// The secret resource, plus the metadata records other interfaces +/// reference. Components that only need to *receive and pass* +/// secrets โ€” most tools, audit middleware, MCP-import bridges โ€” +/// import only this interface. +interface types { + use wasi:clocks/system-clock@0.3.0.{instant as datetime}; + use golem:core/types@2.0.0.{secret}; + + /// The opaque handle to a sensitive value is defined in + /// `golem:core/types` so it can travel inside a `schema-value-tree` as an + /// unforgeable owned handle. This interface exposes only safe metadata + /// operations over that handle. + /// + /// Resource handles are scoped to a component instance's + /// resource table. When a secret is passed across a component + /// boundary (e.g., agent โ†’ tool via `tool-rpc.invoke`'s + /// `value-tree`), the runtime issues a fresh handle in the + /// receiving instance's table that points at the same + /// host-side state. The wire form carries only the + /// `secret-id`, never plaintext. + + /// Stable, opaque identifier scoped to the deployment. + record secret-id { + bytes: list, + } + + record secret-metadata { + /// Config-key path the secret resolved from, when applicable. + /// `none` for secrets returned in tool-result position. + config-key: option>, + /// Pinned version captured at resolve-time. `none` for + /// dynamic-origin secrets (e.g. returned from a tool that + /// didn't itself have a versioned source). + version: option, + /// Time of resolution. + resolved-at: datetime, + /// The semantic category declared on the secret's schema type, when + /// known. Mirrors `secret-spec.category` in `golem:core/types`. + category: option, + } + + /// A secret-store-assigned, monotonic version identifier. The + /// secret-store backend defines the ordering and the format; + /// the type-tree treats it as opaque. + record secret-version { + bytes: list, + } + + /// Stable opaque identifier. Comparing equal across two `secret` handles + /// means "same secret material, same version" โ€” useful for caching and audit + /// correlation. Safe to log, oplog, and emit in traces. + id: func(s: borrow) -> secret-id; + + /// Immutable metadata captured at resolve-time. Includes the config-key + /// path, the resolved version, and the resolution timestamp. No plaintext. + metadata: func(s: borrow) -> secret-metadata; + + /// Errors common to operations on secrets. + variant secret-error { + /// The secret was bound but its current resolution failed + /// (e.g., the secret-store entry was deleted between binding + /// and reveal, or the network to the store is partitioned). + unavailable(string), + /// The secret was version-pinned and the pinned version no + /// longer exists (administratively destroyed). + version-not-found(secret-version), + /// Internal runtime error (carries an opaque message; never + /// includes plaintext). + internal(string), + } +} diff --git a/sdks/python/wit/deps/golem-tool/common.wit b/sdks/python/wit/deps/golem-tool/common.wit new file mode 100644 index 0000000000..8e5af17a35 --- /dev/null +++ b/sdks/python/wit/deps/golem-tool/common.wit @@ -0,0 +1,415 @@ +package golem:tool@0.1.0; + +/// Data model for Golem tool metadata. +/// +/// A "tool" is a callable unit declared from a single piece of +/// metadata. From that metadata the SDKs project two delivered +/// surfaces โ€” typed function signatures in TypeScript / Rust / +/// Python / Scala / MoonBit for programmatic invocation, and +/// help-text rendering for any node in the command tree โ€” and the +/// same metadata is sufficient to drive a future full-CLI +/// projection (parseable args, shell completions, exit codes, +/// terminal-runnable as a Unix utility) without further authoring. +/// The CLI projection is a future possibility enabled by the model; +/// it is not part of the current specification's deliverable. +/// +/// The model is CLI-native: commands, subcommands, options, flags, and +/// positionals are primary โ€” not a generic data schema with CLI mappings +/// layered on top. Constraint-by-construction is preferred over runtime +/// validation: variadic-only-at-tail is structural; mutual exclusion is +/// expressed by subcommand choice or by an explicit `mutex-groups` +/// constraint; co-occurrence is structural via sub-records or via +/// `all-or-none`. +/// +/// Types and values are not modeled by this package: every input/output +/// type and every metadata-time or runtime value is expressed with the +/// shared `golem:core/types@2.0.0` schema model. A tool owns a single +/// `schema-graph` type-node pool (the `tool.schema` field); command bodies +/// reference entries in it by `type-node-index`, exactly the same way the +/// agent model (`golem:agent/common`) references its per-agent +/// `schema-graph`. Metadata-time values (option/positional defaults, the +/// literal side of `value-is` constraint refs) are `schema-value-tree`s +/// interpreted against the referenced type node in `tool.schema`; runtime +/// invocation inputs, results, and custom-error payloads are self-contained +/// `typed-schema-value`s. +/// +/// The remaining tool-specific recursion site is the command tree: a +/// flattened command hierarchy with the root at index 0 and children +/// referenced by `command-index`. +/// +/// Construction invariants (validated by the producer; the WIT shape +/// alone does not enforce them): +/// +/// โ€ข All identifier-like strings (command names, option/flag long +/// names, positional names, error names, formatter names) match +/// `^[a-z][a-z0-9]*(-[a-z0-9]+)*$`. +/// โ€ข Subcommand names + aliases are pairwise unique among siblings. +/// โ€ข Within a `command-body`: option long-names + flag long-names + +/// positional names + aliases are pairwise unique, AND unique against +/// the long-names + aliases of globals inherited from any ancestor. +/// โ€ข Option and flag short forms occupy a separate `char` namespace: +/// they are pairwise unique with other short forms in the body and with +/// inherited global short forms. A string name or alias such as `"f"` +/// does not collide with the short form `'f'`. +/// โ€ข Constraint `ref` string names resolve against body-declared long-names, +/// positional names, aliases, and globals inherited from any ancestor; +/// short forms do not participate in constraint resolution. +/// โ€ข For `ref::value-is(name, lit)`, the literal must be a valid value +/// for the declared type node of `name` in `tool.schema`. +/// โ€ข `default-formatter` resolves to a name in `formatters`. +/// โ€ข `tail-positional`: if `verbatim` is true, `separator` must be +/// `some`; `separator` with `min = 0` is legal (the separator alone, +/// no items, is valid). +/// โ€ข A `positional` / `option` / `result` / `error` `type-node-index` +/// resolves to a node in `tool.schema`. +/// โ€ข A `repeatable-list` option's `default`, if present, is a `list` +/// whose elements are values of the `repeatable-list-shape.item-type` +/// node. A `repeatable-map` option's `default`, if present, is a `map` +/// value of the `repeatable-map-shape.map-type` node. +/// โ€ข A `value-is` ref naming a `repeatable-list` option, tail positional, +/// or otherwise list-shaped target means "any occurrence / element +/// equals this literal"; the literal is a value of the element type. For +/// a `repeatable-map` option the literal is a value of the map's value +/// type (any entry's value equals this literal). +/// โ€ข The tool's identity is its root command name +/// (`commands.nodes[0].name`); `get-tool(name)` and +/// `guest.invoke(tool-name, โ€ฆ)` match against it. `commands.nodes` +/// is always non-empty. +/// +/// Capability scoping is performed by the host. `requires-filesystem` declares +/// that the tool cannot operate without a filesystem binding; it does not grant +/// filesystem access. +interface common { + use golem:core/types@2.0.0.{schema-graph, type-node-index, schema-value-tree, + typed-schema-value, tool-error}; + use golem:core/http@2.0.0.{http-method, path-segment, query-variable, + header-variable, file-response-header, http-route-mode, durable-stream-route-options}; + + // Top level + record tool { + version: string, + requires-filesystem: bool, + http-mount: option, + commands: command-tree, + /// Self-contained type-node pool holding every type referenced from + /// this tool's commands. Command bodies reference entries by + /// `type-node-index`. `schema.root` is a structurally-required + /// placeholder and is not the semantic root of the tool (mirrors + /// `golem:agent/common`'s `agent-type.schema`). + schema: schema-graph, + } + + record tool-middleware { + name: string, + version: string, + aliases: list, + doc: doc, + scope: tool-middleware-scope, + /// Schema of the static configuration supplied for each installation. + parameter-schema: schema-graph, + } + + variant tool-middleware-scope { + monomorphic(monomorphic-scope), + universal, + } + + record monomorphic-scope { + presented: tool, + expected: option, + } + + // Command tree + type command-index = s32; + + record command-tree { + /// Always non-empty; the root command is at index 0. + nodes: list, + } + + /// A command may dispatch to subcommands, run its own body, or both. + /// Globals declared here apply to this command's own body and to + /// every descendant subcommand body (recursive globals โ€” "this level + /// and downward"). + record command-node { + name: string, + aliases: list, + doc: doc, + http: option, + globals: globals, + subcommands: list, + body: option, + } + + record tool-http-mount { + path-prefix: list, + } + + variant command-http { + endpoint(tool-http-endpoint), + prefix(tool-http-prefix), + } + + record tool-http-prefix { + path-suffix: list, + } + + record tool-http-endpoint { + route-id: option, + http-method: http-method, + path-suffix: list, + query-vars: list, + header-vars: list, + response-headers: list, + mode: option, + durable-streams: option, + } + + record globals { + options: list, + %flags: list, + } + + record command-body { + positionals: positionals, + options: list, + %flags: list, + constraints: list, + stdin: option, + stdout: option, + stderr: option, + %result: option, + errors: list, + annotations: option, + } + + /// Behavioral hints surfaced to MCP and other LLM-facing + /// surfaces. All four follow the MCP convention. When absent + /// the surface treats them as untrusted defaults + /// (`destructive: true`, `open-world: true`, `read-only: false`, + /// `idempotent: false`), per MCP guidance. + record command-annotations { + /// Tool performs no destructive updates; safe to call freely. + read-only: bool, + /// Tool may delete or overwrite (default true per MCP semantics). + destructive: bool, + /// Repeated calls with the same input have the same effect. + idempotent: bool, + /// Tool reaches outside the host's controlled environment + /// (network calls, external APIs, the open world). + open-world: bool, + } + + // Positionals (variadic only at the tail, structurally) + record positionals { + fixed: list, + tail: option, + } + + record positional { + name: string, + doc: doc, + value-name: option, + /// Index into `tool.schema`. + %type: type-node-index, + /// Default value, interpreted against `%type` in `tool.schema`. + default: option, + required: bool, + /// If true, the positional's value may be read from standard input + /// (e.g. grep's trailing `files` accepting piped input). + accepts-stdio: bool, + } + + record tail-positional { + name: string, + doc: doc, + value-name: option, + /// Index into `tool.schema`. + item-type: type-node-index, + min: u32, + max: option, + /// Token required before tail items (e.g. "--" for `git log -- `). + separator: option, + /// If true, tokens after `separator` are not flag-parsed (for + /// `kubectl exec -- CMD ARGS...`). + verbatim: bool, + /// If true, the tail items may be read from standard input + /// (e.g. grep's trailing `files` accepting piped input). + accepts-stdio: bool, + } + + // Options and flags + record option-spec { + long: string, + short: option, + aliases: list, + doc: doc, + value-name: option, + shape: option-shape, + /// Default value, interpreted against the option's type node in + /// `tool.schema`. + default: option, + required: bool, + env-var: option, + } + + variant option-shape { + /// Required value: --opt VALUE or --opt=VALUE. Index into `tool.schema`. + scalar(type-node-index), + /// Bare presence collapses to `default`; with value parses normally + /// (--decorate, --signed[=mode], --force-with-lease[=ref]). Index into + /// `tool.schema`. + optional-scalar(type-node-index), + /// Repeatable scalar option (`-e a -e b`); the collected value is a + /// `list` of the element type. + repeatable-list(repeatable-list-shape), + /// Repeatable key-value option (`-c a=1 -c b=2`); the collected value is a + /// `golem:core` `map` node, never a `list`. + repeatable-map(repeatable-map-shape), + } + + record repeatable-list-shape { + repetition: repetition, + /// Index into `tool.schema`; the element type of the collected `list`. + item-type: type-node-index, + } + + record repeatable-map-shape { + repetition: repetition, + /// Index into `tool.schema`; a `golem:core` `map` (key + value) node. The + /// collected value is this map. + map-type: type-node-index, + /// What happens when the same key is supplied more than once. + duplicate-key-policy: duplicate-key-policy, + } + + /// Resolution policy for a repeated key in a `repeatable-map` option. + enum duplicate-key-policy { + /// A repeated key is a usage error. + reject, + /// A repeated key takes the last supplied value. + last-wins, + } + + variant repetition { + /// --inc a --inc b + repeated, + /// --inc=a,b + delimited(char), + /// Both surface forms accepted. + either(char), + } + + record flag-spec { + long: string, + short: option, + aliases: list, + doc: doc, + shape: flag-shape, + env-var: option, + } + + variant flag-shape { + bool-flag(bool-flag-shape), + /// Counted flag (-vvv); optional max count. + count-flag(option), + } + + record bool-flag-shape { + default: bool, + /// If true, --no- is auto-synthesized. + negatable: bool, + } + + // Constraints + variant ref { + present(string), + value-is(value-is-ref), + } + + record value-is-ref { + name: string, + /// Literal value, interpreted against the declared type node of `name` + /// in `tool.schema`. + value: schema-value-tree, + } + + variant constraint { + requires-all(list), + all-or-none(list), + requires-any(list), + mutex-groups(list), + implies(implies-c), + forbids(forbids-c), + } + + record ref-group { + refs: list, + } + + record implies-c { + lhs-quant: quantifier, + lhs: list, + rhs-quant: quantifier, + rhs: list, + } + + record forbids-c { + lhs-quant: quantifier, + lhs: list, + rhs: list, + } + + enum quantifier { all, any } + + // Streams, structured results, errors + record stream-spec { + doc: doc, + mime: list, + required: bool, + } + + record result-spec { + /// Index into `tool.schema`. + %type: type-node-index, + doc: doc, + formatters: list, + default-formatter: string, + } + + record formatter { + name: string, + doc: doc, + } + + record error-case { + name: string, + doc: doc, + kind: error-kind, + exit-code: u8, + /// Index into `tool.schema`. + payload: option, + } + + enum error-kind { usage-error, runtime-error } + + // Documentation, examples + record doc { + summary: string, + description: string, + examples: list, + } + + record example { + title: string, + body: string, + } + + // Invocation contract โ€” shared between guest and host. Both attachment + // fields must be absent: output bytes use the writers supplied to the guest. + record invocation-result { + %result: option, + stdout: option>, + stderr: option>, + } +} diff --git a/sdks/python/wit/deps/golem-tool/guest.wit b/sdks/python/wit/deps/golem-tool/guest.wit new file mode 100644 index 0000000000..c056ced916 --- /dev/null +++ b/sdks/python/wit/deps/golem-tool/guest.wit @@ -0,0 +1,67 @@ +package golem:tool@0.1.0; + +/// Interface exported by a component that provides tools. The component +/// declares which tools it exposes, supplies their metadata, and accepts +/// invocations against a chosen leaf command of any tool. +/// +/// Tools are stateless from the host's perspective: each invocation is +/// independent. State accumulated by the underlying agent (file-system +/// writes, config-store updates, etc.) persists per the agent's normal +/// rules and is independent of the tool calling convention. +interface guest { + use common.{tool, tool-error, invocation-result}; + use streams.{byte-stream-item, tool-output-writer}; + use golem:core/types@2.0.0.{typed-schema-value}; + + /// Enumerate the tools this component exposes. The returned metadata + /// is complete (full command tree and schema graph). + discover-tools: func() -> result, tool-error>; + + /// Look up a single tool by name. + get-tool: func(name: string) -> result; + + /// Invoke a command of a tool. + /// + /// `command-path` selects the command body to execute. An empty list + /// targets the root command's body; non-empty lists walk the + /// `subcommands` field, each segment matching a `command-node.name` + /// or alias. + /// + /// `input` is a self-contained `typed-schema-value` whose root must + /// structurally match the selected body's input schema โ€” a record with + /// one field per positional, option, flag, and inherited global declared + /// on or above the body, each field typed by the matching type node in + /// the body's schema. + /// + /// `stdin` is supplied when the selected body declared a stdin + /// `stream-spec`. Clean EOF is underlying stream closure. A final failed + /// item reports recoverable source failure, abandonment, resource + /// exhaustion, or cancellation before closure. Dropping the reader closes + /// further consumption. + /// + /// `stdout` is supplied when the selected body declared a stdout + /// `stream-spec`. The implementation writes while this function is still + /// running and explicitly finishes or fails the endpoint. Dropping an open + /// writer abandons it. The first selected terminal is immutable. + /// `stderr` follows the same independent attachment contract as `stdout`. + /// + /// The caller's authenticated identity, for authorization and audit, is + /// available from `golem:agent/invocation-context.caller`. + invoke: async func( + tool-name: string, + command-path: list, + input: typed-schema-value, + stdin: option>, + stdout: option>, + stderr: option>, + ) -> result; +} + +world tool-guest { + import golem:api/host@1.5.0; + import golem:agent/host@2.0.0; + import golem:agent/invocation-context@2.0.0; + import host; + import common; + export guest; +} diff --git a/sdks/python/wit/deps/golem-tool/host.wit b/sdks/python/wit/deps/golem-tool/host.wit new file mode 100644 index 0000000000..a8926151e9 --- /dev/null +++ b/sdks/python/wit/deps/golem-tool/host.wit @@ -0,0 +1,154 @@ +package golem:tool@0.1.0; + +/// Interface the runtime exposes to agents and tools for discovering and +/// invoking ambient tools โ€” tools registered by other components in the +/// same Golem environment. +/// +/// Mirrors the structure of `golem:agent/host`, but keyed on tool name +/// (rather than agent-id), and without the agent-instance constructor +/// step (tools are stateless invocables). +interface host { + use common.{tool, invocation-result}; + use streams.{byte-stream-failure, byte-stream-item, byte-stream-close-cause, stream-write-error}; + use golem:core/types@2.0.0.{typed-schema-value, component-id, tool-rpc-error}; + + /// A tool registered in the environment, addressable by name from + /// any agent or other tool. `definition` carries the full metadata; + /// `implemented-by` identifies the component that registers the + /// tool with the runtime โ€” a Golem component exporting + /// `golem:tool/guest` for native tools, the runtime-internal + /// MCP-import bridge component for tools projected from + /// `mcp.imports` (ยง5.7.2), or the runtime itself (a synthesized + /// component-id) for host-implemented privileged tools (ยง4.6). + record registered-tool { + /// Stable leaf name used to construct tool-rpc, independent of adapters. + lookup-name: string, + definition: tool, + implemented-by: component-id, + } + + /// Returns every tool **the calling agent has access to** in + /// the current environment, per the manifest's per-env and + /// per-agent binding rules (ยง5.6 / ยง6.4.3). The set returned + /// is exactly the set the calling agent could `tool-rpc.invoke` + /// against; tools the calling agent has no binding for are + /// excluded. Mirrors the *function shape* of + /// `golem:agent/host`'s `get-all-agent-types`, with the + /// addition of per-caller access filtering. Order is + /// unspecified; callers that + /// want a stable ordering should sort by + /// `lookup-name`. + get-all-tools: func() -> list; + + /// Returns the registered tool with the given name iff the + /// calling agent has access to it (per the same per-env and + /// per-agent binding rules as `get-all-tools`). Returns `none` + /// either if the tool is not registered or if the calling agent + /// has no binding for it; the two cases are not distinguished. + get-tool: func(name: string) -> option; + + /// Producer endpoint for caller-provided stdin. Exactly one write, finish, + /// or fail operation may be outstanding. The first terminal is immutable; + /// dropping an open writer selects `abandoned`. + resource tool-stdin-writer { + write: async func(bytes: list) -> result<_, stream-write-error>; + finish: async func() -> result<_, stream-write-error>; + fail: async func(reason: byte-stream-failure) -> result<_, stream-write-error>; + } + + /// Single-use source capability consumed by one tool invocation. Dropping + /// it unused selects consumer cancellation for the paired writer. + resource tool-stdin; + + /// Independent watcher used by an SDK pump to stop a blocked native source + /// read when the tool no longer consumes stdin. + resource tool-stdin-closed { + wait: async func() -> byte-stream-close-cause; + } + + /// Creates caller stdin endpoints. The writer and closure watcher remain + /// with the caller; the source is moved into one invocation. Before passing + /// the source to `invoke-and-await`, either select a writer terminal or drive + /// the writer concurrently with the invocation. An open source is valid + /// while a concurrent producer can make progress; writing only after the + /// synchronous invocation returns can deadlock. SDK convenience adapters + /// must start their producer pump before awaiting the invocation terminal. + create-stdin: func() -> tuple< + own, + own, + own + >; + + /// Transfers an SDK-native input stream across the component boundary and + /// pumps it into a directional stdin attachment. This is equivalent to + /// `create-stdin` plus a caller-owned pump, but also supports non-numeric + /// stream items that cannot rendezvous within one Component Model task. + create-stdin-from-stream: func(source: stream) -> own; + + /// Single-use output target consumed by one result-bearing invocation. + /// Dropping it unused fails the paired reader as abandoned. + resource tool-output; + + /// Creates the output target and caller-readable stream before invocation. + /// Dropping the reader cancels only this attachment's consumer role. + create-output: func() -> tuple, stream>; + + resource tool-rpc { + /// Binds an ordinary tool client to its configured tool name. + constructor(tool-name: string); + + /// Creates a tool RPC resource without trapping on invalid caller input. + create: static func(tool-name: string) -> result; + + /// Waits for the structured terminal. Callers that supplied stdout or + /// stderr must drive this wait and every already-created reader + /// concurrently. Callers that manually created an open stdin must likewise + /// drive its writer concurrently; see `create-stdin`. + invoke-and-await: async func( + command-path: list, + input: typed-schema-value, + stdin: option>, + stdout: option>, + stderr: option>, + ) -> result; + + /// Durably admits fire-and-forget work. Declared output is discarded by + /// the host so an absent caller reader cannot apply backpressure. + invoke: func( + command-path: list, + input: typed-schema-value, + stdin: option>, + ) -> result<_, tool-rpc-error>; + + /// Durably admits work and returns an independently owned structured + /// result observer. Each requested output was created by the caller and is + /// observed independently from this future. + async-invoke-and-await: func( + command-path: list, + input: typed-schema-value, + stdin: option>, + stdout: option>, + stderr: option>, + ) -> future-invoke-result; + } + + resource future-invoke-result { + /// Sequential calls return the same immutable terminal. Only one call may + /// be outstanding at a time. + get: async func() -> result; + /// Explicitly cancels the operation. Dropping this resource only detaches + /// result observation and does not cancel accepted work. + cancel: func(); + } + + /// Waits for an explicit set of result observers as one causal batch. The + /// input order controls the result order; filesystem-capable bodies become + /// eligible together and execute in durable Start order. + get-invoke-results: async func( + futures: list>, + ) -> list>; +} + +world tool-host { + export host; +} diff --git a/sdks/python/wit/deps/golem-tool/middleware.wit b/sdks/python/wit/deps/golem-tool/middleware.wit new file mode 100644 index 0000000000..377b269338 --- /dev/null +++ b/sdks/python/wit/deps/golem-tool/middleware.wit @@ -0,0 +1,84 @@ +package golem:tool@0.1.0; + +/// Runtime-owned next-layer capabilities, independent of ambient tool dispatch. +interface underlying { + use common.{tool-error}; + use streams.{byte-stream-item}; + use golem:core/types@2.0.0.{typed-schema-value}; + + variant underlying-error { + tool-error(tool-error), + protocol-error(string), + denied(string), + internal-error(string), + /// This call's explicit cancellation won terminal arbitration. + cancelled, + resource-exhausted(string), + } + + resource underlying-tool { + /// Admits one call to the pinned next layer. Calls on this capability may + /// overlap. Output readers can be consumed before awaiting the result. + /// Invoking after the owning handler returned traps. + invoke: async func( + command-path: list, + input: typed-schema-value, + stdin: option>, + ) -> tuple< + own, + option>, + option> + >; + } + + resource underlying-invoke-result { + /// Returns the immutable terminal. Only one get may be outstanding. + get: async func() -> result, underlying-error>; + /// Requests cancellation of this call only. Dropping this resource detaches + /// observation; it does not cancel work admitted by the runtime. + cancel: func(); + } +} + +/// Interface exported by components that provide tool middleware. +interface tool-middleware-guest { + use common.{invocation-result, tool, tool-error, tool-middleware}; + use streams.{byte-stream-item, tool-output-writer}; + use underlying.{underlying-tool}; + use golem:core/types@2.0.0.{typed-schema-value}; + + /// Enumerate every middleware definition exported by this component. + discover-tool-middlewares: func() -> result, tool-error>; + + /// Look up one middleware definition by canonical name. + get-tool-middleware: func(name: string) -> result; + + /// Invoke one middleware layer around its runtime-bound next inner layer. + /// `golem:agent/invocation-context.caller` answers with the caller of the + /// wrapped tool invocation. + invoke-tool-middleware: async func( + middleware-name: string, + tool-name: string, + tool-metadata: tool, + parameters: typed-schema-value, + command-path: list, + input: typed-schema-value, + stdin: option>, + stdout: option>, + stderr: option>, + wrapped: underlying-tool, + ) -> result; +} + +/// Runtime binding projection for invoking middleware exports from a component +/// built against the unified agent guest world. +world tool-middleware-runtime { + import golem:api/host@1.5.0; + import golem:agent/host@2.0.0; + import golem:agent/invocation-context@2.0.0; + import common; + import streams; + import host; + import underlying; + export tool-middleware-guest; +} diff --git a/sdks/python/wit/deps/golem-tool/streams.wit b/sdks/python/wit/deps/golem-tool/streams.wit new file mode 100644 index 0000000000..74edcc46e4 --- /dev/null +++ b/sdks/python/wit/deps/golem-tool/streams.wit @@ -0,0 +1,36 @@ +package golem:tool@0.1.0; + +/// Byte-stream endpoints shared by tool implementations and middleware without +/// granting access to ambient tool discovery or dispatch. +interface streams { + /// Recoverable attachment failures are stream values. Clean EOF is closure. + variant byte-stream-failure { + cancelled, + abandoned, + resource-exhausted, + failed(string), + } + + /// Every successful item contains a non-empty byte chunk. + type byte-stream-item = result, byte-stream-failure>; + + variant byte-stream-close-cause { + finished, + failed(byte-stream-failure), + consumer-cancelled, + } + + variant stream-write-error { + closed(byte-stream-close-cause), + concurrent-operation, + } + + /// Host-owned writer supplied to a tool or middleware implementation. Exactly + /// one write, finish, or fail operation may be outstanding. The first terminal + /// is immutable; dropping an open writer selects `abandoned`. + resource tool-output-writer { + write: async func(bytes: list) -> result<_, stream-write-error>; + finish: async func() -> result<_, stream-write-error>; + fail: async func(reason: byte-stream-failure) -> result<_, stream-write-error>; + } +} diff --git a/sdks/python/wit/deps/golem-websocket/websocket.wit b/sdks/python/wit/deps/golem-websocket/websocket.wit new file mode 100644 index 0000000000..2484a7a541 --- /dev/null +++ b/sdks/python/wit/deps/golem-websocket/websocket.wit @@ -0,0 +1,65 @@ +package golem:websocket@1.5.0; + +interface client { + enum reconstruction-policy { + reconnect-automatically, + report-connection-loss, + } + + variant error { + connection-failure(string), + send-failure(string), + receive-failure(string), + protocol-error(string), + closed(option), + other(string), + /// The physical session did not survive runtime reconstruction. + /// An earlier send may still have reached the remote server. + session-lost, + } + + record close-info { + code: u16, + reason: string, + } + + /// A WebSocket message โ€” text or binary + variant message { + text(string), + binary(list), + } + + /// A WebSocket connection resource + resource websocket-connection { + /// Connect to a WebSocket server at the given URL (ws:// or wss://) + /// Optional headers for auth, subprotocols, etc. + connect: static func( + url: string, + headers: option>>, + /// Defaults to report-connection-loss: after runtime reconstruction the + /// next send, receive, receive-with-timeout or close returns session-lost + /// and opens no replacement connection. Choose reconnect-automatically + /// only when the peer accepts a new session in place of the lost one, + /// for example a stateless feed that needs no initialization handshake. + /// Completed durable operations replay unchanged under either policy. + /// Neither policy retries ordinary network disconnects or bypasses + /// non-idempotent recovery guards. + reconstruction-policy: option + ) -> result; + + /// Send a message (text or binary) + send: func(message: message) -> result<_, error>; + + /// Receive the next message (blocks until available) + receive: async func() -> result; + + /// Receive the next message with a timeout in milliseconds. + /// Returns none if the timeout expires before a message arrives. + receive-with-timeout: async func(timeout-ms: u64) -> result, error>; + + /// Send a close frame with optional code and reason. A reconstructed handle + /// using report-connection-loss returns session-lost without reconnecting. + /// Dropping the resource releases it locally without opening a connection. + close: func(code: option, reason: option) -> result<_, error>; + } +} diff --git a/sdks/python/wit/deps/http-0.2.6/http.wit b/sdks/python/wit/deps/http-0.2.6/http.wit new file mode 100644 index 0000000000..eb1b25f024 --- /dev/null +++ b/sdks/python/wit/deps/http-0.2.6/http.wit @@ -0,0 +1,733 @@ +package wasi:http@0.2.6; + +/// 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), + } + + /// 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, + } + + /// 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), + } + + /// 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 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 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 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>>; + } + + /// 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 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; +} + +/// 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 { + @since(version = 0.2.0) + import wasi:io/poll@0.2.6; + @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; + @since(version = 0.2.0) + import wasi:io/error@0.2.6; + @since(version = 0.2.0) + import wasi:io/streams@0.2.6; + @since(version = 0.2.0) + import wasi:cli/stdout@0.2.6; + @since(version = 0.2.0) + import wasi:cli/stderr@0.2.6; + @since(version = 0.2.0) + import wasi:cli/stdin@0.2.6; + @since(version = 0.2.0) + import types; + @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) + import wasi:io/poll@0.2.6; + @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; + @since(version = 0.2.0) + import wasi:io/error@0.2.6; + @since(version = 0.2.0) + import wasi:io/streams@0.2.6; + @since(version = 0.2.0) + import wasi:cli/stdout@0.2.6; + @since(version = 0.2.0) + import wasi:cli/stderr@0.2.6; + @since(version = 0.2.0) + import wasi:cli/stdin@0.2.6; + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import outgoing-handler; + + @since(version = 0.2.0) + export incoming-handler; +} diff --git a/sdks/python/wit/deps/http/http.wit b/sdks/python/wit/deps/http/http.wit new file mode 100644 index 0000000000..08458f7c68 --- /dev/null +++ b/sdks/python/wit/deps/http/http.wit @@ -0,0 +1,509 @@ +package wasi:http@0.3.0; + +/// This interface defines all of the types and methods for implementing HTTP +/// Requests and Responses, as well as their headers, trailers, and bodies. +@since(version = 0.3.0) +interface types { + use wasi:clocks/types@0.3.0.{duration}; + + /// This type corresponds to HTTP standard Methods. + @since(version = 0.3.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.3.0) + variant scheme { + HTTP, + HTTPS, + other(string), + } + + /// Defines the case payload type for `DNS-error` above: + @since(version = 0.3.0) + record DNS-error-payload { + rcode: option, + info-code: option, + } + + /// Defines the case payload type for `TLS-alert-received` above: + @since(version = 0.3.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.3.0) + record field-size-payload { + field-name: option, + field-size: option, + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + @since(version = 0.3.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), + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + @since(version = 0.3.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, + /// This error indicates that the operation would exceed an + /// implementation-defined limit on field sizes. This may apply to + /// an individual `field-value`, a single `field-name` plus all its + /// values, or the total aggregate size of all fields. + size-exceeded, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. Implementations can use this to extend the error + /// type without breaking existing code. 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. + other(option), + } + + /// This type enumerates the different kinds of errors that may occur when + /// setting fields of a `request-options` resource. + @since(version = 0.3.0) + variant request-options-error { + /// Indicates the specified field is not supported by this implementation. + not-supported, + /// Indicates that the operation on the `request-options` was not permitted + /// because it is immutable. + immutable, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. Implementations can use this to extend the error + /// type without breaking existing code. 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. + other(option), + } + + /// 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.3.0) + type field-name = 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.3.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, + /// `request.headers`) might be be immutable. In an immutable fields, the + /// `set`, `append`, and `delete` operations will fail with + /// `header-error.immutable`. + /// + /// A `fields` resource should store `field-name`s and `field-value`s in their + /// original casing used to construct or mutate the `fields` resource. The `fields` + /// resource should use that original casing when serializing the fields for + /// transport or when returning them from a method. + /// + /// Implementations may impose limits on individual field values and on total + /// aggregate field section size. Operations that would exceed these limits + /// fail with `header-error.size-exceeded` + @since(version = 0.3.0) + resource fields { + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each 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. In a valid Fields, all names + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, if a header was forbidden, or if the + /// entries would exceed an implementation size limit. + 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`, 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. + 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. + 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.size-exceeded` if the name or values would + /// exceed an implementation-defined size limit. + 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. + delete: func(name: field-name) -> result<_, header-error>; + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Returns all values previously corresponding to the name, if any. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + get-and-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.size-exceeded` if the value would exceed + /// an implementation-defined size limit. + 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. + copy-all: func() -> list>; + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `copy-all`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + @since(version = 0.3.0) + type headers = fields; + + /// Trailers is an alias for Fields. + @since(version = 0.3.0) + type trailers = fields; + + /// Represents an HTTP Request. + @since(version = 0.3.0) + resource request { + /// Construct a new `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. + /// + /// `contents` is the optional body content stream with `none` + /// representing a zero-length content stream. + /// Once it is closed, `trailers` future must resolve to a result. + /// If `trailers` resolves to an error, underlying connection + /// will be closed immediately. + /// + /// `options` is optional `request-options` resource to be used + /// if the request is sent over a network connection. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, a `request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `handler.handle` implementation + /// to reject invalid constructions of `request`. + /// + /// The returned future resolves to result of transmission of this request. + new: static func(headers: headers, contents: option>, trailers: future, error-code>>, options: option) -> tuple>>; + /// Get the Method for the Request. + get-method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + /// Get the combination of the HTTP Path and Query for the Request. When + /// `none`, this represents an empty Path and empty Query. + get-path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. When + /// `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + get-scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + /// Get the 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. + get-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. + set-authority: func(authority: option) -> result; + /// Get the `request-options` to be associated with this request + /// + /// The returned `request-options` resource is immutable: `set-*` operations + /// will fail if invoked. + /// + /// This `request-options` resource is a child: it must be dropped before + /// the parent `request` is dropped, or its ownership is transferred to + /// another component by e.g. `handler.handle`. + get-options: 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`. + get-headers: func() -> headers; + /// Get body of the Request. + /// + /// Stream returned by this method represents the contents of the body. + /// Once the stream is reported as closed, callers should await the returned + /// future to determine whether the body was received successfully. + /// The future will only resolve after the stream is reported as closed. + /// + /// This function takes a `res` future as a parameter, which can be used to + /// communicate an error in handling of the request. + /// + /// Note that function will move the `request`, but references to headers or + /// request options acquired from it previously will remain valid. + consume-body: static func(this: request, res: future>) -> tuple, future, error-code>>>; + } + + /// 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 an + /// asynchronous call. + @since(version = 0.3.0) + resource request-options { + /// Construct a default `request-options` value. + constructor(); + /// The timeout for the initial connect to the HTTP Server. + get-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 or that this + /// handle is immutable. + set-connect-timeout: func(duration: option) -> result<_, request-options-error>; + /// The timeout for receiving the first byte of the Response body. + get-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 or that + /// this handle is immutable. + set-first-byte-timeout: func(duration: option) -> result<_, request-options-error>; + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + get-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 or that this handle is immutable. + set-between-bytes-timeout: func(duration: option) -> result<_, request-options-error>; + /// Make a deep copy of the `request-options`. + /// The resulting `request-options` is mutable. + clone: func() -> request-options; + } + + /// This type corresponds to the HTTP standard Status Code. + @since(version = 0.3.0) + type status-code = u16; + + /// Represents an HTTP Response. + @since(version = 0.3.0) + resource response { + /// Construct a new `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. + /// + /// `contents` is the optional body content stream with `none` + /// representing a zero-length content stream. + /// Once it is closed, `trailers` future must resolve to a result. + /// If `trailers` resolves to an error, underlying connection + /// will be closed immediately. + /// + /// The returned future resolves to result of transmission of this response. + new: static func(headers: headers, contents: option>, trailers: future, error-code>>) -> tuple>>; + /// Get the HTTP Status Code for the Response. + get-status-code: func() -> status-code; + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + /// Get the headers associated with the Response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + get-headers: func() -> headers; + /// Get body of the Response. + /// + /// Stream returned by this method represents the contents of the body. + /// Once the stream is reported as closed, callers should await the returned + /// future to determine whether the body was received successfully. + /// The future will only resolve after the stream is reported as closed. + /// + /// This function takes a `res` future as a parameter, which can be used to + /// communicate an error in handling of the response. + /// + /// Note that function will move the `response`, but references to headers + /// acquired from it previously will remain valid. + consume-body: static func(this: response, res: future>) -> tuple, future, error-code>>>; + } +} + +/// This interface defines a handler of HTTP Requests. +/// +/// In a `wasi:http/service` this interface is exported to respond to an +/// incoming HTTP Request with a Response. +/// +/// In `wasi:http/middleware` this interface is both exported and imported as +/// the "downstream" and "upstream" directions of the middleware chain. +@since(version = 0.3.0) +interface handler { + use types.{request, response, error-code}; + + /// This function may be called with either an incoming request read from the + /// network or a request synthesized or forwarded by another component. + handle: async func(request: request) -> result; +} + +/// This interface defines an HTTP client for sending "outgoing" requests. +/// +/// Most components are expected to import this interface to provide the +/// capability to send HTTP requests to arbitrary destinations on a network. +/// +/// The type signature of `client.send` is the same as `handler.handle`. This +/// duplication is currently necessary because some Component Model tooling +/// (including WIT itself) is unable to represent a component importing two +/// instances of the same interface. A `client.send` import may be linked +/// directly to a `handler.handle` export to bypass the network. +@since(version = 0.3.0) +interface client { + use types.{request, response, error-code}; + + /// This function may be used to either send an outgoing request over the + /// network or to forward it to another component. + send: async func(request: request) -> result; +} + +/// The `wasi:http/service` world captures a broad category of HTTP services +/// including web applications, API servers, and proxies. It may be `include`d +/// in more specific worlds such as `wasi:http/middleware`. +@since(version = 0.3.0) +world service { + import wasi:cli/types@0.3.0; + import wasi:cli/stdout@0.3.0; + import wasi:cli/stderr@0.3.0; + import wasi:cli/stdin@0.3.0; + import wasi:clocks/types@0.3.0; + import types; + import client; + import wasi:clocks/monotonic-clock@0.3.0; + import wasi:clocks/system-clock@0.3.0; + @unstable(feature = clocks-timezone) + import wasi:clocks/timezone@0.3.0; + import wasi:random/random@0.3.0; + import wasi:random/insecure@0.3.0; + import wasi:random/insecure-seed@0.3.0; + + export handler; +} +/// The `wasi:http/middleware` world captures HTTP services that forward HTTP +/// Requests to another handler. +/// +/// Components may implement this world to allow them to participate in handler +/// "chains" where a `request` flows through handlers on its way to some terminal +/// `service` and corresponding `response` flows in the opposite direction. +@since(version = 0.3.0) +world middleware { + import wasi:clocks/types@0.3.0; + import types; + import handler; + import wasi:cli/types@0.3.0; + import wasi:cli/stdout@0.3.0; + import wasi:cli/stderr@0.3.0; + import wasi:cli/stdin@0.3.0; + import client; + import wasi:clocks/monotonic-clock@0.3.0; + import wasi:clocks/system-clock@0.3.0; + @unstable(feature = clocks-timezone) + import wasi:clocks/timezone@0.3.0; + import wasi:random/random@0.3.0; + import wasi:random/insecure@0.3.0; + import wasi:random/insecure-seed@0.3.0; + + export handler; +} diff --git a/sdks/python/wit/deps/io-0.2.6/io.wit b/sdks/python/wit/deps/io-0.2.6/io.wit new file mode 100644 index 0000000000..08ad78e6b7 --- /dev/null +++ b/sdks/python/wit/deps/io-0.2.6/io.wit @@ -0,0 +1,331 @@ +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; + } +} + +/// 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; +} + +/// 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(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(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(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(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(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(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(src: borrow, len: u64) -> result; + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + @since(version = 0.2.0) + blocking-splice: func(src: borrow, len: u64) -> result; + } +} + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import error; + @since(version = 0.2.0) + import poll; + @since(version = 0.2.0) + import streams; +} diff --git a/sdks/python/wit/deps/keyvalue/caching.wit b/sdks/python/wit/deps/keyvalue/caching.wit new file mode 100644 index 0000000000..f5b497ef11 --- /dev/null +++ b/sdks/python/wit/deps/keyvalue/caching.wit @@ -0,0 +1,87 @@ +// The `wasi:keyvalue/cache` interface defines the operations of a single +// instance of a "cache", which is a non-durable, weakly-consistent key-value +// store. "Non-durable" means that caches are allowed and expected to +// arbitrarily discard key-value entries. "Weakly-consistent" means that there +// are essentially no guarantees that operations will agree on their results: a +// get following a set may not observe the set value; multiple gets may observe +// different previous set values; etc. The only guarantee is that values are +// not materialized "out of thin air": if a `get` returns a value, that value +// was passed to a `set` operation at some point in time in the past. +// Additionally, caches MUST make a best effort to respect the supplied +// Time-to-Live values (within the usual limitations around time in a +// distributed setting). +interface cache { + use types.{key, incoming-value, outgoing-value, error}; + + // The `get` operation returns the value passed by a previous `set` for the + // same key within the given TTL or none if there is no such value. + get: func(k: key) -> future-get-result; + + // Awaitable result of `get`. The inner `option` returns `none` when the + // requested key wasn't present. + resource future-get-result { + get: async func() -> result, error>; + } + + // The `exists` operation returns whether a value was previously `set` for + // the given key within the TTL. + exists: func(k: key) -> future-exists-result; + + // Awaitable result of `exists`. + resource future-exists-result { + get: async func() -> result; + } + + // The `set` operation sets the given value for the given key for the given + // time-to-live (TTL) duration, if supplied, specified in milliseconds. If + // a TTL is not supplied, the key may be kept indefinitely (as-if a very + // large TTL were used). If the key is already present in the cache, the + // value is updated in-place. In the common case of computing and caching a + // value if the given key is not already in the cache, consider using + // `get-or-set` (below) intead of separate `get` and `set` operations. + set: func(k: key, v: borrow, TTL-ms: option) -> future-result; + + // Awaitable result of `set` and `delete`. + resource future-result { + get: async func() -> result<_, error>; + } + + // The `get-or-set` operation asynchronously returns one of two cases + // enumerated by `get-or-set-entry`: in the `occupied` case, the given key + // already has a value present in the cache; in the `vacant` case, there + // was no value and the caller should write a value into the returned + // `vacancy`. This operation allows multiple concurrent `get-or-set` + // invocations to rendezvous such that only one invocation receives the + // `vacant` result while all other invocations wait until the vacancy is + // filled before receiving an `occupied` result. Implementations are not + // required to implement this rendezvous or to rendezvous in all possible + // cases. + variant get-or-set-entry { + occupied(incoming-value), + vacant(vacancy) + } + get-or-set: func(k: key) -> future-get-or-set-result; + + // Awaitable result of `get-or-set`. + resource future-get-or-set-result { + get: async func() -> result; + } + + // The following block defines the `vacancy` resource type. (When resource + // types are added, the `u32` type aliases can be replaced by proper + // `resource` types.) When the caller of `get-or-set` receives a `vacancy`, + // they must either call the `fill` method or drop the `vacancy` to + // indicate an error that prevents calling `fill`. An implementation MAY + // have a timeout that drops a vacancy that hasn't been filled in order + // to unblock other waiting `get-or-set` callers. + resource vacancy { + vacancy-fill: func(TTL-ms: option) -> outgoing-value; + } + + // The `delete` operation removes any value with the given key from the + // cache. Like all cache operations, `delete` is weakly ordered and thus + // concurrent `get` calls may still see deleted keys for a period of time. + // Additionally, due to weak ordering, concurrent `set` calls for the same + // key may or may not get deleted. + delete: func(k: key) -> future-result; +} diff --git a/sdks/python/wit/deps/keyvalue/error.wit b/sdks/python/wit/deps/keyvalue/error.wit new file mode 100644 index 0000000000..cd244f6fff --- /dev/null +++ b/sdks/python/wit/deps/keyvalue/error.wit @@ -0,0 +1,20 @@ +interface wasi-keyvalue-error { + /// An error resource type for keyvalue operations. + /// + /// Common errors: + /// - Connectivity errors (e.g. network errors): when the client cannot establish + /// a connection to the keyvalue service. + /// - Authentication and Authorization errors: when the client fails to authenticate + /// or does not have the required permissions to perform the operation. + /// - Data errors: when the client sends incompatible or corrupted data. + /// - Resource errors: when the system runs out of resources (e.g. memory). + /// - Internal errors: unexpected errors on the server side. + /// + /// Currently, this provides only one function to return a string representation + /// of the error. In the future, this will be extended to provide more information + /// about the error. + // Soon: switch to `resource error { ... }` + resource error { + trace: func() -> string; + } +} \ No newline at end of file diff --git a/sdks/python/wit/deps/keyvalue/eventual-batch.wit b/sdks/python/wit/deps/keyvalue/eventual-batch.wit new file mode 100644 index 0000000000..080999eeaa --- /dev/null +++ b/sdks/python/wit/deps/keyvalue/eventual-batch.wit @@ -0,0 +1,81 @@ +/// A keyvalue interface that provides eventually consistent batch operations. +/// +/// A batch operation is an operation that operates on multiple keys at once. +/// +/// Batch operations are useful for reducing network round-trip time. For example, +/// if you want to get the values associated with 100 keys, you can either do 100 get +/// operations or you can do 1 batch get operation. The batch operation is +/// faster because it only needs to make 1 network call instead of 100. +/// +/// A batch operation does not guarantee atomicity, meaning that if the batch +/// operation fails, some of the keys may have been modified and some may not. +/// Transactional operations are being worked on and will be added in the future to +/// provide atomicity. +/// +/// Data consistency in a key value store refers to the gaurantee that once a +/// write operation completes, all subsequent read operations will return the +/// value that was written. +/// +/// The level of consistency in batch operations is **eventual consistency**, the same +/// with the readwrite interface. This interface does not guarantee strong consistency, +/// meaning that if a write operation completes, subsequent read operations may not return +/// the value that was written. +interface eventual-batch { + /// A keyvalue interface that provides batch get operations. + use types.{bucket, error, key, incoming-value, outgoing-value}; + + /// Get the values associated with the keys in the bucket. It returns a list of + /// incoming-value that can be consumed to get the value associated with the key. + /// + /// If any of the keys do not exist in the bucket, it returns a `none` value for + /// that key in the list. + /// + /// Note that the key-value pairs are guaranteed to be returned in the same order + /// + /// MAY show an out-of-date value if there are concurrent writes to the bucket. + /// + /// If any other error occurs, it returns an `Err(error)`. + get-many: func(bucket: borrow, keys: list) -> result>, error>; + + /// Get all the keys in the bucket. It returns a list of keys. + /// + /// Note that the keys are not guaranteed to be returned in any particular order. + /// + /// If the bucket is empty, it returns an empty list. + /// + /// MAY show an out-of-date list of keys if there are concurrent writes to the bucket. + /// + /// If any error occurs, it returns an `Err(error)`. + keys: func(bucket: borrow) -> result, error>; + + /// Set the values associated with the keys in the bucket. If the key already + /// exists in the bucket, it overwrites the value. + /// + /// Note that the key-value pairs are not guaranteed to be set in the order + /// they are provided. + /// + /// If any of the keys do not exist in the bucket, it creates a new key-value pair. + /// + /// If any other error occurs, it returns an `Err(error)`. When an error occurs, it + /// does not rollback the key-value pairs that were already set. Thus, this batch operation + /// does not guarantee atomicity, implying that some key-value pairs could be + /// set while others might fail. + /// + /// Other concurrent operations may also be able to see the partial results. + set-many: func(bucket: borrow, key-values: list>>) -> result<_, error>; + + /// Delete the key-value pairs associated with the keys in the bucket. + /// + /// Note that the key-value pairs are not guaranteed to be deleted in the order + /// they are provided. + /// + /// If any of the keys do not exist in the bucket, it skips the key. + /// + /// If any other error occurs, it returns an `Err(error)`. When an error occurs, it + /// does not rollback the key-value pairs that were already deleted. Thus, this batch operation + /// does not guarantee atomicity, implying that some key-value pairs could be + /// deleted while others might fail. + /// + /// Other concurrent operations may also be able to see the partial results. + delete-many: func(bucket: borrow, keys: list) -> result<_, error>; +} \ No newline at end of file diff --git a/sdks/python/wit/deps/keyvalue/eventual.wit b/sdks/python/wit/deps/keyvalue/eventual.wit new file mode 100644 index 0000000000..e6e33cfe74 --- /dev/null +++ b/sdks/python/wit/deps/keyvalue/eventual.wit @@ -0,0 +1,56 @@ +/// A keyvalue interface that provides eventually consistent CRUD operations. +/// +/// A CRUD operation is an operation that acts on a single key-value pair. +/// +/// The value in the key-value pair is defined as a `u8` byte array and the intention +/// is that it is the common denominator for all data types defined by different +/// key-value stores to handle data, ensuring compatibility between different +/// key-value stores. Note: the clients will be expecting serialization/deserialization overhead +/// to be handled by the key-value store. The value could be a serialized object from +/// JSON, HTML or vendor-specific data types like AWS S3 objects. +/// +/// Data consistency in a key value store refers to the gaurantee that once a +/// write operation completes, all subsequent read operations will return the +/// value that was written. +/// +/// The level of consistency in readwrite interfaces is **eventual consistency**, +/// which means that if a write operation completes successfully, all subsequent +/// read operations will eventually return the value that was written. In other words, +/// if we pause the updates to the system, the system eventually will return +/// the last updated value for read. +interface eventual { + /// A keyvalue interface that provides simple read and write operations. + use types.{bucket, error, incoming-value, key, outgoing-value}; + + /// Get the value associated with the key in the bucket. + /// + /// The value is returned as an option. If the key-value pair exists in the + /// bucket, it returns `Ok(value)`. If the key does not exist in the + /// bucket, it returns `Ok(none)`. + /// + /// If any other error occurs, it returns an `Err(error)`. + get: func(bucket: borrow, key: key) -> result, error>; + + /// Set the value associated with the key in the bucket. If the key already + /// exists in the bucket, it overwrites the value. + /// + /// If the key does not exist in the bucket, it creates a new key-value pair. + /// + /// If any other error occurs, it returns an `Err(error)`. + set: func(bucket: borrow, key: key, outgoing-value: borrow) -> result<_, error>; + + /// Delete the key-value pair associated with the key in the bucket. + /// + /// If the key does not exist in the bucket, it does nothing. + /// + /// If any other error occurs, it returns an `Err(error)`. + delete: func(bucket: borrow, key: key) -> result<_, error>; + + /// Check if the key exists in the bucket. + /// + /// If the key exists in the bucket, it returns `Ok(true)`. If the key does + /// not exist in the bucket, it returns `Ok(false)`. + /// + /// If any other error occurs, it returns an `Err(error)`. + exists: func(bucket: borrow, key: key) -> result; +} \ No newline at end of file diff --git a/sdks/python/wit/deps/keyvalue/handle-watch.wit b/sdks/python/wit/deps/keyvalue/handle-watch.wit new file mode 100644 index 0000000000..0ca7b37728 --- /dev/null +++ b/sdks/python/wit/deps/keyvalue/handle-watch.wit @@ -0,0 +1,17 @@ +/// A keyvalue interface that provides handle-watch operations. +/// +/// This interface is used to provide event-driven mechanisms to handle +/// keyvalue changes. +interface handle-watch { + /// A keyvalue interface that provides handle-watch operations. + use types.{bucket, key, incoming-value}; + + /// Handle the `set` event for the given bucket and key. + /// It returns a `incoming-value` that represents the new value being set. + /// The new value can be consumed by the handler. + on-set: func(bucket: bucket, key: key, incoming-value: borrow); + + /// Handle the `delete` event for the given bucket and key. + /// It returns a `key` that represents the key being deleted. + on-delete: func(bucket: bucket, key: key); +} \ No newline at end of file diff --git a/sdks/python/wit/deps/keyvalue/types.wit b/sdks/python/wit/deps/keyvalue/types.wit new file mode 100644 index 0000000000..199c4cd0de --- /dev/null +++ b/sdks/python/wit/deps/keyvalue/types.wit @@ -0,0 +1,67 @@ +// A generic keyvalue interface for WASI. +interface types { + /// A bucket is a collection of key-value pairs. Each key-value pair is stored + /// as a entry in the bucket, and the bucket itself acts as a collection of all + /// these entries. + /// + /// It is worth noting that the exact terminology for bucket in key-value stores + /// can very depending on the specific implementation. For example, + /// 1. Amazon DynamoDB calls a collection of key-value pairs a table + /// 2. Redis has hashes, sets, and sorted sets as different types of collections + /// 3. Cassandra calls a collection of key-value pairs a column family + /// 4. MongoDB calls a collection of key-value pairs a collection + /// 5. Riak calls a collection of key-value pairs a bucket + /// 6. Memcached calls a collection of key-value pairs a slab + /// 7. Azure Cosmos DB calls a collection of key-value pairs a container + /// + /// In this interface, we use the term `bucket` to refer to a collection of key-value + // Soon: switch to `resource bucket { ... }` + resource bucket { + /// Opens a bucket with the given name. + /// + /// If any error occurs, including if the bucket does not exist, it returns an `Err(error)`. + open-bucket: static func(name: string) -> result; + } + /// A key is a unique identifier for a value in a bucket. The key is used to + /// retrieve the value from the bucket. + type key = string; + + use wasi-keyvalue-error.{ error }; + /// A value is the data stored in a key-value pair. The value can be of any type + /// that can be represented in a byte array. + // Soon: switch to `resource value { ... }` + resource outgoing-value { + new-outgoing-value: static func() -> outgoing-value; + /// Writes the value asynchronously by consuming the given `stream`: + /// the caller keeps the writable end and the host appends every received + /// byte to the outgoing value's body. + /// If any other error occurs, it returns an `Err(error)`. + outgoing-value-write-body-async: func(data: stream) -> result<_, error>; + /// Writes the value synchronously. + /// If any other error occurs, it returns an `Err(error)`. + outgoing-value-write-body-sync: func(value: list) -> result<_, error>; + } + + /// A incoming-value is a wrapper around a value. It provides ways to read the value. + /// + /// The incoming-value provides two ways to consume the value: + /// 1. `incoming-value-consume-sync` consumes the value synchronously and returns the + /// value as a `list`. + /// 2. `incoming-value-consume-async` consumes the value asynchronously and returns the + /// value as a `stream`. + /// In addition, it provides a `incoming-value-size` function to get the size of the value. + /// This is useful when the value is large and the caller wants to allocate a buffer of + /// the right size to consume the value. + // Soon: switch to `resource incoming-value { ... }` + resource incoming-value { + /// Consumes the value synchronously and returns the value as a list of bytes. + /// If any other error occurs, it returns an `Err(error)`. + incoming-value-consume-sync: func() -> result, error>; + /// Consumes the value asynchronously and returns the value as a `stream`. + /// If any other error occurs, it returns an `Err(error)`. + incoming-value-consume-async: func() -> result, error>; + /// The size of the value in bytes. + /// If the size is unknown or unavailable, this function returns an `Err(error)`. + incoming-value-size: func() -> result; + } +} diff --git a/sdks/python/wit/deps/keyvalue/world.wit b/sdks/python/wit/deps/keyvalue/world.wit new file mode 100644 index 0000000000..bc556f70db --- /dev/null +++ b/sdks/python/wit/deps/keyvalue/world.wit @@ -0,0 +1,21 @@ +package wasi:keyvalue@0.1.0; + +/// The `wasi:keyvalue/imports` world provides common APIs for interacting +/// with key-value stores. Components targeting this world will be able to +/// do +/// 1. CRUD (create, read, update, delete) operations on key-value stores. +/// 2. Batch operations that can reduce the number of round trips to the network. +world imports { + /// The `eventual` capability allows the component to perform + /// eventually consistent CRUD operations on the key-value store. + import eventual; + + /// The `eventual-batch` capability allows the component to perform eventually + /// consistent batch operations that can reduce the number of round trips to the network. + import eventual-batch; +} + +world keyvalue-handle-watch { + include imports; + export handle-watch; +} \ No newline at end of file diff --git a/sdks/python/wit/deps/logging/logging.wit b/sdks/python/wit/deps/logging/logging.wit new file mode 100644 index 0000000000..adb5ee5fb2 --- /dev/null +++ b/sdks/python/wit/deps/logging/logging.wit @@ -0,0 +1,37 @@ +package wasi:logging; + +/// WASI Logging is a logging API intended to let users emit log messages with +/// simple priority levels and context values. +interface logging { + /// A log level, describing a kind of message. + enum level { + /// Describes messages about the values of variables and the flow of + /// control within a program. + trace, + + /// Describes messages likely to be of interest to someone debugging a + /// program. + debug, + + /// Describes messages likely to be of interest to someone monitoring a + /// program. + info, + + /// Describes messages indicating hazardous situations. + warn, + + /// Describes messages indicating serious errors. + error, + + /// Describes messages indicating fatal errors. + critical, + } + + /// Emit a log message. + /// + /// A log message has a `level` describing what kind of message is being + /// sent, a context, which is an uninterpreted string meant to help + /// consumers group similar messages, and a string containing the message + /// text. + log: func(level: level, context: string, message: string); +} \ No newline at end of file diff --git a/sdks/python/wit/deps/random-0.2.6/random.wit b/sdks/python/wit/deps/random-0.2.6/random.wit new file mode 100644 index 0000000000..73edf5b60e --- /dev/null +++ b/sdks/python/wit/deps/random-0.2.6/random.wit @@ -0,0 +1,92 @@ +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; +} + +/// 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; +} + +/// 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; +} + +@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/sdks/python/wit/deps/random/random.wit b/sdks/python/wit/deps/random/random.wit new file mode 100644 index 0000000000..0b9a55fc09 --- /dev/null +++ b/sdks/python/wit/deps/random/random.wit @@ -0,0 +1,107 @@ +package wasi:random@0.3.0; + +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.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.3.0) + get-insecure-seed: func() -> tuple; +} + +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0) +interface insecure { + /// Return up to `max-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. + /// + /// Implementations MAY return fewer bytes than requested (a short read). + /// Callers that require exactly `max-len` bytes MUST call this function in + /// a loop until the desired number of bytes has been accumulated. + /// Implementations MUST return at least 1 byte when `max-len` is greater + /// than zero. When `max-len` is zero, implementations MUST return an empty + /// list without trapping. + @since(version = 0.3.0) + get-insecure-random-bytes: func(max-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.3.0) + get-insecure-random-u64: func() -> u64; +} + +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.3.0) +interface random { + /// Return up to `max-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. + /// + /// Implementations MAY return fewer bytes than requested (a short read). + /// Callers that require exactly `max-len` bytes MUST call this function in + /// a loop until the desired number of bytes has been accumulated. + /// Implementations MUST return at least 1 byte when `max-len` is greater + /// than zero. When `max-len` is zero, implementations MUST return an empty + /// list without trapping. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + @since(version = 0.3.0) + get-random-bytes: func(max-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.3.0) + get-random-u64: func() -> u64; +} + +@since(version = 0.3.0) +world imports { + @since(version = 0.3.0) + import random; + @since(version = 0.3.0) + import insecure; + @since(version = 0.3.0) + import insecure-seed; +} diff --git a/sdks/python/wit/deps/sockets-0.2.6/sockets.wit b/sdks/python/wit/deps/sockets-0.2.6/sockets.wit new file mode 100644 index 0000000000..db6d1a23b4 --- /dev/null +++ b/sdks/python/wit/deps/sockets-0.2.6/sockets.wit @@ -0,0 +1,949 @@ +package wasi:sockets@0.2.6; + +@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, + } + + @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), + } + + /// 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; +} + +/// 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; +} + +@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}; + + @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; + } + + /// 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) +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>; + } +} + +@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; +} + +@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; + } +} + +@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; +} + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import wasi:io/error@0.2.6; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import wasi:io/poll@0.2.6; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import wasi:io/streams@0.2.6; + @since(version = 0.2.0) + import wasi:clocks/monotonic-clock@0.2.6; + @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/sdks/python/wit/deps/sockets/sockets.wit b/sdks/python/wit/deps/sockets/sockets.wit new file mode 100644 index 0000000000..0dd27a4fc4 --- /dev/null +++ b/sdks/python/wit/deps/sockets/sockets.wit @@ -0,0 +1,839 @@ +package wasi:sockets@0.3.0; + +@since(version = 0.3.0) +interface types { + @since(version = 0.3.0) + use wasi:clocks/types@0.3.0.{duration}; + + /// 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: + /// - `other` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + @since(version = 0.3.0) + variant error-code { + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP, ENOPROTOOPT, EPFNOSUPPORT, EPROTONOSUPPORT, ESOCKTNOSUPPORT + not-supported, + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL, EDESTADDRREQ, EAFNOSUPPORT + invalid-argument, + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS + out-of-memory, + /// The operation timed out before it could finish completely. + /// + /// POSIX equivalent: ETIMEDOUT + timeout, + /// The operation is not valid in the socket's current state. + invalid-state, + /// The local address is not available. + /// + /// POSIX equivalent: EADDRNOTAVAIL + address-not-bindable, + /// A bind operation failed because the provided address is already in + /// use or because there are no ephemeral ports available. + /// + /// POSIX equivalent: EADDRINUSE + address-in-use, + /// The remote address is not reachable. + /// + /// POSIX equivalent: EHOSTUNREACH, EHOSTDOWN, ENETDOWN, ENETUNREACH, ENONET + remote-unreachable, + /// The connection was forcefully rejected. + /// + /// POSIX equivalent: ECONNREFUSED + connection-refused, + /// A write failed because the connection was broken. + /// + /// POSIX equivalent: EPIPE + connection-broken, + /// The connection was reset. + /// + /// POSIX equivalent: ECONNRESET + connection-reset, + /// The connection was aborted. + /// + /// POSIX equivalent: ECONNABORTED + connection-aborted, + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + /// + /// POSIX equivalent: EMSGSIZE + datagram-too-large, + /// A catch-all for errors not captured by the existing variants. + /// Implementations can use this to extend the error type without + /// breaking existing code. + other(option), + } + + @since(version = 0.3.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.3.0) + type ipv4-address = tuple; + + @since(version = 0.3.0) + type ipv6-address = tuple; + + @since(version = 0.3.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.3.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.3.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.3.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bound` (See note below) + /// - `listening` + /// - `connecting` + /// - `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`, `listening`, `connecting` or `connected`) + /// + /// WASI uses shared ownership semantics: the `tcp-socket` handle and all + /// derived `stream` and `future` values reference a single underlying OS + /// socket: + /// - Send/receive streams remain functional after the original `tcp-socket` + /// handle is dropped. + /// - The stream returned by `listen` behaves similarly. + /// - Client sockets returned by `tcp-socket::listen` are independent and do + /// not keep the listening socket alive. + /// + /// The OS socket is closed only after the last handle is dropped. This + /// model has observable effects; for example, it affects when the local + /// port binding is released. + /// + /// In addition to the general error codes documented on the + /// `types::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + @since(version = 0.3.0) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # Typical errors + /// - `not-supported`: The `address-family` is not supported. (EAFNOSUPPORT) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + create: static func(address-family: ip-address-family) -> result; + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # Implementors note + /// The 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. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + /// Connect to a remote endpoint. + /// + /// On success, the socket is transitioned into the `connected` state + /// and 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`. If the socket was not already explicitly + /// bound, this function will implicitly bind the socket to a random + /// free port. + /// + /// 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-state`: The socket is already in the `connecting` state. (EALREADY) + /// - `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) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + connect: async func(remote-address: ip-socket-address) -> result<_, error-code>; + /// Start listening and return a stream of new inbound connections. + /// + /// Transitions the socket into the `listening` state. This can be called + /// at most once per socket. + /// + /// If the socket is not already explicitly bound, this function will + /// implicitly bind the socket to a random free port. + /// + /// Normally, the returned sockets are bound, in the `connected` state + /// and immediately ready for I/O. Though, depending on exact timing and + /// circumstances, a newly accepted connection may already be `closed` + /// by the time the server attempts to perform its first I/O on it. This + /// is true regardless of whether the WASI implementation uses + /// "synthesized" sockets or not (see Implementors Notes below). + /// + /// 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` + /// + /// # Typical errors + /// - `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) + /// + /// # Implementors note + /// This method returns a single perpetual stream that should only close + /// on fatal errors (if any). Yet, the POSIX' `accept` function may also + /// return transient errors (e.g. ECONNABORTED). The exact details differ + /// per operation system. For example, the Linux manual mentions: + /// + /// > Linux accept() passes already-pending network errors on the new + /// > socket as an error code from accept(). This behavior differs from + /// > other BSD socket implementations. For reliable operation the + /// > application should detect the network errors defined for the + /// > protocol after accept() and treat them like EAGAIN by retrying. + /// > In the case of TCP/IP, these are ENETDOWN, EPROTO, ENOPROTOOPT, + /// > EHOSTDOWN, ENONET, EHOSTUNREACH, EOPNOTSUPP, and ENETUNREACH. + /// Source: https://man7.org/linux/man-pages/man2/accept.2.html + /// + /// WASI implementations have two options to handle this: + /// - Optionally log it and then skip over non-fatal errors returned by + /// `accept`. Guest code never gets to see these failures. Or: + /// - Synthesize a `tcp-socket` resource that exposes the error when + /// attempting to send or receive on it. Guest code then sees these + /// failures as regular I/O errors. + /// + /// In either case, the stream returned by this `listen` method remains + /// operational. + /// + /// WASI requires `listen` to perform an implicit bind if the socket + /// has not already been bound. Not all platforms (notably Windows) + /// exhibit this behavior out of the box. On platforms that require it, + /// the WASI implementation can emulate this behavior by performing + /// the bind itself if the guest hasn't already done so. + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + listen: func() -> result, error-code>; + /// Transmit data to peer. + /// + /// The caller should close the stream when it has no more data to send + /// to the peer. Under normal circumstances this will cause a FIN packet + /// to be sent out. Closing the stream is equivalent to calling + /// `shutdown(SHUT_WR)` in POSIX. + /// + /// This function may be called at most once and returns once the full + /// contents of the stream are transmitted or an error is encountered. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `invalid-state`: `send` has already been called on this socket. + /// - `connection-broken`: The connection is not writable anymore. (EPIPE, ECONNABORTED on Windows) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + send: func(data: stream) -> future>; + /// Read data from peer. + /// + /// Returns a `stream` of data sent by the peer. The implementation + /// drops the stream once no more data is available. At that point, the + /// returned `future` resolves to: + /// - `ok` after a graceful shutdown from the peer (i.e. a FIN packet), or + /// - `err` if the socket was closed abnormally. + /// + /// `receive` may be called only once per socket. Subsequent calls return + /// a closed stream and a future resolved to `err(invalid-state)`. + /// + /// If the caller is not expecting to receive any more data from the peer, + /// they should drop the stream. Any data still in the receive queue + /// will be discarded. This is equivalent to calling `shutdown(SHUT_RD)` + /// in POSIX. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// - `invalid-state`: `receive` has already been called on this socket. + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + receive: func() -> tuple, future>>; + /// 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 `get-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.3.0) + get-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.3.0) + get-remote-address: func() -> result; + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.3.0) + get-is-listening: func() -> bool; + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0) + get-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 `connecting` or `connected` state. + @since(version = 0.3.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.3.0) + get-keep-alive-enabled: func() -> result; + @since(version = 0.3.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. + /// All other values are accepted without error, but may be + /// clamped or rounded. As a result, the value read back from + /// this setting may differ from the value that was set. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.3.0) + get-keep-alive-idle-time: func() -> result; + @since(version = 0.3.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. + /// All other values are accepted without error, but may be + /// clamped or rounded. As a result, the value read back from + /// this setting may differ from the value that was set. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.3.0) + get-keep-alive-interval: func() -> result; + @since(version = 0.3.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. + /// All other values are accepted without error, but may be + /// clamped or rounded. As a result, the value read back from + /// this setting may differ from the value that was set. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.3.0) + get-keep-alive-count: func() -> result; + @since(version = 0.3.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.3.0) + get-hop-limit: func() -> result; + @since(version = 0.3.0) + set-hop-limit: func(value: u8) -> result<_, error-code>; + /// Kernel buffer space reserved for sending/receiving on this socket. + /// Implementations usually treat this as a cap the buffer can grow to, + /// rather than allocating the full amount immediately. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// All other values are accepted without error, but may be + /// clamped or rounded. As a result, the value read back from + /// this setting may differ from the value that was set. + /// + /// This is only a performance hint. The implementation may ignore it or + /// tweak it based on real traffic patterns. + /// Linux and macOS appear to behave differently depending on whether a + /// buffer size was explicitly set. When set, they tend to honor it; when + /// not set, they dynamically adjust the buffer size as the connection + /// progresses. This is especially noticeable when comparing the values + /// from before and after connection establishment. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.3.0) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } + + /// A UDP socket handle. + @since(version = 0.3.0) + resource 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. + /// + /// Unlike POSIX, WASI sockets have no notion of a socket-level + /// `O_NONBLOCK` flag. Instead they fully rely on the Component Model's + /// async support. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + create: static func(address-family: ip-address-family) -> result; + /// Bind the socket to 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 can be bound to. (EADDRNOTAVAIL) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + bind: func(local-address: ip-socket-address) -> result<_, error-code>; + /// Associate this socket with a specific peer address. + /// + /// 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`. If the socket was not already explicitly + /// bound, this function will implicitly bind the socket to a random + /// free port. + /// + /// When a UDP socket is "connected", the `send` and `receive` methods + /// are limited to communicating with that peer only: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// The name "connect" was kept to align with the existing POSIX + /// terminology. Other than that, this function only changes the local + /// socket configuration and does not generate any network traffic. + /// The peer is not aware of this "connection". + /// + /// This method may be called multiple times on the same socket to change + /// its association, but only the most recent one will be effective. + /// + /// # 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) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// + /// # Implementors note + /// If the socket is already connected, some platforms (e.g. Linux) + /// require a disconnect before connecting to a different peer address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + connect: func(remote-address: ip-socket-address) -> result<_, error-code>; + /// Dissociate this socket from its peer address. + /// + /// After calling this method, `send` & `receive` are free to communicate + /// with any remote address again. + /// + /// The POSIX equivalent of this is calling `connect` with an `AF_UNSPEC` address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + disconnect: func() -> result<_, error-code>; + /// Send a message on the socket to a particular peer. + /// + /// If the socket is connected, the peer address may be left empty. In + /// that case this is equivalent to `send` in POSIX. Otherwise it is + /// equivalent to `sendto`. + /// + /// Additionally, if the socket is connected, a `remote-address` argument + /// _may_ be provided but then it must be identical to the address + /// passed to `connect`. + /// + /// If the socket has not been explicitly bound, it will be + /// implicitly bound to a random free port. + /// + /// Implementations may trap if the `data` length exceeds 64 KiB. + /// + /// # 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 `connect`. (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) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// + /// # Implementors note + /// WASI requires `send` to perform an implicit bind if the socket + /// has not been bound. Not all platforms (notably Windows) exhibit + /// this behavior natively. On such platforms, the WASI implementation + /// should emulate it by performing the bind if the guest has not + /// already done so. + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + send: async func(data: list, remote-address: option) -> result<_, error-code>; + /// Receive a message on the socket. + /// + /// On success, the return value contains a tuple of the received data + /// and the address of the sender. Theoretical maximum length of the + /// data is 64 KiB. Though in practice, it will typically be less than + /// 1500 bytes. + /// + /// If the socket is connected, the sender address is guaranteed to + /// match the remote address passed to `connect`. + /// + /// # Typical errors + /// - `invalid-state`: The socket has not been bound yet. + /// - `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.3.0) + receive: async func() -> result, ip-socket-address>, 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 `get-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.3.0) + get-local-address: func() -> result; + /// Get the address the socket is currently "connected" to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not "connected" to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + get-remote-address: func() -> result; + /// Whether this is a IPv4 or IPv6 socket. + /// + /// This is the value passed to the constructor. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.3.0) + get-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.3.0) + get-unicast-hop-limit: func() -> result; + @since(version = 0.3.0) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + /// Kernel buffer space reserved for sending/receiving on this socket. + /// Implementations usually treat this as a cap the buffer can grow to, + /// rather than allocating the full amount immediately. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// All other values are accepted without error, but may be + /// clamped or rounded. As a result, the value read back from + /// this setting may differ from the value that was set. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.3.0) + get-receive-buffer-size: func() -> result; + @since(version = 0.3.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.3.0) + get-send-buffer-size: func() -> result; + @since(version = 0.3.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + } +} + +@since(version = 0.3.0) +interface ip-name-lookup { + @since(version = 0.3.0) + use types.{ip-address}; + + /// Lookup error codes. + @since(version = 0.3.0) + variant error-code { + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + /// `name` is a syntactically invalid domain name or IP address. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + /// Name does not exist or has no suitable associated IP addresses. + /// + /// POSIX equivalent: EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY + name-unresolvable, + /// A temporary failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_AGAIN + temporary-resolver-failure, + /// A permanent failure in name resolution occurred. + /// + /// POSIX equivalent: EAI_FAIL + permanent-resolver-failure, + /// A catch-all for errors not captured by the existing variants. + /// Implementations can use this to extend the error type without + /// breaking existing code. + other(option), + } + + /// 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. + /// + /// The results are returned in connection order preference. + /// + /// This function never succeeds with 0 results. It either fails or succeeds + /// with at least one address. Additionally, this function never returns + /// IPv4-mapped IPv6 addresses. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.3.0) + resolve-addresses: async func(name: string) -> result, error-code>; +} + +@since(version = 0.3.0) +world imports { + @since(version = 0.3.0) + import wasi:clocks/types@0.3.0; + @since(version = 0.3.0) + import types; + @since(version = 0.3.0) + import ip-name-lookup; +} diff --git a/sdks/python/wit/main.wit b/sdks/python/wit/main.wit new file mode 100644 index 0000000000..e1a2f8e98c --- /dev/null +++ b/sdks/python/wit/main.wit @@ -0,0 +1,45 @@ +package golem:python; + +world agent-guest { + import golem:api/host@1.5.0; + import golem:agent/host@2.0.0; + import golem:agent/durable-streams@2.0.0; + import golem:tool/host@0.1.0; + + import golem:rdbms/ignite2@1.5.0; + import golem:rdbms/postgres@1.5.0; + import golem:rdbms/mysql@1.5.0; + import golem:rdbms/types@1.5.0; + + import golem:api/context@1.5.0; + import golem:api/oplog@1.5.0; + import golem:api/retry@1.5.0; + import golem:durability/durability@1.6.0; + import golem:quota/types@1.5.0; + import golem:secrets/types@0.1.0; + import golem:secrets/reveal@0.1.0; + import golem:permissions/types@0.1.0; + import golem:permissions/inspect@0.1.0; + import golem:permissions/derive@0.1.0; + import golem:permissions/revoke@0.1.0; + import golem:permissions/wallet@0.1.0; + import golem:permissions/kernel-introspection@0.1.0; + + import wasi:blobstore/blobstore; + import wasi:blobstore/container; + import wasi:blobstore/types; + + import wasi:keyvalue/eventual@0.1.0; + import wasi:keyvalue/eventual-batch@0.1.0; + import wasi:keyvalue/types@0.1.0; + import wasi:keyvalue/wasi-keyvalue-error@0.1.0; + + import wasi:config/store@0.2.0-draft; + + import golem:websocket/client@1.5.0; + import golem:network/dns@0.1.0; + + include golem:agent/agent-guest@2.0.0; + export golem:tool/guest@0.1.0; + export golem:tool/tool-middleware-guest@0.1.0; +} From 52f5fc959f88829d3cbadb26ed661730ad859186 Mon Sep 17 00:00:00 2001 From: David Biro Date: Tue, 17 Nov 2026 01:08:20 +0000 Subject: [PATCH 2/4] Hide host file metadata from Python pre-initialization --- golem-python-assembler/src/lib.rs | 109 ++++++++++++++++++++++- golem-python-assembler/tests/assemble.rs | 38 ++++++++ sdks/python/README.md | 11 ++- 3 files changed, 153 insertions(+), 5 deletions(-) diff --git a/golem-python-assembler/src/lib.rs b/golem-python-assembler/src/lib.rs index 75357a8e68..ef8faf2800 100644 --- a/golem-python-assembler/src/lib.rs +++ b/golem-python-assembler/src/lib.rs @@ -7,6 +7,7 @@ //! does not process WIT, generate code or compile CPython. use std::{ + collections::HashMap, path::Path, sync::atomic::{AtomicU64, Ordering}, time::Duration, @@ -15,12 +16,19 @@ use std::{ use anyhow::{Context, Result, ensure}; use componentize_py::prepared::{Assembler, Prepared}; use wasmtime::{ - Engine, Store, - component::{Linker, ResourceTable}, + Engine, Store, StoreContextMut, + component::{Linker, Resource, ResourceTable}, }; use wasmtime_wasi::{ Deterministic, FsPerms, IoCtx, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, - p2::pipe::MemoryOutputPipe, + filesystem::WasiFilesystemView, + p2::{ + FsResult, + bindings::filesystem::types::{ + Descriptor, DescriptorStat, ErrorCode, HostDescriptor, MetadataHashValue, PathFlags, + }, + pipe::MemoryOutputPipe, + }, }; #[cfg(test)] @@ -62,6 +70,99 @@ struct Host { ctx: WasiCtx, io: IoCtx, table: ResourceTable, + metadata_hashes: HashMap<(u64, u64), u64>, +} + +impl Host { + /// Replaces a host metadata hash with the order in which the guest first + /// saw it. The same object keeps one value and different objects get + /// different values, but the values do not depend on host inodes. + fn stable_metadata_hash( + &mut self, + hash: FsResult, + ) -> wasmtime::Result> { + let hash = match hash { + Ok(hash) => hash, + Err(error) => return Ok(Err(error.downcast()?)), + }; + let next = self.metadata_hashes.len() as u64 + 1; + let lower = *self + .metadata_hashes + .entry((hash.upper, hash.lower)) + .or_insert(next); + Ok(Ok(MetadataHashValue { upper: 0, lower })) + } +} + +/// Removes the host timestamps from a stat result. The application's source +/// files and the unpacked runtime get new times on every build, and CPython +/// keeps the times it reads in memory that the component saves. +fn without_timestamps( + stat: FsResult, +) -> wasmtime::Result> { + match stat { + Ok(stat) => Ok(Ok(DescriptorStat { + data_access_timestamp: None, + data_modification_timestamp: None, + status_change_timestamp: None, + ..stat + })), + Err(error) => Ok(Err(error.downcast()?)), + } +} + +/// Makes the file metadata that pre-initialization sees independent of the +/// host: stat results have no timestamps, and metadata hashes, from which the +/// guest derives inode numbers, do not depend on host inodes. CPython keeps +/// this metadata in memory that the component saves. +fn add_host_independent_metadata(linker: &mut Linker) -> Result<()> { + linker.allow_shadowing(true); + let mut types = linker.instance("wasi:filesystem/types@0.2.12")?; + types.func_wrap_async( + "[method]descriptor.metadata-hash", + |mut store: StoreContextMut<'_, Host>, (fd,): (Resource,)| { + Box::new(async move { + let host = store.data_mut(); + let hash = HostDescriptor::metadata_hash(&mut host.filesystem(), fd).await; + Ok((host.stable_metadata_hash(hash)?,)) + }) + }, + )?; + types.func_wrap_async( + "[method]descriptor.metadata-hash-at", + |mut store: StoreContextMut<'_, Host>, + (fd, flags, path): (Resource, PathFlags, String)| { + Box::new(async move { + let host = store.data_mut(); + let hash = + HostDescriptor::metadata_hash_at(&mut host.filesystem(), fd, flags, path).await; + Ok((host.stable_metadata_hash(hash)?,)) + }) + }, + )?; + types.func_wrap_async( + "[method]descriptor.stat", + |mut store: StoreContextMut<'_, Host>, (fd,): (Resource,)| { + Box::new(async move { + let stat = HostDescriptor::stat(&mut store.data_mut().filesystem(), fd).await; + Ok((without_timestamps(stat)?,)) + }) + }, + )?; + types.func_wrap_async( + "[method]descriptor.stat-at", + |mut store: StoreContextMut<'_, Host>, + (fd, flags, path): (Resource, PathFlags, String)| { + Box::new(async move { + let stat = + HostDescriptor::stat_at(&mut store.data_mut().filesystem(), fd, flags, path) + .await; + Ok((without_timestamps(stat)?,)) + }) + }, + )?; + linker.allow_shadowing(false); + Ok(()) } impl WasiView for Host { @@ -175,6 +276,7 @@ pub async fn build(prepared: &Prepared, app: &Application<'_>) -> Result Engine::new(&golem_common::wasmtime_config::create_wasmtime_config_without_fs_cache())?; let mut linker = Linker::::new(&engine); wasmtime_wasi::p2::add_to_linker_async(&mut linker)?; + add_host_independent_metadata(&mut linker)?; componentize_py::add_trapping_stubs(&mut linker, &plan.stubs)?; let mut store = Store::new( @@ -183,6 +285,7 @@ pub async fn build(prepared: &Prepared, app: &Application<'_>) -> Result ctx, io, table: ResourceTable::new(), + metadata_hashes: HashMap::new(), }, ); // The shared engine meters fuel and interrupts on epochs; initialization diff --git a/golem-python-assembler/tests/assemble.rs b/golem-python-assembler/tests/assemble.rs index 9809e3d408..5dcabef55c 100644 --- a/golem-python-assembler/tests/assemble.rs +++ b/golem-python-assembler/tests/assemble.rs @@ -190,3 +190,41 @@ async fn invalid_entry_modules_fail_before_imports() -> Result<()> { ); Ok(()) } + +#[test] +async fn identical_inputs_give_identical_components() -> Result<()> { + let prepared = prepared()?; + let sdk = python_sdk().join("src"); + let source = "import json\n\nVALUE = json.dumps({'a': [1, 2]})\n"; + + let mut components = Vec::new(); + // Each build uses a new application directory, and the assembler unpacks + // the prepared assets into new directories. The application directories + // stay alive until both builds finish, so the second one cannot reuse + // the host inode of the first. + let mut dirs = Vec::new(); + for _ in 0..2 { + let dir = tempfile::tempdir()?; + write_app(dir.path(), "app", source)?; + components.push( + build( + &prepared, + &Application { + sdk_dir: &sdk, + source_dir: dir.path(), + entry_modules: &["app"], + }, + ) + .await?, + ); + dirs.push(dir); + } + let differing = components[0] + .iter() + .zip(&components[1]) + .filter(|(a, b)| a != b) + .count(); + assert_eq!(components[0].len(), components[1].len()); + assert_eq!(differing, 0, "the two builds differ in {differing} bytes"); + Ok(()) +} diff --git a/sdks/python/README.md b/sdks/python/README.md index da02064c47..c09657943e 100644 --- a/sdks/python/README.md +++ b/sdks/python/README.md @@ -37,5 +37,12 @@ cargo test -p golem-python-assembler More output fails the build. - The C stack is 96 KiB. Deep recursion in `repr`, `json`, `pickle` and `__repr__` raises `RecursionError` at a lower depth than in native CPython. -- Two builds of the same input can differ in a few bytes. The difference - comes from host file metadata that pre-initialization records. +- During pre-initialization, file timestamps read as the Unix epoch, and + inode numbers follow the order in which files are first seen, so that the + saved component does not depend on the host. Two builds of the same input in + different directories give the same bytes on the same host. Builds on + different file systems or hosts are not yet checked: directory listing order + and link counts still come from the host. +- Because directory timestamps do not change during pre-initialization, call + `importlib.invalidate_caches()` before importing a module that a module + wrote during pre-initialization. From a50b51a561f224a145377acf81e3e2627516699a Mon Sep 17 00:00:00 2001 From: David Biro Date: Thu, 26 Nov 2026 00:07:25 +0000 Subject: [PATCH 3/4] Pass stdout and stderr to Tools.invoke and update componentize-py The generated binding calls golem:tool/guest.invoke with six arguments, so the five-parameter method raised TypeError instead of returning invalid-tool-name. componentize-py moves to 58d479e. Its lowering checks accept number types such as numpy.int64, build entropy also covers the app name and Python path files, prepared blobs with links are rejected, and the initialization WIT digest normalizes line endings. --- Cargo.lock | 6 +++--- Cargo.toml | 4 ++-- Makefile.toml | 2 +- sdks/python/src/golem/_guest.py | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cd177786e3..c08115ea5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1891,7 +1891,7 @@ dependencies = [ [[package]] name = "componentize-py" version = "0.25.0" -source = "git+https://github.com/golemcloud/componentize-py?rev=189e903b00ca43500f95e2d32eaf44496a7a3640#189e903b00ca43500f95e2d32eaf44496a7a3640" +source = "git+https://github.com/golemcloud/componentize-py?rev=58d479e5993b744314ec51a77a20e3b487c69aac#58d479e5993b744314ec51a77a20e3b487c69aac" dependencies = [ "anyhow", "async-trait", @@ -1920,7 +1920,7 @@ dependencies = [ [[package]] name = "componentize-py-test-generator" version = "0.25.0" -source = "git+https://github.com/golemcloud/componentize-py?rev=189e903b00ca43500f95e2d32eaf44496a7a3640#189e903b00ca43500f95e2d32eaf44496a7a3640" +source = "git+https://github.com/golemcloud/componentize-py?rev=58d479e5993b744314ec51a77a20e3b487c69aac#58d479e5993b744314ec51a77a20e3b487c69aac" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -13964,7 +13964,7 @@ dependencies = [ [[package]] name = "wit-component" version = "0.258.3" -source = "git+https://github.com/golemcloud/componentize-py?rev=189e903b00ca43500f95e2d32eaf44496a7a3640#189e903b00ca43500f95e2d32eaf44496a7a3640" +source = "git+https://github.com/golemcloud/componentize-py?rev=58d479e5993b744314ec51a77a20e3b487c69aac#58d479e5993b744314ec51a77a20e3b487c69aac" dependencies = [ "anyhow", "bitflags 2.13.2", diff --git a/Cargo.toml b/Cargo.toml index 4a27156482..31f7607e01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,7 @@ print_stderr = "deny" license-file = "LICENSE" [workspace.dependencies] -componentize-py = { git = "https://github.com/golemcloud/componentize-py", rev = "189e903b00ca43500f95e2d32eaf44496a7a3640", default-features = false } +componentize-py = { git = "https://github.com/golemcloud/componentize-py", rev = "58d479e5993b744314ec51a77a20e3b487c69aac", default-features = false } golem-api-grpc = { version = "=0.0.0", path = "golem-api-grpc" } golem-async-trait = { version = "=0.0.0", path = "golem-async-trait" } golem-cli = { version = "=0.0.0", path = "cli/golem-cli" } @@ -384,7 +384,7 @@ wasmtime-wasi = { git = "https://github.com/golemcloud/wasmtime.git", branch = " wasmtime-wasi-http = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } wasmtime-wizer = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } # wit-component 0.258.3 with the dlopen symbol-table fix that componentize-py links with. -wit-component = { git = "https://github.com/golemcloud/componentize-py", rev = "189e903b00ca43500f95e2d32eaf44496a7a3640" } +wit-component = { git = "https://github.com/golemcloud/componentize-py", rev = "58d479e5993b744314ec51a77a20e3b487c69aac" } # The head of the branch `golem-rustic_core-v0.13.0` of the fork. rustic_core = { git = "https://github.com/golemcloud/rustic_core", rev = "2269cbb0b2b89dc55cd4dca0172ead894b7b43fd" } diff --git a/Makefile.toml b/Makefile.toml index a16d63a22a..4b772a7faa 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -3366,7 +3366,7 @@ end description = "Prepares the Python SDK runtime and bindings in sdks/python/target/prepared" script_runner = "@duckscript" script = ''' -rev = set 189e903b00ca43500f95e2d32eaf44496a7a3640 +rev = set 58d479e5993b744314ec51a77a20e3b487c69aac tools = set sdks/python/target/tools exec --fail-on-error cargo install --locked --git https://github.com/golemcloud/componentize-py --rev ${rev} --root ${tools} componentize-py rm -r sdks/python/target/prepared diff --git a/sdks/python/src/golem/_guest.py b/sdks/python/src/golem/_guest.py index 20059d1faa..41757749ea 100644 --- a/sdks/python/src/golem/_guest.py +++ b/sdks/python/src/golem/_guest.py @@ -45,7 +45,7 @@ def discover_tools(self): def get_tool(self, name): raise Err(ToolError_InvalidToolName(name)) - async def invoke(self, tool_name, command_path, input, stdin): + async def invoke(self, tool_name, command_path, input, stdin, stdout, stderr): raise Err(ToolError_InvalidToolName(tool_name)) From a0c4cb32c26aa52adfe37aadfcb03b76dd647095 Mon Sep 17 00:00:00 2001 From: David Biro Date: Thu, 26 Nov 2026 14:02:40 +0000 Subject: [PATCH 4/4] Take wit-component from the wasm-tools fork The dlopen symbol-count fix is merged into the golem-2.0 branch of golemcloud/wasm-tools, and componentize-py cad25ee removed its vendored copy and pins that commit. The workspace patch now pins the same wasm-tools commit, and componentize-py moves to cad25ee. The sibling crates of wit-component still come from crates.io. --- Cargo.lock | 6 +++--- Cargo.toml | 7 ++++--- Makefile.toml | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c08115ea5d..f0f07bc6a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1891,7 +1891,7 @@ dependencies = [ [[package]] name = "componentize-py" version = "0.25.0" -source = "git+https://github.com/golemcloud/componentize-py?rev=58d479e5993b744314ec51a77a20e3b487c69aac#58d479e5993b744314ec51a77a20e3b487c69aac" +source = "git+https://github.com/golemcloud/componentize-py?rev=cad25eefaa090c158bca5ba5882c389eade4bcac#cad25eefaa090c158bca5ba5882c389eade4bcac" dependencies = [ "anyhow", "async-trait", @@ -1920,7 +1920,7 @@ dependencies = [ [[package]] name = "componentize-py-test-generator" version = "0.25.0" -source = "git+https://github.com/golemcloud/componentize-py?rev=58d479e5993b744314ec51a77a20e3b487c69aac#58d479e5993b744314ec51a77a20e3b487c69aac" +source = "git+https://github.com/golemcloud/componentize-py?rev=cad25eefaa090c158bca5ba5882c389eade4bcac#cad25eefaa090c158bca5ba5882c389eade4bcac" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -13964,7 +13964,7 @@ dependencies = [ [[package]] name = "wit-component" version = "0.258.3" -source = "git+https://github.com/golemcloud/componentize-py?rev=58d479e5993b744314ec51a77a20e3b487c69aac#58d479e5993b744314ec51a77a20e3b487c69aac" +source = "git+https://github.com/golemcloud/wasm-tools?rev=801650b5c9e5e4aa32451283f7a6d14100f92889#801650b5c9e5e4aa32451283f7a6d14100f92889" dependencies = [ "anyhow", "bitflags 2.13.2", diff --git a/Cargo.toml b/Cargo.toml index 31f7607e01..904e9e5ad9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,7 @@ print_stderr = "deny" license-file = "LICENSE" [workspace.dependencies] -componentize-py = { git = "https://github.com/golemcloud/componentize-py", rev = "58d479e5993b744314ec51a77a20e3b487c69aac", default-features = false } +componentize-py = { git = "https://github.com/golemcloud/componentize-py", rev = "cad25eefaa090c158bca5ba5882c389eade4bcac", default-features = false } golem-api-grpc = { version = "=0.0.0", path = "golem-api-grpc" } golem-async-trait = { version = "=0.0.0", path = "golem-async-trait" } golem-cli = { version = "=0.0.0", path = "cli/golem-cli" } @@ -383,8 +383,9 @@ wasmtime = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem wasmtime-wasi = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } wasmtime-wasi-http = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } wasmtime-wizer = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } -# wit-component 0.258.3 with the dlopen symbol-table fix that componentize-py links with. -wit-component = { git = "https://github.com/golemcloud/componentize-py", rev = "58d479e5993b744314ec51a77a20e3b487c69aac" } +# wit-component 0.258.3 with the dlopen symbol-table fix, from the golem-2.0 branch of the +# wasm-tools fork. componentize-py links with the same commit; keep the two revisions equal. +wit-component = { git = "https://github.com/golemcloud/wasm-tools", rev = "801650b5c9e5e4aa32451283f7a6d14100f92889" } # The head of the branch `golem-rustic_core-v0.13.0` of the fork. rustic_core = { git = "https://github.com/golemcloud/rustic_core", rev = "2269cbb0b2b89dc55cd4dca0172ead894b7b43fd" } diff --git a/Makefile.toml b/Makefile.toml index 4b772a7faa..bb7d72dc5e 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -3366,7 +3366,7 @@ end description = "Prepares the Python SDK runtime and bindings in sdks/python/target/prepared" script_runner = "@duckscript" script = ''' -rev = set 58d479e5993b744314ec51a77a20e3b487c69aac +rev = set cad25eefaa090c158bca5ba5882c389eade4bcac tools = set sdks/python/target/tools exec --fail-on-error cargo install --locked --git https://github.com/golemcloud/componentize-py --rev ${rev} --root ${tools} componentize-py rm -r sdks/python/target/prepared