diff --git a/.github/workflows/go.yaml b/.github/workflows/go.yaml index 91d0246..8ec5710 100644 --- a/.github/workflows/go.yaml +++ b/.github/workflows/go.yaml @@ -54,6 +54,7 @@ jobs: matrix: example: - http-server + - http-client runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -63,6 +64,10 @@ jobs: - uses: acifani/setup-tinygo@v2 with: tinygo-version: ${{ env.TINYGO_VERSION }} + - uses: golangci/golangci-lint-action@v6 + with: + version: ${{ env.GOLANGCI_VERSION }} + working-directory: "_examples/${{ matrix.example }}" - uses: wasmCloud/common-actions/install-wash@main - uses: cargo-bins/cargo-binstall@main - name: Tools @@ -82,4 +87,5 @@ jobs: - name: wash build working-directory: "_examples/${{ matrix.example }}" - run: wash build \ No newline at end of file + run: wash build + diff --git a/.golangci.yaml b/.golangci.yaml index 1bf5e46..1edecd7 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,3 +1,7 @@ +run: + tests: false + modules-download-mode: readonly + output: uniq-by-line: false show-stats: true @@ -10,8 +14,7 @@ output: linters: enable: - gofmt - # TODO(lxf): enable once we are ready to start releasing - #- revive + - revive - thelper - mirror - usestdlibvars @@ -95,5 +98,4 @@ linters-settings: # List of words to ignore # among the one defined in https://github.com/golangci/misspell/blob/master/words.go ignore-words: - # - valor - # - and \ No newline at end of file + - WASM diff --git a/_examples/http-client/.gitignore b/_examples/http-client/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/_examples/http-client/build/.gitignore b/_examples/http-client/build/.gitignore new file mode 100644 index 0000000..071ca07 --- /dev/null +++ b/_examples/http-client/build/.gitignore @@ -0,0 +1,3 @@ +# Keep the directory but ignore all files. Dir is required to exist by the build process +* +!.gitignore diff --git a/_examples/http-client/gen/example/http-client/example/example.wit.go b/_examples/http-client/gen/example/http-client/example/example.wit.go new file mode 100644 index 0000000..0b59238 --- /dev/null +++ b/_examples/http-client/gen/example/http-client/example/example.wit.go @@ -0,0 +1,4 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package example represents the world "example:http-client/example". +package example diff --git a/_examples/http-client/gen/wasi/cli/environment/empty.s b/_examples/http-client/gen/wasi/cli/environment/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/environment/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/environment/environment.wit.go b/_examples/http-client/gen/wasi/cli/environment/environment.wit.go new file mode 100644 index 0000000..48e066d --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/environment/environment.wit.go @@ -0,0 +1,64 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package environment represents the imported interface "wasi:cli/environment@0.2.0". +package environment + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// GetEnvironment represents the imported function "get-environment". +// +// Get the POSIX-style environment variables. +// +// Each environment variable is provided as a pair of string variable names +// and string value. +// +// Morally, these are a value import, but until value imports are available +// in the component model, this import function should return the same +// values each time it is called. +// +// get-environment: func() -> list> +// +//go:nosplit +func GetEnvironment() (result cm.List[[2]string]) { + wasmimport_GetEnvironment(&result) + return +} + +//go:wasmimport wasi:cli/environment@0.2.0 get-environment +//go:noescape +func wasmimport_GetEnvironment(result *cm.List[[2]string]) + +// GetArguments represents the imported function "get-arguments". +// +// Get the POSIX-style arguments to the program. +// +// get-arguments: func() -> list +// +//go:nosplit +func GetArguments() (result cm.List[string]) { + wasmimport_GetArguments(&result) + return +} + +//go:wasmimport wasi:cli/environment@0.2.0 get-arguments +//go:noescape +func wasmimport_GetArguments(result *cm.List[string]) + +// InitialCWD represents the imported function "initial-cwd". +// +// Return a path that programs should use as their initial current working +// directory, interpreting `.` as shorthand for this. +// +// initial-cwd: func() -> option +// +//go:nosplit +func InitialCWD() (result cm.Option[string]) { + wasmimport_InitialCWD(&result) + return +} + +//go:wasmimport wasi:cli/environment@0.2.0 initial-cwd +//go:noescape +func wasmimport_InitialCWD(result *cm.Option[string]) diff --git a/_examples/http-client/gen/wasi/cli/exit/empty.s b/_examples/http-client/gen/wasi/cli/exit/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/exit/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/exit/exit.wit.go b/_examples/http-client/gen/wasi/cli/exit/exit.wit.go new file mode 100644 index 0000000..3fccd93 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/exit/exit.wit.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package exit represents the imported interface "wasi:cli/exit@0.2.0". +package exit + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// Exit represents the imported function "exit". +// +// Exit the current instance and any linked instances. +// +// exit: func(status: result) +// +//go:nosplit +func Exit(status cm.BoolResult) { + status0 := cm.BoolToU32(status) + wasmimport_Exit((uint32)(status0)) + return +} + +//go:wasmimport wasi:cli/exit@0.2.0 exit +//go:noescape +func wasmimport_Exit(status0 uint32) diff --git a/_examples/http-client/gen/wasi/cli/stderr/empty.s b/_examples/http-client/gen/wasi/cli/stderr/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/stderr/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/stderr/stderr.wit.go b/_examples/http-client/gen/wasi/cli/stderr/stderr.wit.go new file mode 100644 index 0000000..bde8b76 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/stderr/stderr.wit.go @@ -0,0 +1,24 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package stderr represents the imported interface "wasi:cli/stderr@0.2.0". +package stderr + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/streams" +) + +// GetStderr represents the imported function "get-stderr". +// +// get-stderr: func() -> output-stream +// +//go:nosplit +func GetStderr() (result streams.OutputStream) { + result0 := wasmimport_GetStderr() + result = cm.Reinterpret[streams.OutputStream]((uint32)(result0)) + return +} + +//go:wasmimport wasi:cli/stderr@0.2.0 get-stderr +//go:noescape +func wasmimport_GetStderr() (result0 uint32) diff --git a/_examples/http-client/gen/wasi/cli/stdin/empty.s b/_examples/http-client/gen/wasi/cli/stdin/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/stdin/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/stdin/stdin.wit.go b/_examples/http-client/gen/wasi/cli/stdin/stdin.wit.go new file mode 100644 index 0000000..582295e --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/stdin/stdin.wit.go @@ -0,0 +1,24 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package stdin represents the imported interface "wasi:cli/stdin@0.2.0". +package stdin + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/streams" +) + +// GetStdin represents the imported function "get-stdin". +// +// get-stdin: func() -> input-stream +// +//go:nosplit +func GetStdin() (result streams.InputStream) { + result0 := wasmimport_GetStdin() + result = cm.Reinterpret[streams.InputStream]((uint32)(result0)) + return +} + +//go:wasmimport wasi:cli/stdin@0.2.0 get-stdin +//go:noescape +func wasmimport_GetStdin() (result0 uint32) diff --git a/_examples/http-client/gen/wasi/cli/stdout/empty.s b/_examples/http-client/gen/wasi/cli/stdout/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/stdout/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/stdout/stdout.wit.go b/_examples/http-client/gen/wasi/cli/stdout/stdout.wit.go new file mode 100644 index 0000000..253aaba --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/stdout/stdout.wit.go @@ -0,0 +1,24 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package stdout represents the imported interface "wasi:cli/stdout@0.2.0". +package stdout + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/streams" +) + +// GetStdout represents the imported function "get-stdout". +// +// get-stdout: func() -> output-stream +// +//go:nosplit +func GetStdout() (result streams.OutputStream) { + result0 := wasmimport_GetStdout() + result = cm.Reinterpret[streams.OutputStream]((uint32)(result0)) + return +} + +//go:wasmimport wasi:cli/stdout@0.2.0 get-stdout +//go:noescape +func wasmimport_GetStdout() (result0 uint32) diff --git a/_examples/http-client/gen/wasi/cli/terminal-input/empty.s b/_examples/http-client/gen/wasi/cli/terminal-input/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-input/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/terminal-input/terminal-input.wit.go b/_examples/http-client/gen/wasi/cli/terminal-input/terminal-input.wit.go new file mode 100644 index 0000000..e0114e0 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-input/terminal-input.wit.go @@ -0,0 +1,36 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalinput represents the imported interface "wasi:cli/terminal-input@0.2.0". +// +// Terminal input. +// +// In the future, this may include functions for disabling echoing, +// disabling input buffering so that keyboard events are sent through +// immediately, querying supported features, and so on. +package terminalinput + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// TerminalInput represents the imported resource "wasi:cli/terminal-input@0.2.0#terminal-input". +// +// The input side of a terminal. +// +// resource terminal-input +type TerminalInput cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "terminal-input". +// +// Drops a resource handle. +// +//go:nosplit +func (self TerminalInput) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TerminalInputResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:cli/terminal-input@0.2.0 [resource-drop]terminal-input +//go:noescape +func wasmimport_TerminalInputResourceDrop(self0 uint32) diff --git a/_examples/http-client/gen/wasi/cli/terminal-output/empty.s b/_examples/http-client/gen/wasi/cli/terminal-output/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-output/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/terminal-output/terminal-output.wit.go b/_examples/http-client/gen/wasi/cli/terminal-output/terminal-output.wit.go new file mode 100644 index 0000000..a63b0e6 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-output/terminal-output.wit.go @@ -0,0 +1,36 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminaloutput represents the imported interface "wasi:cli/terminal-output@0.2.0". +// +// Terminal output. +// +// In the future, this may include functions for querying the terminal +// size, being notified of terminal size changes, querying supported +// features, and so on. +package terminaloutput + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// TerminalOutput represents the imported resource "wasi:cli/terminal-output@0.2.0#terminal-output". +// +// The output side of a terminal. +// +// resource terminal-output +type TerminalOutput cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "terminal-output". +// +// Drops a resource handle. +// +//go:nosplit +func (self TerminalOutput) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TerminalOutputResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:cli/terminal-output@0.2.0 [resource-drop]terminal-output +//go:noescape +func wasmimport_TerminalOutputResourceDrop(self0 uint32) diff --git a/_examples/http-client/gen/wasi/cli/terminal-stderr/empty.s b/_examples/http-client/gen/wasi/cli/terminal-stderr/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-stderr/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/terminal-stderr/terminal-stderr.wit.go b/_examples/http-client/gen/wasi/cli/terminal-stderr/terminal-stderr.wit.go new file mode 100644 index 0000000..b295731 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-stderr/terminal-stderr.wit.go @@ -0,0 +1,29 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalstderr represents the imported interface "wasi:cli/terminal-stderr@0.2.0". +// +// An interface providing an optional `terminal-output` for stderr as a +// link-time authority. +package terminalstderr + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + terminaloutput "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/cli/terminal-output" +) + +// GetTerminalStderr represents the imported function "get-terminal-stderr". +// +// If stderr is connected to a terminal, return a `terminal-output` handle +// allowing further interaction with it. +// +// get-terminal-stderr: func() -> option +// +//go:nosplit +func GetTerminalStderr() (result cm.Option[terminaloutput.TerminalOutput]) { + wasmimport_GetTerminalStderr(&result) + return +} + +//go:wasmimport wasi:cli/terminal-stderr@0.2.0 get-terminal-stderr +//go:noescape +func wasmimport_GetTerminalStderr(result *cm.Option[terminaloutput.TerminalOutput]) diff --git a/_examples/http-client/gen/wasi/cli/terminal-stdin/empty.s b/_examples/http-client/gen/wasi/cli/terminal-stdin/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-stdin/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/terminal-stdin/terminal-stdin.wit.go b/_examples/http-client/gen/wasi/cli/terminal-stdin/terminal-stdin.wit.go new file mode 100644 index 0000000..fcbc8a1 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-stdin/terminal-stdin.wit.go @@ -0,0 +1,29 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalstdin represents the imported interface "wasi:cli/terminal-stdin@0.2.0". +// +// An interface providing an optional `terminal-input` for stdin as a +// link-time authority. +package terminalstdin + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + terminalinput "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/cli/terminal-input" +) + +// GetTerminalStdin represents the imported function "get-terminal-stdin". +// +// If stdin is connected to a terminal, return a `terminal-input` handle +// allowing further interaction with it. +// +// get-terminal-stdin: func() -> option +// +//go:nosplit +func GetTerminalStdin() (result cm.Option[terminalinput.TerminalInput]) { + wasmimport_GetTerminalStdin(&result) + return +} + +//go:wasmimport wasi:cli/terminal-stdin@0.2.0 get-terminal-stdin +//go:noescape +func wasmimport_GetTerminalStdin(result *cm.Option[terminalinput.TerminalInput]) diff --git a/_examples/http-client/gen/wasi/cli/terminal-stdout/empty.s b/_examples/http-client/gen/wasi/cli/terminal-stdout/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-stdout/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/cli/terminal-stdout/terminal-stdout.wit.go b/_examples/http-client/gen/wasi/cli/terminal-stdout/terminal-stdout.wit.go new file mode 100644 index 0000000..b5caaa4 --- /dev/null +++ b/_examples/http-client/gen/wasi/cli/terminal-stdout/terminal-stdout.wit.go @@ -0,0 +1,29 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package terminalstdout represents the imported interface "wasi:cli/terminal-stdout@0.2.0". +// +// An interface providing an optional `terminal-output` for stdout as a +// link-time authority. +package terminalstdout + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + terminaloutput "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/cli/terminal-output" +) + +// GetTerminalStdout represents the imported function "get-terminal-stdout". +// +// If stdout is connected to a terminal, return a `terminal-output` handle +// allowing further interaction with it. +// +// get-terminal-stdout: func() -> option +// +//go:nosplit +func GetTerminalStdout() (result cm.Option[terminaloutput.TerminalOutput]) { + wasmimport_GetTerminalStdout(&result) + return +} + +//go:wasmimport wasi:cli/terminal-stdout@0.2.0 get-terminal-stdout +//go:noescape +func wasmimport_GetTerminalStdout(result *cm.Option[terminaloutput.TerminalOutput]) diff --git a/_examples/http-client/gen/wasi/clocks/monotonic-clock/empty.s b/_examples/http-client/gen/wasi/clocks/monotonic-clock/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/clocks/monotonic-clock/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/clocks/monotonic-clock/monotonic-clock.wit.go b/_examples/http-client/gen/wasi/clocks/monotonic-clock/monotonic-clock.wit.go new file mode 100644 index 0000000..16d47cf --- /dev/null +++ b/_examples/http-client/gen/wasi/clocks/monotonic-clock/monotonic-clock.wit.go @@ -0,0 +1,113 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package monotonicclock represents the imported interface "wasi:clocks/monotonic-clock@0.2.0". +// +// WASI Monotonic Clock is a clock API intended to let users measure elapsed +// time. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +// +// A monotonic clock is a clock which has an unspecified initial value, and +// successive reads of the clock will produce non-decreasing values. +// +// It is intended for measuring elapsed time. +package monotonicclock + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/poll" +) + +// Instant represents the u64 "wasi:clocks/monotonic-clock@0.2.0#instant". +// +// An instant in time, in nanoseconds. An instant is relative to an +// unspecified initial value, and can only be compared to instances from +// the same monotonic-clock. +// +// type instant = u64 +type Instant uint64 + +// Duration represents the u64 "wasi:clocks/monotonic-clock@0.2.0#duration". +// +// A duration of time, in nanoseconds. +// +// type duration = u64 +type Duration uint64 + +// Now represents the imported function "now". +// +// Read the current value of the clock. +// +// The clock is monotonic, therefore calling this function repeatedly will +// produce a sequence of non-decreasing values. +// +// now: func() -> instant +// +//go:nosplit +func Now() (result Instant) { + result0 := wasmimport_Now() + result = (Instant)((uint64)(result0)) + return +} + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 now +//go:noescape +func wasmimport_Now() (result0 uint64) + +// Resolution represents the imported function "resolution". +// +// Query the resolution of the clock. Returns the duration of time +// corresponding to a clock tick. +// +// resolution: func() -> duration +// +//go:nosplit +func Resolution() (result Duration) { + result0 := wasmimport_Resolution() + result = (Duration)((uint64)(result0)) + return +} + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 resolution +//go:noescape +func wasmimport_Resolution() (result0 uint64) + +// SubscribeInstant represents the imported function "subscribe-instant". +// +// Create a `pollable` which will resolve once the specified instant +// occured. +// +// subscribe-instant: func(when: instant) -> pollable +// +//go:nosplit +func SubscribeInstant(when Instant) (result poll.Pollable) { + when0 := (uint64)(when) + result0 := wasmimport_SubscribeInstant((uint64)(when0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 subscribe-instant +//go:noescape +func wasmimport_SubscribeInstant(when0 uint64) (result0 uint32) + +// SubscribeDuration represents the imported function "subscribe-duration". +// +// Create a `pollable` which will resolve once the given duration has +// elapsed, starting at the time at which this function was called. +// occured. +// +// subscribe-duration: func(when: duration) -> pollable +// +//go:nosplit +func SubscribeDuration(when Duration) (result poll.Pollable) { + when0 := (uint64)(when) + result0 := wasmimport_SubscribeDuration((uint64)(when0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:clocks/monotonic-clock@0.2.0 subscribe-duration +//go:noescape +func wasmimport_SubscribeDuration(when0 uint64) (result0 uint32) diff --git a/_examples/http-client/gen/wasi/clocks/wall-clock/empty.s b/_examples/http-client/gen/wasi/clocks/wall-clock/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/clocks/wall-clock/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/clocks/wall-clock/wall-clock.wit.go b/_examples/http-client/gen/wasi/clocks/wall-clock/wall-clock.wit.go new file mode 100644 index 0000000..a59a313 --- /dev/null +++ b/_examples/http-client/gen/wasi/clocks/wall-clock/wall-clock.wit.go @@ -0,0 +1,78 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package wallclock represents the imported interface "wasi:clocks/wall-clock@0.2.0". +// +// WASI Wall Clock is a clock API intended to let users query the current +// time. The name "wall" makes an analogy to a "clock on the wall", which +// is not necessarily monotonic as it may be reset. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +// +// A wall clock is a clock which measures the date and time according to +// some external reference. +// +// External references may be reset, so this clock is not necessarily +// monotonic, making it unsuitable for measuring elapsed time. +// +// It is intended for reporting the current date and time for humans. +package wallclock + +// DateTime represents the record "wasi:clocks/wall-clock@0.2.0#datetime". +// +// A time and date in seconds plus nanoseconds. +// +// record datetime { +// seconds: u64, +// nanoseconds: u32, +// } +type DateTime struct { + Seconds uint64 + Nanoseconds uint32 +} + +// Now represents the imported function "now". +// +// Read the current value of the clock. +// +// This clock is not monotonic, therefore calling this function repeatedly +// will not necessarily produce a sequence of non-decreasing values. +// +// The returned timestamps represent the number of seconds since +// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], +// also known as [Unix Time]. +// +// The nanoseconds field of the output is always less than 1000000000. +// +// now: func() -> datetime +// +// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 +// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time +// +//go:nosplit +func Now() (result DateTime) { + wasmimport_Now(&result) + return +} + +//go:wasmimport wasi:clocks/wall-clock@0.2.0 now +//go:noescape +func wasmimport_Now(result *DateTime) + +// Resolution represents the imported function "resolution". +// +// Query the resolution of the clock. +// +// The nanoseconds field of the output is always less than 1000000000. +// +// resolution: func() -> datetime +// +//go:nosplit +func Resolution() (result DateTime) { + wasmimport_Resolution(&result) + return +} + +//go:wasmimport wasi:clocks/wall-clock@0.2.0 resolution +//go:noescape +func wasmimport_Resolution(result *DateTime) diff --git a/_examples/http-client/gen/wasi/config/runtime/abi.go b/_examples/http-client/gen/wasi/config/runtime/abi.go new file mode 100644 index 0000000..9e4d898 --- /dev/null +++ b/_examples/http-client/gen/wasi/config/runtime/abi.go @@ -0,0 +1,18 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package runtime + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "unsafe" +) + +// OptionStringShape is used for storage in variant or result types. +type OptionStringShape struct { + shape [unsafe.Sizeof(cm.Option[string]{})]byte +} + +// ConfigErrorShape is used for storage in variant or result types. +type ConfigErrorShape struct { + shape [unsafe.Sizeof(ConfigError{})]byte +} diff --git a/_examples/http-client/gen/wasi/config/runtime/empty.s b/_examples/http-client/gen/wasi/config/runtime/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/config/runtime/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/config/runtime/runtime.wit.go b/_examples/http-client/gen/wasi/config/runtime/runtime.wit.go new file mode 100644 index 0000000..edf169f --- /dev/null +++ b/_examples/http-client/gen/wasi/config/runtime/runtime.wit.go @@ -0,0 +1,84 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package runtime represents the imported interface "wasi:config/runtime@0.2.0-draft". +package runtime + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// ConfigError represents the variant "wasi:config/runtime@0.2.0-draft#config-error". +// +// An error type that encapsulates the different errors that can occur fetching config +// +// variant config-error { +// upstream(string), +// io(string), +// } +type ConfigError cm.Variant[uint8, string, string] + +// ConfigErrorUpstream returns a [ConfigError] of case "upstream". +// +// 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. +func ConfigErrorUpstream(data string) ConfigError { + return cm.New[ConfigError](0, data) +} + +// Upstream returns a non-nil *[string] if [ConfigError] represents the variant case "upstream". +func (self *ConfigError) Upstream() *string { + return cm.Case[string](self, 0) +} + +// ConfigErrorIO returns a [ConfigError] of case "io". +// +// 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. +func ConfigErrorIO(data string) ConfigError { + return cm.New[ConfigError](1, data) +} + +// IO returns a non-nil *[string] if [ConfigError] represents the variant case "io". +func (self *ConfigError) IO() *string { + return cm.Case[string](self, 1) +} + +// Get represents the imported function "get". +// +// Gets a single opaque config value set at the given key if it exists +// +// get: func(key: string) -> result, config-error> +// +//go:nosplit +func Get(key string) (result cm.Result[OptionStringShape, cm.Option[string], ConfigError]) { + key0, key1 := cm.LowerString(key) + wasmimport_Get((*uint8)(key0), (uint32)(key1), &result) + return +} + +//go:wasmimport wasi:config/runtime@0.2.0-draft get +//go:noescape +func wasmimport_Get(key0 *uint8, key1 uint32, result *cm.Result[OptionStringShape, cm.Option[string], ConfigError]) + +// GetAll represents the imported function "get-all". +// +// Gets a list of all set config data +// +// get-all: func() -> result>, config-error> +// +//go:nosplit +func GetAll() (result cm.Result[ConfigErrorShape, cm.List[[2]string], ConfigError]) { + wasmimport_GetAll(&result) + return +} + +//go:wasmimport wasi:config/runtime@0.2.0-draft get-all +//go:noescape +func wasmimport_GetAll(result *cm.Result[ConfigErrorShape, cm.List[[2]string], ConfigError]) diff --git a/_examples/http-client/gen/wasi/filesystem/preopens/empty.s b/_examples/http-client/gen/wasi/filesystem/preopens/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/filesystem/preopens/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/filesystem/preopens/preopens.wit.go b/_examples/http-client/gen/wasi/filesystem/preopens/preopens.wit.go new file mode 100644 index 0000000..2192a64 --- /dev/null +++ b/_examples/http-client/gen/wasi/filesystem/preopens/preopens.wit.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package preopens represents the imported interface "wasi:filesystem/preopens@0.2.0". +package preopens + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/filesystem/types" +) + +// GetDirectories represents the imported function "get-directories". +// +// Return the set of preopened directories, and their path. +// +// get-directories: func() -> list> +// +//go:nosplit +func GetDirectories() (result cm.List[cm.Tuple[types.Descriptor, string]]) { + wasmimport_GetDirectories(&result) + return +} + +//go:wasmimport wasi:filesystem/preopens@0.2.0 get-directories +//go:noescape +func wasmimport_GetDirectories(result *cm.List[cm.Tuple[types.Descriptor, string]]) diff --git a/_examples/http-client/gen/wasi/filesystem/types/abi.go b/_examples/http-client/gen/wasi/filesystem/types/abi.go new file mode 100644 index 0000000..e417f17 --- /dev/null +++ b/_examples/http-client/gen/wasi/filesystem/types/abi.go @@ -0,0 +1,51 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package types + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + wallclock "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/clocks/wall-clock" + "unsafe" +) + +// DateTimeShape is used for storage in variant or result types. +type DateTimeShape struct { + shape [unsafe.Sizeof(wallclock.DateTime{})]byte +} + +// MetadataHashValueShape is used for storage in variant or result types. +type MetadataHashValueShape struct { + shape [unsafe.Sizeof(MetadataHashValue{})]byte +} + +// TupleListU8BoolShape is used for storage in variant or result types. +type TupleListU8BoolShape struct { + shape [unsafe.Sizeof(cm.Tuple[cm.List[uint8], bool]{})]byte +} + +func lower_DateTime(v wallclock.DateTime) (f0 uint64, f1 uint32) { + f0 = (uint64)(v.Seconds) + f1 = (uint32)(v.Nanoseconds) + return +} + +func lower_NewTimestamp(v NewTimestamp) (f0 uint32, f1 uint64, f2 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 2: // timestamp + v1, v2 := lower_DateTime(*v.Timestamp()) + f1 = (uint64)(v1) + f2 = (uint32)(v2) + } + return +} + +// DescriptorStatShape is used for storage in variant or result types. +type DescriptorStatShape struct { + shape [unsafe.Sizeof(DescriptorStat{})]byte +} + +// OptionDirectoryEntryShape is used for storage in variant or result types. +type OptionDirectoryEntryShape struct { + shape [unsafe.Sizeof(cm.Option[DirectoryEntry]{})]byte +} diff --git a/_examples/http-client/gen/wasi/filesystem/types/empty.s b/_examples/http-client/gen/wasi/filesystem/types/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/filesystem/types/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/filesystem/types/types.wit.go b/_examples/http-client/gen/wasi/filesystem/types/types.wit.go new file mode 100644 index 0000000..2c32fce --- /dev/null +++ b/_examples/http-client/gen/wasi/filesystem/types/types.wit.go @@ -0,0 +1,1357 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package types represents the imported interface "wasi:filesystem/types@0.2.0". +// +// WASI filesystem is a filesystem API primarily intended to let users run WASI +// programs that access their files on their existing filesystems, without +// significant overhead. +// +// It is intended to be roughly portable between Unix-family platforms and +// Windows, though it does not hide many of the major differences. +// +// Paths are passed as interface-type `string`s, meaning they must consist of +// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +// paths which are not accessible by this API. +// +// The directory separator in WASI is always the forward-slash (`/`). +// +// All paths in WASI are relative paths, and are interpreted relative to a +// `descriptor` referring to a base directory. If a `path` argument to any WASI +// function starts with `/`, or if any step of resolving a `path`, including +// `..` and symbolic link steps, reaches a directory outside of the base +// directory, or reaches a symlink to an absolute or rooted path in the +// underlying filesystem, the function fails with `error-code::not-permitted`. +// +// For more information about WASI path resolution and sandboxing, see +// [WASI filesystem path resolution]. +// +// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +package types + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + wallclock "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/clocks/wall-clock" + ioerror "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/error" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/streams" +) + +// FileSize represents the u64 "wasi:filesystem/types@0.2.0#filesize". +// +// File size or length of a region within a file. +// +// type filesize = u64 +type FileSize uint64 + +// DescriptorType represents the enum "wasi:filesystem/types@0.2.0#descriptor-type". +// +// The type of a filesystem object referenced by a descriptor. +// +// Note: This was called `filetype` in earlier versions of WASI. +// +// enum descriptor-type { +// unknown, +// block-device, +// character-device, +// directory, +// fifo, +// symbolic-link, +// regular-file, +// socket +// } +type DescriptorType uint8 + +const ( + // The type of the descriptor or file is unknown or is different from + // any of the other types specified. + DescriptorTypeUnknown DescriptorType = iota + + // The descriptor refers to a block device inode. + DescriptorTypeBlockDevice + + // The descriptor refers to a character device inode. + DescriptorTypeCharacterDevice + + // The descriptor refers to a directory inode. + DescriptorTypeDirectory + + // The descriptor refers to a named pipe. + DescriptorTypeFIFO + + // The file refers to a symbolic link inode. + DescriptorTypeSymbolicLink + + // The descriptor refers to a regular file inode. + DescriptorTypeRegularFile + + // The descriptor refers to a socket. + DescriptorTypeSocket +) + +var stringsDescriptorType = [8]string{ + "unknown", + "block-device", + "character-device", + "directory", + "fifo", + "symbolic-link", + "regular-file", + "socket", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e DescriptorType) String() string { + return stringsDescriptorType[e] +} + +// DescriptorFlags represents the flags "wasi:filesystem/types@0.2.0#descriptor-flags". +// +// Descriptor flags. +// +// Note: This was called `fdflags` in earlier versions of WASI. +// +// flags descriptor-flags { +// read, +// write, +// file-integrity-sync, +// data-integrity-sync, +// requested-write-sync, +// mutate-directory, +// } +type DescriptorFlags uint8 + +const ( + // Read mode: Data can be read. + DescriptorFlagsRead DescriptorFlags = 1 << iota + + // Write mode: Data can be written to. + DescriptorFlagsWrite + + // Request that writes be performed according to synchronized I/O file + // integrity completion. The data stored in the file and the file's + // metadata are synchronized. This is similar to `O_SYNC` in POSIX. + // + // The precise semantics of this operation have not yet been defined for + // WASI. At this time, it should be interpreted as a request, and not a + // requirement. + DescriptorFlagsFileIntegritySync + + // Request that writes be performed according to synchronized I/O data + // integrity completion. Only the data stored in the file is + // synchronized. This is similar to `O_DSYNC` in POSIX. + // + // The precise semantics of this operation have not yet been defined for + // WASI. At this time, it should be interpreted as a request, and not a + // requirement. + DescriptorFlagsDataIntegritySync + + // Requests that reads be performed at the same level of integrety + // requested for writes. This is similar to `O_RSYNC` in POSIX. + // + // The precise semantics of this operation have not yet been defined for + // WASI. At this time, it should be interpreted as a request, and not a + // requirement. + DescriptorFlagsRequestedWriteSync + + // Mutating directories mode: Directory contents may be mutated. + // + // When this flag is unset on a descriptor, operations using the + // descriptor which would create, rename, delete, modify the data or + // metadata of filesystem objects, or obtain another handle which + // would permit any of those, shall fail with `error-code::read-only` if + // they would otherwise succeed. + // + // This may only be set on directories. + DescriptorFlagsMutateDirectory +) + +// PathFlags represents the flags "wasi:filesystem/types@0.2.0#path-flags". +// +// Flags determining the method of how paths are resolved. +// +// flags path-flags { +// symlink-follow, +// } +type PathFlags uint8 + +const ( + // As long as the resolved path corresponds to a symbolic link, it is + // expanded. + PathFlagsSymlinkFollow PathFlags = 1 << iota +) + +// OpenFlags represents the flags "wasi:filesystem/types@0.2.0#open-flags". +// +// Open flags used by `open-at`. +// +// flags open-flags { +// create, +// directory, +// exclusive, +// truncate, +// } +type OpenFlags uint8 + +const ( + // Create file if it does not exist, similar to `O_CREAT` in POSIX. + OpenFlagsCreate OpenFlags = 1 << iota + + // Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + OpenFlagsDirectory + + // Fail if file already exists, similar to `O_EXCL` in POSIX. + OpenFlagsExclusive + + // Truncate file to size 0, similar to `O_TRUNC` in POSIX. + OpenFlagsTruncate +) + +// LinkCount represents the u64 "wasi:filesystem/types@0.2.0#link-count". +// +// Number of hard links to an inode. +// +// type link-count = u64 +type LinkCount uint64 + +// DescriptorStat represents the record "wasi:filesystem/types@0.2.0#descriptor-stat". +// +// File attributes. +// +// Note: This was called `filestat` in earlier versions of WASI. +// +// record descriptor-stat { +// %type: descriptor-type, +// link-count: link-count, +// size: filesize, +// data-access-timestamp: option, +// data-modification-timestamp: option, +// status-change-timestamp: option, +// } +type DescriptorStat struct { + // File type. + Type DescriptorType + + // Number of hard links to the file. + LinkCount LinkCount + + // 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. + DataAccessTimestamp cm.Option[wallclock.DateTime] + + // Last data modification timestamp. + // + // If the `option` is none, the platform doesn't maintain a + // modification timestamp for this file. + DataModificationTimestamp cm.Option[wallclock.DateTime] + + // Last file status-change timestamp. + // + // If the `option` is none, the platform doesn't maintain a + // status-change timestamp for this file. + StatusChangeTimestamp cm.Option[wallclock.DateTime] +} + +// NewTimestamp represents the variant "wasi:filesystem/types@0.2.0#new-timestamp". +// +// When setting a timestamp, this gives the value to set it to. +// +// variant new-timestamp { +// no-change, +// now, +// timestamp(datetime), +// } +type NewTimestamp cm.Variant[uint8, wallclock.DateTime, wallclock.DateTime] + +// NewTimestampNoChange returns a [NewTimestamp] of case "no-change". +// +// Leave the timestamp set to its previous value. +func NewTimestampNoChange() NewTimestamp { + var data struct{} + return cm.New[NewTimestamp](0, data) +} + +// NoChange returns true if [NewTimestamp] represents the variant case "no-change". +func (self *NewTimestamp) NoChange() bool { + return self.Tag() == 0 +} + +// NewTimestampNow returns a [NewTimestamp] of case "now". +// +// Set the timestamp to the current time of the system clock associated +// with the filesystem. +func NewTimestampNow() NewTimestamp { + var data struct{} + return cm.New[NewTimestamp](1, data) +} + +// Now returns true if [NewTimestamp] represents the variant case "now". +func (self *NewTimestamp) Now() bool { + return self.Tag() == 1 +} + +// NewTimestampTimestamp returns a [NewTimestamp] of case "timestamp". +// +// Set the timestamp to the given value. +func NewTimestampTimestamp(data wallclock.DateTime) NewTimestamp { + return cm.New[NewTimestamp](2, data) +} + +// Timestamp returns a non-nil *[wallclock.DateTime] if [NewTimestamp] represents the variant case "timestamp". +func (self *NewTimestamp) Timestamp() *wallclock.DateTime { + return cm.Case[wallclock.DateTime](self, 2) +} + +// DirectoryEntry represents the record "wasi:filesystem/types@0.2.0#directory-entry". +// +// A directory entry. +// +// record directory-entry { +// %type: descriptor-type, +// name: string, +// } +type DirectoryEntry struct { + // The type of the file referred to by this directory entry. + Type DescriptorType + + // The name of the object. + Name string +} + +// ErrorCode represents the enum "wasi:filesystem/types@0.2.0#error-code". +// +// Error codes returned by functions, similar to `errno` in POSIX. +// Not all of these error codes are returned by the functions provided by this +// API; some are used in higher-level library layers, and others are provided +// merely for alignment with POSIX. +// +// enum error-code { +// access, +// would-block, +// already, +// bad-descriptor, +// busy, +// deadlock, +// quota, +// exist, +// file-too-large, +// illegal-byte-sequence, +// in-progress, +// interrupted, +// invalid, +// io, +// is-directory, +// loop, +// too-many-links, +// message-size, +// name-too-long, +// no-device, +// no-entry, +// no-lock, +// insufficient-memory, +// insufficient-space, +// not-directory, +// not-empty, +// not-recoverable, +// unsupported, +// no-tty, +// no-such-device, +// overflow, +// not-permitted, +// pipe, +// read-only, +// invalid-seek, +// text-file-busy, +// cross-device +// } +type ErrorCode uint8 + +const ( + // Permission denied, similar to `EACCES` in POSIX. + ErrorCodeAccess ErrorCode = iota + + // Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` + // in POSIX. + ErrorCodeWouldBlock + + // Connection already in progress, similar to `EALREADY` in POSIX. + ErrorCodeAlready + + // Bad descriptor, similar to `EBADF` in POSIX. + ErrorCodeBadDescriptor + + // Device or resource busy, similar to `EBUSY` in POSIX. + ErrorCodeBusy + + // Resource deadlock would occur, similar to `EDEADLK` in POSIX. + ErrorCodeDeadlock + + // Storage quota exceeded, similar to `EDQUOT` in POSIX. + ErrorCodeQuota + + // File exists, similar to `EEXIST` in POSIX. + ErrorCodeExist + + // File too large, similar to `EFBIG` in POSIX. + ErrorCodeFileTooLarge + + // Illegal byte sequence, similar to `EILSEQ` in POSIX. + ErrorCodeIllegalByteSequence + + // Operation in progress, similar to `EINPROGRESS` in POSIX. + ErrorCodeInProgress + + // Interrupted function, similar to `EINTR` in POSIX. + ErrorCodeInterrupted + + // Invalid argument, similar to `EINVAL` in POSIX. + ErrorCodeInvalid + + // I/O error, similar to `EIO` in POSIX. + ErrorCodeIO + + // Is a directory, similar to `EISDIR` in POSIX. + ErrorCodeIsDirectory + + // Too many levels of symbolic links, similar to `ELOOP` in POSIX. + ErrorCodeLoop + + // Too many links, similar to `EMLINK` in POSIX. + ErrorCodeTooManyLinks + + // Message too large, similar to `EMSGSIZE` in POSIX. + ErrorCodeMessageSize + + // Filename too long, similar to `ENAMETOOLONG` in POSIX. + ErrorCodeNameTooLong + + // No such device, similar to `ENODEV` in POSIX. + ErrorCodeNoDevice + + // No such file or directory, similar to `ENOENT` in POSIX. + ErrorCodeNoEntry + + // No locks available, similar to `ENOLCK` in POSIX. + ErrorCodeNoLock + + // Not enough space, similar to `ENOMEM` in POSIX. + ErrorCodeInsufficientMemory + + // No space left on device, similar to `ENOSPC` in POSIX. + ErrorCodeInsufficientSpace + + // Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + ErrorCodeNotDirectory + + // Directory not empty, similar to `ENOTEMPTY` in POSIX. + ErrorCodeNotEmpty + + // State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + ErrorCodeNotRecoverable + + // Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + ErrorCodeUnsupported + + // Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + ErrorCodeNoTTY + + // No such device or address, similar to `ENXIO` in POSIX. + ErrorCodeNoSuchDevice + + // Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + ErrorCodeOverflow + + // Operation not permitted, similar to `EPERM` in POSIX. + ErrorCodeNotPermitted + + // Broken pipe, similar to `EPIPE` in POSIX. + ErrorCodePipe + + // Read-only file system, similar to `EROFS` in POSIX. + ErrorCodeReadOnly + + // Invalid seek, similar to `ESPIPE` in POSIX. + ErrorCodeInvalidSeek + + // Text file busy, similar to `ETXTBSY` in POSIX. + ErrorCodeTextFileBusy + + // Cross-device link, similar to `EXDEV` in POSIX. + ErrorCodeCrossDevice +) + +var stringsErrorCode = [37]string{ + "access", + "would-block", + "already", + "bad-descriptor", + "busy", + "deadlock", + "quota", + "exist", + "file-too-large", + "illegal-byte-sequence", + "in-progress", + "interrupted", + "invalid", + "io", + "is-directory", + "loop", + "too-many-links", + "message-size", + "name-too-long", + "no-device", + "no-entry", + "no-lock", + "insufficient-memory", + "insufficient-space", + "not-directory", + "not-empty", + "not-recoverable", + "unsupported", + "no-tty", + "no-such-device", + "overflow", + "not-permitted", + "pipe", + "read-only", + "invalid-seek", + "text-file-busy", + "cross-device", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e ErrorCode) String() string { + return stringsErrorCode[e] +} + +// Advice represents the enum "wasi:filesystem/types@0.2.0#advice". +// +// File or memory access pattern advisory information. +// +// enum advice { +// normal, +// sequential, +// random, +// will-need, +// dont-need, +// no-reuse +// } +type Advice uint8 + +const ( + // The application has no advice to give on its behavior with respect + // to the specified data. + AdviceNormal Advice = iota + + // The application expects to access the specified data sequentially + // from lower offsets to higher offsets. + AdviceSequential + + // The application expects to access the specified data in a random + // order. + AdviceRandom + + // The application expects to access the specified data in the near + // future. + AdviceWillNeed + + // The application expects that it will not access the specified data + // in the near future. + AdviceDontNeed + + // The application expects to access the specified data once and then + // not reuse it thereafter. + AdviceNoReuse +) + +var stringsAdvice = [6]string{ + "normal", + "sequential", + "random", + "will-need", + "dont-need", + "no-reuse", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e Advice) String() string { + return stringsAdvice[e] +} + +// MetadataHashValue represents the record "wasi:filesystem/types@0.2.0#metadata-hash-value". +// +// A 128-bit hash value, split into parts because wasm doesn't have a +// 128-bit integer type. +// +// record metadata-hash-value { +// lower: u64, +// upper: u64, +// } +type MetadataHashValue struct { + // 64 bits of a 128-bit hash value. + Lower uint64 + + // Another 64 bits of a 128-bit hash value. + Upper uint64 +} + +// Descriptor represents the imported resource "wasi:filesystem/types@0.2.0#descriptor". +// +// A descriptor is a reference to a filesystem object, which may be a file, +// directory, named pipe, special file, or other object on which filesystem +// calls may be made. +// +// resource descriptor +type Descriptor cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "descriptor". +// +// Drops a resource handle. +// +//go:nosplit +func (self Descriptor) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [resource-drop]descriptor +//go:noescape +func wasmimport_DescriptorResourceDrop(self0 uint32) + +// Advise represents the imported method "advise". +// +// Provide file advisory information on a descriptor. +// +// This is similar to `posix_fadvise` in POSIX. +// +// advise: func(offset: filesize, length: filesize, advice: advice) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) Advise(offset FileSize, length FileSize, advice Advice) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + offset0 := (uint64)(offset) + length0 := (uint64)(length) + advice0 := (uint32)(advice) + wasmimport_DescriptorAdvise((uint32)(self0), (uint64)(offset0), (uint64)(length0), (uint32)(advice0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.advise +//go:noescape +func wasmimport_DescriptorAdvise(self0 uint32, offset0 uint64, length0 uint64, advice0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// AppendViaStream represents the imported method "append-via-stream". +// +// Return a stream for appending to a file, if available. +// +// May fail with an error-code describing why the file cannot be appended. +// +// Note: This allows using `write-stream`, which is similar to `write` with +// `O_APPEND` in in POSIX. +// +// append-via-stream: func() -> result +// +//go:nosplit +func (self Descriptor) AppendViaStream() (result cm.Result[streams.OutputStream, streams.OutputStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorAppendViaStream((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.append-via-stream +//go:noescape +func wasmimport_DescriptorAppendViaStream(self0 uint32, result *cm.Result[streams.OutputStream, streams.OutputStream, ErrorCode]) + +// CreateDirectoryAt represents the imported method "create-directory-at". +// +// Create a directory. +// +// Note: This is similar to `mkdirat` in POSIX. +// +// create-directory-at: func(path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) CreateDirectoryAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorCreateDirectoryAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.create-directory-at +//go:noescape +func wasmimport_DescriptorCreateDirectoryAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// GetFlags represents the imported method "get-flags". +// +// Get flags associated with a descriptor. +// +// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. +// +// Note: This returns the value that was the `fs_flags` value returned +// from `fdstat_get` in earlier versions of WASI. +// +// get-flags: func() -> result +// +//go:nosplit +func (self Descriptor) GetFlags() (result cm.Result[DescriptorFlags, DescriptorFlags, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorGetFlags((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.get-flags +//go:noescape +func wasmimport_DescriptorGetFlags(self0 uint32, result *cm.Result[DescriptorFlags, DescriptorFlags, ErrorCode]) + +// GetType represents the imported method "get-type". +// +// Get the dynamic type of a descriptor. +// +// Note: This returns the same value as the `type` field of the `fd-stat` +// returned by `stat`, `stat-at` and similar. +// +// Note: This returns similar flags to the `st_mode & S_IFMT` value provided +// by `fstat` in POSIX. +// +// Note: This returns the value that was the `fs_filetype` value returned +// from `fdstat_get` in earlier versions of WASI. +// +// get-type: func() -> result +// +//go:nosplit +func (self Descriptor) GetType() (result cm.Result[DescriptorType, DescriptorType, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorGetType((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.get-type +//go:noescape +func wasmimport_DescriptorGetType(self0 uint32, result *cm.Result[DescriptorType, DescriptorType, ErrorCode]) + +// IsSameObject represents the imported method "is-same-object". +// +// Test whether two descriptors refer to the same filesystem object. +// +// In POSIX, this corresponds to testing whether the two descriptors have the +// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. +// wasi-filesystem does not expose device and inode numbers, so this function +// may be used instead. +// +// is-same-object: func(other: borrow) -> bool +// +//go:nosplit +func (self Descriptor) IsSameObject(other Descriptor) (result bool) { + self0 := cm.Reinterpret[uint32](self) + other0 := cm.Reinterpret[uint32](other) + result0 := wasmimport_DescriptorIsSameObject((uint32)(self0), (uint32)(other0)) + result = cm.U32ToBool((uint32)(result0)) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.is-same-object +//go:noescape +func wasmimport_DescriptorIsSameObject(self0 uint32, other0 uint32) (result0 uint32) + +// LinkAt represents the imported method "link-at". +// +// Create a hard link. +// +// Note: This is similar to `linkat` in POSIX. +// +// link-at: func(old-path-flags: path-flags, old-path: string, new-descriptor: borrow, +// new-path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) LinkAt(oldPathFlags PathFlags, oldPath string, newDescriptor Descriptor, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + oldPathFlags0 := (uint32)(oldPathFlags) + oldPath0, oldPath1 := cm.LowerString(oldPath) + newDescriptor0 := cm.Reinterpret[uint32](newDescriptor) + newPath0, newPath1 := cm.LowerString(newPath) + wasmimport_DescriptorLinkAt((uint32)(self0), (uint32)(oldPathFlags0), (*uint8)(oldPath0), (uint32)(oldPath1), (uint32)(newDescriptor0), (*uint8)(newPath0), (uint32)(newPath1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.link-at +//go:noescape +func wasmimport_DescriptorLinkAt(self0 uint32, oldPathFlags0 uint32, oldPath0 *uint8, oldPath1 uint32, newDescriptor0 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// MetadataHash represents the imported method "metadata-hash". +// +// Return a hash of the metadata associated with a filesystem object referred +// to by a descriptor. +// +// This returns a hash of the last-modification timestamp and file size, and +// may also include the inode number, device number, birth timestamp, and +// other metadata fields that may change when the file is modified or +// replaced. It may also include a secret value chosen by the +// implementation and not otherwise exposed. +// +// Implementations are encourated to provide the following properties: +// +// - If the file is not modified or replaced, the computed hash value should +// usually not change. +// - If the object is modified or replaced, the computed hash value should +// usually change. +// - The inputs to the hash should not be easily computable from the +// computed hash. +// +// However, none of these is required. +// +// metadata-hash: func() -> result +// +//go:nosplit +func (self Descriptor) MetadataHash() (result cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorMetadataHash((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.metadata-hash +//go:noescape +func wasmimport_DescriptorMetadataHash(self0 uint32, result *cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) + +// MetadataHashAt represents the imported method "metadata-hash-at". +// +// Return a hash of the metadata associated with a filesystem object referred +// to by a directory descriptor and a relative path. +// +// This performs the same hash computation as `metadata-hash`. +// +// metadata-hash-at: func(path-flags: path-flags, path: string) -> result +// +//go:nosplit +func (self Descriptor) MetadataHashAt(pathFlags PathFlags, path string) (result cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorMetadataHashAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.metadata-hash-at +//go:noescape +func wasmimport_DescriptorMetadataHashAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, result *cm.Result[MetadataHashValueShape, MetadataHashValue, ErrorCode]) + +// OpenAt represents the imported method "open-at". +// +// Open a file or directory. +// +// The returned descriptor is not guaranteed to be the lowest-numbered +// descriptor not currently open/ it is randomized to prevent applications +// from depending on making assumptions about indexes, since this is +// error-prone in multi-threaded contexts. The returned descriptor is +// guaranteed to be less than 2**31. +// +// If `flags` contains `descriptor-flags::mutate-directory`, and the base +// descriptor doesn't have `descriptor-flags::mutate-directory` set, +// `open-at` fails with `error-code::read-only`. +// +// If `flags` contains `write` or `mutate-directory`, or `open-flags` +// contains `truncate` or `create`, and the base descriptor doesn't have +// `descriptor-flags::mutate-directory` set, `open-at` fails with +// `error-code::read-only`. +// +// Note: This is similar to `openat` in POSIX. +// +// open-at: func(path-flags: path-flags, path: string, open-flags: open-flags, %flags: +// descriptor-flags) -> result +// +//go:nosplit +func (self Descriptor) OpenAt(pathFlags PathFlags, path string, openFlags OpenFlags, flags DescriptorFlags) (result cm.Result[Descriptor, Descriptor, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + openFlags0 := (uint32)(openFlags) + flags0 := (uint32)(flags) + wasmimport_DescriptorOpenAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), (uint32)(openFlags0), (uint32)(flags0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.open-at +//go:noescape +func wasmimport_DescriptorOpenAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, openFlags0 uint32, flags0 uint32, result *cm.Result[Descriptor, Descriptor, ErrorCode]) + +// Read represents the imported method "read". +// +// Read from a descriptor, without using and updating the descriptor's offset. +// +// This function returns a list of bytes containing the data that was +// read, along with a bool which, when true, indicates that the end of the +// file was reached. The returned list will contain up to `length` bytes; it +// may return fewer than requested, if the end of the file is reached or +// if the I/O operation is interrupted. +// +// In the future, this may change to return a `stream`. +// +// Note: This is similar to `pread` in POSIX. +// +// read: func(length: filesize, offset: filesize) -> result, bool>, +// error-code> +// +//go:nosplit +func (self Descriptor) Read(length FileSize, offset FileSize) (result cm.Result[TupleListU8BoolShape, cm.Tuple[cm.List[uint8], bool], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + length0 := (uint64)(length) + offset0 := (uint64)(offset) + wasmimport_DescriptorRead((uint32)(self0), (uint64)(length0), (uint64)(offset0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read +//go:noescape +func wasmimport_DescriptorRead(self0 uint32, length0 uint64, offset0 uint64, result *cm.Result[TupleListU8BoolShape, cm.Tuple[cm.List[uint8], bool], ErrorCode]) + +// ReadDirectory represents the imported method "read-directory". +// +// Read directory entries from a directory. +// +// On filesystems where directories contain entries referring to themselves +// and their parents, often named `.` and `..` respectively, these entries +// are omitted. +// +// This always returns a new stream which starts at the beginning of the +// directory. Multiple streams may be active on the same directory, and they +// do not interfere with each other. +// +// read-directory: func() -> result +// +//go:nosplit +func (self Descriptor) ReadDirectory() (result cm.Result[DirectoryEntryStream, DirectoryEntryStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorReadDirectory((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read-directory +//go:noescape +func wasmimport_DescriptorReadDirectory(self0 uint32, result *cm.Result[DirectoryEntryStream, DirectoryEntryStream, ErrorCode]) + +// ReadViaStream represents the imported method "read-via-stream". +// +// Return a stream for reading from a file, if available. +// +// May fail with an error-code describing why the file cannot be read. +// +// Multiple read, write, and append streams may be active on the same open +// file and they do not interfere with each other. +// +// Note: This allows using `read-stream`, which is similar to `read` in POSIX. +// +// read-via-stream: func(offset: filesize) -> result +// +//go:nosplit +func (self Descriptor) ReadViaStream(offset FileSize) (result cm.Result[streams.InputStream, streams.InputStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + offset0 := (uint64)(offset) + wasmimport_DescriptorReadViaStream((uint32)(self0), (uint64)(offset0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.read-via-stream +//go:noescape +func wasmimport_DescriptorReadViaStream(self0 uint32, offset0 uint64, result *cm.Result[streams.InputStream, streams.InputStream, ErrorCode]) + +// ReadLinkAt represents the imported method "readlink-at". +// +// Read the contents of a symbolic link. +// +// If the contents contain an absolute or rooted path in the underlying +// filesystem, this function fails with `error-code::not-permitted`. +// +// Note: This is similar to `readlinkat` in POSIX. +// +// readlink-at: func(path: string) -> result +// +//go:nosplit +func (self Descriptor) ReadLinkAt(path string) (result cm.Result[string, string, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorReadLinkAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.readlink-at +//go:noescape +func wasmimport_DescriptorReadLinkAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[string, string, ErrorCode]) + +// RemoveDirectoryAt represents the imported method "remove-directory-at". +// +// Remove a directory. +// +// Return `error-code::not-empty` if the directory is not empty. +// +// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. +// +// remove-directory-at: func(path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) RemoveDirectoryAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorRemoveDirectoryAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.remove-directory-at +//go:noescape +func wasmimport_DescriptorRemoveDirectoryAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// RenameAt represents the imported method "rename-at". +// +// Rename a filesystem object. +// +// Note: This is similar to `renameat` in POSIX. +// +// rename-at: func(old-path: string, new-descriptor: borrow, new-path: +// string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) RenameAt(oldPath string, newDescriptor Descriptor, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + oldPath0, oldPath1 := cm.LowerString(oldPath) + newDescriptor0 := cm.Reinterpret[uint32](newDescriptor) + newPath0, newPath1 := cm.LowerString(newPath) + wasmimport_DescriptorRenameAt((uint32)(self0), (*uint8)(oldPath0), (uint32)(oldPath1), (uint32)(newDescriptor0), (*uint8)(newPath0), (uint32)(newPath1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.rename-at +//go:noescape +func wasmimport_DescriptorRenameAt(self0 uint32, oldPath0 *uint8, oldPath1 uint32, newDescriptor0 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// SetSize represents the imported method "set-size". +// +// Adjust the size of an open file. If this increases the file's size, the +// extra bytes are filled with zeros. +// +// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. +// +// set-size: func(size: filesize) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SetSize(size FileSize) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + size0 := (uint64)(size) + wasmimport_DescriptorSetSize((uint32)(self0), (uint64)(size0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-size +//go:noescape +func wasmimport_DescriptorSetSize(self0 uint32, size0 uint64, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// SetTimes represents the imported method "set-times". +// +// Adjust the timestamps of an open file or directory. +// +// Note: This is similar to `futimens` in POSIX. +// +// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. +// +// set-times: func(data-access-timestamp: new-timestamp, data-modification-timestamp: +// new-timestamp) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SetTimes(dataAccessTimestamp NewTimestamp, dataModificationTimestamp NewTimestamp) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + dataAccessTimestamp0, dataAccessTimestamp1, dataAccessTimestamp2 := lower_NewTimestamp(dataAccessTimestamp) + dataModificationTimestamp0, dataModificationTimestamp1, dataModificationTimestamp2 := lower_NewTimestamp(dataModificationTimestamp) + wasmimport_DescriptorSetTimes((uint32)(self0), (uint32)(dataAccessTimestamp0), (uint64)(dataAccessTimestamp1), (uint32)(dataAccessTimestamp2), (uint32)(dataModificationTimestamp0), (uint64)(dataModificationTimestamp1), (uint32)(dataModificationTimestamp2), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-times +//go:noescape +func wasmimport_DescriptorSetTimes(self0 uint32, dataAccessTimestamp0 uint32, dataAccessTimestamp1 uint64, dataAccessTimestamp2 uint32, dataModificationTimestamp0 uint32, dataModificationTimestamp1 uint64, dataModificationTimestamp2 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// SetTimesAt represents the imported method "set-times-at". +// +// Adjust the timestamps of a file or directory. +// +// Note: This is similar to `utimensat` in POSIX. +// +// Note: This was called `path_filestat_set_times` in earlier versions of +// WASI. +// +// set-times-at: func(path-flags: path-flags, path: string, data-access-timestamp: +// new-timestamp, data-modification-timestamp: new-timestamp) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SetTimesAt(pathFlags PathFlags, path string, dataAccessTimestamp NewTimestamp, dataModificationTimestamp NewTimestamp) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + dataAccessTimestamp0, dataAccessTimestamp1, dataAccessTimestamp2 := lower_NewTimestamp(dataAccessTimestamp) + dataModificationTimestamp0, dataModificationTimestamp1, dataModificationTimestamp2 := lower_NewTimestamp(dataModificationTimestamp) + wasmimport_DescriptorSetTimesAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), (uint32)(dataAccessTimestamp0), (uint64)(dataAccessTimestamp1), (uint32)(dataAccessTimestamp2), (uint32)(dataModificationTimestamp0), (uint64)(dataModificationTimestamp1), (uint32)(dataModificationTimestamp2), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.set-times-at +//go:noescape +func wasmimport_DescriptorSetTimesAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, dataAccessTimestamp0 uint32, dataAccessTimestamp1 uint64, dataAccessTimestamp2 uint32, dataModificationTimestamp0 uint32, dataModificationTimestamp1 uint64, dataModificationTimestamp2 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// Stat represents the imported method "stat". +// +// Return the attributes of an open file or directory. +// +// Note: This is similar to `fstat` in POSIX, except that it does not return +// device and inode information. For testing whether two descriptors refer to +// the same underlying filesystem object, use `is-same-object`. To obtain +// additional data that can be used do determine whether a file has been +// modified, use `metadata-hash`. +// +// Note: This was called `fd_filestat_get` in earlier versions of WASI. +// +// stat: func() -> result +// +//go:nosplit +func (self Descriptor) Stat() (result cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorStat((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.stat +//go:noescape +func wasmimport_DescriptorStat(self0 uint32, result *cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) + +// StatAt represents the imported method "stat-at". +// +// Return the attributes of a file or directory. +// +// Note: This is similar to `fstatat` in POSIX, except that it does not +// return device and inode information. See the `stat` description for a +// discussion of alternatives. +// +// Note: This was called `path_filestat_get` in earlier versions of WASI. +// +// stat-at: func(path-flags: path-flags, path: string) -> result +// +//go:nosplit +func (self Descriptor) StatAt(pathFlags PathFlags, path string) (result cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + pathFlags0 := (uint32)(pathFlags) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorStatAt((uint32)(self0), (uint32)(pathFlags0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.stat-at +//go:noescape +func wasmimport_DescriptorStatAt(self0 uint32, pathFlags0 uint32, path0 *uint8, path1 uint32, result *cm.Result[DescriptorStatShape, DescriptorStat, ErrorCode]) + +// SymlinkAt represents the imported method "symlink-at". +// +// Create a symbolic link (also known as a "symlink"). +// +// If `old-path` starts with `/`, the function fails with +// `error-code::not-permitted`. +// +// Note: This is similar to `symlinkat` in POSIX. +// +// symlink-at: func(old-path: string, new-path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SymlinkAt(oldPath string, newPath string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + oldPath0, oldPath1 := cm.LowerString(oldPath) + newPath0, newPath1 := cm.LowerString(newPath) + wasmimport_DescriptorSymlinkAt((uint32)(self0), (*uint8)(oldPath0), (uint32)(oldPath1), (*uint8)(newPath0), (uint32)(newPath1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.symlink-at +//go:noescape +func wasmimport_DescriptorSymlinkAt(self0 uint32, oldPath0 *uint8, oldPath1 uint32, newPath0 *uint8, newPath1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// Sync represents the imported method "sync". +// +// Synchronize the data and metadata of a file to disk. +// +// This function succeeds with no effect if the file descriptor is not +// opened for writing. +// +// Note: This is similar to `fsync` in POSIX. +// +// sync: func() -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) Sync() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorSync((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.sync +//go:noescape +func wasmimport_DescriptorSync(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// SyncData represents the imported method "sync-data". +// +// Synchronize the data of a file to disk. +// +// This function succeeds with no effect if the file descriptor is not +// opened for writing. +// +// Note: This is similar to `fdatasync` in POSIX. +// +// sync-data: func() -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) SyncData() (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DescriptorSyncData((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.sync-data +//go:noescape +func wasmimport_DescriptorSyncData(self0 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// UnlinkFileAt represents the imported method "unlink-file-at". +// +// Unlink a filesystem object that is not a directory. +// +// Return `error-code::is-directory` if the path refers to a directory. +// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. +// +// unlink-file-at: func(path: string) -> result<_, error-code> +// +//go:nosplit +func (self Descriptor) UnlinkFileAt(path string) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + path0, path1 := cm.LowerString(path) + wasmimport_DescriptorUnlinkFileAt((uint32)(self0), (*uint8)(path0), (uint32)(path1), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.unlink-file-at +//go:noescape +func wasmimport_DescriptorUnlinkFileAt(self0 uint32, path0 *uint8, path1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// Write represents the imported method "write". +// +// Write to a descriptor, without using and updating the descriptor's offset. +// +// It is valid to write past the end of a file; the file is extended to the +// extent of the write, with bytes between the previous end and the start of +// the write set to zero. +// +// In the future, this may change to take a `stream`. +// +// Note: This is similar to `pwrite` in POSIX. +// +// write: func(buffer: list, offset: filesize) -> result +// +//go:nosplit +func (self Descriptor) Write(buffer cm.List[uint8], offset FileSize) (result cm.Result[uint64, FileSize, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + buffer0, buffer1 := cm.LowerList(buffer) + offset0 := (uint64)(offset) + wasmimport_DescriptorWrite((uint32)(self0), (*uint8)(buffer0), (uint32)(buffer1), (uint64)(offset0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.write +//go:noescape +func wasmimport_DescriptorWrite(self0 uint32, buffer0 *uint8, buffer1 uint32, offset0 uint64, result *cm.Result[uint64, FileSize, ErrorCode]) + +// WriteViaStream represents the imported method "write-via-stream". +// +// Return a stream for writing to a file, if available. +// +// May fail with an error-code describing why the file cannot be written. +// +// Note: This allows using `write-stream`, which is similar to `write` in +// POSIX. +// +// write-via-stream: func(offset: filesize) -> result +// +//go:nosplit +func (self Descriptor) WriteViaStream(offset FileSize) (result cm.Result[streams.OutputStream, streams.OutputStream, ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + offset0 := (uint64)(offset) + wasmimport_DescriptorWriteViaStream((uint32)(self0), (uint64)(offset0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]descriptor.write-via-stream +//go:noescape +func wasmimport_DescriptorWriteViaStream(self0 uint32, offset0 uint64, result *cm.Result[streams.OutputStream, streams.OutputStream, ErrorCode]) + +// DirectoryEntryStream represents the imported resource "wasi:filesystem/types@0.2.0#directory-entry-stream". +// +// A stream of directory entries. +// +// resource directory-entry-stream +type DirectoryEntryStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "directory-entry-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self DirectoryEntryStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DirectoryEntryStreamResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [resource-drop]directory-entry-stream +//go:noescape +func wasmimport_DirectoryEntryStreamResourceDrop(self0 uint32) + +// ReadDirectoryEntry represents the imported method "read-directory-entry". +// +// Read a single directory entry from a `directory-entry-stream`. +// +// read-directory-entry: func() -> result, error-code> +// +//go:nosplit +func (self DirectoryEntryStream) ReadDirectoryEntry() (result cm.Result[OptionDirectoryEntryShape, cm.Option[DirectoryEntry], ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_DirectoryEntryStreamReadDirectoryEntry((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 [method]directory-entry-stream.read-directory-entry +//go:noescape +func wasmimport_DirectoryEntryStreamReadDirectoryEntry(self0 uint32, result *cm.Result[OptionDirectoryEntryShape, cm.Option[DirectoryEntry], ErrorCode]) + +// FilesystemErrorCode represents the imported function "filesystem-error-code". +// +// Attempts to extract a filesystem-related `error-code` from the stream +// `error` provided. +// +// Stream operations which return `stream-error::last-operation-failed` +// have a payload with more information about the operation that failed. +// This payload can be passed through to this function to see if there's +// filesystem-related information about the error to return. +// +// Note that this function is fallible because not all stream-related +// errors are filesystem-related errors. +// +// filesystem-error-code: func(err: borrow) -> option +// +//go:nosplit +func FilesystemErrorCode(err ioerror.Error) (result cm.Option[ErrorCode]) { + err0 := cm.Reinterpret[uint32](err) + wasmimport_FilesystemErrorCode((uint32)(err0), &result) + return +} + +//go:wasmimport wasi:filesystem/types@0.2.0 filesystem-error-code +//go:noescape +func wasmimport_FilesystemErrorCode(err0 uint32, result *cm.Option[ErrorCode]) diff --git a/_examples/http-client/gen/wasi/http/incoming-handler/empty.s b/_examples/http-client/gen/wasi/http/incoming-handler/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/http/incoming-handler/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/http/incoming-handler/incoming-handler.exports.go b/_examples/http-client/gen/wasi/http/incoming-handler/incoming-handler.exports.go new file mode 100644 index 0000000..92aaafe --- /dev/null +++ b/_examples/http-client/gen/wasi/http/incoming-handler/incoming-handler.exports.go @@ -0,0 +1,26 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package incominghandler + +import ( + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/http/types" +) + +// Exports represents the caller-defined exports from "wasi:http/incoming-handler@0.2.0". +var Exports struct { + // Handle represents the caller-defined, exported function "handle". + // + // This function is invoked with an incoming HTTP Request, and a resource + // `response-outparam` which provides the capability to reply with an HTTP + // Response. The response is sent by calling the `response-outparam.set` + // method, which allows execution to continue after the response has been + // sent. This enables both streaming to the response body, and performing other + // work. + // + // The implementor of this function must write a response to the + // `response-outparam` before returning, or else the caller will respond + // with an error on its behalf. + // + // handle: func(request: incoming-request, response-out: response-outparam) + Handle func(request types.IncomingRequest, responseOut types.ResponseOutparam) +} diff --git a/_examples/http-client/gen/wasi/http/incoming-handler/incoming-handler.wit.go b/_examples/http-client/gen/wasi/http/incoming-handler/incoming-handler.wit.go new file mode 100644 index 0000000..6ac3402 --- /dev/null +++ b/_examples/http-client/gen/wasi/http/incoming-handler/incoming-handler.wit.go @@ -0,0 +1,21 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package incominghandler represents the exported interface "wasi:http/incoming-handler@0.2.0". +// +// This interface defines a handler of incoming HTTP Requests. It should +// be exported by components which can respond to HTTP Requests. +package incominghandler + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/http/types" +) + +//go:wasmexport wasi:http/incoming-handler@0.2.0#handle +//export wasi:http/incoming-handler@0.2.0#handle +func wasmexport_Handle(request0 uint32, responseOut0 uint32) { + request := cm.Reinterpret[types.IncomingRequest]((uint32)(request0)) + responseOut := cm.Reinterpret[types.ResponseOutparam]((uint32)(responseOut0)) + Exports.Handle(request, responseOut) + return +} diff --git a/_examples/http-client/gen/wasi/http/outgoing-handler/abi.go b/_examples/http-client/gen/wasi/http/outgoing-handler/abi.go new file mode 100644 index 0000000..ac99f50 --- /dev/null +++ b/_examples/http-client/gen/wasi/http/outgoing-handler/abi.go @@ -0,0 +1,24 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package outgoinghandler + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/http/types" + "unsafe" +) + +// ErrorCodeShape is used for storage in variant or result types. +type ErrorCodeShape struct { + shape [unsafe.Sizeof(types.ErrorCode{})]byte +} + +func lower_OptionRequestOptions(v cm.Option[types.RequestOptions]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := cm.Reinterpret[uint32](*some) + f1 = (uint32)(v1) + } + return +} diff --git a/_examples/http-client/gen/wasi/http/outgoing-handler/empty.s b/_examples/http-client/gen/wasi/http/outgoing-handler/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/http/outgoing-handler/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/http/outgoing-handler/outgoing-handler.wit.go b/_examples/http-client/gen/wasi/http/outgoing-handler/outgoing-handler.wit.go new file mode 100644 index 0000000..ac63f0b --- /dev/null +++ b/_examples/http-client/gen/wasi/http/outgoing-handler/outgoing-handler.wit.go @@ -0,0 +1,40 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package outgoinghandler represents the imported interface "wasi:http/outgoing-handler@0.2.0". +// +// This interface defines a handler of outgoing HTTP Requests. It should be +// imported by components which wish to make HTTP Requests. +package outgoinghandler + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/http/types" +) + +// Handle represents the imported function "handle". +// +// This function is invoked with an outgoing HTTP Request, and it returns +// a resource `future-incoming-response` which represents an HTTP Response +// which may arrive in the future. +// +// The `options` argument accepts optional parameters for the HTTP +// protocol's transport layer. +// +// This function may return an error if the `outgoing-request` is invalid +// or not allowed to be made. Otherwise, protocol errors are reported +// through the `future-incoming-response`. +// +// handle: func(request: outgoing-request, options: option) -> result +// +//go:nosplit +func Handle(request types.OutgoingRequest, options cm.Option[types.RequestOptions]) (result cm.Result[ErrorCodeShape, types.FutureIncomingResponse, types.ErrorCode]) { + request0 := cm.Reinterpret[uint32](request) + options0, options1 := lower_OptionRequestOptions(options) + wasmimport_Handle((uint32)(request0), (uint32)(options0), (uint32)(options1), &result) + return +} + +//go:wasmimport wasi:http/outgoing-handler@0.2.0 handle +//go:noescape +func wasmimport_Handle(request0 uint32, options0 uint32, options1 uint32, result *cm.Result[ErrorCodeShape, types.FutureIncomingResponse, types.ErrorCode]) diff --git a/_examples/http-client/gen/wasi/http/types/abi.go b/_examples/http-client/gen/wasi/http/types/abi.go new file mode 100644 index 0000000..d5bf374 --- /dev/null +++ b/_examples/http-client/gen/wasi/http/types/abi.go @@ -0,0 +1,273 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package types + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + monotonicclock "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/clocks/monotonic-clock" + "unsafe" +) + +// OptionFieldSizePayloadShape is used for storage in variant or result types. +type OptionFieldSizePayloadShape struct { + shape [unsafe.Sizeof(cm.Option[FieldSizePayload]{})]byte +} + +func lower_OptionString(v cm.Option[string]) (f0 uint32, f1 *uint8, f2 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2 := cm.LowerString(*some) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_Method(v Method) (f0 uint32, f1 *uint8, f2 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 9: // other + v1, v2 := cm.LowerString(*v.Other()) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_Scheme(v Scheme) (f0 uint32, f1 *uint8, f2 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 2: // other + v1, v2 := cm.LowerString(*v.Other()) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_OptionScheme(v cm.Option[Scheme]) (f0 uint32, f1 uint32, f2 *uint8, f3 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2, v3 := lower_Scheme(*some) + f1 = (uint32)(v1) + f2 = (*uint8)(v2) + f3 = (uint32)(v3) + } + return +} + +func lower_OptionDuration(v cm.Option[monotonicclock.Duration]) (f0 uint32, f1 uint64) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint64)(*some) + f1 = (uint64)(v1) + } + return +} + +// ErrorCodeShape is used for storage in variant or result types. +type ErrorCodeShape struct { + shape [unsafe.Sizeof(ErrorCode{})]byte +} + +func lower_OptionU16(v cm.Option[uint16]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint32)(*some) + f1 = (uint32)(v1) + } + return +} + +func lower_DNSErrorPayload(v DNSErrorPayload) (f0 uint32, f1 *uint8, f2 uint32, f3 uint32, f4 uint32) { + f0, f1, f2 = lower_OptionString(v.Rcode) + f3, f4 = lower_OptionU16(v.InfoCode) + return +} + +func lower_OptionU8(v cm.Option[uint8]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint32)(*some) + f1 = (uint32)(v1) + } + return +} + +func lower_TLSAlertReceivedPayload(v TLSAlertReceivedPayload) (f0 uint32, f1 uint32, f2 uint32, f3 *uint8, f4 uint32) { + f0, f1 = lower_OptionU8(v.AlertID) + f2, f3, f4 = lower_OptionString(v.AlertMessage) + return +} + +func lower_OptionU64(v cm.Option[uint64]) (f0 uint32, f1 uint64) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint64)(*some) + f1 = (uint64)(v1) + } + return +} + +func lower_OptionU32(v cm.Option[uint32]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := (uint32)(*some) + f1 = (uint32)(v1) + } + return +} + +func lower_FieldSizePayload(v FieldSizePayload) (f0 uint32, f1 *uint8, f2 uint32, f3 uint32, f4 uint32) { + f0, f1, f2 = lower_OptionString(v.FieldName) + f3, f4 = lower_OptionU32(v.FieldSize) + return +} + +func lower_OptionFieldSizePayload(v cm.Option[FieldSizePayload]) (f0 uint32, f1 uint32, f2 *uint8, f3 uint32, f4 uint32, f5 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*some) + f1 = (uint32)(v1) + f2 = (*uint8)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + } + return +} + +func lower_ErrorCode(v ErrorCode) (f0 uint32, f1 uint32, f2 uint64, f3 uint32, f4 uint32, f5 uint32, f6 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 1: // DNS-error + v1, v2, v3, v4, v5 := lower_DNSErrorPayload(*v.DNSError()) + f1 = (uint32)(v1) + f2 = cm.PointerToU64(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 14: // TLS-alert-received + v1, v2, v3, v4, v5 := lower_TLSAlertReceivedPayload(*v.TLSAlertReceived()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + f3 = (uint32)(v3) + f4 = cm.PointerToU32(v4) + f5 = (uint32)(v5) + case 17: // HTTP-request-body-size + v1, v2 := lower_OptionU64(*v.HTTPRequestBodySize()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 21: // HTTP-request-header-section-size + v1, v2 := lower_OptionU32(*v.HTTPRequestHeaderSectionSize()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 22: // HTTP-request-header-size + v1, v2, v3, v4, v5, v6 := lower_OptionFieldSizePayload(*v.HTTPRequestHeaderSize()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + f3 = cm.PointerToU32(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + case 23: // HTTP-request-trailer-section-size + v1, v2 := lower_OptionU32(*v.HTTPRequestTrailerSectionSize()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 24: // HTTP-request-trailer-size + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*v.HTTPRequestTrailerSize()) + f1 = (uint32)(v1) + f2 = cm.PointerToU64(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 26: // HTTP-response-header-section-size + v1, v2 := lower_OptionU32(*v.HTTPResponseHeaderSectionSize()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 27: // HTTP-response-header-size + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*v.HTTPResponseHeaderSize()) + f1 = (uint32)(v1) + f2 = cm.PointerToU64(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 28: // HTTP-response-body-size + v1, v2 := lower_OptionU64(*v.HTTPResponseBodySize()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 29: // HTTP-response-trailer-section-size + v1, v2 := lower_OptionU32(*v.HTTPResponseTrailerSectionSize()) + f1 = (uint32)(v1) + f2 = (uint64)(v2) + case 30: // HTTP-response-trailer-size + v1, v2, v3, v4, v5 := lower_FieldSizePayload(*v.HTTPResponseTrailerSize()) + f1 = (uint32)(v1) + f2 = cm.PointerToU64(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 31: // HTTP-response-transfer-coding + v1, v2, v3 := lower_OptionString(*v.HTTPResponseTransferCoding()) + f1 = (uint32)(v1) + f2 = cm.PointerToU64(v2) + f3 = (uint32)(v3) + case 32: // HTTP-response-content-coding + v1, v2, v3 := lower_OptionString(*v.HTTPResponseContentCoding()) + f1 = (uint32)(v1) + f2 = cm.PointerToU64(v2) + f3 = (uint32)(v3) + case 38: // internal-error + v1, v2, v3 := lower_OptionString(*v.InternalError()) + f1 = (uint32)(v1) + f2 = cm.PointerToU64(v2) + f3 = (uint32)(v3) + } + return +} + +func lower_ResultOutgoingResponseErrorCode(v cm.Result[ErrorCodeShape, OutgoingResponse, ErrorCode]) (f0 uint32, f1 uint32, f2 uint32, f3 uint64, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { + if v.IsOK() { + v1 := cm.Reinterpret[uint32](*v.OK()) + f1 = (uint32)(v1) + } else { + f0 = 1 + v1, v2, v3, v4, v5, v6, v7 := lower_ErrorCode(*v.Err()) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint64)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + } + return +} + +// ResultOptionTrailersErrorCodeShape is used for storage in variant or result types. +type ResultOptionTrailersErrorCodeShape struct { + shape [unsafe.Sizeof(cm.Result[ErrorCodeShape, cm.Option[Fields], ErrorCode]{})]byte +} + +func lower_OptionTrailers(v cm.Option[Fields]) (f0 uint32, f1 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1 := cm.Reinterpret[uint32](*some) + f1 = (uint32)(v1) + } + return +} + +// ResultIncomingResponseErrorCodeShape is used for storage in variant or result types. +type ResultIncomingResponseErrorCodeShape struct { + shape [unsafe.Sizeof(cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode]{})]byte +} diff --git a/_examples/http-client/gen/wasi/http/types/empty.s b/_examples/http-client/gen/wasi/http/types/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/http/types/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/http/types/types.wit.go b/_examples/http-client/gen/wasi/http/types/types.wit.go new file mode 100644 index 0000000..f4a092b --- /dev/null +++ b/_examples/http-client/gen/wasi/http/types/types.wit.go @@ -0,0 +1,2141 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package types represents the imported interface "wasi:http/types@0.2.0". +// +// This interface defines all of the types and methods for implementing +// HTTP Requests and Responses, both incoming and outgoing, as well as +// their headers, trailers, and bodies. +package types + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + monotonicclock "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/clocks/monotonic-clock" + ioerror "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/error" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/poll" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/streams" +) + +// Method represents the variant "wasi:http/types@0.2.0#method". +// +// This type corresponds to HTTP standard Methods. +// +// variant method { +// get, +// head, +// post, +// put, +// delete, +// connect, +// options, +// trace, +// patch, +// other(string), +// } +type Method cm.Variant[uint8, string, string] + +// MethodGet returns a [Method] of case "get". +func MethodGet() Method { + var data struct{} + return cm.New[Method](0, data) +} + +// Get returns true if [Method] represents the variant case "get". +func (self *Method) Get() bool { + return self.Tag() == 0 +} + +// MethodHead returns a [Method] of case "head". +func MethodHead() Method { + var data struct{} + return cm.New[Method](1, data) +} + +// Head returns true if [Method] represents the variant case "head". +func (self *Method) Head() bool { + return self.Tag() == 1 +} + +// MethodPost returns a [Method] of case "post". +func MethodPost() Method { + var data struct{} + return cm.New[Method](2, data) +} + +// Post returns true if [Method] represents the variant case "post". +func (self *Method) Post() bool { + return self.Tag() == 2 +} + +// MethodPut returns a [Method] of case "put". +func MethodPut() Method { + var data struct{} + return cm.New[Method](3, data) +} + +// Put returns true if [Method] represents the variant case "put". +func (self *Method) Put() bool { + return self.Tag() == 3 +} + +// MethodDelete returns a [Method] of case "delete". +func MethodDelete() Method { + var data struct{} + return cm.New[Method](4, data) +} + +// Delete returns true if [Method] represents the variant case "delete". +func (self *Method) Delete() bool { + return self.Tag() == 4 +} + +// MethodConnect returns a [Method] of case "connect". +func MethodConnect() Method { + var data struct{} + return cm.New[Method](5, data) +} + +// Connect returns true if [Method] represents the variant case "connect". +func (self *Method) Connect() bool { + return self.Tag() == 5 +} + +// MethodOptions returns a [Method] of case "options". +func MethodOptions() Method { + var data struct{} + return cm.New[Method](6, data) +} + +// Options returns true if [Method] represents the variant case "options". +func (self *Method) Options() bool { + return self.Tag() == 6 +} + +// MethodTrace returns a [Method] of case "trace". +func MethodTrace() Method { + var data struct{} + return cm.New[Method](7, data) +} + +// Trace returns true if [Method] represents the variant case "trace". +func (self *Method) Trace() bool { + return self.Tag() == 7 +} + +// MethodPatch returns a [Method] of case "patch". +func MethodPatch() Method { + var data struct{} + return cm.New[Method](8, data) +} + +// Patch returns true if [Method] represents the variant case "patch". +func (self *Method) Patch() bool { + return self.Tag() == 8 +} + +// MethodOther returns a [Method] of case "other". +func MethodOther(data string) Method { + return cm.New[Method](9, data) +} + +// Other returns a non-nil *[string] if [Method] represents the variant case "other". +func (self *Method) Other() *string { + return cm.Case[string](self, 9) +} + +// Scheme represents the variant "wasi:http/types@0.2.0#scheme". +// +// This type corresponds to HTTP standard Related Schemes. +// +// variant scheme { +// HTTP, +// HTTPS, +// other(string), +// } +type Scheme cm.Variant[uint8, string, string] + +// SchemeHTTP returns a [Scheme] of case "HTTP". +func SchemeHTTP() Scheme { + var data struct{} + return cm.New[Scheme](0, data) +} + +// HTTP returns true if [Scheme] represents the variant case "HTTP". +func (self *Scheme) HTTP() bool { + return self.Tag() == 0 +} + +// SchemeHTTPS returns a [Scheme] of case "HTTPS". +func SchemeHTTPS() Scheme { + var data struct{} + return cm.New[Scheme](1, data) +} + +// HTTPS returns true if [Scheme] represents the variant case "HTTPS". +func (self *Scheme) HTTPS() bool { + return self.Tag() == 1 +} + +// SchemeOther returns a [Scheme] of case "other". +func SchemeOther(data string) Scheme { + return cm.New[Scheme](2, data) +} + +// Other returns a non-nil *[string] if [Scheme] represents the variant case "other". +func (self *Scheme) Other() *string { + return cm.Case[string](self, 2) +} + +// DNSErrorPayload represents the record "wasi:http/types@0.2.0#DNS-error-payload". +// +// Defines the case payload type for `DNS-error` above: +// +// record DNS-error-payload { +// rcode: option, +// info-code: option, +// } +type DNSErrorPayload struct { + Rcode cm.Option[string] + InfoCode cm.Option[uint16] +} + +// TLSAlertReceivedPayload represents the record "wasi:http/types@0.2.0#TLS-alert-received-payload". +// +// Defines the case payload type for `TLS-alert-received` above: +// +// record TLS-alert-received-payload { +// alert-id: option, +// alert-message: option, +// } +type TLSAlertReceivedPayload struct { + AlertID cm.Option[uint8] + AlertMessage cm.Option[string] +} + +// FieldSizePayload represents the record "wasi:http/types@0.2.0#field-size-payload". +// +// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: +// +// record field-size-payload { +// field-name: option, +// field-size: option, +// } +type FieldSizePayload struct { + FieldName cm.Option[string] + FieldSize cm.Option[uint32] +} + +// ErrorCode represents the variant "wasi:http/types@0.2.0#error-code". +// +// These cases are inspired by the IANA HTTP Proxy Error Types: +// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types +// +// variant error-code { +// DNS-timeout, +// DNS-error(DNS-error-payload), +// destination-not-found, +// destination-unavailable, +// destination-IP-prohibited, +// destination-IP-unroutable, +// connection-refused, +// connection-terminated, +// connection-timeout, +// connection-read-timeout, +// connection-write-timeout, +// connection-limit-reached, +// TLS-protocol-error, +// TLS-certificate-error, +// TLS-alert-received(TLS-alert-received-payload), +// HTTP-request-denied, +// HTTP-request-length-required, +// HTTP-request-body-size(option), +// HTTP-request-method-invalid, +// HTTP-request-URI-invalid, +// HTTP-request-URI-too-long, +// HTTP-request-header-section-size(option), +// HTTP-request-header-size(option), +// HTTP-request-trailer-section-size(option), +// HTTP-request-trailer-size(field-size-payload), +// HTTP-response-incomplete, +// HTTP-response-header-section-size(option), +// HTTP-response-header-size(field-size-payload), +// HTTP-response-body-size(option), +// HTTP-response-trailer-section-size(option), +// HTTP-response-trailer-size(field-size-payload), +// HTTP-response-transfer-coding(option), +// HTTP-response-content-coding(option), +// HTTP-response-timeout, +// HTTP-upgrade-failed, +// HTTP-protocol-error, +// loop-detected, +// configuration-error, +// internal-error(option), +// } +type ErrorCode cm.Variant[uint8, OptionFieldSizePayloadShape, cm.Option[uint64]] + +// ErrorCodeDNSTimeout returns a [ErrorCode] of case "DNS-timeout". +func ErrorCodeDNSTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](0, data) +} + +// DNSTimeout returns true if [ErrorCode] represents the variant case "DNS-timeout". +func (self *ErrorCode) DNSTimeout() bool { + return self.Tag() == 0 +} + +// ErrorCodeDNSError returns a [ErrorCode] of case "DNS-error". +func ErrorCodeDNSError(data DNSErrorPayload) ErrorCode { + return cm.New[ErrorCode](1, data) +} + +// DNSError returns a non-nil *[DNSErrorPayload] if [ErrorCode] represents the variant case "DNS-error". +func (self *ErrorCode) DNSError() *DNSErrorPayload { + return cm.Case[DNSErrorPayload](self, 1) +} + +// ErrorCodeDestinationNotFound returns a [ErrorCode] of case "destination-not-found". +func ErrorCodeDestinationNotFound() ErrorCode { + var data struct{} + return cm.New[ErrorCode](2, data) +} + +// DestinationNotFound returns true if [ErrorCode] represents the variant case "destination-not-found". +func (self *ErrorCode) DestinationNotFound() bool { + return self.Tag() == 2 +} + +// ErrorCodeDestinationUnavailable returns a [ErrorCode] of case "destination-unavailable". +func ErrorCodeDestinationUnavailable() ErrorCode { + var data struct{} + return cm.New[ErrorCode](3, data) +} + +// DestinationUnavailable returns true if [ErrorCode] represents the variant case "destination-unavailable". +func (self *ErrorCode) DestinationUnavailable() bool { + return self.Tag() == 3 +} + +// ErrorCodeDestinationIPProhibited returns a [ErrorCode] of case "destination-IP-prohibited". +func ErrorCodeDestinationIPProhibited() ErrorCode { + var data struct{} + return cm.New[ErrorCode](4, data) +} + +// DestinationIPProhibited returns true if [ErrorCode] represents the variant case "destination-IP-prohibited". +func (self *ErrorCode) DestinationIPProhibited() bool { + return self.Tag() == 4 +} + +// ErrorCodeDestinationIPUnroutable returns a [ErrorCode] of case "destination-IP-unroutable". +func ErrorCodeDestinationIPUnroutable() ErrorCode { + var data struct{} + return cm.New[ErrorCode](5, data) +} + +// DestinationIPUnroutable returns true if [ErrorCode] represents the variant case "destination-IP-unroutable". +func (self *ErrorCode) DestinationIPUnroutable() bool { + return self.Tag() == 5 +} + +// ErrorCodeConnectionRefused returns a [ErrorCode] of case "connection-refused". +func ErrorCodeConnectionRefused() ErrorCode { + var data struct{} + return cm.New[ErrorCode](6, data) +} + +// ConnectionRefused returns true if [ErrorCode] represents the variant case "connection-refused". +func (self *ErrorCode) ConnectionRefused() bool { + return self.Tag() == 6 +} + +// ErrorCodeConnectionTerminated returns a [ErrorCode] of case "connection-terminated". +func ErrorCodeConnectionTerminated() ErrorCode { + var data struct{} + return cm.New[ErrorCode](7, data) +} + +// ConnectionTerminated returns true if [ErrorCode] represents the variant case "connection-terminated". +func (self *ErrorCode) ConnectionTerminated() bool { + return self.Tag() == 7 +} + +// ErrorCodeConnectionTimeout returns a [ErrorCode] of case "connection-timeout". +func ErrorCodeConnectionTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](8, data) +} + +// ConnectionTimeout returns true if [ErrorCode] represents the variant case "connection-timeout". +func (self *ErrorCode) ConnectionTimeout() bool { + return self.Tag() == 8 +} + +// ErrorCodeConnectionReadTimeout returns a [ErrorCode] of case "connection-read-timeout". +func ErrorCodeConnectionReadTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](9, data) +} + +// ConnectionReadTimeout returns true if [ErrorCode] represents the variant case "connection-read-timeout". +func (self *ErrorCode) ConnectionReadTimeout() bool { + return self.Tag() == 9 +} + +// ErrorCodeConnectionWriteTimeout returns a [ErrorCode] of case "connection-write-timeout". +func ErrorCodeConnectionWriteTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](10, data) +} + +// ConnectionWriteTimeout returns true if [ErrorCode] represents the variant case "connection-write-timeout". +func (self *ErrorCode) ConnectionWriteTimeout() bool { + return self.Tag() == 10 +} + +// ErrorCodeConnectionLimitReached returns a [ErrorCode] of case "connection-limit-reached". +func ErrorCodeConnectionLimitReached() ErrorCode { + var data struct{} + return cm.New[ErrorCode](11, data) +} + +// ConnectionLimitReached returns true if [ErrorCode] represents the variant case "connection-limit-reached". +func (self *ErrorCode) ConnectionLimitReached() bool { + return self.Tag() == 11 +} + +// ErrorCodeTLSProtocolError returns a [ErrorCode] of case "TLS-protocol-error". +func ErrorCodeTLSProtocolError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](12, data) +} + +// TLSProtocolError returns true if [ErrorCode] represents the variant case "TLS-protocol-error". +func (self *ErrorCode) TLSProtocolError() bool { + return self.Tag() == 12 +} + +// ErrorCodeTLSCertificateError returns a [ErrorCode] of case "TLS-certificate-error". +func ErrorCodeTLSCertificateError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](13, data) +} + +// TLSCertificateError returns true if [ErrorCode] represents the variant case "TLS-certificate-error". +func (self *ErrorCode) TLSCertificateError() bool { + return self.Tag() == 13 +} + +// ErrorCodeTLSAlertReceived returns a [ErrorCode] of case "TLS-alert-received". +func ErrorCodeTLSAlertReceived(data TLSAlertReceivedPayload) ErrorCode { + return cm.New[ErrorCode](14, data) +} + +// TLSAlertReceived returns a non-nil *[TLSAlertReceivedPayload] if [ErrorCode] represents the variant case "TLS-alert-received". +func (self *ErrorCode) TLSAlertReceived() *TLSAlertReceivedPayload { + return cm.Case[TLSAlertReceivedPayload](self, 14) +} + +// ErrorCodeHTTPRequestDenied returns a [ErrorCode] of case "HTTP-request-denied". +func ErrorCodeHTTPRequestDenied() ErrorCode { + var data struct{} + return cm.New[ErrorCode](15, data) +} + +// HTTPRequestDenied returns true if [ErrorCode] represents the variant case "HTTP-request-denied". +func (self *ErrorCode) HTTPRequestDenied() bool { + return self.Tag() == 15 +} + +// ErrorCodeHTTPRequestLengthRequired returns a [ErrorCode] of case "HTTP-request-length-required". +func ErrorCodeHTTPRequestLengthRequired() ErrorCode { + var data struct{} + return cm.New[ErrorCode](16, data) +} + +// HTTPRequestLengthRequired returns true if [ErrorCode] represents the variant case "HTTP-request-length-required". +func (self *ErrorCode) HTTPRequestLengthRequired() bool { + return self.Tag() == 16 +} + +// ErrorCodeHTTPRequestBodySize returns a [ErrorCode] of case "HTTP-request-body-size". +func ErrorCodeHTTPRequestBodySize(data cm.Option[uint64]) ErrorCode { + return cm.New[ErrorCode](17, data) +} + +// HTTPRequestBodySize returns a non-nil *[cm.Option[uint64]] if [ErrorCode] represents the variant case "HTTP-request-body-size". +func (self *ErrorCode) HTTPRequestBodySize() *cm.Option[uint64] { + return cm.Case[cm.Option[uint64]](self, 17) +} + +// ErrorCodeHTTPRequestMethodInvalid returns a [ErrorCode] of case "HTTP-request-method-invalid". +func ErrorCodeHTTPRequestMethodInvalid() ErrorCode { + var data struct{} + return cm.New[ErrorCode](18, data) +} + +// HTTPRequestMethodInvalid returns true if [ErrorCode] represents the variant case "HTTP-request-method-invalid". +func (self *ErrorCode) HTTPRequestMethodInvalid() bool { + return self.Tag() == 18 +} + +// ErrorCodeHTTPRequestURIInvalid returns a [ErrorCode] of case "HTTP-request-URI-invalid". +func ErrorCodeHTTPRequestURIInvalid() ErrorCode { + var data struct{} + return cm.New[ErrorCode](19, data) +} + +// HTTPRequestURIInvalid returns true if [ErrorCode] represents the variant case "HTTP-request-URI-invalid". +func (self *ErrorCode) HTTPRequestURIInvalid() bool { + return self.Tag() == 19 +} + +// ErrorCodeHTTPRequestURITooLong returns a [ErrorCode] of case "HTTP-request-URI-too-long". +func ErrorCodeHTTPRequestURITooLong() ErrorCode { + var data struct{} + return cm.New[ErrorCode](20, data) +} + +// HTTPRequestURITooLong returns true if [ErrorCode] represents the variant case "HTTP-request-URI-too-long". +func (self *ErrorCode) HTTPRequestURITooLong() bool { + return self.Tag() == 20 +} + +// ErrorCodeHTTPRequestHeaderSectionSize returns a [ErrorCode] of case "HTTP-request-header-section-size". +func ErrorCodeHTTPRequestHeaderSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](21, data) +} + +// HTTPRequestHeaderSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-request-header-section-size". +func (self *ErrorCode) HTTPRequestHeaderSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 21) +} + +// ErrorCodeHTTPRequestHeaderSize returns a [ErrorCode] of case "HTTP-request-header-size". +func ErrorCodeHTTPRequestHeaderSize(data cm.Option[FieldSizePayload]) ErrorCode { + return cm.New[ErrorCode](22, data) +} + +// HTTPRequestHeaderSize returns a non-nil *[cm.Option[FieldSizePayload]] if [ErrorCode] represents the variant case "HTTP-request-header-size". +func (self *ErrorCode) HTTPRequestHeaderSize() *cm.Option[FieldSizePayload] { + return cm.Case[cm.Option[FieldSizePayload]](self, 22) +} + +// ErrorCodeHTTPRequestTrailerSectionSize returns a [ErrorCode] of case "HTTP-request-trailer-section-size". +func ErrorCodeHTTPRequestTrailerSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](23, data) +} + +// HTTPRequestTrailerSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-request-trailer-section-size". +func (self *ErrorCode) HTTPRequestTrailerSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 23) +} + +// ErrorCodeHTTPRequestTrailerSize returns a [ErrorCode] of case "HTTP-request-trailer-size". +func ErrorCodeHTTPRequestTrailerSize(data FieldSizePayload) ErrorCode { + return cm.New[ErrorCode](24, data) +} + +// HTTPRequestTrailerSize returns a non-nil *[FieldSizePayload] if [ErrorCode] represents the variant case "HTTP-request-trailer-size". +func (self *ErrorCode) HTTPRequestTrailerSize() *FieldSizePayload { + return cm.Case[FieldSizePayload](self, 24) +} + +// ErrorCodeHTTPResponseIncomplete returns a [ErrorCode] of case "HTTP-response-incomplete". +func ErrorCodeHTTPResponseIncomplete() ErrorCode { + var data struct{} + return cm.New[ErrorCode](25, data) +} + +// HTTPResponseIncomplete returns true if [ErrorCode] represents the variant case "HTTP-response-incomplete". +func (self *ErrorCode) HTTPResponseIncomplete() bool { + return self.Tag() == 25 +} + +// ErrorCodeHTTPResponseHeaderSectionSize returns a [ErrorCode] of case "HTTP-response-header-section-size". +func ErrorCodeHTTPResponseHeaderSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](26, data) +} + +// HTTPResponseHeaderSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-response-header-section-size". +func (self *ErrorCode) HTTPResponseHeaderSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 26) +} + +// ErrorCodeHTTPResponseHeaderSize returns a [ErrorCode] of case "HTTP-response-header-size". +func ErrorCodeHTTPResponseHeaderSize(data FieldSizePayload) ErrorCode { + return cm.New[ErrorCode](27, data) +} + +// HTTPResponseHeaderSize returns a non-nil *[FieldSizePayload] if [ErrorCode] represents the variant case "HTTP-response-header-size". +func (self *ErrorCode) HTTPResponseHeaderSize() *FieldSizePayload { + return cm.Case[FieldSizePayload](self, 27) +} + +// ErrorCodeHTTPResponseBodySize returns a [ErrorCode] of case "HTTP-response-body-size". +func ErrorCodeHTTPResponseBodySize(data cm.Option[uint64]) ErrorCode { + return cm.New[ErrorCode](28, data) +} + +// HTTPResponseBodySize returns a non-nil *[cm.Option[uint64]] if [ErrorCode] represents the variant case "HTTP-response-body-size". +func (self *ErrorCode) HTTPResponseBodySize() *cm.Option[uint64] { + return cm.Case[cm.Option[uint64]](self, 28) +} + +// ErrorCodeHTTPResponseTrailerSectionSize returns a [ErrorCode] of case "HTTP-response-trailer-section-size". +func ErrorCodeHTTPResponseTrailerSectionSize(data cm.Option[uint32]) ErrorCode { + return cm.New[ErrorCode](29, data) +} + +// HTTPResponseTrailerSectionSize returns a non-nil *[cm.Option[uint32]] if [ErrorCode] represents the variant case "HTTP-response-trailer-section-size". +func (self *ErrorCode) HTTPResponseTrailerSectionSize() *cm.Option[uint32] { + return cm.Case[cm.Option[uint32]](self, 29) +} + +// ErrorCodeHTTPResponseTrailerSize returns a [ErrorCode] of case "HTTP-response-trailer-size". +func ErrorCodeHTTPResponseTrailerSize(data FieldSizePayload) ErrorCode { + return cm.New[ErrorCode](30, data) +} + +// HTTPResponseTrailerSize returns a non-nil *[FieldSizePayload] if [ErrorCode] represents the variant case "HTTP-response-trailer-size". +func (self *ErrorCode) HTTPResponseTrailerSize() *FieldSizePayload { + return cm.Case[FieldSizePayload](self, 30) +} + +// ErrorCodeHTTPResponseTransferCoding returns a [ErrorCode] of case "HTTP-response-transfer-coding". +func ErrorCodeHTTPResponseTransferCoding(data cm.Option[string]) ErrorCode { + return cm.New[ErrorCode](31, data) +} + +// HTTPResponseTransferCoding returns a non-nil *[cm.Option[string]] if [ErrorCode] represents the variant case "HTTP-response-transfer-coding". +func (self *ErrorCode) HTTPResponseTransferCoding() *cm.Option[string] { + return cm.Case[cm.Option[string]](self, 31) +} + +// ErrorCodeHTTPResponseContentCoding returns a [ErrorCode] of case "HTTP-response-content-coding". +func ErrorCodeHTTPResponseContentCoding(data cm.Option[string]) ErrorCode { + return cm.New[ErrorCode](32, data) +} + +// HTTPResponseContentCoding returns a non-nil *[cm.Option[string]] if [ErrorCode] represents the variant case "HTTP-response-content-coding". +func (self *ErrorCode) HTTPResponseContentCoding() *cm.Option[string] { + return cm.Case[cm.Option[string]](self, 32) +} + +// ErrorCodeHTTPResponseTimeout returns a [ErrorCode] of case "HTTP-response-timeout". +func ErrorCodeHTTPResponseTimeout() ErrorCode { + var data struct{} + return cm.New[ErrorCode](33, data) +} + +// HTTPResponseTimeout returns true if [ErrorCode] represents the variant case "HTTP-response-timeout". +func (self *ErrorCode) HTTPResponseTimeout() bool { + return self.Tag() == 33 +} + +// ErrorCodeHTTPUpgradeFailed returns a [ErrorCode] of case "HTTP-upgrade-failed". +func ErrorCodeHTTPUpgradeFailed() ErrorCode { + var data struct{} + return cm.New[ErrorCode](34, data) +} + +// HTTPUpgradeFailed returns true if [ErrorCode] represents the variant case "HTTP-upgrade-failed". +func (self *ErrorCode) HTTPUpgradeFailed() bool { + return self.Tag() == 34 +} + +// ErrorCodeHTTPProtocolError returns a [ErrorCode] of case "HTTP-protocol-error". +func ErrorCodeHTTPProtocolError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](35, data) +} + +// HTTPProtocolError returns true if [ErrorCode] represents the variant case "HTTP-protocol-error". +func (self *ErrorCode) HTTPProtocolError() bool { + return self.Tag() == 35 +} + +// ErrorCodeLoopDetected returns a [ErrorCode] of case "loop-detected". +func ErrorCodeLoopDetected() ErrorCode { + var data struct{} + return cm.New[ErrorCode](36, data) +} + +// LoopDetected returns true if [ErrorCode] represents the variant case "loop-detected". +func (self *ErrorCode) LoopDetected() bool { + return self.Tag() == 36 +} + +// ErrorCodeConfigurationError returns a [ErrorCode] of case "configuration-error". +func ErrorCodeConfigurationError() ErrorCode { + var data struct{} + return cm.New[ErrorCode](37, data) +} + +// ConfigurationError returns true if [ErrorCode] represents the variant case "configuration-error". +func (self *ErrorCode) ConfigurationError() bool { + return self.Tag() == 37 +} + +// ErrorCodeInternalError returns a [ErrorCode] of case "internal-error". +// +// This is a catch-all error for anything that doesn't fit cleanly into a +// more specific case. It also includes an optional string for an +// unstructured description of the error. Users should not depend on the +// string for diagnosing errors, as it's not required to be consistent +// between implementations. +func ErrorCodeInternalError(data cm.Option[string]) ErrorCode { + return cm.New[ErrorCode](38, data) +} + +// InternalError returns a non-nil *[cm.Option[string]] if [ErrorCode] represents the variant case "internal-error". +func (self *ErrorCode) InternalError() *cm.Option[string] { + return cm.Case[cm.Option[string]](self, 38) +} + +// HeaderError represents the variant "wasi:http/types@0.2.0#header-error". +// +// This type enumerates the different kinds of errors that may occur when +// setting or appending to a `fields` resource. +// +// variant header-error { +// invalid-syntax, +// forbidden, +// immutable, +// } +type HeaderError uint8 + +const ( + // This error indicates that a `field-key` or `field-value` was + // syntactically invalid when used with an operation that sets headers in a + // `fields`. + HeaderErrorInvalidSyntax HeaderError = iota + + // This error indicates that a forbidden `field-key` was used when trying + // to set a header in a `fields`. + HeaderErrorForbidden + + // This error indicates that the operation on the `fields` was not + // permitted because the fields are immutable. + HeaderErrorImmutable +) + +var stringsHeaderError = [3]string{ + "invalid-syntax", + "forbidden", + "immutable", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e HeaderError) String() string { + return stringsHeaderError[e] +} + +// FieldKey represents the string "wasi:http/types@0.2.0#field-key". +// +// Field keys are always strings. +// +// type field-key = string +type FieldKey string + +// FieldValue represents the list "wasi:http/types@0.2.0#field-value". +// +// Field values should always be ASCII strings. However, in +// reality, HTTP implementations often have to interpret malformed values, +// so they are provided as a list of bytes. +// +// type field-value = list +type FieldValue cm.List[uint8] + +// Fields represents the imported resource "wasi:http/types@0.2.0#fields". +// +// This following block defines the `fields` resource which corresponds to +// HTTP standard Fields. Fields are a common representation used for both +// Headers and Trailers. +// +// A `fields` may be mutable or immutable. A `fields` created using the +// constructor, `from-list`, or `clone` will be mutable, but a `fields` +// resource given by other means (including, but not limited to, +// `incoming-request.headers`, `outgoing-request.headers`) might be be +// immutable. In an immutable fields, the `set`, `append`, and `delete` +// operations will fail with `header-error.immutable`. +// +// resource fields +type Fields cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "fields". +// +// Drops a resource handle. +// +//go:nosplit +func (self Fields) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FieldsResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]fields +//go:noescape +func wasmimport_FieldsResourceDrop(self0 uint32) + +// NewFields represents the imported constructor for resource "fields". +// +// Construct an empty HTTP Fields. +// +// The resulting `fields` is mutable. +// +// constructor() +// +//go:nosplit +func NewFields() (result Fields) { + result0 := wasmimport_NewFields() + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [constructor]fields +//go:noescape +func wasmimport_NewFields() (result0 uint32) + +// FieldsFromList represents the imported static function "from-list". +// +// Construct an HTTP Fields. +// +// The resulting `fields` is mutable. +// +// The list represents each key-value pair in the Fields. Keys +// which have multiple values are represented by multiple entries in this +// list with the same key. +// +// The tuple is a pair of the field key, represented as a string, and +// Value, represented as a list of bytes. In a valid Fields, all keys +// and values are valid UTF-8 strings. However, values are not always +// well-formed, so they are represented as a raw list of bytes. +// +// An error result will be returned if any header or value was +// syntactically invalid, or if a header was forbidden. +// +// from-list: static func(entries: list>) -> result +// +//go:nosplit +func FieldsFromList(entries cm.List[cm.Tuple[FieldKey, FieldValue]]) (result cm.Result[Fields, Fields, HeaderError]) { + entries0, entries1 := cm.LowerList(entries) + wasmimport_FieldsFromList((*cm.Tuple[FieldKey, FieldValue])(entries0), (uint32)(entries1), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [static]fields.from-list +//go:noescape +func wasmimport_FieldsFromList(entries0 *cm.Tuple[FieldKey, FieldValue], entries1 uint32, result *cm.Result[Fields, Fields, HeaderError]) + +// Append represents the imported method "append". +// +// Append a value for a key. Does not change or delete any existing +// values for that key. +// +// Fails with `header-error.immutable` if the `fields` are immutable. +// +// append: func(name: field-key, value: field-value) -> result<_, header-error> +// +//go:nosplit +func (self Fields) Append(name FieldKey, value FieldValue) (result cm.Result[HeaderError, struct{}, HeaderError]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + value0, value1 := cm.LowerList(value) + wasmimport_FieldsAppend((uint32)(self0), (*uint8)(name0), (uint32)(name1), (*uint8)(value0), (uint32)(value1), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.append +//go:noescape +func wasmimport_FieldsAppend(self0 uint32, name0 *uint8, name1 uint32, value0 *uint8, value1 uint32, result *cm.Result[HeaderError, struct{}, HeaderError]) + +// Clone represents the imported method "clone". +// +// Make a deep copy of the Fields. Equivelant in behavior to calling the +// `fields` constructor on the return value of `entries`. The resulting +// `fields` is mutable. +// +// clone: func() -> fields +// +//go:nosplit +func (self Fields) Clone() (result Fields) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_FieldsClone((uint32)(self0)) + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.clone +//go:noescape +func wasmimport_FieldsClone(self0 uint32) (result0 uint32) + +// Delete represents the imported method "delete". +// +// Delete all values for a key. Does nothing if no values for the key +// exist. +// +// Fails with `header-error.immutable` if the `fields` are immutable. +// +// delete: func(name: field-key) -> result<_, header-error> +// +//go:nosplit +func (self Fields) Delete(name FieldKey) (result cm.Result[HeaderError, struct{}, HeaderError]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + wasmimport_FieldsDelete((uint32)(self0), (*uint8)(name0), (uint32)(name1), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.delete +//go:noescape +func wasmimport_FieldsDelete(self0 uint32, name0 *uint8, name1 uint32, result *cm.Result[HeaderError, struct{}, HeaderError]) + +// Entries represents the imported method "entries". +// +// Retrieve the full set of keys and values in the Fields. Like the +// constructor, the list represents each key-value pair. +// +// The outer list represents each key-value pair in the Fields. Keys +// which have multiple values are represented by multiple entries in this +// list with the same key. +// +// entries: func() -> list> +// +//go:nosplit +func (self Fields) Entries() (result cm.List[cm.Tuple[FieldKey, FieldValue]]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FieldsEntries((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.entries +//go:noescape +func wasmimport_FieldsEntries(self0 uint32, result *cm.List[cm.Tuple[FieldKey, FieldValue]]) + +// Get represents the imported method "get". +// +// Get all of the values corresponding to a key. If the key is not present +// in this `fields`, an empty list is returned. However, if the key is +// present but empty, this is represented by a list with one or more +// empty field-values present. +// +// get: func(name: field-key) -> list +// +//go:nosplit +func (self Fields) Get(name FieldKey) (result cm.List[FieldValue]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + wasmimport_FieldsGet((uint32)(self0), (*uint8)(name0), (uint32)(name1), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.get +//go:noescape +func wasmimport_FieldsGet(self0 uint32, name0 *uint8, name1 uint32, result *cm.List[FieldValue]) + +// Has represents the imported method "has". +// +// Returns `true` when the key is present in this `fields`. If the key is +// syntactically invalid, `false` is returned. +// +// has: func(name: field-key) -> bool +// +//go:nosplit +func (self Fields) Has(name FieldKey) (result bool) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + result0 := wasmimport_FieldsHas((uint32)(self0), (*uint8)(name0), (uint32)(name1)) + result = cm.U32ToBool((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.has +//go:noescape +func wasmimport_FieldsHas(self0 uint32, name0 *uint8, name1 uint32) (result0 uint32) + +// Set represents the imported method "set". +// +// Set all of the values for a key. Clears any existing values for that +// key, if they have been set. +// +// Fails with `header-error.immutable` if the `fields` are immutable. +// +// set: func(name: field-key, value: list) -> result<_, header-error> +// +//go:nosplit +func (self Fields) Set(name FieldKey, value cm.List[FieldValue]) (result cm.Result[HeaderError, struct{}, HeaderError]) { + self0 := cm.Reinterpret[uint32](self) + name0, name1 := cm.LowerString(name) + value0, value1 := cm.LowerList(value) + wasmimport_FieldsSet((uint32)(self0), (*uint8)(name0), (uint32)(name1), (*FieldValue)(value0), (uint32)(value1), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]fields.set +//go:noescape +func wasmimport_FieldsSet(self0 uint32, name0 *uint8, name1 uint32, value0 *FieldValue, value1 uint32, result *cm.Result[HeaderError, struct{}, HeaderError]) + +// IncomingRequest represents the imported resource "wasi:http/types@0.2.0#incoming-request". +// +// Represents an incoming HTTP Request. +// +// resource incoming-request +type IncomingRequest cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-request". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingRequest) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]incoming-request +//go:noescape +func wasmimport_IncomingRequestResourceDrop(self0 uint32) + +// Authority represents the imported method "authority". +// +// Returns the authority from the request, if it was present. +// +// authority: func() -> option +// +//go:nosplit +func (self IncomingRequest) Authority() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestAuthority((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.authority +//go:noescape +func wasmimport_IncomingRequestAuthority(self0 uint32, result *cm.Option[string]) + +// Consume represents the imported method "consume". +// +// Gives the `incoming-body` associated with this request. Will only +// return success at most once, and subsequent calls will return error. +// +// consume: func() -> result +// +//go:nosplit +func (self IncomingRequest) Consume() (result cm.Result[IncomingBody, IncomingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestConsume((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.consume +//go:noescape +func wasmimport_IncomingRequestConsume(self0 uint32, result *cm.Result[IncomingBody, IncomingBody, struct{}]) + +// Headers represents the imported method "headers". +// +// Get the `headers` associated with the request. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// The `headers` returned are a child resource: it must be dropped before +// the parent `incoming-request` is dropped. Dropping this +// `incoming-request` before all children are dropped will trap. +// +// headers: func() -> headers +// +//go:nosplit +func (self IncomingRequest) Headers() (result Fields) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingRequestHeaders((uint32)(self0)) + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.headers +//go:noescape +func wasmimport_IncomingRequestHeaders(self0 uint32) (result0 uint32) + +// Method represents the imported method "method". +// +// Returns the method of the incoming request. +// +// method: func() -> method +// +//go:nosplit +func (self IncomingRequest) Method() (result Method) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestMethod((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.method +//go:noescape +func wasmimport_IncomingRequestMethod(self0 uint32, result *Method) + +// PathWithQuery represents the imported method "path-with-query". +// +// Returns the path with query parameters from the request, as a string. +// +// path-with-query: func() -> option +// +//go:nosplit +func (self IncomingRequest) PathWithQuery() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestPathWithQuery((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.path-with-query +//go:noescape +func wasmimport_IncomingRequestPathWithQuery(self0 uint32, result *cm.Option[string]) + +// Scheme represents the imported method "scheme". +// +// Returns the protocol scheme from the request. +// +// scheme: func() -> option +// +//go:nosplit +func (self IncomingRequest) Scheme() (result cm.Option[Scheme]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingRequestScheme((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-request.scheme +//go:noescape +func wasmimport_IncomingRequestScheme(self0 uint32, result *cm.Option[Scheme]) + +// OutgoingRequest represents the imported resource "wasi:http/types@0.2.0#outgoing-request". +// +// Represents an outgoing HTTP Request. +// +// resource outgoing-request +type OutgoingRequest cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-request". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingRequest) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]outgoing-request +//go:noescape +func wasmimport_OutgoingRequestResourceDrop(self0 uint32) + +// NewOutgoingRequest represents the imported constructor for resource "outgoing-request". +// +// Construct a new `outgoing-request` with a default `method` of `GET`, and +// `none` values for `path-with-query`, `scheme`, and `authority`. +// +// * `headers` is the HTTP Headers for the Request. +// +// It is possible to construct, or manipulate with the accessor functions +// below, an `outgoing-request` with an invalid combination of `scheme` +// and `authority`, or `headers` which are not permitted to be sent. +// It is the obligation of the `outgoing-handler.handle` implementation +// to reject invalid constructions of `outgoing-request`. +// +// constructor(headers: headers) +// +//go:nosplit +func NewOutgoingRequest(headers Fields) (result OutgoingRequest) { + headers0 := cm.Reinterpret[uint32](headers) + result0 := wasmimport_NewOutgoingRequest((uint32)(headers0)) + result = cm.Reinterpret[OutgoingRequest]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [constructor]outgoing-request +//go:noescape +func wasmimport_NewOutgoingRequest(headers0 uint32) (result0 uint32) + +// Authority represents the imported method "authority". +// +// Get the HTTP Authority for the Request. A value of `none` may be used +// with Related Schemes which do not require an Authority. The HTTP and +// HTTPS schemes always require an authority. +// +// authority: func() -> option +// +//go:nosplit +func (self OutgoingRequest) Authority() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestAuthority((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.authority +//go:noescape +func wasmimport_OutgoingRequestAuthority(self0 uint32, result *cm.Option[string]) + +// Body represents the imported method "body". +// +// Returns the resource corresponding to the outgoing Body for this +// Request. +// +// Returns success on the first call: the `outgoing-body` resource for +// this `outgoing-request` can be retrieved at most once. Subsequent +// calls will return error. +// +// body: func() -> result +// +//go:nosplit +func (self OutgoingRequest) Body() (result cm.Result[OutgoingBody, OutgoingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestBody((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.body +//go:noescape +func wasmimport_OutgoingRequestBody(self0 uint32, result *cm.Result[OutgoingBody, OutgoingBody, struct{}]) + +// Headers represents the imported method "headers". +// +// Get the headers associated with the Request. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// This headers resource is a child: it must be dropped before the parent +// `outgoing-request` is dropped, or its ownership is transfered to +// another component by e.g. `outgoing-handler.handle`. +// +// headers: func() -> headers +// +//go:nosplit +func (self OutgoingRequest) Headers() (result Fields) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingRequestHeaders((uint32)(self0)) + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.headers +//go:noescape +func wasmimport_OutgoingRequestHeaders(self0 uint32) (result0 uint32) + +// Method represents the imported method "method". +// +// Get the Method for the Request. +// +// method: func() -> method +// +//go:nosplit +func (self OutgoingRequest) Method() (result Method) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestMethod((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.method +//go:noescape +func wasmimport_OutgoingRequestMethod(self0 uint32, result *Method) + +// PathWithQuery represents the imported method "path-with-query". +// +// Get the combination of the HTTP Path and Query for the Request. +// When `none`, this represents an empty Path and empty Query. +// +// path-with-query: func() -> option +// +//go:nosplit +func (self OutgoingRequest) PathWithQuery() (result cm.Option[string]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestPathWithQuery((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.path-with-query +//go:noescape +func wasmimport_OutgoingRequestPathWithQuery(self0 uint32, result *cm.Option[string]) + +// Scheme represents the imported method "scheme". +// +// Get the HTTP Related Scheme for the Request. When `none`, the +// implementation may choose an appropriate default scheme. +// +// scheme: func() -> option +// +//go:nosplit +func (self OutgoingRequest) Scheme() (result cm.Option[Scheme]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingRequestScheme((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.scheme +//go:noescape +func wasmimport_OutgoingRequestScheme(self0 uint32, result *cm.Option[Scheme]) + +// SetAuthority represents the imported method "set-authority". +// +// Set the HTTP Authority for the Request. A value of `none` may be used +// with Related Schemes which do not require an Authority. The HTTP and +// HTTPS schemes always require an authority. Fails if the string given is +// not a syntactically valid uri authority. +// +// set-authority: func(authority: option) -> result +// +//go:nosplit +func (self OutgoingRequest) SetAuthority(authority cm.Option[string]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + authority0, authority1, authority2 := lower_OptionString(authority) + result0 := wasmimport_OutgoingRequestSetAuthority((uint32)(self0), (uint32)(authority0), (*uint8)(authority1), (uint32)(authority2)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-authority +//go:noescape +func wasmimport_OutgoingRequestSetAuthority(self0 uint32, authority0 uint32, authority1 *uint8, authority2 uint32) (result0 uint32) + +// SetMethod represents the imported method "set-method". +// +// Set the Method for the Request. Fails if the string present in a +// `method.other` argument is not a syntactically valid method. +// +// set-method: func(method: method) -> result +// +//go:nosplit +func (self OutgoingRequest) SetMethod(method Method) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + method0, method1, method2 := lower_Method(method) + result0 := wasmimport_OutgoingRequestSetMethod((uint32)(self0), (uint32)(method0), (*uint8)(method1), (uint32)(method2)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-method +//go:noescape +func wasmimport_OutgoingRequestSetMethod(self0 uint32, method0 uint32, method1 *uint8, method2 uint32) (result0 uint32) + +// SetPathWithQuery represents the imported method "set-path-with-query". +// +// Set the combination of the HTTP Path and Query for the Request. +// When `none`, this represents an empty Path and empty Query. Fails is the +// string given is not a syntactically valid path and query uri component. +// +// set-path-with-query: func(path-with-query: option) -> result +// +//go:nosplit +func (self OutgoingRequest) SetPathWithQuery(pathWithQuery cm.Option[string]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + pathWithQuery0, pathWithQuery1, pathWithQuery2 := lower_OptionString(pathWithQuery) + result0 := wasmimport_OutgoingRequestSetPathWithQuery((uint32)(self0), (uint32)(pathWithQuery0), (*uint8)(pathWithQuery1), (uint32)(pathWithQuery2)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-path-with-query +//go:noescape +func wasmimport_OutgoingRequestSetPathWithQuery(self0 uint32, pathWithQuery0 uint32, pathWithQuery1 *uint8, pathWithQuery2 uint32) (result0 uint32) + +// SetScheme represents the imported method "set-scheme". +// +// Set the HTTP Related Scheme for the Request. When `none`, the +// implementation may choose an appropriate default scheme. Fails if the +// string given is not a syntactically valid uri scheme. +// +// set-scheme: func(scheme: option) -> result +// +//go:nosplit +func (self OutgoingRequest) SetScheme(scheme cm.Option[Scheme]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + scheme0, scheme1, scheme2, scheme3 := lower_OptionScheme(scheme) + result0 := wasmimport_OutgoingRequestSetScheme((uint32)(self0), (uint32)(scheme0), (uint32)(scheme1), (*uint8)(scheme2), (uint32)(scheme3)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-request.set-scheme +//go:noescape +func wasmimport_OutgoingRequestSetScheme(self0 uint32, scheme0 uint32, scheme1 uint32, scheme2 *uint8, scheme3 uint32) (result0 uint32) + +// RequestOptions represents the imported resource "wasi:http/types@0.2.0#request-options". +// +// Parameters for making an HTTP Request. Each of these parameters is +// currently an optional timeout applicable to the transport layer of the +// HTTP protocol. +// +// These timeouts are separate from any the user may use to bound a +// blocking call to `wasi:io/poll.poll`. +// +// resource request-options +type RequestOptions cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "request-options". +// +// Drops a resource handle. +// +//go:nosplit +func (self RequestOptions) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]request-options +//go:noescape +func wasmimport_RequestOptionsResourceDrop(self0 uint32) + +// NewRequestOptions represents the imported constructor for resource "request-options". +// +// Construct a default `request-options` value. +// +// constructor() +// +//go:nosplit +func NewRequestOptions() (result RequestOptions) { + result0 := wasmimport_NewRequestOptions() + result = cm.Reinterpret[RequestOptions]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [constructor]request-options +//go:noescape +func wasmimport_NewRequestOptions() (result0 uint32) + +// BetweenBytesTimeout represents the imported method "between-bytes-timeout". +// +// The timeout for receiving subsequent chunks of bytes in the Response +// body stream. +// +// between-bytes-timeout: func() -> option +// +//go:nosplit +func (self RequestOptions) BetweenBytesTimeout() (result cm.Option[monotonicclock.Duration]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsBetweenBytesTimeout((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.between-bytes-timeout +//go:noescape +func wasmimport_RequestOptionsBetweenBytesTimeout(self0 uint32, result *cm.Option[monotonicclock.Duration]) + +// ConnectTimeout represents the imported method "connect-timeout". +// +// The timeout for the initial connect to the HTTP Server. +// +// connect-timeout: func() -> option +// +//go:nosplit +func (self RequestOptions) ConnectTimeout() (result cm.Option[monotonicclock.Duration]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsConnectTimeout((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.connect-timeout +//go:noescape +func wasmimport_RequestOptionsConnectTimeout(self0 uint32, result *cm.Option[monotonicclock.Duration]) + +// FirstByteTimeout represents the imported method "first-byte-timeout". +// +// The timeout for receiving the first byte of the Response body. +// +// first-byte-timeout: func() -> option +// +//go:nosplit +func (self RequestOptions) FirstByteTimeout() (result cm.Option[monotonicclock.Duration]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_RequestOptionsFirstByteTimeout((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.first-byte-timeout +//go:noescape +func wasmimport_RequestOptionsFirstByteTimeout(self0 uint32, result *cm.Option[monotonicclock.Duration]) + +// SetBetweenBytesTimeout represents the imported method "set-between-bytes-timeout". +// +// Set the timeout for receiving subsequent chunks of bytes in the Response +// body stream. An error return value indicates that this timeout is not +// supported. +// +// set-between-bytes-timeout: func(duration: option) -> result +// +//go:nosplit +func (self RequestOptions) SetBetweenBytesTimeout(duration cm.Option[monotonicclock.Duration]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + duration0, duration1 := lower_OptionDuration(duration) + result0 := wasmimport_RequestOptionsSetBetweenBytesTimeout((uint32)(self0), (uint32)(duration0), (uint64)(duration1)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.set-between-bytes-timeout +//go:noescape +func wasmimport_RequestOptionsSetBetweenBytesTimeout(self0 uint32, duration0 uint32, duration1 uint64) (result0 uint32) + +// SetConnectTimeout represents the imported method "set-connect-timeout". +// +// Set the timeout for the initial connect to the HTTP Server. An error +// return value indicates that this timeout is not supported. +// +// set-connect-timeout: func(duration: option) -> result +// +//go:nosplit +func (self RequestOptions) SetConnectTimeout(duration cm.Option[monotonicclock.Duration]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + duration0, duration1 := lower_OptionDuration(duration) + result0 := wasmimport_RequestOptionsSetConnectTimeout((uint32)(self0), (uint32)(duration0), (uint64)(duration1)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.set-connect-timeout +//go:noescape +func wasmimport_RequestOptionsSetConnectTimeout(self0 uint32, duration0 uint32, duration1 uint64) (result0 uint32) + +// SetFirstByteTimeout represents the imported method "set-first-byte-timeout". +// +// Set the timeout for receiving the first byte of the Response body. An +// error return value indicates that this timeout is not supported. +// +// set-first-byte-timeout: func(duration: option) -> result +// +//go:nosplit +func (self RequestOptions) SetFirstByteTimeout(duration cm.Option[monotonicclock.Duration]) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + duration0, duration1 := lower_OptionDuration(duration) + result0 := wasmimport_RequestOptionsSetFirstByteTimeout((uint32)(self0), (uint32)(duration0), (uint64)(duration1)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]request-options.set-first-byte-timeout +//go:noescape +func wasmimport_RequestOptionsSetFirstByteTimeout(self0 uint32, duration0 uint32, duration1 uint64) (result0 uint32) + +// ResponseOutparam represents the imported resource "wasi:http/types@0.2.0#response-outparam". +// +// Represents the ability to send an HTTP Response. +// +// This resource is used by the `wasi:http/incoming-handler` interface to +// allow a Response to be sent corresponding to the Request provided as the +// other argument to `incoming-handler.handle`. +// +// resource response-outparam +type ResponseOutparam cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "response-outparam". +// +// Drops a resource handle. +// +//go:nosplit +func (self ResponseOutparam) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ResponseOutparamResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]response-outparam +//go:noescape +func wasmimport_ResponseOutparamResourceDrop(self0 uint32) + +// ResponseOutparamSet represents the imported static function "set". +// +// Set the value of the `response-outparam` to either send a response, +// or indicate an error. +// +// This method consumes the `response-outparam` to ensure that it is +// called at most once. If it is never called, the implementation +// will respond with an error. +// +// The user may provide an `error` to `response` to allow the +// implementation determine how to respond with an HTTP error response. +// +// set: static func(param: response-outparam, response: result) +// +//go:nosplit +func ResponseOutparamSet(param ResponseOutparam, response cm.Result[ErrorCodeShape, OutgoingResponse, ErrorCode]) { + param0 := cm.Reinterpret[uint32](param) + response0, response1, response2, response3, response4, response5, response6, response7 := lower_ResultOutgoingResponseErrorCode(response) + wasmimport_ResponseOutparamSet((uint32)(param0), (uint32)(response0), (uint32)(response1), (uint32)(response2), (uint64)(response3), (uint32)(response4), (uint32)(response5), (uint32)(response6), (uint32)(response7)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [static]response-outparam.set +//go:noescape +func wasmimport_ResponseOutparamSet(param0 uint32, response0 uint32, response1 uint32, response2 uint32, response3 uint64, response4 uint32, response5 uint32, response6 uint32, response7 uint32) + +// StatusCode represents the u16 "wasi:http/types@0.2.0#status-code". +// +// This type corresponds to the HTTP standard Status Code. +// +// type status-code = u16 +type StatusCode uint16 + +// IncomingResponse represents the imported resource "wasi:http/types@0.2.0#incoming-response". +// +// Represents an incoming HTTP Response. +// +// resource incoming-response +type IncomingResponse cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-response". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingResponse) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingResponseResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]incoming-response +//go:noescape +func wasmimport_IncomingResponseResourceDrop(self0 uint32) + +// Consume represents the imported method "consume". +// +// Returns the incoming body. May be called at most once. Returns error +// if called additional times. +// +// consume: func() -> result +// +//go:nosplit +func (self IncomingResponse) Consume() (result cm.Result[IncomingBody, IncomingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingResponseConsume((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-response.consume +//go:noescape +func wasmimport_IncomingResponseConsume(self0 uint32, result *cm.Result[IncomingBody, IncomingBody, struct{}]) + +// Headers represents the imported method "headers". +// +// Returns the headers from the incoming response. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// This headers resource is a child: it must be dropped before the parent +// `incoming-response` is dropped. +// +// headers: func() -> headers +// +//go:nosplit +func (self IncomingResponse) Headers() (result Fields) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingResponseHeaders((uint32)(self0)) + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-response.headers +//go:noescape +func wasmimport_IncomingResponseHeaders(self0 uint32) (result0 uint32) + +// Status represents the imported method "status". +// +// Returns the status code from the incoming response. +// +// status: func() -> status-code +// +//go:nosplit +func (self IncomingResponse) Status() (result StatusCode) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingResponseStatus((uint32)(self0)) + result = (StatusCode)((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-response.status +//go:noescape +func wasmimport_IncomingResponseStatus(self0 uint32) (result0 uint32) + +// IncomingBody represents the imported resource "wasi:http/types@0.2.0#incoming-body". +// +// Represents an incoming HTTP Request or Response's Body. +// +// A body has both its contents - a stream of bytes - and a (possibly +// empty) set of trailers, indicating that the full contents of the +// body have been received. This resource represents the contents as +// an `input-stream` and the delivery of trailers as a `future-trailers`, +// and ensures that the user of this interface may only be consuming either +// the body contents or waiting on trailers at any given time. +// +// resource incoming-body +type IncomingBody cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-body". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingBody) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingBodyResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]incoming-body +//go:noescape +func wasmimport_IncomingBodyResourceDrop(self0 uint32) + +// IncomingBodyFinish represents the imported static function "finish". +// +// Takes ownership of `incoming-body`, and returns a `future-trailers`. +// This function will trap if the `input-stream` child is still alive. +// +// finish: static func(this: incoming-body) -> future-trailers +// +//go:nosplit +func IncomingBodyFinish(this IncomingBody) (result FutureTrailers) { + this0 := cm.Reinterpret[uint32](this) + result0 := wasmimport_IncomingBodyFinish((uint32)(this0)) + result = cm.Reinterpret[FutureTrailers]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [static]incoming-body.finish +//go:noescape +func wasmimport_IncomingBodyFinish(this0 uint32) (result0 uint32) + +// Stream represents the imported method "stream". +// +// Returns the contents of the body, as a stream of bytes. +// +// Returns success on first call: the stream representing the contents +// can be retrieved at most once. Subsequent calls will return error. +// +// The returned `input-stream` resource is a child: it must be dropped +// before the parent `incoming-body` is dropped, or consumed by +// `incoming-body.finish`. +// +// This invariant ensures that the implementation can determine whether +// the user is consuming the contents of the body, waiting on the +// `future-trailers` to be ready, or neither. This allows for network +// backpressure is to be applied when the user is consuming the body, +// and for that backpressure to not inhibit delivery of the trailers if +// the user does not read the entire body. +// +// %stream: func() -> result +// +//go:nosplit +func (self IncomingBody) Stream() (result cm.Result[streams.InputStream, streams.InputStream, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingBodyStream((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]incoming-body.stream +//go:noescape +func wasmimport_IncomingBodyStream(self0 uint32, result *cm.Result[streams.InputStream, streams.InputStream, struct{}]) + +// FutureTrailers represents the imported resource "wasi:http/types@0.2.0#future-trailers". +// +// Represents a future which may eventaully return trailers, or an error. +// +// In the case that the incoming HTTP Request or Response did not have any +// trailers, this future will resolve to the empty set of trailers once the +// complete Request or Response body has been received. +// +// resource future-trailers +type FutureTrailers cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "future-trailers". +// +// Drops a resource handle. +// +//go:nosplit +func (self FutureTrailers) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureTrailersResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]future-trailers +//go:noescape +func wasmimport_FutureTrailersResourceDrop(self0 uint32) + +// Get represents the imported method "get". +// +// Returns the contents of the trailers, or an error which occured, +// once the future is ready. +// +// The outer `option` represents future readiness. Users can wait on this +// `option` to become `some` using the `subscribe` method. +// +// The outer `result` is used to retrieve the trailers or error at most +// once. It will be success on the first call in which the outer option +// is `some`, and error on subsequent calls. +// +// The inner `result` represents that either the HTTP Request or Response +// body, as well as any trailers, were received successfully, or that an +// error occured receiving them. The optional `trailers` indicates whether +// or not trailers were present in the body. +// +// When some `trailers` are returned by this method, the `trailers` +// resource is immutable, and a child. Use of the `set`, `append`, or +// `delete` methods will return an error, and the resource must be +// dropped before the parent `future-trailers` is dropped. +// +// get: func() -> option, error-code>>> +// +//go:nosplit +func (self FutureTrailers) Get() (result cm.Option[cm.Result[cm.Result[ErrorCodeShape, cm.Option[Fields], ErrorCode], cm.Result[ErrorCodeShape, cm.Option[Fields], ErrorCode], struct{}]]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureTrailersGet((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]future-trailers.get +//go:noescape +func wasmimport_FutureTrailersGet(self0 uint32, result *cm.Option[cm.Result[cm.Result[ErrorCodeShape, cm.Option[Fields], ErrorCode], cm.Result[ErrorCodeShape, cm.Option[Fields], ErrorCode], struct{}]]) + +// Subscribe represents the imported method "subscribe". +// +// Returns a pollable which becomes ready when either the trailers have +// been received, or an error has occured. When this pollable is ready, +// the `get` method will return `some`. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self FutureTrailers) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_FutureTrailersSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]future-trailers.subscribe +//go:noescape +func wasmimport_FutureTrailersSubscribe(self0 uint32) (result0 uint32) + +// OutgoingResponse represents the imported resource "wasi:http/types@0.2.0#outgoing-response". +// +// Represents an outgoing HTTP Response. +// +// resource outgoing-response +type OutgoingResponse cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-response". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingResponse) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingResponseResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]outgoing-response +//go:noescape +func wasmimport_OutgoingResponseResourceDrop(self0 uint32) + +// NewOutgoingResponse represents the imported constructor for resource "outgoing-response". +// +// Construct an `outgoing-response`, with a default `status-code` of `200`. +// If a different `status-code` is needed, it must be set via the +// `set-status-code` method. +// +// * `headers` is the HTTP Headers for the Response. +// +// constructor(headers: headers) +// +//go:nosplit +func NewOutgoingResponse(headers Fields) (result OutgoingResponse) { + headers0 := cm.Reinterpret[uint32](headers) + result0 := wasmimport_NewOutgoingResponse((uint32)(headers0)) + result = cm.Reinterpret[OutgoingResponse]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [constructor]outgoing-response +//go:noescape +func wasmimport_NewOutgoingResponse(headers0 uint32) (result0 uint32) + +// Body represents the imported method "body". +// +// Returns the resource corresponding to the outgoing Body for this Response. +// +// Returns success on the first call: the `outgoing-body` resource for +// this `outgoing-response` can be retrieved at most once. Subsequent +// calls will return error. +// +// body: func() -> result +// +//go:nosplit +func (self OutgoingResponse) Body() (result cm.Result[OutgoingBody, OutgoingBody, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingResponseBody((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.body +//go:noescape +func wasmimport_OutgoingResponseBody(self0 uint32, result *cm.Result[OutgoingBody, OutgoingBody, struct{}]) + +// Headers represents the imported method "headers". +// +// Get the headers associated with the Request. +// +// The returned `headers` resource is immutable: `set`, `append`, and +// `delete` operations will fail with `header-error.immutable`. +// +// This headers resource is a child: it must be dropped before the parent +// `outgoing-request` is dropped, or its ownership is transfered to +// another component by e.g. `outgoing-handler.handle`. +// +// headers: func() -> headers +// +//go:nosplit +func (self OutgoingResponse) Headers() (result Fields) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingResponseHeaders((uint32)(self0)) + result = cm.Reinterpret[Fields]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.headers +//go:noescape +func wasmimport_OutgoingResponseHeaders(self0 uint32) (result0 uint32) + +// SetStatusCode represents the imported method "set-status-code". +// +// Set the HTTP Status Code for the Response. Fails if the status-code +// given is not a valid http status code. +// +// set-status-code: func(status-code: status-code) -> result +// +//go:nosplit +func (self OutgoingResponse) SetStatusCode(statusCode StatusCode) (result cm.BoolResult) { + self0 := cm.Reinterpret[uint32](self) + statusCode0 := (uint32)(statusCode) + result0 := wasmimport_OutgoingResponseSetStatusCode((uint32)(self0), (uint32)(statusCode0)) + result = (cm.BoolResult)(cm.U32ToBool((uint32)(result0))) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.set-status-code +//go:noescape +func wasmimport_OutgoingResponseSetStatusCode(self0 uint32, statusCode0 uint32) (result0 uint32) + +// StatusCode represents the imported method "status-code". +// +// Get the HTTP Status Code for the Response. +// +// status-code: func() -> status-code +// +//go:nosplit +func (self OutgoingResponse) StatusCode() (result StatusCode) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingResponseStatusCode((uint32)(self0)) + result = (StatusCode)((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-response.status-code +//go:noescape +func wasmimport_OutgoingResponseStatusCode(self0 uint32) (result0 uint32) + +// OutgoingBody represents the imported resource "wasi:http/types@0.2.0#outgoing-body". +// +// Represents an outgoing HTTP Request or Response's Body. +// +// A body has both its contents - a stream of bytes - and a (possibly +// empty) set of trailers, inducating the full contents of the body +// have been sent. This resource represents the contents as an +// `output-stream` child resource, and the completion of the body (with +// optional trailers) with a static function that consumes the +// `outgoing-body` resource, and ensures that the user of this interface +// may not write to the body contents after the body has been finished. +// +// If the user code drops this resource, as opposed to calling the static +// method `finish`, the implementation should treat the body as incomplete, +// and that an error has occured. The implementation should propogate this +// error to the HTTP protocol by whatever means it has available, +// including: corrupting the body on the wire, aborting the associated +// Request, or sending a late status code for the Response. +// +// resource outgoing-body +type OutgoingBody cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-body". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingBody) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingBodyResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]outgoing-body +//go:noescape +func wasmimport_OutgoingBodyResourceDrop(self0 uint32) + +// OutgoingBodyFinish represents the imported static function "finish". +// +// Finalize an outgoing body, optionally providing trailers. This must be +// called to signal that the response is complete. If the `outgoing-body` +// is dropped without calling `outgoing-body.finalize`, the implementation +// should treat the body as corrupted. +// +// Fails if the body's `outgoing-request` or `outgoing-response` was +// constructed with a Content-Length header, and the contents written +// to the body (via `write`) does not match the value given in the +// Content-Length. +// +// finish: static func(this: outgoing-body, trailers: option) -> result<_, +// error-code> +// +//go:nosplit +func OutgoingBodyFinish(this OutgoingBody, trailers cm.Option[Fields]) (result cm.Result[ErrorCode, struct{}, ErrorCode]) { + this0 := cm.Reinterpret[uint32](this) + trailers0, trailers1 := lower_OptionTrailers(trailers) + wasmimport_OutgoingBodyFinish((uint32)(this0), (uint32)(trailers0), (uint32)(trailers1), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [static]outgoing-body.finish +//go:noescape +func wasmimport_OutgoingBodyFinish(this0 uint32, trailers0 uint32, trailers1 uint32, result *cm.Result[ErrorCode, struct{}, ErrorCode]) + +// Write represents the imported method "write". +// +// Returns a stream for writing the body contents. +// +// The returned `output-stream` is a child resource: it must be dropped +// before the parent `outgoing-body` resource is dropped (or finished), +// otherwise the `outgoing-body` drop or `finish` will trap. +// +// Returns success on the first call: the `output-stream` resource for +// this `outgoing-body` may be retrieved at most once. Subsequent calls +// will return error. +// +// write: func() -> result +// +//go:nosplit +func (self OutgoingBody) Write() (result cm.Result[streams.OutputStream, streams.OutputStream, struct{}]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingBodyWrite((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]outgoing-body.write +//go:noescape +func wasmimport_OutgoingBodyWrite(self0 uint32, result *cm.Result[streams.OutputStream, streams.OutputStream, struct{}]) + +// FutureIncomingResponse represents the imported resource "wasi:http/types@0.2.0#future-incoming-response". +// +// Represents a future which may eventaully return an incoming HTTP +// Response, or an error. +// +// This resource is returned by the `wasi:http/outgoing-handler` interface to +// provide the HTTP Response corresponding to the sent Request. +// +// resource future-incoming-response +type FutureIncomingResponse cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "future-incoming-response". +// +// Drops a resource handle. +// +//go:nosplit +func (self FutureIncomingResponse) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureIncomingResponseResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [resource-drop]future-incoming-response +//go:noescape +func wasmimport_FutureIncomingResponseResourceDrop(self0 uint32) + +// Get represents the imported method "get". +// +// Returns the incoming HTTP Response, or an error, once one is ready. +// +// The outer `option` represents future readiness. Users can wait on this +// `option` to become `some` using the `subscribe` method. +// +// The outer `result` is used to retrieve the response or error at most +// once. It will be success on the first call in which the outer option +// is `some`, and error on subsequent calls. +// +// The inner `result` represents that either the incoming HTTP Response +// status and headers have recieved successfully, or that an error +// occured. Errors may also occur while consuming the response body, +// but those will be reported by the `incoming-body` and its +// `output-stream` child. +// +// get: func() -> option>> +// +//go:nosplit +func (self FutureIncomingResponse) Get() (result cm.Option[cm.Result[cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], struct{}]]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_FutureIncomingResponseGet((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]future-incoming-response.get +//go:noescape +func wasmimport_FutureIncomingResponseGet(self0 uint32, result *cm.Option[cm.Result[cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], cm.Result[ErrorCodeShape, IncomingResponse, ErrorCode], struct{}]]) + +// Subscribe represents the imported method "subscribe". +// +// Returns a pollable which becomes ready when either the Response has +// been received, or an error has occured. When this pollable is ready, +// the `get` method will return `some`. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self FutureIncomingResponse) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_FutureIncomingResponseSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:http/types@0.2.0 [method]future-incoming-response.subscribe +//go:noescape +func wasmimport_FutureIncomingResponseSubscribe(self0 uint32) (result0 uint32) + +// HTTPErrorCode represents the imported function "http-error-code". +// +// Attempts to extract a http-related `error` from the wasi:io `error` +// provided. +// +// Stream operations which return +// `wasi:io/stream/stream-error::last-operation-failed` have a payload of +// type `wasi:io/error/error` with more information about the operation +// that failed. This payload can be passed through to this function to see +// if there's http-related information about the error to return. +// +// Note that this function is fallible because not all io-errors are +// http-related errors. +// +// http-error-code: func(err: borrow) -> option +// +//go:nosplit +func HTTPErrorCode(err ioerror.Error) (result cm.Option[ErrorCode]) { + err0 := cm.Reinterpret[uint32](err) + wasmimport_HTTPErrorCode((uint32)(err0), &result) + return +} + +//go:wasmimport wasi:http/types@0.2.0 http-error-code +//go:noescape +func wasmimport_HTTPErrorCode(err0 uint32, result *cm.Option[ErrorCode]) diff --git a/_examples/http-client/gen/wasi/io/error/empty.s b/_examples/http-client/gen/wasi/io/error/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/io/error/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/io/error/error.wit.go b/_examples/http-client/gen/wasi/io/error/error.wit.go new file mode 100644 index 0000000..61d61db --- /dev/null +++ b/_examples/http-client/gen/wasi/io/error/error.wit.go @@ -0,0 +1,71 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package ioerror represents the imported interface "wasi:io/error@0.2.0". +package ioerror + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// Error represents the imported resource "wasi:io/error@0.2.0#error". +// +// A resource which represents some error information. +// +// The only method provided by this resource is `to-debug-string`, +// which provides some human-readable information about the error. +// +// In the `wasi:io` package, this resource is returned through the +// `wasi:io/streams/stream-error` type. +// +// To provide more specific error information, other interfaces may +// provide functions to further "downcast" this error into more specific +// error information. For example, `error`s returned in streams derived +// from filesystem types to be described using the filesystem's own +// error-code type, using the function +// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter +// `borrow` and returns +// `option`. +// +// The set of functions which can "downcast" an `error` into a more +// concrete type is open. +// +// resource error +type Error cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "error". +// +// Drops a resource handle. +// +//go:nosplit +func (self Error) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ErrorResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:io/error@0.2.0 [resource-drop]error +//go:noescape +func wasmimport_ErrorResourceDrop(self0 uint32) + +// ToDebugString represents the imported method "to-debug-string". +// +// Returns a string that is suitable to assist humans in debugging +// this error. +// +// WARNING: The returned string should not be consumed mechanically! +// It may change across platforms, hosts, or other implementation +// details. Parsing this string is a major platform-compatibility +// hazard. +// +// to-debug-string: func() -> string +// +//go:nosplit +func (self Error) ToDebugString() (result string) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ErrorToDebugString((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:io/error@0.2.0 [method]error.to-debug-string +//go:noescape +func wasmimport_ErrorToDebugString(self0 uint32, result *string) diff --git a/_examples/http-client/gen/wasi/io/poll/empty.s b/_examples/http-client/gen/wasi/io/poll/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/io/poll/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/io/poll/poll.wit.go b/_examples/http-client/gen/wasi/io/poll/poll.wit.go new file mode 100644 index 0000000..d11852f --- /dev/null +++ b/_examples/http-client/gen/wasi/io/poll/poll.wit.go @@ -0,0 +1,108 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package poll represents the imported interface "wasi:io/poll@0.2.0". +// +// A poll API intended to let users wait for I/O events on multiple handles +// at once. +package poll + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// Pollable represents the imported resource "wasi:io/poll@0.2.0#pollable". +// +// `pollable` represents a single I/O event which may be ready, or not. +// +// resource pollable +type Pollable cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "pollable". +// +// Drops a resource handle. +// +//go:nosplit +func (self Pollable) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_PollableResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:io/poll@0.2.0 [resource-drop]pollable +//go:noescape +func wasmimport_PollableResourceDrop(self0 uint32) + +// Block represents the imported method "block". +// +// `block` returns immediately if the pollable is ready, and otherwise +// blocks until ready. +// +// This function is equivalent to calling `poll.poll` on a list +// containing only this pollable. +// +// block: func() +// +//go:nosplit +func (self Pollable) Block() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_PollableBlock((uint32)(self0)) + return +} + +//go:wasmimport wasi:io/poll@0.2.0 [method]pollable.block +//go:noescape +func wasmimport_PollableBlock(self0 uint32) + +// Ready represents the imported method "ready". +// +// Return the readiness of a pollable. This function never blocks. +// +// Returns `true` when the pollable is ready, and `false` otherwise. +// +// ready: func() -> bool +// +//go:nosplit +func (self Pollable) Ready() (result bool) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_PollableReady((uint32)(self0)) + result = cm.U32ToBool((uint32)(result0)) + return +} + +//go:wasmimport wasi:io/poll@0.2.0 [method]pollable.ready +//go:noescape +func wasmimport_PollableReady(self0 uint32) (result0 uint32) + +// Poll represents the imported function "poll". +// +// Poll for completion on a set of pollables. +// +// This function takes a list of pollables, which identify I/O sources of +// interest, and waits until one or more of the events is ready for I/O. +// +// The result `list` contains one or more indices of handles in the +// argument list that is ready for I/O. +// +// If the list contains more elements than can be indexed with a `u32` +// value, this function traps. +// +// A timeout can be implemented by adding a pollable from the +// wasi-clocks API to the list. +// +// This function does not return a `result`; polling in itself does not +// do any I/O so it doesn't fail. If any of the I/O sources identified by +// the pollables has an error, it is indicated by marking the source as +// being reaedy for I/O. +// +// poll: func(in: list>) -> list +// +//go:nosplit +func Poll(in cm.List[Pollable]) (result cm.List[uint32]) { + in0, in1 := cm.LowerList(in) + wasmimport_Poll((*Pollable)(in0), (uint32)(in1), &result) + return +} + +//go:wasmimport wasi:io/poll@0.2.0 poll +//go:noescape +func wasmimport_Poll(in0 *Pollable, in1 uint32, result *cm.List[uint32]) diff --git a/_examples/http-client/gen/wasi/io/streams/abi.go b/_examples/http-client/gen/wasi/io/streams/abi.go new file mode 100644 index 0000000..5f15002 --- /dev/null +++ b/_examples/http-client/gen/wasi/io/streams/abi.go @@ -0,0 +1,12 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package streams + +import ( + "unsafe" +) + +// StreamErrorShape is used for storage in variant or result types. +type StreamErrorShape struct { + shape [unsafe.Sizeof(StreamError{})]byte +} diff --git a/_examples/http-client/gen/wasi/io/streams/empty.s b/_examples/http-client/gen/wasi/io/streams/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/io/streams/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/io/streams/streams.wit.go b/_examples/http-client/gen/wasi/io/streams/streams.wit.go new file mode 100644 index 0000000..2e20407 --- /dev/null +++ b/_examples/http-client/gen/wasi/io/streams/streams.wit.go @@ -0,0 +1,519 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package streams represents the imported interface "wasi:io/streams@0.2.0". +// +// WASI I/O is an I/O abstraction API which is currently focused on providing +// stream types. +// +// In the future, the component model is expected to add built-in stream types; +// when it does, they are expected to subsume this API. +package streams + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + ioerror "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/error" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/poll" +) + +// StreamError represents the imported variant "wasi:io/streams@0.2.0#stream-error". +// +// An error for input-stream and output-stream operations. +// +// variant stream-error { +// last-operation-failed(error), +// closed, +// } +type StreamError cm.Variant[uint8, ioerror.Error, ioerror.Error] + +// StreamErrorLastOperationFailed returns a [StreamError] of case "last-operation-failed". +// +// The last operation (a write or flush) failed before completion. +// +// More information is available in the `error` payload. +func StreamErrorLastOperationFailed(data ioerror.Error) StreamError { + return cm.New[StreamError](0, data) +} + +// LastOperationFailed returns a non-nil *[ioerror.Error] if [StreamError] represents the variant case "last-operation-failed". +func (self *StreamError) LastOperationFailed() *ioerror.Error { + return cm.Case[ioerror.Error](self, 0) +} + +// StreamErrorClosed returns a [StreamError] of case "closed". +// +// The stream is closed: no more input will be accepted by the +// stream. A closed output-stream will return this error on all +// future operations. +func StreamErrorClosed() StreamError { + var data struct{} + return cm.New[StreamError](1, data) +} + +// Closed returns true if [StreamError] represents the variant case "closed". +func (self *StreamError) Closed() bool { + return self.Tag() == 1 +} + +// InputStream represents the imported resource "wasi:io/streams@0.2.0#input-stream". +// +// An input bytestream. +// +// `input-stream`s are *non-blocking* to the extent practical on underlying +// platforms. I/O operations always return promptly; if fewer bytes are +// promptly available than requested, they return the number of bytes promptly +// available, which could even be zero. To wait for data to be available, +// use the `subscribe` function to obtain a `pollable` which can be polled +// for using `wasi:io/poll`. +// +// resource input-stream +type InputStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "input-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self InputStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_InputStreamResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [resource-drop]input-stream +//go:noescape +func wasmimport_InputStreamResourceDrop(self0 uint32) + +// BlockingRead represents the imported method "blocking-read". +// +// Read bytes from a stream, after blocking until at least one byte can +// be read. Except for blocking, behavior is identical to `read`. +// +// blocking-read: func(len: u64) -> result, stream-error> +// +//go:nosplit +func (self InputStream) BlockingRead(len_ uint64) (result cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamBlockingRead((uint32)(self0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.blocking-read +//go:noescape +func wasmimport_InputStreamBlockingRead(self0 uint32, len0 uint64, result *cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) + +// BlockingSkip represents the imported method "blocking-skip". +// +// Skip bytes from a stream, after blocking until at least one byte +// can be skipped. Except for blocking behavior, identical to `skip`. +// +// blocking-skip: func(len: u64) -> result +// +//go:nosplit +func (self InputStream) BlockingSkip(len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamBlockingSkip((uint32)(self0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.blocking-skip +//go:noescape +func wasmimport_InputStreamBlockingSkip(self0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +// Read represents the imported method "read". +// +// Perform a non-blocking read from the stream. +// +// When the source of a `read` is binary data, the bytes from the source +// are returned verbatim. When the source of a `read` is known to the +// implementation to be text, bytes containing the UTF-8 encoding of the +// text are returned. +// +// This function returns a list of bytes containing the read data, +// when successful. The returned list will contain up to `len` bytes; +// it may return fewer than requested, but not more. The list is +// empty when no bytes are available for reading at this time. The +// pollable given by `subscribe` will be ready when more bytes are +// available. +// +// This function fails with a `stream-error` when the operation +// encounters an error, giving `last-operation-failed`, or when the +// stream is closed, giving `closed`. +// +// When the caller gives a `len` of 0, it represents a request to +// read 0 bytes. If the stream is still open, this call should +// succeed and return an empty list, or otherwise fail with `closed`. +// +// The `len` parameter is a `u64`, which could represent a list of u8 which +// is not possible to allocate in wasm32, or not desirable to allocate as +// as a return value by the callee. The callee may return a list of bytes +// less than `len` in size while more bytes are available for reading. +// +// read: func(len: u64) -> result, stream-error> +// +//go:nosplit +func (self InputStream) Read(len_ uint64) (result cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamRead((uint32)(self0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.read +//go:noescape +func wasmimport_InputStreamRead(self0 uint32, len0 uint64, result *cm.Result[cm.List[uint8], cm.List[uint8], StreamError]) + +// Skip represents the imported method "skip". +// +// Skip bytes from a stream. Returns number of bytes skipped. +// +// Behaves identical to `read`, except instead of returning a list +// of bytes, returns the number of bytes consumed from the stream. +// +// skip: func(len: u64) -> result +// +//go:nosplit +func (self InputStream) Skip(len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_InputStreamSkip((uint32)(self0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.skip +//go:noescape +func wasmimport_InputStreamSkip(self0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once either the specified stream +// has bytes available to read or the other end of the stream has been +// closed. +// The created `pollable` is a child resource of the `input-stream`. +// Implementations may trap if the `input-stream` is dropped before +// all derived `pollable`s created with this function are dropped. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self InputStream) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_InputStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]input-stream.subscribe +//go:noescape +func wasmimport_InputStreamSubscribe(self0 uint32) (result0 uint32) + +// OutputStream represents the imported resource "wasi:io/streams@0.2.0#output-stream". +// +// An output bytestream. +// +// `output-stream`s are *non-blocking* to the extent practical on +// underlying platforms. Except where specified otherwise, I/O operations also +// always return promptly, after the number of bytes that can be written +// promptly, which could even be zero. To wait for the stream to be ready to +// accept data, the `subscribe` function to obtain a `pollable` which can be +// polled for using `wasi:io/poll`. +// +// resource output-stream +type OutputStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "output-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutputStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [resource-drop]output-stream +//go:noescape +func wasmimport_OutputStreamResourceDrop(self0 uint32) + +// BlockingFlush represents the imported method "blocking-flush". +// +// Request to flush buffered output, and block until flush completes +// and stream is ready for writing again. +// +// blocking-flush: func() -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) BlockingFlush() (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamBlockingFlush((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-flush +//go:noescape +func wasmimport_OutputStreamBlockingFlush(self0 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +// BlockingSplice represents the imported method "blocking-splice". +// +// Read from one stream and write to another, with blocking. +// +// This is similar to `splice`, except that it blocks until the +// `output-stream` is ready for writing, and the `input-stream` +// is ready for reading, before performing the `splice`. +// +// blocking-splice: func(src: borrow, len: u64) -> result +// +//go:nosplit +func (self OutputStream) BlockingSplice(src InputStream, len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + src0 := cm.Reinterpret[uint32](src) + len0 := (uint64)(len_) + wasmimport_OutputStreamBlockingSplice((uint32)(self0), (uint32)(src0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-splice +//go:noescape +func wasmimport_OutputStreamBlockingSplice(self0 uint32, src0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +// BlockingWriteAndFlush represents the imported method "blocking-write-and-flush". +// +// Perform a write of up to 4096 bytes, and then flush the stream. Block +// until all of these operations are complete, or an error occurs. +// +// This is a convenience wrapper around the use of `check-write`, +// `subscribe`, `write`, and `flush`, and is implemented with the +// following pseudo-code: +// +// let pollable = this.subscribe(); +// while !contents.is_empty() { +// // Wait for the stream to become writable +// pollable.block(); +// let Ok(n) = this.check-write(); // eliding error handling +// let len = min(n, contents.len()); +// let (chunk, rest) = contents.split_at(len); +// this.write(chunk ); // eliding error handling +// contents = rest; +// } +// this.flush(); +// // Wait for completion of `flush` +// pollable.block(); +// // Check for any errors that arose during `flush` +// let _ = this.check-write(); // eliding error handling +// +// blocking-write-and-flush: func(contents: list) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) BlockingWriteAndFlush(contents cm.List[uint8]) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + contents0, contents1 := cm.LowerList(contents) + wasmimport_OutputStreamBlockingWriteAndFlush((uint32)(self0), (*uint8)(contents0), (uint32)(contents1), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-write-and-flush +//go:noescape +func wasmimport_OutputStreamBlockingWriteAndFlush(self0 uint32, contents0 *uint8, contents1 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +// BlockingWriteZeroesAndFlush represents the imported method "blocking-write-zeroes-and-flush". +// +// Perform a write of up to 4096 zeroes, and then flush the stream. +// Block until all of these operations are complete, or an error +// occurs. +// +// This is a convenience wrapper around the use of `check-write`, +// `subscribe`, `write-zeroes`, and `flush`, and is implemented with +// the following pseudo-code: +// +// let pollable = this.subscribe(); +// while num_zeroes != 0 { +// // Wait for the stream to become writable +// pollable.block(); +// let Ok(n) = this.check-write(); // eliding error handling +// let len = min(n, num_zeroes); +// this.write-zeroes(len); // eliding error handling +// num_zeroes -= len; +// } +// this.flush(); +// // Wait for completion of `flush` +// pollable.block(); +// // Check for any errors that arose during `flush` +// let _ = this.check-write(); // eliding error handling +// +// blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) BlockingWriteZeroesAndFlush(len_ uint64) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_OutputStreamBlockingWriteZeroesAndFlush((uint32)(self0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.blocking-write-zeroes-and-flush +//go:noescape +func wasmimport_OutputStreamBlockingWriteZeroesAndFlush(self0 uint32, len0 uint64, result *cm.Result[StreamError, struct{}, StreamError]) + +// CheckWrite represents the imported method "check-write". +// +// Check readiness for writing. This function never blocks. +// +// Returns the number of bytes permitted for the next call to `write`, +// or an error. Calling `write` with more bytes than this function has +// permitted will trap. +// +// When this function returns 0 bytes, the `subscribe` pollable will +// become ready when this function will report at least 1 byte, or an +// error. +// +// check-write: func() -> result +// +//go:nosplit +func (self OutputStream) CheckWrite() (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamCheckWrite((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.check-write +//go:noescape +func wasmimport_OutputStreamCheckWrite(self0 uint32, result *cm.Result[uint64, uint64, StreamError]) + +// Flush represents the imported method "flush". +// +// Request to flush buffered output. This function never blocks. +// +// This tells the output-stream that the caller intends any buffered +// output to be flushed. the output which is expected to be flushed +// is all that has been passed to `write` prior to this call. +// +// Upon calling this function, the `output-stream` will not accept any +// writes (`check-write` will return `ok(0)`) until the flush has +// completed. The `subscribe` pollable will become ready when the +// flush has completed and the stream can accept more writes. +// +// flush: func() -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) Flush() (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutputStreamFlush((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.flush +//go:noescape +func wasmimport_OutputStreamFlush(self0 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +// Splice represents the imported method "splice". +// +// Read from one stream and write to another. +// +// The behavior of splice is equivelant to: +// 1. calling `check-write` on the `output-stream` +// 2. calling `read` on the `input-stream` with the smaller of the +// `check-write` permitted length and the `len` provided to `splice` +// 3. calling `write` on the `output-stream` with that read data. +// +// Any error reported by the call to `check-write`, `read`, or +// `write` ends the splice and reports that error. +// +// This function returns the number of bytes transferred; it may be less +// than `len`. +// +// splice: func(src: borrow, len: u64) -> result +// +//go:nosplit +func (self OutputStream) Splice(src InputStream, len_ uint64) (result cm.Result[uint64, uint64, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + src0 := cm.Reinterpret[uint32](src) + len0 := (uint64)(len_) + wasmimport_OutputStreamSplice((uint32)(self0), (uint32)(src0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.splice +//go:noescape +func wasmimport_OutputStreamSplice(self0 uint32, src0 uint32, len0 uint64, result *cm.Result[uint64, uint64, StreamError]) + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the output-stream +// is ready for more writing, or an error has occured. When this +// pollable is ready, `check-write` will return `ok(n)` with n>0, or an +// error. +// +// If the stream is closed, this pollable is always ready immediately. +// +// The created `pollable` is a child resource of the `output-stream`. +// Implementations may trap if the `output-stream` is dropped before +// all derived `pollable`s created with this function are dropped. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self OutputStream) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutputStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.subscribe +//go:noescape +func wasmimport_OutputStreamSubscribe(self0 uint32) (result0 uint32) + +// Write represents the imported method "write". +// +// Perform a write. This function never blocks. +// +// When the destination of a `write` is binary data, the bytes from +// `contents` are written verbatim. When the destination of a `write` is +// known to the implementation to be text, the bytes of `contents` are +// transcoded from UTF-8 into the encoding of the destination and then +// written. +// +// Precondition: check-write gave permit of Ok(n) and contents has a +// length of less than or equal to n. Otherwise, this function will trap. +// +// returns Err(closed) without writing if the stream has closed since +// the last call to check-write provided a permit. +// +// write: func(contents: list) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) Write(contents cm.List[uint8]) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + contents0, contents1 := cm.LowerList(contents) + wasmimport_OutputStreamWrite((uint32)(self0), (*uint8)(contents0), (uint32)(contents1), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.write +//go:noescape +func wasmimport_OutputStreamWrite(self0 uint32, contents0 *uint8, contents1 uint32, result *cm.Result[StreamError, struct{}, StreamError]) + +// WriteZeroes represents the imported method "write-zeroes". +// +// Write zeroes to a stream. +// +// This should be used precisely like `write` with the exact same +// preconditions (must use check-write first), but instead of +// passing a list of bytes, you simply pass the number of zero-bytes +// that should be written. +// +// write-zeroes: func(len: u64) -> result<_, stream-error> +// +//go:nosplit +func (self OutputStream) WriteZeroes(len_ uint64) (result cm.Result[StreamError, struct{}, StreamError]) { + self0 := cm.Reinterpret[uint32](self) + len0 := (uint64)(len_) + wasmimport_OutputStreamWriteZeroes((uint32)(self0), (uint64)(len0), &result) + return +} + +//go:wasmimport wasi:io/streams@0.2.0 [method]output-stream.write-zeroes +//go:noescape +func wasmimport_OutputStreamWriteZeroes(self0 uint32, len0 uint64, result *cm.Result[StreamError, struct{}, StreamError]) diff --git a/_examples/http-client/gen/wasi/logging/logging/empty.s b/_examples/http-client/gen/wasi/logging/logging/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/logging/logging/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/logging/logging/logging.wit.go b/_examples/http-client/gen/wasi/logging/logging/logging.wit.go new file mode 100644 index 0000000..15b6e95 --- /dev/null +++ b/_examples/http-client/gen/wasi/logging/logging/logging.wit.go @@ -0,0 +1,86 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package logging represents the imported interface "wasi:logging/logging". +// +// WASI Logging is a logging API intended to let users emit log messages with +// simple priority levels and context values. +package logging + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// Level represents the enum "wasi:logging/logging#level". +// +// A log level, describing a kind of message. +// +// enum level { +// trace, +// debug, +// info, +// warn, +// error, +// critical +// } +type Level uint8 + +const ( + // Describes messages about the values of variables and the flow of + // control within a program. + LevelTrace Level = iota + + // Describes messages likely to be of interest to someone debugging a + // program. + LevelDebug + + // Describes messages likely to be of interest to someone monitoring a + // program. + LevelInfo + + // Describes messages indicating hazardous situations. + LevelWarn + + // Describes messages indicating serious errors. + LevelError + + // Describes messages indicating fatal errors. + LevelCritical +) + +var stringsLevel = [6]string{ + "trace", + "debug", + "info", + "warn", + "error", + "critical", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e Level) String() string { + return stringsLevel[e] +} + +// Log represents the imported function "log". +// +// 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) +// +//go:nosplit +func Log(level Level, context string, message string) { + level0 := (uint32)(level) + context0, context1 := cm.LowerString(context) + message0, message1 := cm.LowerString(message) + wasmimport_Log((uint32)(level0), (*uint8)(context0), (uint32)(context1), (*uint8)(message0), (uint32)(message1)) + return +} + +//go:wasmimport wasi:logging/logging log +//go:noescape +func wasmimport_Log(level0 uint32, context0 *uint8, context1 uint32, message0 *uint8, message1 uint32) diff --git a/_examples/http-client/gen/wasi/random/insecure-seed/empty.s b/_examples/http-client/gen/wasi/random/insecure-seed/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/random/insecure-seed/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/random/insecure-seed/insecure-seed.wit.go b/_examples/http-client/gen/wasi/random/insecure-seed/insecure-seed.wit.go new file mode 100644 index 0000000..3b8f33c --- /dev/null +++ b/_examples/http-client/gen/wasi/random/insecure-seed/insecure-seed.wit.go @@ -0,0 +1,41 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package insecureseed represents the imported interface "wasi:random/insecure-seed@0.2.0". +// +// The insecure-seed interface for seeding hash-map DoS resistance. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +package insecureseed + +// InsecureSeed represents the imported function "insecure-seed". +// +// Return a 128-bit value that may contain a pseudo-random value. +// +// The returned value is not required to be computed from a CSPRNG, and may +// even be entirely deterministic. Host implementations are encouraged to +// provide pseudo-random values to any program exposed to +// attacker-controlled content, to enable DoS protection built into many +// languages' hash-map implementations. +// +// This function is intended to only be called once, by a source language +// to initialize Denial Of Service (DoS) protection in its hash-map +// implementation. +// +// # Expected future evolution +// +// This will likely be changed to a value import, to prevent it from being +// called multiple times and potentially used for purposes other than DoS +// protection. +// +// insecure-seed: func() -> tuple +// +//go:nosplit +func InsecureSeed() (result [2]uint64) { + wasmimport_InsecureSeed(&result) + return +} + +//go:wasmimport wasi:random/insecure-seed@0.2.0 insecure-seed +//go:noescape +func wasmimport_InsecureSeed(result *[2]uint64) diff --git a/_examples/http-client/gen/wasi/random/insecure/empty.s b/_examples/http-client/gen/wasi/random/insecure/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/random/insecure/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/random/insecure/insecure.wit.go b/_examples/http-client/gen/wasi/random/insecure/insecure.wit.go new file mode 100644 index 0000000..bfe1e6c --- /dev/null +++ b/_examples/http-client/gen/wasi/random/insecure/insecure.wit.go @@ -0,0 +1,57 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package insecure represents the imported interface "wasi:random/insecure@0.2.0". +// +// The insecure interface for insecure pseudo-random numbers. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +package insecure + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// GetInsecureRandomBytes represents the imported function "get-insecure-random-bytes". +// +// Return `len` insecure pseudo-random bytes. +// +// This function is not cryptographically secure. Do not use it for +// anything related to security. +// +// There are no requirements on the values of the returned bytes, however +// implementations are encouraged to return evenly distributed values with +// a long period. +// +// get-insecure-random-bytes: func(len: u64) -> list +// +//go:nosplit +func GetInsecureRandomBytes(len_ uint64) (result cm.List[uint8]) { + len0 := (uint64)(len_) + wasmimport_GetInsecureRandomBytes((uint64)(len0), &result) + return +} + +//go:wasmimport wasi:random/insecure@0.2.0 get-insecure-random-bytes +//go:noescape +func wasmimport_GetInsecureRandomBytes(len0 uint64, result *cm.List[uint8]) + +// GetInsecureRandomU64 represents the imported function "get-insecure-random-u64". +// +// Return an insecure pseudo-random `u64` value. +// +// This function returns the same type of pseudo-random data as +// `get-insecure-random-bytes`, represented as a `u64`. +// +// get-insecure-random-u64: func() -> u64 +// +//go:nosplit +func GetInsecureRandomU64() (result uint64) { + result0 := wasmimport_GetInsecureRandomU64() + result = (uint64)((uint64)(result0)) + return +} + +//go:wasmimport wasi:random/insecure@0.2.0 get-insecure-random-u64 +//go:noescape +func wasmimport_GetInsecureRandomU64() (result0 uint64) diff --git a/_examples/http-client/gen/wasi/random/random/empty.s b/_examples/http-client/gen/wasi/random/random/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/random/random/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/random/random/random.wit.go b/_examples/http-client/gen/wasi/random/random/random.wit.go new file mode 100644 index 0000000..da2eb57 --- /dev/null +++ b/_examples/http-client/gen/wasi/random/random/random.wit.go @@ -0,0 +1,61 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package random represents the imported interface "wasi:random/random@0.2.0". +// +// WASI Random is a random data API. +// +// It is intended to be portable at least between Unix-family platforms and +// Windows. +package random + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// GetRandomBytes represents the imported function "get-random-bytes". +// +// Return `len` cryptographically-secure random or pseudo-random bytes. +// +// This function must produce data at least as cryptographically secure and +// fast as an adequately seeded cryptographically-secure pseudo-random +// number generator (CSPRNG). It must not block, from the perspective of +// the calling program, under any circumstances, including on the first +// request and on requests for numbers of bytes. The returned data must +// always be unpredictable. +// +// This function must always return fresh data. Deterministic environments +// must omit this function, rather than implementing it with deterministic +// data. +// +// get-random-bytes: func(len: u64) -> list +// +//go:nosplit +func GetRandomBytes(len_ uint64) (result cm.List[uint8]) { + len0 := (uint64)(len_) + wasmimport_GetRandomBytes((uint64)(len0), &result) + return +} + +//go:wasmimport wasi:random/random@0.2.0 get-random-bytes +//go:noescape +func wasmimport_GetRandomBytes(len0 uint64, result *cm.List[uint8]) + +// GetRandomU64 represents the imported function "get-random-u64". +// +// Return a cryptographically-secure random or pseudo-random `u64` value. +// +// This function returns the same type of data as `get-random-bytes`, +// represented as a `u64`. +// +// get-random-u64: func() -> u64 +// +//go:nosplit +func GetRandomU64() (result uint64) { + result0 := wasmimport_GetRandomU64() + result = (uint64)((uint64)(result0)) + return +} + +//go:wasmimport wasi:random/random@0.2.0 get-random-u64 +//go:noescape +func wasmimport_GetRandomU64() (result0 uint64) diff --git a/_examples/http-client/gen/wasi/sockets/instance-network/empty.s b/_examples/http-client/gen/wasi/sockets/instance-network/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/instance-network/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/sockets/instance-network/instance-network.wit.go b/_examples/http-client/gen/wasi/sockets/instance-network/instance-network.wit.go new file mode 100644 index 0000000..91bc794 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/instance-network/instance-network.wit.go @@ -0,0 +1,28 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package instancenetwork represents the imported interface "wasi:sockets/instance-network@0.2.0". +// +// This interface provides a value-export of the default network handle.. +package instancenetwork + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" +) + +// InstanceNetwork represents the imported function "instance-network". +// +// Get a handle to the default network. +// +// instance-network: func() -> network +// +//go:nosplit +func InstanceNetwork() (result network.Network) { + result0 := wasmimport_InstanceNetwork() + result = cm.Reinterpret[network.Network]((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/instance-network@0.2.0 instance-network +//go:noescape +func wasmimport_InstanceNetwork() (result0 uint32) diff --git a/_examples/http-client/gen/wasi/sockets/ip-name-lookup/abi.go b/_examples/http-client/gen/wasi/sockets/ip-name-lookup/abi.go new file mode 100644 index 0000000..fb16670 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/ip-name-lookup/abi.go @@ -0,0 +1,14 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package ipnamelookup + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" + "unsafe" +) + +// OptionIPAddressShape is used for storage in variant or result types. +type OptionIPAddressShape struct { + shape [unsafe.Sizeof(cm.Option[network.IPAddress]{})]byte +} diff --git a/_examples/http-client/gen/wasi/sockets/ip-name-lookup/empty.s b/_examples/http-client/gen/wasi/sockets/ip-name-lookup/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/ip-name-lookup/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go b/_examples/http-client/gen/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go new file mode 100644 index 0000000..af6dbc1 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/ip-name-lookup/ip-name-lookup.wit.go @@ -0,0 +1,121 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package ipnamelookup represents the imported interface "wasi:sockets/ip-name-lookup@0.2.0". +package ipnamelookup + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/poll" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" +) + +// ResolveAddressStream represents the imported resource "wasi:sockets/ip-name-lookup@0.2.0#resolve-address-stream". +// +// resource resolve-address-stream +type ResolveAddressStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "resolve-address-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self ResolveAddressStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ResolveAddressStreamResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [resource-drop]resolve-address-stream +//go:noescape +func wasmimport_ResolveAddressStreamResourceDrop(self0 uint32) + +// ResolveNextAddress represents the imported method "resolve-next-address". +// +// Returns the next address from the resolver. +// +// This function should be called multiple times. On each call, it will +// return the next address in connection order preference. If all +// addresses have been exhausted, this function returns `none`. +// +// This function never returns IPv4-mapped IPv6 addresses. +// +// # Typical errors +// - `name-unresolvable`: Name does not exist or has no suitable associated +// IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) +// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. +// (EAI_AGAIN) +// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. +// (EAI_FAIL) +// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) +// +// resolve-next-address: func() -> result, error-code> +// +//go:nosplit +func (self ResolveAddressStream) ResolveNextAddress() (result cm.Result[OptionIPAddressShape, cm.Option[network.IPAddress], network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_ResolveAddressStreamResolveNextAddress((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [method]resolve-address-stream.resolve-next-address +//go:noescape +func wasmimport_ResolveAddressStreamResolveNextAddress(self0 uint32, result *cm.Result[OptionIPAddressShape, cm.Option[network.IPAddress], network.ErrorCode]) + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the stream is ready for I/O. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self ResolveAddressStream) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_ResolveAddressStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 [method]resolve-address-stream.subscribe +//go:noescape +func wasmimport_ResolveAddressStreamSubscribe(self0 uint32) (result0 uint32) + +// ResolveAddresses represents the imported function "resolve-addresses". +// +// Resolve an internet host name to a list of IP addresses. +// +// Unicode domain names are automatically converted to ASCII using IDNA encoding. +// If the input is an IP address string, the address is parsed and returned +// as-is without making any external requests. +// +// See the wasi-socket proposal README.md for a comparison with getaddrinfo. +// +// This function never blocks. It either immediately fails or immediately +// returns successfully with a `resolve-address-stream` that can be used +// to (asynchronously) fetch the results. +// +// # Typical errors +// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. +// +// # References: +// - +// - +// - +// - +// +// resolve-addresses: func(network: borrow, name: string) -> result +// +//go:nosplit +func ResolveAddresses(network_ network.Network, name string) (result cm.Result[ResolveAddressStream, ResolveAddressStream, network.ErrorCode]) { + network0 := cm.Reinterpret[uint32](network_) + name0, name1 := cm.LowerString(name) + wasmimport_ResolveAddresses((uint32)(network0), (*uint8)(name0), (uint32)(name1), &result) + return +} + +//go:wasmimport wasi:sockets/ip-name-lookup@0.2.0 resolve-addresses +//go:noescape +func wasmimport_ResolveAddresses(network0 uint32, name0 *uint8, name1 uint32, result *cm.Result[ResolveAddressStream, ResolveAddressStream, network.ErrorCode]) diff --git a/_examples/http-client/gen/wasi/sockets/network/abi.go b/_examples/http-client/gen/wasi/sockets/network/abi.go new file mode 100644 index 0000000..54820be --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/network/abi.go @@ -0,0 +1,12 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package network + +import ( + "unsafe" +) + +// IPv6SocketAddressShape is used for storage in variant or result types. +type IPv6SocketAddressShape struct { + shape [unsafe.Sizeof(IPv6SocketAddress{})]byte +} diff --git a/_examples/http-client/gen/wasi/sockets/network/empty.s b/_examples/http-client/gen/wasi/sockets/network/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/network/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/sockets/network/network.wit.go b/_examples/http-client/gen/wasi/sockets/network/network.wit.go new file mode 100644 index 0000000..b18bec9 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/network/network.wit.go @@ -0,0 +1,315 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package network represents the imported interface "wasi:sockets/network@0.2.0". +package network + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// Network represents the imported resource "wasi:sockets/network@0.2.0#network". +// +// An opaque resource that represents access to (a subset of) the network. +// This enables context-based security for networking. +// There is no need for this to map 1:1 to a physical network interface. +// +// resource network +type Network cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "network". +// +// Drops a resource handle. +// +//go:nosplit +func (self Network) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_NetworkResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:sockets/network@0.2.0 [resource-drop]network +//go:noescape +func wasmimport_NetworkResourceDrop(self0 uint32) + +// ErrorCode represents the enum "wasi:sockets/network@0.2.0#error-code". +// +// Error codes. +// +// In theory, every API can return any error code. +// In practice, API's typically only return the errors documented per API +// combined with a couple of errors that are always possible: +// - `unknown` +// - `access-denied` +// - `not-supported` +// - `out-of-memory` +// - `concurrency-conflict` +// +// See each individual API for what the POSIX equivalents are. They sometimes differ +// per API. +// +// enum error-code { +// unknown, +// access-denied, +// not-supported, +// invalid-argument, +// out-of-memory, +// timeout, +// concurrency-conflict, +// not-in-progress, +// would-block, +// invalid-state, +// new-socket-limit, +// address-not-bindable, +// address-in-use, +// remote-unreachable, +// connection-refused, +// connection-reset, +// connection-aborted, +// datagram-too-large, +// name-unresolvable, +// temporary-resolver-failure, +// permanent-resolver-failure +// } +type ErrorCode uint8 + +const ( + // Unknown error + ErrorCodeUnknown ErrorCode = iota + + // Access denied. + // + // POSIX equivalent: EACCES, EPERM + ErrorCodeAccessDenied + + // The operation is not supported. + // + // POSIX equivalent: EOPNOTSUPP + ErrorCodeNotSupported + + // One of the arguments is invalid. + // + // POSIX equivalent: EINVAL + ErrorCodeInvalidArgument + + // Not enough memory to complete the operation. + // + // POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + ErrorCodeOutOfMemory + + // The operation timed out before it could finish completely. + ErrorCodeTimeout + + // This operation is incompatible with another asynchronous operation that is already + // in progress. + // + // POSIX equivalent: EALREADY + ErrorCodeConcurrencyConflict + + // Trying to finish an asynchronous operation that: + // - has not been started yet, or: + // - was already finished by a previous `finish-*` call. + // + // Note: this is scheduled to be removed when `future`s are natively supported. + ErrorCodeNotInProgress + + // The operation has been aborted because it could not be completed immediately. + // + // Note: this is scheduled to be removed when `future`s are natively supported. + ErrorCodeWouldBlock + + // The operation is not valid in the socket's current state. + ErrorCodeInvalidState + + // A new socket resource could not be created because of a system limit. + ErrorCodeNewSocketLimit + + // A bind operation failed because the provided address is not an address that the + // `network` can bind to. + ErrorCodeAddressNotBindable + + // A bind operation failed because the provided address is already in use or because + // there are no ephemeral ports available. + ErrorCodeAddressInUse + + // The remote address is not reachable + ErrorCodeRemoteUnreachable + + // The TCP connection was forcefully rejected + ErrorCodeConnectionRefused + + // The TCP connection was reset. + ErrorCodeConnectionReset + + // A TCP connection was aborted. + ErrorCodeConnectionAborted + + // The size of a datagram sent to a UDP socket exceeded the maximum + // supported size. + ErrorCodeDatagramTooLarge + + // Name does not exist or has no suitable associated IP addresses. + ErrorCodeNameUnresolvable + + // A temporary failure in name resolution occurred. + ErrorCodeTemporaryResolverFailure + + // A permanent failure in name resolution occurred. + ErrorCodePermanentResolverFailure +) + +var stringsErrorCode = [21]string{ + "unknown", + "access-denied", + "not-supported", + "invalid-argument", + "out-of-memory", + "timeout", + "concurrency-conflict", + "not-in-progress", + "would-block", + "invalid-state", + "new-socket-limit", + "address-not-bindable", + "address-in-use", + "remote-unreachable", + "connection-refused", + "connection-reset", + "connection-aborted", + "datagram-too-large", + "name-unresolvable", + "temporary-resolver-failure", + "permanent-resolver-failure", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e ErrorCode) String() string { + return stringsErrorCode[e] +} + +// IPAddressFamily represents the enum "wasi:sockets/network@0.2.0#ip-address-family". +// +// enum ip-address-family { +// ipv4, +// ipv6 +// } +type IPAddressFamily uint8 + +const ( + // Similar to `AF_INET` in POSIX. + IPAddressFamilyIPv4 IPAddressFamily = iota + + // Similar to `AF_INET6` in POSIX. + IPAddressFamilyIPv6 +) + +var stringsIPAddressFamily = [2]string{ + "ipv4", + "ipv6", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e IPAddressFamily) String() string { + return stringsIPAddressFamily[e] +} + +// IPv4Address represents the tuple "wasi:sockets/network@0.2.0#ipv4-address". +// +// type ipv4-address = tuple +type IPv4Address [4]uint8 + +// IPv6Address represents the tuple "wasi:sockets/network@0.2.0#ipv6-address". +// +// type ipv6-address = tuple +type IPv6Address [8]uint16 + +// IPAddress represents the variant "wasi:sockets/network@0.2.0#ip-address". +// +// variant ip-address { +// ipv4(ipv4-address), +// ipv6(ipv6-address), +// } +type IPAddress cm.Variant[uint8, IPv6Address, IPv6Address] + +// IPAddressIPv4 returns a [IPAddress] of case "ipv4". +func IPAddressIPv4(data IPv4Address) IPAddress { + return cm.New[IPAddress](0, data) +} + +// IPv4 returns a non-nil *[IPv4Address] if [IPAddress] represents the variant case "ipv4". +func (self *IPAddress) IPv4() *IPv4Address { + return cm.Case[IPv4Address](self, 0) +} + +// IPAddressIPv6 returns a [IPAddress] of case "ipv6". +func IPAddressIPv6(data IPv6Address) IPAddress { + return cm.New[IPAddress](1, data) +} + +// IPv6 returns a non-nil *[IPv6Address] if [IPAddress] represents the variant case "ipv6". +func (self *IPAddress) IPv6() *IPv6Address { + return cm.Case[IPv6Address](self, 1) +} + +// IPv4SocketAddress represents the record "wasi:sockets/network@0.2.0#ipv4-socket-address". +// +// record ipv4-socket-address { +// port: u16, +// address: ipv4-address, +// } +type IPv4SocketAddress struct { + // sin_port + Port uint16 + + // sin_addr + Address IPv4Address +} + +// IPv6SocketAddress represents the record "wasi:sockets/network@0.2.0#ipv6-socket-address". +// +// record ipv6-socket-address { +// port: u16, +// flow-info: u32, +// address: ipv6-address, +// scope-id: u32, +// } +type IPv6SocketAddress struct { + // sin6_port + Port uint16 + + // sin6_flowinfo + FlowInfo uint32 + + // sin6_addr + Address IPv6Address + + // sin6_scope_id + ScopeID uint32 +} + +// IPSocketAddress represents the variant "wasi:sockets/network@0.2.0#ip-socket-address". +// +// variant ip-socket-address { +// ipv4(ipv4-socket-address), +// ipv6(ipv6-socket-address), +// } +type IPSocketAddress cm.Variant[uint8, IPv6SocketAddressShape, IPv6SocketAddress] + +// IPSocketAddressIPv4 returns a [IPSocketAddress] of case "ipv4". +func IPSocketAddressIPv4(data IPv4SocketAddress) IPSocketAddress { + return cm.New[IPSocketAddress](0, data) +} + +// IPv4 returns a non-nil *[IPv4SocketAddress] if [IPSocketAddress] represents the variant case "ipv4". +func (self *IPSocketAddress) IPv4() *IPv4SocketAddress { + return cm.Case[IPv4SocketAddress](self, 0) +} + +// IPSocketAddressIPv6 returns a [IPSocketAddress] of case "ipv6". +func IPSocketAddressIPv6(data IPv6SocketAddress) IPSocketAddress { + return cm.New[IPSocketAddress](1, data) +} + +// IPv6 returns a non-nil *[IPv6SocketAddress] if [IPSocketAddress] represents the variant case "ipv6". +func (self *IPSocketAddress) IPv6() *IPv6SocketAddress { + return cm.Case[IPv6SocketAddress](self, 1) +} diff --git a/_examples/http-client/gen/wasi/sockets/tcp-create-socket/empty.s b/_examples/http-client/gen/wasi/sockets/tcp-create-socket/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/tcp-create-socket/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go b/_examples/http-client/gen/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go new file mode 100644 index 0000000..c1f18c8 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/tcp-create-socket/tcp-create-socket.wit.go @@ -0,0 +1,52 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package tcpcreatesocket represents the imported interface "wasi:sockets/tcp-create-socket@0.2.0". +package tcpcreatesocket + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/tcp" +) + +// CreateTCPSocket represents the imported function "create-tcp-socket". +// +// Create a new TCP socket. +// +// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. +// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. +// +// This function does not require a network capability handle. This is considered +// to be safe because +// at time of creation, the socket is not bound to any `network` yet. Up to the moment +// `bind`/`connect` +// is called, the socket is effectively an in-memory configuration object, unable +// to communicate with the outside world. +// +// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous +// operations. +// +// # Typical errors +// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) +// - `new-socket-limit`: The new socket resource could not be created because of +// a system limit. (EMFILE, ENFILE) +// +// # References +// - +// - +// - +// - +// +// create-tcp-socket: func(address-family: ip-address-family) -> result +// +//go:nosplit +func CreateTCPSocket(addressFamily network.IPAddressFamily) (result cm.Result[tcp.TCPSocket, tcp.TCPSocket, network.ErrorCode]) { + addressFamily0 := (uint32)(addressFamily) + wasmimport_CreateTCPSocket((uint32)(addressFamily0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp-create-socket@0.2.0 create-tcp-socket +//go:noescape +func wasmimport_CreateTCPSocket(addressFamily0 uint32, result *cm.Result[tcp.TCPSocket, tcp.TCPSocket, network.ErrorCode]) diff --git a/_examples/http-client/gen/wasi/sockets/tcp/abi.go b/_examples/http-client/gen/wasi/sockets/tcp/abi.go new file mode 100644 index 0000000..d78cb6c --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/tcp/abi.go @@ -0,0 +1,86 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package tcp + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/streams" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" + "unsafe" +) + +// TupleTCPSocketInputStreamOutputStreamShape is used for storage in variant or result types. +type TupleTCPSocketInputStreamOutputStreamShape struct { + shape [unsafe.Sizeof(cm.Tuple3[TCPSocket, streams.InputStream, streams.OutputStream]{})]byte +} + +// TupleInputStreamOutputStreamShape is used for storage in variant or result types. +type TupleInputStreamOutputStreamShape struct { + shape [unsafe.Sizeof(cm.Tuple[streams.InputStream, streams.OutputStream]{})]byte +} + +// IPSocketAddressShape is used for storage in variant or result types. +type IPSocketAddressShape struct { + shape [unsafe.Sizeof(network.IPSocketAddress{})]byte +} + +func lower_IPv4Address(v network.IPv4Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + return +} + +func lower_IPv4SocketAddress(v network.IPv4SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32) { + f0 = (uint32)(v.Port) + f1, f2, f3, f4 = lower_IPv4Address(v.Address) + return +} + +func lower_IPv6Address(v network.IPv6Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + f4 = (uint32)(v[4]) + f5 = (uint32)(v[5]) + f6 = (uint32)(v[6]) + f7 = (uint32)(v[7]) + return +} + +func lower_IPv6SocketAddress(v network.IPv6SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32) { + f0 = (uint32)(v.Port) + f1 = (uint32)(v.FlowInfo) + f2, f3, f4, f5, f6, f7, f8, f9 = lower_IPv6Address(v.Address) + f10 = (uint32)(v.ScopeID) + return +} + +func lower_IPSocketAddress(v network.IPSocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 0: // ipv4 + v1, v2, v3, v4, v5 := lower_IPv4SocketAddress(*v.IPv4()) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 1: // ipv6 + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 := lower_IPv6SocketAddress(*v.IPv6()) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + f8 = (uint32)(v8) + f9 = (uint32)(v9) + f10 = (uint32)(v10) + f11 = (uint32)(v11) + } + return +} diff --git a/_examples/http-client/gen/wasi/sockets/tcp/empty.s b/_examples/http-client/gen/wasi/sockets/tcp/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/tcp/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/sockets/tcp/tcp.wit.go b/_examples/http-client/gen/wasi/sockets/tcp/tcp.wit.go new file mode 100644 index 0000000..a70a28c --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/tcp/tcp.wit.go @@ -0,0 +1,848 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package tcp represents the imported interface "wasi:sockets/tcp@0.2.0". +package tcp + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + monotonicclock "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/clocks/monotonic-clock" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/poll" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/streams" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" +) + +// ShutdownType represents the enum "wasi:sockets/tcp@0.2.0#shutdown-type". +// +// enum shutdown-type { +// receive, +// send, +// both +// } +type ShutdownType uint8 + +const ( + // Similar to `SHUT_RD` in POSIX. + ShutdownTypeReceive ShutdownType = iota + + // Similar to `SHUT_WR` in POSIX. + ShutdownTypeSend + + // Similar to `SHUT_RDWR` in POSIX. + ShutdownTypeBoth +) + +var stringsShutdownType = [3]string{ + "receive", + "send", + "both", +} + +// String implements [fmt.Stringer], returning the enum case name of e. +func (e ShutdownType) String() string { + return stringsShutdownType[e] +} + +// TCPSocket represents the imported resource "wasi:sockets/tcp@0.2.0#tcp-socket". +// +// A TCP socket resource. +// +// The socket can be in one of the following states: +// - `unbound` +// - `bind-in-progress` +// - `bound` (See note below) +// - `listen-in-progress` +// - `listening` +// - `connect-in-progress` +// - `connected` +// - `closed` +// See +// for a more information. +// +// Note: Except where explicitly mentioned, whenever this documentation uses +// the term "bound" without backticks it actually means: in the `bound` state *or +// higher*. +// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) +// +// In addition to the general error codes documented on the +// `network::error-code` type, TCP socket methods may always return +// `error(invalid-state)` when in the `closed` state. +// +// resource tcp-socket +type TCPSocket cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "tcp-socket". +// +// Drops a resource handle. +// +//go:nosplit +func (self TCPSocket) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [resource-drop]tcp-socket +//go:noescape +func wasmimport_TCPSocketResourceDrop(self0 uint32) + +// Accept represents the imported method "accept". +// +// Accept a new client socket. +// +// The returned socket is bound and in the `connected` state. The following properties +// are inherited from the listener socket: +// - `address-family` +// - `keep-alive-enabled` +// - `keep-alive-idle-time` +// - `keep-alive-interval` +// - `keep-alive-count` +// - `hop-limit` +// - `receive-buffer-size` +// - `send-buffer-size` +// +// On success, this function returns the newly accepted client socket along with +// a pair of streams that can be used to read & write to the connection. +// +// # Typical errors +// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) +// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) +// - `connection-aborted`: An incoming connection was pending, but was terminated +// by the client before this listener could accept it. (ECONNABORTED) +// - `new-socket-limit`: The new socket resource could not be created because of +// a system limit. (EMFILE, ENFILE) +// +// # References +// - +// - +// - +// - +// +// accept: func() -> result, error-code> +// +//go:nosplit +func (self TCPSocket) Accept() (result cm.Result[TupleTCPSocketInputStreamOutputStreamShape, cm.Tuple3[TCPSocket, streams.InputStream, streams.OutputStream], network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketAccept((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.accept +//go:noescape +func wasmimport_TCPSocketAccept(self0 uint32, result *cm.Result[TupleTCPSocketInputStreamOutputStreamShape, cm.Tuple3[TCPSocket, streams.InputStream, streams.OutputStream], network.ErrorCode]) + +// AddressFamily represents the imported method "address-family". +// +// Whether this is a IPv4 or IPv6 socket. +// +// Equivalent to the SO_DOMAIN socket option. +// +// address-family: func() -> ip-address-family +// +//go:nosplit +func (self TCPSocket) AddressFamily() (result network.IPAddressFamily) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_TCPSocketAddressFamily((uint32)(self0)) + result = (network.IPAddressFamily)((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.address-family +//go:noescape +func wasmimport_TCPSocketAddressFamily(self0 uint32) (result0 uint32) + +// FinishBind represents the imported method "finish-bind". +// +// finish-bind: func() -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) FinishBind() (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketFinishBind((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-bind +//go:noescape +func wasmimport_TCPSocketFinishBind(self0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// FinishConnect represents the imported method "finish-connect". +// +// finish-connect: func() -> result, error-code> +// +//go:nosplit +func (self TCPSocket) FinishConnect() (result cm.Result[TupleInputStreamOutputStreamShape, cm.Tuple[streams.InputStream, streams.OutputStream], network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketFinishConnect((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-connect +//go:noescape +func wasmimport_TCPSocketFinishConnect(self0 uint32, result *cm.Result[TupleInputStreamOutputStreamShape, cm.Tuple[streams.InputStream, streams.OutputStream], network.ErrorCode]) + +// FinishListen represents the imported method "finish-listen". +// +// finish-listen: func() -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) FinishListen() (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketFinishListen((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.finish-listen +//go:noescape +func wasmimport_TCPSocketFinishListen(self0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// HopLimit represents the imported method "hop-limit". +// +// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// +// # Typical errors +// - `invalid-argument`: (set) The TTL value must be 1 or higher. +// +// hop-limit: func() -> result +// +//go:nosplit +func (self TCPSocket) HopLimit() (result cm.Result[uint8, uint8, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketHopLimit((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.hop-limit +//go:noescape +func wasmimport_TCPSocketHopLimit(self0 uint32, result *cm.Result[uint8, uint8, network.ErrorCode]) + +// IsListening represents the imported method "is-listening". +// +// Whether the socket is in the `listening` state. +// +// Equivalent to the SO_ACCEPTCONN socket option. +// +// is-listening: func() -> bool +// +//go:nosplit +func (self TCPSocket) IsListening() (result bool) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_TCPSocketIsListening((uint32)(self0)) + result = cm.U32ToBool((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.is-listening +//go:noescape +func wasmimport_TCPSocketIsListening(self0 uint32) (result0 uint32) + +// KeepAliveCount represents the imported method "keep-alive-count". +// +// The maximum amount of keepalive packets TCP should send before aborting the connection. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the TCP_KEEPCNT socket option. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// keep-alive-count: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveCount() (result cm.Result[uint32, uint32, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveCount((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-count +//go:noescape +func wasmimport_TCPSocketKeepAliveCount(self0 uint32, result *cm.Result[uint32, uint32, network.ErrorCode]) + +// KeepAliveEnabled represents the imported method "keep-alive-enabled". +// +// Enables or disables keepalive. +// +// The keepalive behavior can be adjusted using: +// - `keep-alive-idle-time` +// - `keep-alive-interval` +// - `keep-alive-count` +// These properties can be configured while `keep-alive-enabled` is false, but only +// come into effect when `keep-alive-enabled` is true. +// +// Equivalent to the SO_KEEPALIVE socket option. +// +// keep-alive-enabled: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveEnabled() (result cm.Result[bool, bool, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveEnabled((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-enabled +//go:noescape +func wasmimport_TCPSocketKeepAliveEnabled(self0 uint32, result *cm.Result[bool, bool, network.ErrorCode]) + +// KeepAliveIdleTime represents the imported method "keep-alive-idle-time". +// +// Amount of time the connection has to be idle before TCP starts sending keepalive +// packets. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// keep-alive-idle-time: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveIdleTime() (result cm.Result[uint64, monotonicclock.Duration, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveIdleTime((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-idle-time +//go:noescape +func wasmimport_TCPSocketKeepAliveIdleTime(self0 uint32, result *cm.Result[uint64, monotonicclock.Duration, network.ErrorCode]) + +// KeepAliveInterval represents the imported method "keep-alive-interval". +// +// The time between keepalive packets. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the TCP_KEEPINTVL socket option. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// keep-alive-interval: func() -> result +// +//go:nosplit +func (self TCPSocket) KeepAliveInterval() (result cm.Result[uint64, monotonicclock.Duration, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketKeepAliveInterval((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.keep-alive-interval +//go:noescape +func wasmimport_TCPSocketKeepAliveInterval(self0 uint32, result *cm.Result[uint64, monotonicclock.Duration, network.ErrorCode]) + +// LocalAddress represents the imported method "local-address". +// +// Get the bound local address. +// +// POSIX mentions: +// > If the socket has not been bound to a local name, the value +// > stored in the object pointed to by `address` is unspecified. +// +// WASI is stricter and requires `local-address` to return `invalid-state` when the +// socket hasn't been bound yet. +// +// # Typical errors +// - `invalid-state`: The socket is not bound to any local address. +// +// # References +// - +// - +// - +// - +// +// local-address: func() -> result +// +//go:nosplit +func (self TCPSocket) LocalAddress() (result cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketLocalAddress((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.local-address +//go:noescape +func wasmimport_TCPSocketLocalAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) + +// ReceiveBufferSize represents the imported method "receive-buffer-size". +// +// The kernel buffer space reserved for sends/receives on this socket. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// receive-buffer-size: func() -> result +// +//go:nosplit +func (self TCPSocket) ReceiveBufferSize() (result cm.Result[uint64, uint64, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketReceiveBufferSize((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.receive-buffer-size +//go:noescape +func wasmimport_TCPSocketReceiveBufferSize(self0 uint32, result *cm.Result[uint64, uint64, network.ErrorCode]) + +// RemoteAddress represents the imported method "remote-address". +// +// Get the remote address. +// +// # Typical errors +// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) +// +// # References +// - +// - +// - +// - +// +// remote-address: func() -> result +// +//go:nosplit +func (self TCPSocket) RemoteAddress() (result cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketRemoteAddress((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.remote-address +//go:noescape +func wasmimport_TCPSocketRemoteAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) + +// SendBufferSize represents the imported method "send-buffer-size". +// +// send-buffer-size: func() -> result +// +//go:nosplit +func (self TCPSocket) SendBufferSize() (result cm.Result[uint64, uint64, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketSendBufferSize((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.send-buffer-size +//go:noescape +func wasmimport_TCPSocketSendBufferSize(self0 uint32, result *cm.Result[uint64, uint64, network.ErrorCode]) + +// SetHopLimit represents the imported method "set-hop-limit". +// +// set-hop-limit: func(value: u8) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetHopLimit(value uint8) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint32)(value) + wasmimport_TCPSocketSetHopLimit((uint32)(self0), (uint32)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-hop-limit +//go:noescape +func wasmimport_TCPSocketSetHopLimit(self0 uint32, value0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetKeepAliveCount represents the imported method "set-keep-alive-count". +// +// set-keep-alive-count: func(value: u32) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveCount(value uint32) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint32)(value) + wasmimport_TCPSocketSetKeepAliveCount((uint32)(self0), (uint32)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-count +//go:noescape +func wasmimport_TCPSocketSetKeepAliveCount(self0 uint32, value0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetKeepAliveEnabled represents the imported method "set-keep-alive-enabled". +// +// set-keep-alive-enabled: func(value: bool) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveEnabled(value bool) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := cm.BoolToU32(value) + wasmimport_TCPSocketSetKeepAliveEnabled((uint32)(self0), (uint32)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-enabled +//go:noescape +func wasmimport_TCPSocketSetKeepAliveEnabled(self0 uint32, value0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetKeepAliveIdleTime represents the imported method "set-keep-alive-idle-time". +// +// set-keep-alive-idle-time: func(value: duration) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveIdleTime(value monotonicclock.Duration) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetKeepAliveIdleTime((uint32)(self0), (uint64)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-idle-time +//go:noescape +func wasmimport_TCPSocketSetKeepAliveIdleTime(self0 uint32, value0 uint64, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetKeepAliveInterval represents the imported method "set-keep-alive-interval". +// +// set-keep-alive-interval: func(value: duration) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetKeepAliveInterval(value monotonicclock.Duration) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetKeepAliveInterval((uint32)(self0), (uint64)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-keep-alive-interval +//go:noescape +func wasmimport_TCPSocketSetKeepAliveInterval(self0 uint32, value0 uint64, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetListenBacklogSize represents the imported method "set-listen-backlog-size". +// +// Hints the desired listen queue size. Implementations are free to ignore this. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// +// # Typical errors +// - `not-supported`: (set) The platform does not support changing the backlog +// size after the initial listen. +// - `invalid-argument`: (set) The provided value was 0. +// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` +// state. +// +// set-listen-backlog-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetListenBacklogSize(value uint64) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetListenBacklogSize((uint32)(self0), (uint64)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-listen-backlog-size +//go:noescape +func wasmimport_TCPSocketSetListenBacklogSize(self0 uint32, value0 uint64, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetReceiveBufferSize represents the imported method "set-receive-buffer-size". +// +// set-receive-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetReceiveBufferSize(value uint64) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetReceiveBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-receive-buffer-size +//go:noescape +func wasmimport_TCPSocketSetReceiveBufferSize(self0 uint32, value0 uint64, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetSendBufferSize represents the imported method "set-send-buffer-size". +// +// set-send-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) SetSendBufferSize(value uint64) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_TCPSocketSetSendBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.set-send-buffer-size +//go:noescape +func wasmimport_TCPSocketSetSendBufferSize(self0 uint32, value0 uint64, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// Shutdown represents the imported method "shutdown". +// +// Initiate a graceful shutdown. +// +// - `receive`: The socket is not expecting to receive any data from +// the peer. The `input-stream` associated with this socket will be +// closed. Any data still in the receive queue at time of calling +// this method will be discarded. +// - `send`: The socket has no more data to send to the peer. The `output-stream` +// associated with this socket will be closed and a FIN packet will be sent. +// - `both`: Same effect as `receive` & `send` combined. +// +// This function is idempotent. Shutting a down a direction more than once +// has no effect and returns `ok`. +// +// The shutdown function does not close (drop) the socket. +// +// # Typical errors +// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) +// +// # References +// - +// - +// - +// - +// +// shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) Shutdown(shutdownType ShutdownType) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + shutdownType0 := (uint32)(shutdownType) + wasmimport_TCPSocketShutdown((uint32)(self0), (uint32)(shutdownType0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.shutdown +//go:noescape +func wasmimport_TCPSocketShutdown(self0 uint32, shutdownType0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// StartBind represents the imported method "start-bind". +// +// Bind the socket to a specific network on the provided IP address and port. +// +// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the +// implementation to decide which +// network interface(s) to bind to. +// If the TCP/UDP port is zero, the socket will be bound to a random free port. +// +// Bind can be attempted multiple times on the same socket, even with +// different arguments on each iteration. But never concurrently and +// only as long as the previous bind failed. Once a bind succeeds, the +// binding can't be changed anymore. +// +// # Typical errors +// - `invalid-argument`: The `local-address` has the wrong address family. +// (EAFNOSUPPORT, EFAULT on Windows) +// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) +// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. +// (EINVAL) +// - `invalid-state`: The socket is already bound. (EINVAL) +// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS +// on Windows) +// - `address-in-use`: Address is already in use. (EADDRINUSE) +// - `address-not-bindable`: `local-address` is not an address that the `network` +// can bind to. (EADDRNOTAVAIL) +// - `not-in-progress`: A `bind` operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// When binding to a non-zero port, this bind operation shouldn't be affected by the +// TIME_WAIT +// state of a recently closed socket on the same local address. In practice this means +// that the SO_REUSEADDR +// socket option should be set implicitly on all platforms, except on Windows where +// this is the default behavior +// and SO_REUSEADDR performs something different entirely. +// +// Unlike in POSIX, in WASI the bind operation is async. This enables +// interactive WASI hosts to inject permission prompts. Runtimes that +// don't want to make use of this ability can simply call the native +// `bind` as part of either `start-bind` or `finish-bind`. +// +// # References +// - +// - +// - +// - +// +// start-bind: func(network: borrow, local-address: ip-socket-address) -> +// result<_, error-code> +// +//go:nosplit +func (self TCPSocket) StartBind(network_ network.Network, localAddress network.IPSocketAddress) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + network0 := cm.Reinterpret[uint32](network_) + localAddress0, localAddress1, localAddress2, localAddress3, localAddress4, localAddress5, localAddress6, localAddress7, localAddress8, localAddress9, localAddress10, localAddress11 := lower_IPSocketAddress(localAddress) + wasmimport_TCPSocketStartBind((uint32)(self0), (uint32)(network0), (uint32)(localAddress0), (uint32)(localAddress1), (uint32)(localAddress2), (uint32)(localAddress3), (uint32)(localAddress4), (uint32)(localAddress5), (uint32)(localAddress6), (uint32)(localAddress7), (uint32)(localAddress8), (uint32)(localAddress9), (uint32)(localAddress10), (uint32)(localAddress11), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-bind +//go:noescape +func wasmimport_TCPSocketStartBind(self0 uint32, network0 uint32, localAddress0 uint32, localAddress1 uint32, localAddress2 uint32, localAddress3 uint32, localAddress4 uint32, localAddress5 uint32, localAddress6 uint32, localAddress7 uint32, localAddress8 uint32, localAddress9 uint32, localAddress10 uint32, localAddress11 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// StartConnect represents the imported method "start-connect". +// +// Connect to a remote endpoint. +// +// On success: +// - the socket is transitioned into the `connection` state. +// - a pair of streams is returned that can be used to read & write to the connection +// +// After a failed connection attempt, the socket will be in the `closed` +// state and the only valid action left is to `drop` the socket. A single +// socket can not be used to connect more than once. +// +// # Typical errors +// - `invalid-argument`: The `remote-address` has the wrong address family. +// (EAFNOSUPPORT) +// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, +// ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) +// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. +// (EINVAL, EADDRNOTAVAIL on Illumos) +// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY +// (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) +// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL +// on Windows) +// - `invalid-argument`: The socket is already attached to a different network. +// The `network` passed to `connect` must be identical to the one passed to `bind`. +// - `invalid-state`: The socket is already in the `connected` state. +// (EISCONN) +// - `invalid-state`: The socket is already in the `listening` state. +// (EOPNOTSUPP, EINVAL on Windows) +// - `timeout`: Connection timed out. (ETIMEDOUT) +// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) +// - `connection-reset`: The connection was reset. (ECONNRESET) +// - `connection-aborted`: The connection was aborted. (ECONNABORTED) +// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, +// EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `address-in-use`: Tried to perform an implicit bind, but there were +// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) +// - `not-in-progress`: A connect operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// The POSIX equivalent of `start-connect` is the regular `connect` syscall. +// Because all WASI sockets are non-blocking this is expected to return +// EINPROGRESS, which should be translated to `ok()` in WASI. +// +// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` +// with a timeout of 0 on the socket descriptor. Followed by a check for +// the `SO_ERROR` socket option, in case the poll signaled readiness. +// +// # References +// - +// - +// - +// - +// +// start-connect: func(network: borrow, remote-address: ip-socket-address) +// -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) StartConnect(network_ network.Network, remoteAddress network.IPSocketAddress) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + network0 := cm.Reinterpret[uint32](network_) + remoteAddress0, remoteAddress1, remoteAddress2, remoteAddress3, remoteAddress4, remoteAddress5, remoteAddress6, remoteAddress7, remoteAddress8, remoteAddress9, remoteAddress10, remoteAddress11 := lower_IPSocketAddress(remoteAddress) + wasmimport_TCPSocketStartConnect((uint32)(self0), (uint32)(network0), (uint32)(remoteAddress0), (uint32)(remoteAddress1), (uint32)(remoteAddress2), (uint32)(remoteAddress3), (uint32)(remoteAddress4), (uint32)(remoteAddress5), (uint32)(remoteAddress6), (uint32)(remoteAddress7), (uint32)(remoteAddress8), (uint32)(remoteAddress9), (uint32)(remoteAddress10), (uint32)(remoteAddress11), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-connect +//go:noescape +func wasmimport_TCPSocketStartConnect(self0 uint32, network0 uint32, remoteAddress0 uint32, remoteAddress1 uint32, remoteAddress2 uint32, remoteAddress3 uint32, remoteAddress4 uint32, remoteAddress5 uint32, remoteAddress6 uint32, remoteAddress7 uint32, remoteAddress8 uint32, remoteAddress9 uint32, remoteAddress10 uint32, remoteAddress11 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// StartListen represents the imported method "start-listen". +// +// Start listening for new connections. +// +// Transitions the socket into the `listening` state. +// +// Unlike POSIX, the socket must already be explicitly bound. +// +// # Typical errors +// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) +// - `invalid-state`: The socket is already in the `connected` state. +// (EISCONN, EINVAL on BSD) +// - `invalid-state`: The socket is already in the `listening` state. +// - `address-in-use`: Tried to perform an implicit bind, but there were +// no ephemeral ports available. (EADDRINUSE) +// - `not-in-progress`: A listen operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// Unlike in POSIX, in WASI the listen operation is async. This enables +// interactive WASI hosts to inject permission prompts. Runtimes that +// don't want to make use of this ability can simply call the native +// `listen` as part of either `start-listen` or `finish-listen`. +// +// # References +// - +// - +// - +// - +// +// start-listen: func() -> result<_, error-code> +// +//go:nosplit +func (self TCPSocket) StartListen() (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_TCPSocketStartListen((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.start-listen +//go:noescape +func wasmimport_TCPSocketStartListen(self0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which can be used to poll for, or block on, +// completion of any of the asynchronous operations of this socket. +// +// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` +// return `error(would-block)`, this pollable can be used to wait for +// their success or failure, after which the method can be retried. +// +// The pollable is not limited to the async operation that happens to be +// in progress at the time of calling `subscribe` (if any). Theoretically, +// `subscribe` only has to be called once per socket and can then be +// (re)used for the remainder of the socket's lifetime. +// +// See +// for a more information. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self TCPSocket) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_TCPSocketSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/tcp@0.2.0 [method]tcp-socket.subscribe +//go:noescape +func wasmimport_TCPSocketSubscribe(self0 uint32) (result0 uint32) diff --git a/_examples/http-client/gen/wasi/sockets/udp-create-socket/empty.s b/_examples/http-client/gen/wasi/sockets/udp-create-socket/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/udp-create-socket/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/sockets/udp-create-socket/udp-create-socket.wit.go b/_examples/http-client/gen/wasi/sockets/udp-create-socket/udp-create-socket.wit.go new file mode 100644 index 0000000..e77481b --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/udp-create-socket/udp-create-socket.wit.go @@ -0,0 +1,52 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package udpcreatesocket represents the imported interface "wasi:sockets/udp-create-socket@0.2.0". +package udpcreatesocket + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/udp" +) + +// CreateUDPSocket represents the imported function "create-udp-socket". +// +// Create a new UDP socket. +// +// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. +// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. +// +// This function does not require a network capability handle. This is considered +// to be safe because +// at time of creation, the socket is not bound to any `network` yet. Up to the moment +// `bind` is called, +// the socket is effectively an in-memory configuration object, unable to communicate +// with the outside world. +// +// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous +// operations. +// +// # Typical errors +// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) +// - `new-socket-limit`: The new socket resource could not be created because of +// a system limit. (EMFILE, ENFILE) +// +// # References: +// - +// - +// - +// - +// +// create-udp-socket: func(address-family: ip-address-family) -> result +// +//go:nosplit +func CreateUDPSocket(addressFamily network.IPAddressFamily) (result cm.Result[udp.UDPSocket, udp.UDPSocket, network.ErrorCode]) { + addressFamily0 := (uint32)(addressFamily) + wasmimport_CreateUDPSocket((uint32)(addressFamily0), &result) + return +} + +//go:wasmimport wasi:sockets/udp-create-socket@0.2.0 create-udp-socket +//go:noescape +func wasmimport_CreateUDPSocket(addressFamily0 uint32, result *cm.Result[udp.UDPSocket, udp.UDPSocket, network.ErrorCode]) diff --git a/_examples/http-client/gen/wasi/sockets/udp/abi.go b/_examples/http-client/gen/wasi/sockets/udp/abi.go new file mode 100644 index 0000000..27dc815 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/udp/abi.go @@ -0,0 +1,101 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package udp + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" + "unsafe" +) + +// IPSocketAddressShape is used for storage in variant or result types. +type IPSocketAddressShape struct { + shape [unsafe.Sizeof(network.IPSocketAddress{})]byte +} + +func lower_IPv4Address(v network.IPv4Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + return +} + +func lower_IPv4SocketAddress(v network.IPv4SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32) { + f0 = (uint32)(v.Port) + f1, f2, f3, f4 = lower_IPv4Address(v.Address) + return +} + +func lower_IPv6Address(v network.IPv6Address) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32) { + f0 = (uint32)(v[0]) + f1 = (uint32)(v[1]) + f2 = (uint32)(v[2]) + f3 = (uint32)(v[3]) + f4 = (uint32)(v[4]) + f5 = (uint32)(v[5]) + f6 = (uint32)(v[6]) + f7 = (uint32)(v[7]) + return +} + +func lower_IPv6SocketAddress(v network.IPv6SocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32) { + f0 = (uint32)(v.Port) + f1 = (uint32)(v.FlowInfo) + f2, f3, f4, f5, f6, f7, f8, f9 = lower_IPv6Address(v.Address) + f10 = (uint32)(v.ScopeID) + return +} + +func lower_IPSocketAddress(v network.IPSocketAddress) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32) { + f0 = (uint32)(v.Tag()) + switch f0 { + case 0: // ipv4 + v1, v2, v3, v4, v5 := lower_IPv4SocketAddress(*v.IPv4()) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + case 1: // ipv6 + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 := lower_IPv6SocketAddress(*v.IPv6()) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + f8 = (uint32)(v8) + f9 = (uint32)(v9) + f10 = (uint32)(v10) + f11 = (uint32)(v11) + } + return +} + +// TupleIncomingDatagramStreamOutgoingDatagramStreamShape is used for storage in variant or result types. +type TupleIncomingDatagramStreamOutgoingDatagramStreamShape struct { + shape [unsafe.Sizeof(cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream]{})]byte +} + +func lower_OptionIPSocketAddress(v cm.Option[network.IPSocketAddress]) (f0 uint32, f1 uint32, f2 uint32, f3 uint32, f4 uint32, f5 uint32, f6 uint32, f7 uint32, f8 uint32, f9 uint32, f10 uint32, f11 uint32, f12 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 := lower_IPSocketAddress(*some) + f1 = (uint32)(v1) + f2 = (uint32)(v2) + f3 = (uint32)(v3) + f4 = (uint32)(v4) + f5 = (uint32)(v5) + f6 = (uint32)(v6) + f7 = (uint32)(v7) + f8 = (uint32)(v8) + f9 = (uint32)(v9) + f10 = (uint32)(v10) + f11 = (uint32)(v11) + f12 = (uint32)(v12) + } + return +} diff --git a/_examples/http-client/gen/wasi/sockets/udp/empty.s b/_examples/http-client/gen/wasi/sockets/udp/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/udp/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasi/sockets/udp/udp.wit.go b/_examples/http-client/gen/wasi/sockets/udp/udp.wit.go new file mode 100644 index 0000000..bce399e --- /dev/null +++ b/_examples/http-client/gen/wasi/sockets/udp/udp.wit.go @@ -0,0 +1,641 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package udp represents the imported interface "wasi:sockets/udp@0.2.0". +package udp + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/io/poll" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasi/sockets/network" +) + +// IncomingDatagram represents the record "wasi:sockets/udp@0.2.0#incoming-datagram". +// +// A received datagram. +// +// record incoming-datagram { +// data: list, +// remote-address: ip-socket-address, +// } +type IncomingDatagram struct { + // The payload. + // + // Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + Data cm.List[uint8] + + // The source address. + // + // This field is guaranteed to match the remote address the stream was initialized + // with, if any. + // + // Equivalent to the `src_addr` out parameter of `recvfrom`. + RemoteAddress network.IPSocketAddress +} + +// OutgoingDatagram represents the record "wasi:sockets/udp@0.2.0#outgoing-datagram". +// +// A datagram to be sent out. +// +// record outgoing-datagram { +// data: list, +// remote-address: option, +// } +type OutgoingDatagram struct { + // The payload. + Data cm.List[uint8] + + // The destination address. + // + // The requirements on this field depend on how the stream was initialized: + // - with a remote address: this field must be None or match the stream's remote address + // exactly. + // - without a remote address: this field is required. + // + // If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise + // it is equivalent to `sendto`. + RemoteAddress cm.Option[network.IPSocketAddress] +} + +// UDPSocket represents the imported resource "wasi:sockets/udp@0.2.0#udp-socket". +// +// A UDP socket handle. +// +// resource udp-socket +type UDPSocket cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "udp-socket". +// +// Drops a resource handle. +// +//go:nosplit +func (self UDPSocket) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]udp-socket +//go:noescape +func wasmimport_UDPSocketResourceDrop(self0 uint32) + +// AddressFamily represents the imported method "address-family". +// +// Whether this is a IPv4 or IPv6 socket. +// +// Equivalent to the SO_DOMAIN socket option. +// +// address-family: func() -> ip-address-family +// +//go:nosplit +func (self UDPSocket) AddressFamily() (result network.IPAddressFamily) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_UDPSocketAddressFamily((uint32)(self0)) + result = (network.IPAddressFamily)((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.address-family +//go:noescape +func wasmimport_UDPSocketAddressFamily(self0 uint32) (result0 uint32) + +// FinishBind represents the imported method "finish-bind". +// +// finish-bind: func() -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) FinishBind() (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketFinishBind((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.finish-bind +//go:noescape +func wasmimport_UDPSocketFinishBind(self0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// LocalAddress represents the imported method "local-address". +// +// Get the current bound address. +// +// POSIX mentions: +// > If the socket has not been bound to a local name, the value +// > stored in the object pointed to by `address` is unspecified. +// +// WASI is stricter and requires `local-address` to return `invalid-state` when the +// socket hasn't been bound yet. +// +// # Typical errors +// - `invalid-state`: The socket is not bound to any local address. +// +// # References +// - +// - +// - +// - +// +// local-address: func() -> result +// +//go:nosplit +func (self UDPSocket) LocalAddress() (result cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketLocalAddress((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.local-address +//go:noescape +func wasmimport_UDPSocketLocalAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) + +// ReceiveBufferSize represents the imported method "receive-buffer-size". +// +// The kernel buffer space reserved for sends/receives on this socket. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// Any other value will never cause an error, but it might be silently clamped and/or +// rounded. +// I.e. after setting a value, reading the same setting back may return a different +// value. +// +// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. +// +// # Typical errors +// - `invalid-argument`: (set) The provided value was 0. +// +// receive-buffer-size: func() -> result +// +//go:nosplit +func (self UDPSocket) ReceiveBufferSize() (result cm.Result[uint64, uint64, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketReceiveBufferSize((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.receive-buffer-size +//go:noescape +func wasmimport_UDPSocketReceiveBufferSize(self0 uint32, result *cm.Result[uint64, uint64, network.ErrorCode]) + +// RemoteAddress represents the imported method "remote-address". +// +// Get the address the socket is currently streaming to. +// +// # Typical errors +// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) +// +// # References +// - +// - +// - +// - +// +// remote-address: func() -> result +// +//go:nosplit +func (self UDPSocket) RemoteAddress() (result cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketRemoteAddress((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.remote-address +//go:noescape +func wasmimport_UDPSocketRemoteAddress(self0 uint32, result *cm.Result[IPSocketAddressShape, network.IPSocketAddress, network.ErrorCode]) + +// SendBufferSize represents the imported method "send-buffer-size". +// +// send-buffer-size: func() -> result +// +//go:nosplit +func (self UDPSocket) SendBufferSize() (result cm.Result[uint64, uint64, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketSendBufferSize((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.send-buffer-size +//go:noescape +func wasmimport_UDPSocketSendBufferSize(self0 uint32, result *cm.Result[uint64, uint64, network.ErrorCode]) + +// SetReceiveBufferSize represents the imported method "set-receive-buffer-size". +// +// set-receive-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) SetReceiveBufferSize(value uint64) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_UDPSocketSetReceiveBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-receive-buffer-size +//go:noescape +func wasmimport_UDPSocketSetReceiveBufferSize(self0 uint32, value0 uint64, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetSendBufferSize represents the imported method "set-send-buffer-size". +// +// set-send-buffer-size: func(value: u64) -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) SetSendBufferSize(value uint64) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint64)(value) + wasmimport_UDPSocketSetSendBufferSize((uint32)(self0), (uint64)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-send-buffer-size +//go:noescape +func wasmimport_UDPSocketSetSendBufferSize(self0 uint32, value0 uint64, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// SetUnicastHopLimit represents the imported method "set-unicast-hop-limit". +// +// set-unicast-hop-limit: func(value: u8) -> result<_, error-code> +// +//go:nosplit +func (self UDPSocket) SetUnicastHopLimit(value uint8) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + value0 := (uint32)(value) + wasmimport_UDPSocketSetUnicastHopLimit((uint32)(self0), (uint32)(value0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.set-unicast-hop-limit +//go:noescape +func wasmimport_UDPSocketSetUnicastHopLimit(self0 uint32, value0 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// StartBind represents the imported method "start-bind". +// +// Bind the socket to a specific network on the provided IP address and port. +// +// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the +// implementation to decide which +// network interface(s) to bind to. +// If the port is zero, the socket will be bound to a random free port. +// +// # Typical errors +// - `invalid-argument`: The `local-address` has the wrong address family. +// (EAFNOSUPPORT, EFAULT on Windows) +// - `invalid-state`: The socket is already bound. (EINVAL) +// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS +// on Windows) +// - `address-in-use`: Address is already in use. (EADDRINUSE) +// - `address-not-bindable`: `local-address` is not an address that the `network` +// can bind to. (EADDRNOTAVAIL) +// - `not-in-progress`: A `bind` operation is not in progress. +// - `would-block`: Can't finish the operation, it is still in progress. +// (EWOULDBLOCK, EAGAIN) +// +// # Implementors note +// Unlike in POSIX, in WASI the bind operation is async. This enables +// interactive WASI hosts to inject permission prompts. Runtimes that +// don't want to make use of this ability can simply call the native +// `bind` as part of either `start-bind` or `finish-bind`. +// +// # References +// - +// - +// - +// - +// +// start-bind: func(network: borrow, local-address: ip-socket-address) -> +// result<_, error-code> +// +//go:nosplit +func (self UDPSocket) StartBind(network_ network.Network, localAddress network.IPSocketAddress) (result cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + network0 := cm.Reinterpret[uint32](network_) + localAddress0, localAddress1, localAddress2, localAddress3, localAddress4, localAddress5, localAddress6, localAddress7, localAddress8, localAddress9, localAddress10, localAddress11 := lower_IPSocketAddress(localAddress) + wasmimport_UDPSocketStartBind((uint32)(self0), (uint32)(network0), (uint32)(localAddress0), (uint32)(localAddress1), (uint32)(localAddress2), (uint32)(localAddress3), (uint32)(localAddress4), (uint32)(localAddress5), (uint32)(localAddress6), (uint32)(localAddress7), (uint32)(localAddress8), (uint32)(localAddress9), (uint32)(localAddress10), (uint32)(localAddress11), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.start-bind +//go:noescape +func wasmimport_UDPSocketStartBind(self0 uint32, network0 uint32, localAddress0 uint32, localAddress1 uint32, localAddress2 uint32, localAddress3 uint32, localAddress4 uint32, localAddress5 uint32, localAddress6 uint32, localAddress7 uint32, localAddress8 uint32, localAddress9 uint32, localAddress10 uint32, localAddress11 uint32, result *cm.Result[network.ErrorCode, struct{}, network.ErrorCode]) + +// Stream represents the imported method "stream". +// +// Set up inbound & outbound communication channels, optionally to a specific peer. +// +// This function only changes the local socket configuration and does not generate +// any network traffic. +// On success, the `remote-address` of the socket is updated. The `local-address` +// may be updated as well, +// based on the best network path to `remote-address`. +// +// When a `remote-address` is provided, the returned streams are limited to communicating +// with that specific peer: +// - `send` can only be used to send to this destination. +// - `receive` will only return datagrams sent from the provided `remote-address`. +// +// This method may be called multiple times on the same socket to change its association, +// but +// only the most recently returned pair of streams will be operational. Implementations +// may trap if +// the streams returned by a previous invocation haven't been dropped yet before calling +// `stream` again. +// +// The POSIX equivalent in pseudo-code is: +// +// if (was previously connected) { +// connect(s, AF_UNSPEC) +// } +// if (remote_address is Some) { +// connect(s, remote_address) +// } +// +// Unlike in POSIX, the socket must already be explicitly bound. +// +// # Typical errors +// - `invalid-argument`: The `remote-address` has the wrong address family. +// (EAFNOSUPPORT) +// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY +// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) +// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, +// EADDRNOTAVAIL) +// - `invalid-state`: The socket is not bound. +// - `address-in-use`: Tried to perform an implicit bind, but there were +// no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) +// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, +// ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `connection-refused`: The connection was refused. (ECONNREFUSED) +// +// # References +// - +// - +// - +// - +// +// %stream: func(remote-address: option) -> result, error-code> +// +//go:nosplit +func (self UDPSocket) Stream(remoteAddress cm.Option[network.IPSocketAddress]) (result cm.Result[TupleIncomingDatagramStreamOutgoingDatagramStreamShape, cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream], network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + remoteAddress0, remoteAddress1, remoteAddress2, remoteAddress3, remoteAddress4, remoteAddress5, remoteAddress6, remoteAddress7, remoteAddress8, remoteAddress9, remoteAddress10, remoteAddress11, remoteAddress12 := lower_OptionIPSocketAddress(remoteAddress) + wasmimport_UDPSocketStream((uint32)(self0), (uint32)(remoteAddress0), (uint32)(remoteAddress1), (uint32)(remoteAddress2), (uint32)(remoteAddress3), (uint32)(remoteAddress4), (uint32)(remoteAddress5), (uint32)(remoteAddress6), (uint32)(remoteAddress7), (uint32)(remoteAddress8), (uint32)(remoteAddress9), (uint32)(remoteAddress10), (uint32)(remoteAddress11), (uint32)(remoteAddress12), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.stream +//go:noescape +func wasmimport_UDPSocketStream(self0 uint32, remoteAddress0 uint32, remoteAddress1 uint32, remoteAddress2 uint32, remoteAddress3 uint32, remoteAddress4 uint32, remoteAddress5 uint32, remoteAddress6 uint32, remoteAddress7 uint32, remoteAddress8 uint32, remoteAddress9 uint32, remoteAddress10 uint32, remoteAddress11 uint32, remoteAddress12 uint32, result *cm.Result[TupleIncomingDatagramStreamOutgoingDatagramStreamShape, cm.Tuple[IncomingDatagramStream, OutgoingDatagramStream], network.ErrorCode]) + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the socket is ready for I/O. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self UDPSocket) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_UDPSocketSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.subscribe +//go:noescape +func wasmimport_UDPSocketSubscribe(self0 uint32) (result0 uint32) + +// UnicastHopLimit represents the imported method "unicast-hop-limit". +// +// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. +// +// If the provided value is 0, an `invalid-argument` error is returned. +// +// # Typical errors +// - `invalid-argument`: (set) The TTL value must be 1 or higher. +// +// unicast-hop-limit: func() -> result +// +//go:nosplit +func (self UDPSocket) UnicastHopLimit() (result cm.Result[uint8, uint8, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_UDPSocketUnicastHopLimit((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]udp-socket.unicast-hop-limit +//go:noescape +func wasmimport_UDPSocketUnicastHopLimit(self0 uint32, result *cm.Result[uint8, uint8, network.ErrorCode]) + +// IncomingDatagramStream represents the imported resource "wasi:sockets/udp@0.2.0#incoming-datagram-stream". +// +// resource incoming-datagram-stream +type IncomingDatagramStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "incoming-datagram-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self IncomingDatagramStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_IncomingDatagramStreamResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]incoming-datagram-stream +//go:noescape +func wasmimport_IncomingDatagramStreamResourceDrop(self0 uint32) + +// Receive represents the imported method "receive". +// +// Receive messages on the socket. +// +// This function attempts to receive up to `max-results` datagrams on the socket without +// blocking. +// The returned list may contain fewer elements than requested, but never more. +// +// This function returns successfully with an empty list when either: +// - `max-results` is 0, or: +// - `max-results` is greater than 0, but no results are immediately available. +// This function never returns `error(would-block)`. +// +// # Typical errors +// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET +// on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `connection-refused`: The connection was refused. (ECONNREFUSED) +// +// # References +// - +// - +// - +// - +// - +// - +// - +// - +// +// receive: func(max-results: u64) -> result, error-code> +// +//go:nosplit +func (self IncomingDatagramStream) Receive(maxResults uint64) (result cm.Result[cm.List[IncomingDatagram], cm.List[IncomingDatagram], network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + maxResults0 := (uint64)(maxResults) + wasmimport_IncomingDatagramStreamReceive((uint32)(self0), (uint64)(maxResults0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]incoming-datagram-stream.receive +//go:noescape +func wasmimport_IncomingDatagramStreamReceive(self0 uint32, maxResults0 uint64, result *cm.Result[cm.List[IncomingDatagram], cm.List[IncomingDatagram], network.ErrorCode]) + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the stream is ready to receive again. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self IncomingDatagramStream) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_IncomingDatagramStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]incoming-datagram-stream.subscribe +//go:noescape +func wasmimport_IncomingDatagramStreamSubscribe(self0 uint32) (result0 uint32) + +// OutgoingDatagramStream represents the imported resource "wasi:sockets/udp@0.2.0#outgoing-datagram-stream". +// +// resource outgoing-datagram-stream +type OutgoingDatagramStream cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "outgoing-datagram-stream". +// +// Drops a resource handle. +// +//go:nosplit +func (self OutgoingDatagramStream) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingDatagramStreamResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [resource-drop]outgoing-datagram-stream +//go:noescape +func wasmimport_OutgoingDatagramStreamResourceDrop(self0 uint32) + +// CheckSend represents the imported method "check-send". +// +// Check readiness for sending. This function never blocks. +// +// Returns the number of datagrams permitted for the next call to `send`, +// or an error. Calling `send` with more datagrams than this function has +// permitted will trap. +// +// When this function returns ok(0), the `subscribe` pollable will +// become ready when this function will report at least ok(1), or an +// error. +// +// Never returns `would-block`. +// +// check-send: func() -> result +// +//go:nosplit +func (self OutgoingDatagramStream) CheckSend() (result cm.Result[uint64, uint64, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + wasmimport_OutgoingDatagramStreamCheckSend((uint32)(self0), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.check-send +//go:noescape +func wasmimport_OutgoingDatagramStreamCheckSend(self0 uint32, result *cm.Result[uint64, uint64, network.ErrorCode]) + +// Send represents the imported method "send". +// +// Send messages on the socket. +// +// This function attempts to send all provided `datagrams` on the socket without blocking +// and +// returns how many messages were actually sent (or queued for sending). This function +// never +// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` +// is returned. +// +// This function semantically behaves the same as iterating the `datagrams` list and +// sequentially +// sending each individual datagram until either the end of the list has been reached +// or the first error occurred. +// If at least one datagram has been sent successfully, this function never returns +// an error. +// +// If the input list is empty, the function returns `ok(0)`. +// +// Each call to `send` must be permitted by a preceding `check-send`. Implementations +// must trap if +// either `check-send` was not called or `datagrams` contains more items than `check-send` +// permitted. +// +// # Typical errors +// - `invalid-argument`: The `remote-address` has the wrong address family. +// (EAFNOSUPPORT) +// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY +// (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) +// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, +// EADDRNOTAVAIL) +// - `invalid-argument`: The socket is in "connected" mode and `remote-address` +// is `some` value that does not match the address passed to `stream`. (EISCONN) +// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` +// was provided. (EDESTADDRREQ) +// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, +// ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) +// - `connection-refused`: The connection was refused. (ECONNREFUSED) +// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) +// +// # References +// - +// - +// - +// - +// - +// - +// - +// - +// +// send: func(datagrams: list) -> result +// +//go:nosplit +func (self OutgoingDatagramStream) Send(datagrams cm.List[OutgoingDatagram]) (result cm.Result[uint64, uint64, network.ErrorCode]) { + self0 := cm.Reinterpret[uint32](self) + datagrams0, datagrams1 := cm.LowerList(datagrams) + wasmimport_OutgoingDatagramStreamSend((uint32)(self0), (*OutgoingDatagram)(datagrams0), (uint32)(datagrams1), &result) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.send +//go:noescape +func wasmimport_OutgoingDatagramStreamSend(self0 uint32, datagrams0 *OutgoingDatagram, datagrams1 uint32, result *cm.Result[uint64, uint64, network.ErrorCode]) + +// Subscribe represents the imported method "subscribe". +// +// Create a `pollable` which will resolve once the stream is ready to send again. +// +// Note: this function is here for WASI Preview2 only. +// It's planned to be removed when `future` is natively supported in Preview3. +// +// subscribe: func() -> pollable +// +//go:nosplit +func (self OutgoingDatagramStream) Subscribe() (result poll.Pollable) { + self0 := cm.Reinterpret[uint32](self) + result0 := wasmimport_OutgoingDatagramStreamSubscribe((uint32)(self0)) + result = cm.Reinterpret[poll.Pollable]((uint32)(result0)) + return +} + +//go:wasmimport wasi:sockets/udp@0.2.0 [method]outgoing-datagram-stream.subscribe +//go:noescape +func wasmimport_OutgoingDatagramStreamSubscribe(self0 uint32) (result0 uint32) diff --git a/_examples/http-client/gen/wasmcloud/bus/lattice/empty.s b/_examples/http-client/gen/wasmcloud/bus/lattice/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/bus/lattice/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasmcloud/bus/lattice/lattice.wit.go b/_examples/http-client/gen/wasmcloud/bus/lattice/lattice.wit.go new file mode 100644 index 0000000..9e04515 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/bus/lattice/lattice.wit.go @@ -0,0 +1,70 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package lattice represents the imported interface "wasmcloud:bus/lattice@1.0.0". +package lattice + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// CallTargetInterface represents the imported resource "wasmcloud:bus/lattice@1.0.0#call-target-interface". +// +// Interface target. This represents an interface, which can be selected by `set-link-name`. +// +// resource call-target-interface +type CallTargetInterface cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "call-target-interface". +// +// Drops a resource handle. +// +//go:nosplit +func (self CallTargetInterface) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_CallTargetInterfaceResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasmcloud:bus/lattice@1.0.0 [resource-drop]call-target-interface +//go:noescape +func wasmimport_CallTargetInterfaceResourceDrop(self0 uint32) + +// NewCallTargetInterface represents the imported constructor for resource "call-target-interface". +// +// constructor(namespace: string, %package: string, %interface: string) +// +//go:nosplit +func NewCallTargetInterface(namespace string, package_ string, interface_ string) (result CallTargetInterface) { + namespace0, namespace1 := cm.LowerString(namespace) + package0, package1 := cm.LowerString(package_) + interface0, interface1 := cm.LowerString(interface_) + result0 := wasmimport_NewCallTargetInterface((*uint8)(namespace0), (uint32)(namespace1), (*uint8)(package0), (uint32)(package1), (*uint8)(interface0), (uint32)(interface1)) + result = cm.Reinterpret[CallTargetInterface]((uint32)(result0)) + return +} + +//go:wasmimport wasmcloud:bus/lattice@1.0.0 [constructor]call-target-interface +//go:noescape +func wasmimport_NewCallTargetInterface(namespace0 *uint8, namespace1 uint32, package0 *uint8, package1 uint32, interface0 *uint8, interface1 uint32) (result0 uint32) + +// SetLinkName represents the imported function "set-link-name". +// +// Set an optional link name to use for all interfaces specified. This is advanced +// functionality only available within wasmcloud and, as such, is exposed here as +// part of the +// wasmcloud:bus package. This is used when you are linking multiple of the same interfaces +// (i.e. a keyvalue implementation for caching and another one for secrets) to a component +// +// set-link-name: func(name: string, interfaces: list) +// +//go:nosplit +func SetLinkName(name string, interfaces cm.List[CallTargetInterface]) { + name0, name1 := cm.LowerString(name) + interfaces0, interfaces1 := cm.LowerList(interfaces) + wasmimport_SetLinkName((*uint8)(name0), (uint32)(name1), (*CallTargetInterface)(interfaces0), (uint32)(interfaces1)) + return +} + +//go:wasmimport wasmcloud:bus/lattice@1.0.0 set-link-name +//go:noescape +func wasmimport_SetLinkName(name0 *uint8, name1 uint32, interfaces0 *CallTargetInterface, interfaces1 uint32) diff --git a/_examples/http-client/gen/wasmcloud/messaging/consumer/abi.go b/_examples/http-client/gen/wasmcloud/messaging/consumer/abi.go new file mode 100644 index 0000000..1e44dea --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/messaging/consumer/abi.go @@ -0,0 +1,32 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package consumer + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasmcloud/messaging/types" + "unsafe" +) + +// BrokerMessageShape is used for storage in variant or result types. +type BrokerMessageShape struct { + shape [unsafe.Sizeof(types.BrokerMessage{})]byte +} + +func lower_OptionString(v cm.Option[string]) (f0 uint32, f1 *uint8, f2 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2 := cm.LowerString(*some) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_BrokerMessage(v types.BrokerMessage) (f0 *uint8, f1 uint32, f2 *uint8, f3 uint32, f4 uint32, f5 *uint8, f6 uint32) { + f0, f1 = cm.LowerString(v.Subject) + f2, f3 = cm.LowerList(v.Body) + f4, f5, f6 = lower_OptionString(v.ReplyTo) + return +} diff --git a/_examples/http-client/gen/wasmcloud/messaging/consumer/consumer.wit.go b/_examples/http-client/gen/wasmcloud/messaging/consumer/consumer.wit.go new file mode 100644 index 0000000..ce8e6ef --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/messaging/consumer/consumer.wit.go @@ -0,0 +1,46 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package consumer represents the imported interface "wasmcloud:messaging/consumer@0.2.0". +package consumer + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasmcloud/messaging/types" +) + +// Request represents the imported function "request". +// +// Perform a request operation on a subject +// +// request: func(subject: string, body: list, timeout-ms: u32) -> result +// +//go:nosplit +func Request(subject string, body cm.List[uint8], timeoutMs uint32) (result cm.Result[BrokerMessageShape, types.BrokerMessage, string]) { + subject0, subject1 := cm.LowerString(subject) + body0, body1 := cm.LowerList(body) + timeoutMs0 := (uint32)(timeoutMs) + wasmimport_Request((*uint8)(subject0), (uint32)(subject1), (*uint8)(body0), (uint32)(body1), (uint32)(timeoutMs0), &result) + return +} + +//go:wasmimport wasmcloud:messaging/consumer@0.2.0 request +//go:noescape +func wasmimport_Request(subject0 *uint8, subject1 uint32, body0 *uint8, body1 uint32, timeoutMs0 uint32, result *cm.Result[BrokerMessageShape, types.BrokerMessage, string]) + +// Publish represents the imported function "publish". +// +// Publish a message to a subject without awaiting a response +// +// publish: func(msg: broker-message) -> result<_, string> +// +//go:nosplit +func Publish(msg types.BrokerMessage) (result cm.Result[string, struct{}, string]) { + msg0, msg1, msg2, msg3, msg4, msg5, msg6 := lower_BrokerMessage(msg) + wasmimport_Publish((*uint8)(msg0), (uint32)(msg1), (*uint8)(msg2), (uint32)(msg3), (uint32)(msg4), (*uint8)(msg5), (uint32)(msg6), &result) + return +} + +//go:wasmimport wasmcloud:messaging/consumer@0.2.0 publish +//go:noescape +func wasmimport_Publish(msg0 *uint8, msg1 uint32, msg2 *uint8, msg3 uint32, msg4 uint32, msg5 *uint8, msg6 uint32, result *cm.Result[string, struct{}, string]) diff --git a/_examples/http-client/gen/wasmcloud/messaging/consumer/empty.s b/_examples/http-client/gen/wasmcloud/messaging/consumer/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/messaging/consumer/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasmcloud/messaging/types/types.wit.go b/_examples/http-client/gen/wasmcloud/messaging/types/types.wit.go new file mode 100644 index 0000000..6fbc9e9 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/messaging/types/types.wit.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package types represents the imported interface "wasmcloud:messaging/types@0.2.0". +// +// Types common to message broker interactions +package types + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// BrokerMessage represents the record "wasmcloud:messaging/types@0.2.0#broker-message". +// +// A message sent to or received from a broker +// +// record broker-message { +// subject: string, +// body: list, +// reply-to: option, +// } +type BrokerMessage struct { + Subject string + Body cm.List[uint8] + ReplyTo cm.Option[string] +} diff --git a/_examples/http-client/gen/wasmcloud/secrets/reveal/empty.s b/_examples/http-client/gen/wasmcloud/secrets/reveal/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/secrets/reveal/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasmcloud/secrets/reveal/reveal.wit.go b/_examples/http-client/gen/wasmcloud/secrets/reveal/reveal.wit.go new file mode 100644 index 0000000..ac4c1b8 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/secrets/reveal/reveal.wit.go @@ -0,0 +1,27 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package reveal represents the imported interface "wasmcloud:secrets/reveal@0.1.0-draft". +package reveal + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-client/gen/wasmcloud/secrets/store" +) + +// Reveal represents the imported function "reveal". +// +// Reveals the value of a secret to the caller. +// This lets you easily audit your code to discover where secrets are being used. +// +// reveal: func(s: borrow) -> secret-value +// +//go:nosplit +func Reveal(s store.Secret) (result store.SecretValue) { + s0 := cm.Reinterpret[uint32](s) + wasmimport_Reveal((uint32)(s0), &result) + return +} + +//go:wasmimport wasmcloud:secrets/reveal@0.1.0-draft reveal +//go:noescape +func wasmimport_Reveal(s0 uint32, result *store.SecretValue) diff --git a/_examples/http-client/gen/wasmcloud/secrets/store/abi.go b/_examples/http-client/gen/wasmcloud/secrets/store/abi.go new file mode 100644 index 0000000..71add12 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/secrets/store/abi.go @@ -0,0 +1,12 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package store + +import ( + "unsafe" +) + +// SecretsErrorShape is used for storage in variant or result types. +type SecretsErrorShape struct { + shape [unsafe.Sizeof(SecretsError{})]byte +} diff --git a/_examples/http-client/gen/wasmcloud/secrets/store/empty.s b/_examples/http-client/gen/wasmcloud/secrets/store/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/secrets/store/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-client/gen/wasmcloud/secrets/store/store.wit.go b/_examples/http-client/gen/wasmcloud/secrets/store/store.wit.go new file mode 100644 index 0000000..06891e7 --- /dev/null +++ b/_examples/http-client/gen/wasmcloud/secrets/store/store.wit.go @@ -0,0 +1,144 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package store represents the imported interface "wasmcloud:secrets/store@0.1.0-draft". +package store + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// SecretsError represents the variant "wasmcloud:secrets/store@0.1.0-draft#secrets-error". +// +// An error type that encapsulates the different errors that can occur fetching secrets +// +// variant secrets-error { +// upstream(string), +// io(string), +// not-found, +// } +type SecretsError cm.Variant[uint8, string, string] + +// SecretsErrorUpstream returns a [SecretsError] of case "upstream". +// +// This indicates an error from an "upstream" secrets source. +// As this could be almost _anything_ (such as Vault, Kubernetes Secrets, KeyValue +// buckets, etc), +// the error message is a string. +func SecretsErrorUpstream(data string) SecretsError { + return cm.New[SecretsError](0, data) +} + +// Upstream returns a non-nil *[string] if [SecretsError] represents the variant case "upstream". +func (self *SecretsError) Upstream() *string { + return cm.Case[string](self, 0) +} + +// SecretsErrorIO returns a [SecretsError] of case "io". +// +// 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. +func SecretsErrorIO(data string) SecretsError { + return cm.New[SecretsError](1, data) +} + +// IO returns a non-nil *[string] if [SecretsError] represents the variant case "io". +func (self *SecretsError) IO() *string { + return cm.Case[string](self, 1) +} + +// SecretsErrorNotFound returns a [SecretsError] of case "not-found". +// +// This indicates that the secret was not found. Generally "not found" errors will +// be handled by the upstream secrets backend, but there are cases where the host +// may need to return this error. +func SecretsErrorNotFound() SecretsError { + var data struct{} + return cm.New[SecretsError](2, data) +} + +// NotFound returns true if [SecretsError] represents the variant case "not-found". +func (self *SecretsError) NotFound() bool { + return self.Tag() == 2 +} + +// SecretValue represents the variant "wasmcloud:secrets/store@0.1.0-draft#secret-value". +// +// A secret value can be either a string or a byte array, which lets you +// store binary data as a secret. +// +// variant secret-value { +// string(string), +// bytes(list), +// } +type SecretValue cm.Variant[uint8, string, cm.List[uint8]] + +// SecretValueString returns a [SecretValue] of case "string". +// +// A string value +func SecretValueString(data string) SecretValue { + return cm.New[SecretValue](0, data) +} + +// String returns a non-nil *[string] if [SecretValue] represents the variant case "string". +func (self *SecretValue) String() *string { + return cm.Case[string](self, 0) +} + +// SecretValueBytes returns a [SecretValue] of case "bytes". +// +// A byte array value +func SecretValueBytes(data cm.List[uint8]) SecretValue { + return cm.New[SecretValue](1, data) +} + +// Bytes returns a non-nil *[cm.List[uint8]] if [SecretValue] represents the variant case "bytes". +func (self *SecretValue) Bytes() *cm.List[uint8] { + return cm.Case[cm.List[uint8]](self, 1) +} + +// Secret represents the imported resource "wasmcloud:secrets/store@0.1.0-draft#secret". +// +// A secret is a resource that can only be borrowed. This allows you to +// pass around handles to secrets and not reveal the values until a +// component needs them. +// You need to use the reveal interface to get the value. +// +// resource secret +type Secret cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "secret". +// +// Drops a resource handle. +// +//go:nosplit +func (self Secret) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_SecretResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasmcloud:secrets/store@0.1.0-draft [resource-drop]secret +//go:noescape +func wasmimport_SecretResourceDrop(self0 uint32) + +// Get represents the imported function "get". +// +// Gets a single opaque secrets value set at the given key if it exists +// +// get: func(key: string) -> result +// +//go:nosplit +func Get(key string) (result cm.Result[SecretsErrorShape, Secret, SecretsError]) { + key0, key1 := cm.LowerString(key) + wasmimport_Get((*uint8)(key0), (uint32)(key1), &result) + return +} + +//go:wasmimport wasmcloud:secrets/store@0.1.0-draft get +//go:noescape +func wasmimport_Get(key0 *uint8, key1 uint32, result *cm.Result[SecretsErrorShape, Secret, SecretsError]) diff --git a/_examples/http-client/go.mod b/_examples/http-client/go.mod new file mode 100644 index 0000000..6880b69 --- /dev/null +++ b/_examples/http-client/go.mod @@ -0,0 +1,18 @@ +module github.com/wasmCloud/component-sdk-go/_examples/http-client + +go 1.23.0 + +require ( + github.com/bytecodealliance/wasm-tools-go v0.2.0 + go.wasmcloud.dev/component v0.0.0-20240910182305-2785f866ff0f +) + +require ( + github.com/coreos/go-semver v0.3.1 // indirect + github.com/urfave/cli/v3 v3.0.0-alpha9 // indirect + github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + golang.org/x/mod v0.21.0 // indirect +) + +// TODO(lxf): remove this line once the module is published +replace go.wasmcloud.dev/component => ../.. diff --git a/_examples/http-client/go.sum b/_examples/http-client/go.sum new file mode 100644 index 0000000..d4fb71d --- /dev/null +++ b/_examples/http-client/go.sum @@ -0,0 +1,25 @@ +github.com/bytecodealliance/wasm-tools-go v0.2.0 h1:JdmiZew7ewHjf+ZGGRE4gZM85Ad/PGW/5I57hepEOjQ= +github.com/bytecodealliance/wasm-tools-go v0.2.0/go.mod h1:2GnJCUlcDrslZ/L6+yYqoUnewDlBvqRS2N/0NW9ro6w= +github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= +github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= +github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/urfave/cli/v3 v3.0.0-alpha9 h1:P0RMy5fQm1AslQS+XCmy9UknDXctOmG/q/FZkUFnJSo= +github.com/urfave/cli/v3 v3.0.0-alpha9/go.mod h1:0kK/RUFHyh+yIKSfWxwheGndfnrvYSmYFVeKCh03ZUc= +github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= +github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= +golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/_examples/http-client/main.go b/_examples/http-client/main.go new file mode 100644 index 0000000..425651a --- /dev/null +++ b/_examples/http-client/main.go @@ -0,0 +1,41 @@ +package main + +//go:generate go run github.com/bytecodealliance/wasm-tools-go/cmd/wit-bindgen-go generate --world example --out gen ./wit + +import ( + "io" + "net/http" + + "go.wasmcloud.dev/component/net/wasihttp" +) + +var ( + wasiTransport = &wasihttp.Transport{} + httpClient = &http.Client{Transport: wasiTransport} +) + +func init() { + wasihttp.HandleFunc(proxyHandler) +} + +func proxyHandler(w http.ResponseWriter, _ *http.Request) { + url := "http://www.randomnumberapi.com/api/v1.0/random?min=100&max=1000&count=5" + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + http.Error(w, "failed to create request", http.StatusBadGateway) + return + } + + resp, err := httpClient.Do(req) + if err != nil { + http.Error(w, "failed to make outbound request", http.StatusBadGateway) + return + } + defer resp.Body.Close() + + w.Header().Set("X-Custom-Header", "proxied") + w.WriteHeader(resp.StatusCode) + + _, _ = io.Copy(w, resp.Body) +} +func main() {} diff --git a/_examples/http-client/tools.go b/_examples/http-client/tools.go new file mode 100644 index 0000000..1f23a0e --- /dev/null +++ b/_examples/http-client/tools.go @@ -0,0 +1,7 @@ +//go:build tools + +package main + +import ( + _ "github.com/bytecodealliance/wasm-tools-go/cmd/wit-bindgen-go" +) diff --git a/_examples/http-client/wadm.yaml b/_examples/http-client/wadm.yaml new file mode 100644 index 0000000..dd9edf3 --- /dev/null +++ b/_examples/http-client/wadm.yaml @@ -0,0 +1,51 @@ +apiVersion: core.oam.dev/v1beta1 +kind: Application +metadata: + name: http-client-example + annotations: + description: All-in-one demo + wasmcloud.dev/authors: wasmCloud team + wasmcloud.dev/source-url: https://github.com/wasmCloud/wasmCloud/blob/main/examples/rust/components/http-image-processor/wadm.yaml + wasmcloud.dev/readme-md-url: https://github.com/wasmCloud/wasmCloud/blob/main/examples/rust/components/http-image-processor/README.md + wasmcloud.dev/homepage: https://github.com/wasmCloud/wasmCloud/tree/main/examples/rust/components/http-image-processor + wasmcloud.dev/categories: | + http,http-client,rust,hello-world,example +spec: + components: + - name: http-component + type: component + properties: + image: file://./build/http_client_s.wasm + traits: + - type: spreadscaler + properties: + replicas: 1 + - type: link + properties: + target: httpclient + namespace: wasi + package: http + interfaces: [outgoing-handler] + - name: httpserver + type: capability + properties: + image: ghcr.io/wasmcloud/http-server:0.22.0 + traits: + - type: link + properties: + target: http-component + namespace: wasi + package: http + interfaces: [incoming-handler] + source_config: + - name: default-http + properties: + address: 0.0.0.0:30001 + - name: httpclient + type: capability + properties: + image: ghcr.io/wasmcloud/http-client:0.12.0 + traits: + - type: spreadscaler + properties: + replicas: 1 diff --git a/_examples/http-client/wasmcloud.toml b/_examples/http-client/wasmcloud.toml new file mode 100644 index 0000000..969a6cf --- /dev/null +++ b/_examples/http-client/wasmcloud.toml @@ -0,0 +1,10 @@ +name = "http_client" +language = "other" +type = "component" +version = "0.1.0" + +[component] +build_command = "tinygo build -target=wasip2 --wit-package ./wit --wit-world example -o build/http_client.wasm main.go" +wit_world = "example" +wasm_target = "wasm32-wasi-preview2" +destination = "build/http_client_s.wasm" diff --git a/_examples/http-client/wit/deps.lock b/_examples/http-client/wit/deps.lock new file mode 100644 index 0000000..9b4d85b --- /dev/null +++ b/_examples/http-client/wit/deps.lock @@ -0,0 +1,55 @@ +[cli] +sha256 = "285865a31d777181b075f39e92bcfe59c89cd6bacce660be1b9a627646956258" +sha512 = "da2622210a9e3eea82b99f1a5b8a44ce5443d009cb943f7bca0bf9cf4360829b289913d7ee727c011f0f72994ea7dc8e661ebcc0a6b34b587297d80cd9b3f7e8" + +[clocks] +sha256 = "468b4d12892fe926b8eb5d398dbf579d566c93231fa44f415440572c695b7613" +sha512 = "e6b53a07221f1413953c9797c68f08b815fdaebf66419bbc1ea3e8b7dece73731062693634731f311a03957b268cf9cc509c518bd15e513c318aa04a8459b93a" + +[component] +path = "../../../wit" +sha256 = "ec5b1fc6183ecd80b8328e2345d96d2b7e9fc8c2085300389d21c078ab03729f" +sha512 = "5b1488b7be9f9e05b713aa9cc5465eb730550eab3ae3a9a5ca8a243947a6ae9b90e4a4f06ecd9cc9a375306bb619c54b16856a73d25aa227c45352b88ec741db" +deps = ["cli", "clocks", "config", "filesystem", "io", "lattice", "logging", "messaging", "random", "secrets", "sockets"] + +[config] +sha256 = "9148c06861712b69170af7b8ec37896b4104297d920fdec9f3bcc0b1eee4a5c8" +sha512 = "25a54101620f279c835b39f56f6dbf8a92b374b6faaf6cf6aaa1ea06d8b97b9b79788cf8abd9c2ad0c11e3629dba6a2513b71f2c54b9f95027054ae54a4615b8" + +[filesystem] +sha256 = "498c465cfd04587db40f970fff2185daa597d074c20b68a8bcbae558f261499b" +sha512 = "ead452f9b7bfb88593a502ec00d76d4228003d51c40fd0408aebc32d35c94673551b00230d730873361567cc209ec218c41fb4e95bad194268592c49e7964347" + +[http] +url = "https://github.com/WebAssembly/wasi-http/archive/v0.2.0.tar.gz" +sha256 = "8f44402bde16c48e28c47dc53eab0b26af5b3b3482a1852cf77673e0880ba1c1" +sha512 = "760695f9a25c25bf75a25b731cb21c3bda9e288e450edda823324ecbc73d5d798bbb5de2edad999566980836f037463ee9e57d61789d04b3f3e381475b1a9a0f" +deps = ["cli", "clocks", "filesystem", "io", "random", "sockets"] + +[io] +sha256 = "7210e5653539a15478f894d4da24cc69d61924cbcba21d2804d69314a88e5a4c" +sha512 = "49184a1b0945a889abd52d25271172ed3dc2db6968fcdddb1bab7ee0081f4a3eeee0977ad2291126a37631c0d86eeea75d822fa8af224c422134500bf9f0f2bb" + +[lattice] +sha256 = "b4946a8bfa48b2f4ac404de03617d25712879596be5417bde3de09ca9c369462" +sha512 = "09918bb2fa8f7af022f71453348be38ec7fd1a35df6809b8d0c5f246856712f969557ff65d9e5d4619e905191e27fba2fbbcc9f38c777a7b09eb73c30909d33f" + +[logging] +sha256 = "9676b482485bb0fd2751a390374c1108865a096b7037f4b5dbe524f066bfb06e" +sha512 = "30a621a6d48a0175e8047c062e618523a85f69c45a7c31918da2b888f7527fce1aca67fa132552222725d0f6cdcaed95be7f16c28488d9468c0fad00cb7450b9" + +[messaging] +sha256 = "41ada083aceb2b4ba92d9bd16d19b6462cc02b10378c9a49135c3447f9138a44" +sha512 = "aa9c819dfd9e85b19661f6087ffd824c44fc38c8a4bc1005c4e7fd34fe844633c52cae7a0412e9ea90f71826e0660e8a3b5672a0f0303c524e4139643ae675ac" + +[random] +sha256 = "7371d03c037d924caba2587fb2e7c5773a0d3c5fcecbf7971e0e0ba57973c53d" +sha512 = "964c4e8925a53078e4d94ba907b54f89a0b7e154f46823a505391471466c17f53c8692682e5c85771712acd88b348686173fc07c53a3cfe3d301b8cd8ddd0de4" + +[secrets] +sha256 = "4c965f81e4f8510e917976dc7017b070d23b964724e3ca058f28ec9e3d691854" +sha512 = "c23d3d86846b7f35238347974c104a3056e5871db85a8e17c607cf2c48c5fc6dc550fa698a233b78de2c7b25e80ff6c590d0a4bf8c8892b48b3cec52bc141d32" + +[sockets] +sha256 = "622bd28bbeb43736375dc02bd003fd3a016ff8ee91e14bab488325c6b38bf966" +sha512 = "5a63c1f36de0c4548e1d2297bdbededb28721cbad94ef7825c469eae29d7451c97e00b4c1d6730ee1ec0c4a5aac922961a2795762d4a0c3bb54e30a391a84bae" diff --git a/_examples/http-client/wit/deps.toml b/_examples/http-client/wit/deps.toml new file mode 100644 index 0000000..9a0440f --- /dev/null +++ b/_examples/http-client/wit/deps.toml @@ -0,0 +1,2 @@ +http = "https://github.com/WebAssembly/wasi-http/archive/v0.2.0.tar.gz" +component = "../../../wit" diff --git a/_examples/http-client/wit/deps/cli/command.wit b/_examples/http-client/wit/deps/cli/command.wit new file mode 100644 index 0000000..d8005bd --- /dev/null +++ b/_examples/http-client/wit/deps/cli/command.wit @@ -0,0 +1,7 @@ +package wasi:cli@0.2.0; + +world command { + include imports; + + export run; +} diff --git a/_examples/http-client/wit/deps/cli/environment.wit b/_examples/http-client/wit/deps/cli/environment.wit new file mode 100644 index 0000000..7006523 --- /dev/null +++ b/_examples/http-client/wit/deps/cli/environment.wit @@ -0,0 +1,18 @@ +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + initial-cwd: func() -> option; +} diff --git a/_examples/http-client/wit/deps/cli/exit.wit b/_examples/http-client/wit/deps/cli/exit.wit new file mode 100644 index 0000000..d0c2b82 --- /dev/null +++ b/_examples/http-client/wit/deps/cli/exit.wit @@ -0,0 +1,4 @@ +interface exit { + /// Exit the current instance and any linked instances. + exit: func(status: result); +} diff --git a/_examples/http-client/wit/deps/cli/imports.wit b/_examples/http-client/wit/deps/cli/imports.wit new file mode 100644 index 0000000..083b84a --- /dev/null +++ b/_examples/http-client/wit/deps/cli/imports.wit @@ -0,0 +1,20 @@ +package wasi:cli@0.2.0; + +world imports { + include wasi:clocks/imports@0.2.0; + include wasi:filesystem/imports@0.2.0; + include wasi:sockets/imports@0.2.0; + include wasi:random/imports@0.2.0; + include wasi:io/imports@0.2.0; + + import environment; + import exit; + import stdin; + import stdout; + import stderr; + import terminal-input; + import terminal-output; + import terminal-stdin; + import terminal-stdout; + import terminal-stderr; +} diff --git a/_examples/http-client/wit/deps/cli/run.wit b/_examples/http-client/wit/deps/cli/run.wit new file mode 100644 index 0000000..a70ee8c --- /dev/null +++ b/_examples/http-client/wit/deps/cli/run.wit @@ -0,0 +1,4 @@ +interface run { + /// Run the program. + run: func() -> result; +} diff --git a/_examples/http-client/wit/deps/cli/stdio.wit b/_examples/http-client/wit/deps/cli/stdio.wit new file mode 100644 index 0000000..31ef35b --- /dev/null +++ b/_examples/http-client/wit/deps/cli/stdio.wit @@ -0,0 +1,17 @@ +interface stdin { + use wasi:io/streams@0.2.0.{input-stream}; + + get-stdin: func() -> input-stream; +} + +interface stdout { + use wasi:io/streams@0.2.0.{output-stream}; + + get-stdout: func() -> output-stream; +} + +interface stderr { + use wasi:io/streams@0.2.0.{output-stream}; + + get-stderr: func() -> output-stream; +} diff --git a/_examples/http-client/wit/deps/cli/terminal.wit b/_examples/http-client/wit/deps/cli/terminal.wit new file mode 100644 index 0000000..38c724e --- /dev/null +++ b/_examples/http-client/wit/deps/cli/terminal.wit @@ -0,0 +1,49 @@ +/// Terminal input. +/// +/// In the future, this may include functions for disabling echoing, +/// disabling input buffering so that keyboard events are sent through +/// immediately, querying supported features, and so on. +interface terminal-input { + /// The input side of a terminal. + resource terminal-input; +} + +/// Terminal output. +/// +/// In the future, this may include functions for querying the terminal +/// size, being notified of terminal size changes, querying supported +/// features, and so on. +interface terminal-output { + /// The output side of a terminal. + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +interface terminal-stdin { + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +interface terminal-stdout { + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +interface terminal-stderr { + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + get-terminal-stderr: func() -> option; +} diff --git a/_examples/http-client/wit/deps/clocks/monotonic-clock.wit b/_examples/http-client/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 0000000..4e4dc3a --- /dev/null +++ b/_examples/http-client/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,45 @@ +package wasi:clocks@0.2.0; +/// WASI Monotonic Clock is a clock API intended to let users measure elapsed +/// time. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A monotonic clock is a clock which has an unspecified initial value, and +/// successive reads of the clock will produce non-decreasing values. +/// +/// It is intended for measuring elapsed time. +interface monotonic-clock { + use wasi:io/poll@0.2.0.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + type instant = u64; + + /// A duration of time, in nanoseconds. + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// occured. + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` which will resolve once the given duration has + /// elapsed, starting at the time at which this function was called. + /// occured. + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/_examples/http-client/wit/deps/clocks/wall-clock.wit b/_examples/http-client/wit/deps/clocks/wall-clock.wit new file mode 100644 index 0000000..440ca0f --- /dev/null +++ b/_examples/http-client/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,42 @@ +package wasi:clocks@0.2.0; +/// WASI Wall Clock is a clock API intended to let users query the current +/// time. The name "wall" makes an analogy to a "clock on the wall", which +/// is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A wall clock is a clock which measures the date and time according to +/// some external reference. +/// +/// External references may be reset, so this clock is not necessarily +/// monotonic, making it unsuitable for measuring elapsed time. +/// +/// It is intended for reporting the current date and time for humans. +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + resolution: func() -> datetime; +} diff --git a/_examples/http-client/wit/deps/clocks/world.wit b/_examples/http-client/wit/deps/clocks/world.wit new file mode 100644 index 0000000..c022457 --- /dev/null +++ b/_examples/http-client/wit/deps/clocks/world.wit @@ -0,0 +1,6 @@ +package wasi:clocks@0.2.0; + +world imports { + import monotonic-clock; + import wall-clock; +} diff --git a/_examples/http-client/wit/deps/component/world.wit b/_examples/http-client/wit/deps/component/world.wit new file mode 100644 index 0000000..186845a --- /dev/null +++ b/_examples/http-client/wit/deps/component/world.wit @@ -0,0 +1,30 @@ +package wasmcloud:component; + +world exports { + // wasi + export wasi:http/incoming-handler@0.2.0; + + // wasmcloud + export wasmcloud:messaging/handler@0.2.0; +} + +world imports { + // tinygo + include wasi:cli/imports@0.2.0; + + // wasi + import wasi:logging/logging; + import wasi:config/runtime@0.2.0-draft; + import wasi:http/outgoing-handler@0.2.0; + + // wasmcloud + import wasmcloud:bus/lattice@1.0.0; + import wasmcloud:messaging/consumer@0.2.0; + import wasmcloud:secrets/store@0.1.0-draft; + import wasmcloud:secrets/reveal@0.1.0-draft; +} + +world sdk { + include exports; + include imports; +} diff --git a/_examples/http-client/wit/deps/config/runtime_config.wit b/_examples/http-client/wit/deps/config/runtime_config.wit new file mode 100644 index 0000000..29d53b1 --- /dev/null +++ b/_examples/http-client/wit/deps/config/runtime_config.wit @@ -0,0 +1,25 @@ +interface runtime { + /// An error type that encapsulates the different errors that can occur fetching config + variant config-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 single opaque config value set at the given key if it exists + get: func( + /// A string key to fetch + key: string + ) -> result, config-error>; + + /// Gets a list of all set config data + get-all: func() -> result>, config-error>; +} diff --git a/_examples/http-client/wit/deps/config/world.wit b/_examples/http-client/wit/deps/config/world.wit new file mode 100644 index 0000000..378c4a7 --- /dev/null +++ b/_examples/http-client/wit/deps/config/world.wit @@ -0,0 +1,6 @@ +package wasi:config@0.2.0-draft; + +world imports { + /// The runtime interface for config + import runtime; +} \ No newline at end of file diff --git a/_examples/http-client/wit/deps/filesystem/preopens.wit b/_examples/http-client/wit/deps/filesystem/preopens.wit new file mode 100644 index 0000000..da801f6 --- /dev/null +++ b/_examples/http-client/wit/deps/filesystem/preopens.wit @@ -0,0 +1,8 @@ +package wasi:filesystem@0.2.0; + +interface preopens { + use types.{descriptor}; + + /// Return the set of preopened directories, and their path. + get-directories: func() -> list>; +} diff --git a/_examples/http-client/wit/deps/filesystem/types.wit b/_examples/http-client/wit/deps/filesystem/types.wit new file mode 100644 index 0000000..11108fc --- /dev/null +++ b/_examples/http-client/wit/deps/filesystem/types.wit @@ -0,0 +1,634 @@ +package wasi:filesystem@0.2.0; +/// WASI filesystem is a filesystem API primarily intended to let users run WASI +/// programs that access their files on their existing filesystems, without +/// significant overhead. +/// +/// It is intended to be roughly portable between Unix-family platforms and +/// Windows, though it does not hide many of the major differences. +/// +/// Paths are passed as interface-type `string`s, meaning they must consist of +/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +/// paths which are not accessible by this API. +/// +/// The directory separator in WASI is always the forward-slash (`/`). +/// +/// All paths in WASI are relative paths, and are interpreted relative to a +/// `descriptor` referring to a base directory. If a `path` argument to any WASI +/// function starts with `/`, or if any step of resolving a `path`, including +/// `..` and symbolic link steps, reaches a directory outside of the base +/// directory, or reaches a symlink to an absolute or rooted path in the +/// underlying filesystem, the function fails with `error-code::not-permitted`. +/// +/// For more information about WASI path resolution and sandboxing, see +/// [WASI filesystem path resolution]. +/// +/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +interface types { + use wasi:io/streams@0.2.0.{input-stream, output-stream, error}; + use wasi:clocks/wall-clock@0.2.0.{datetime}; + + /// File size or length of a region within a file. + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrety + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// Flags determining the method of how paths are resolved. + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device, + } + + /// File or memory access pattern advisory information. + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse, + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + resource descriptor { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in in POSIX. + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + sync-data: func() -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + get-type: func() -> result; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + read-directory: func() -> result; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func( + /// The relative path of the symbolic link from which to read. + path: string, + ) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + is-same-object: func(other: borrow) -> bool; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encourated to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/_examples/http-client/wit/deps/filesystem/world.wit b/_examples/http-client/wit/deps/filesystem/world.wit new file mode 100644 index 0000000..663f579 --- /dev/null +++ b/_examples/http-client/wit/deps/filesystem/world.wit @@ -0,0 +1,6 @@ +package wasi:filesystem@0.2.0; + +world imports { + import types; + import preopens; +} diff --git a/_examples/http-client/wit/deps/http/handler.wit b/_examples/http-client/wit/deps/http/handler.wit new file mode 100644 index 0000000..a34a064 --- /dev/null +++ b/_examples/http-client/wit/deps/http/handler.wit @@ -0,0 +1,43 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +interface incoming-handler { + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + handle: func( + request: incoming-request, + response-out: response-outparam + ); +} + +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +interface outgoing-handler { + use types.{ + outgoing-request, request-options, future-incoming-response, error-code + }; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/_examples/http-client/wit/deps/http/proxy.wit b/_examples/http-client/wit/deps/http/proxy.wit new file mode 100644 index 0000000..687c24d --- /dev/null +++ b/_examples/http-client/wit/deps/http/proxy.wit @@ -0,0 +1,32 @@ +package wasi:http@0.2.0; + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +world proxy { + /// HTTP proxies have access to time and randomness. + include wasi:clocks/imports@0.2.0; + import wasi:random/random@0.2.0; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + import wasi:cli/stdout@0.2.0; + import wasi:cli/stderr@0.2.0; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + import wasi:cli/stdin@0.2.0; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + import outgoing-handler; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + export incoming-handler; +} diff --git a/_examples/http-client/wit/deps/http/types.wit b/_examples/http-client/wit/deps/http/types.wit new file mode 100644 index 0000000..755ac6a --- /dev/null +++ b/_examples/http-client/wit/deps/http/types.wit @@ -0,0 +1,570 @@ +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +interface types { + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use wasi:io/streams@0.2.0.{input-stream, output-stream}; + use wasi:io/error@0.2.0.{error as io-error}; + use wasi:io/poll@0.2.0.{pollable}; + + /// This type corresponds to HTTP standard Methods. + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// https://www.iana.org/assignments/http-proxy-status/http-proxy-status.xhtml#table-http-proxy-error-types + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option) + } + + /// Defines the case payload type for `DNS-error` above: + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + record field-size-payload { + field-name: option, + field-size: option + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + http-error-code: func(err: borrow) -> option; + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + variant header-error { + /// This error indicates that a `field-key` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + + /// This error indicates that a forbidden `field-key` was used when trying + /// to set a header in a `fields`. + forbidden, + + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field keys are always strings. + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + /// + /// The tuple is a pair of the field key, represented as a string, and + /// Value, represented as a list of bytes. In a valid Fields, all keys + /// and values are valid UTF-8 strings. However, values are not always + /// well-formed, so they are represented as a raw list of bytes. + /// + /// An error result will be returned if any header or value was + /// syntactically invalid, or if a header was forbidden. + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a key. If the key is not present + /// in this `fields`, an empty list is returned. However, if the key is + /// present but empty, this is represented by a list with one or more + /// empty field-values present. + get: func(name: field-key) -> list; + + /// Returns `true` when the key is present in this `fields`. If the key is + /// syntactically invalid, `false` is returned. + has: func(name: field-key) -> bool; + + /// Set all of the values for a key. Clears any existing values for that + /// key, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + set: func(name: field-key, value: list) -> result<_, header-error>; + + /// Delete all values for a key. Does nothing if no values for the key + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + delete: func(name: field-key) -> result<_, header-error>; + + /// Append a value for a key. Does not change or delete any existing + /// values for that key. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + append: func(name: field-key, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of keys and values in the Fields. Like the + /// constructor, the list represents each key-value pair. + /// + /// The outer list represents each key-value pair in the Fields. Keys + /// which have multiple values are represented by multiple entries in this + /// list with the same key. + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivelant in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + type headers = fields; + + /// Trailers is an alias for Fields. + type trailers = fields; + + /// Represents an incoming HTTP Request. + resource incoming-request { + + /// Returns the method of the incoming request. + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + scheme: func() -> option; + + /// Returns the authority from the request, if it was present. + authority: func() -> option; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + resource outgoing-request { + + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + constructor( + headers: headers + ); + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + + /// Get the Method for the Request. + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + set-method: func(method: method) -> result; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + set-path-with-query: func(path-with-query: option) -> result; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + set-scheme: func(scheme: option) -> result; + + /// Get the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. + authority: func() -> option; + /// Set the HTTP Authority for the Request. A value of `none` may be used + /// with Related Schemes which do not require an Authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid uri authority. + set-authority: func(authority: option) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + resource request-options { + /// Construct a default `request-options` value. + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + between-bytes-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + type status-code = u16; + + /// Represents an incoming HTTP Response. + resource incoming-response { + + /// Returns the status code from the incoming response. + status: func() -> status-code; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventaully return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occured, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occured receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + resource outgoing-response { + + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + status-code: func() -> status-code; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + set-status-code: func(status-code: status-code) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transfered to + /// another component by e.g. `outgoing-handler.handle`. + headers: func() -> headers; + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occured. The implementation should propogate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventaully return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occured. When this pollable is ready, + /// the `get` method will return `some`. + subscribe: func() -> pollable; + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have recieved successfully, or that an error + /// occured. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + get: func() -> option>>; + + } +} diff --git a/_examples/http-client/wit/deps/io/error.wit b/_examples/http-client/wit/deps/io/error.wit new file mode 100644 index 0000000..22e5b64 --- /dev/null +++ b/_examples/http-client/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.0; + + +interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// provide functions to further "downcast" this error into more specific + /// error information. For example, `error`s returned in streams derived + /// from filesystem types to be described using the filesystem's own + /// error-code type, using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a parameter + /// `borrow` and returns + /// `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + resource error { + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + to-debug-string: func() -> string; + } +} diff --git a/_examples/http-client/wit/deps/io/poll.wit b/_examples/http-client/wit/deps/io/poll.wit new file mode 100644 index 0000000..ddc67f8 --- /dev/null +++ b/_examples/http-client/wit/deps/io/poll.wit @@ -0,0 +1,41 @@ +package wasi:io@0.2.0; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + ready: func() -> bool; + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + block: func(); + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// If the list contains more elements than can be indexed with a `u32` + /// value, this function traps. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being reaedy for I/O. + poll: func(in: list>) -> list; +} diff --git a/_examples/http-client/wit/deps/io/streams.wit b/_examples/http-client/wit/deps/io/streams.wit new file mode 100644 index 0000000..6d2f871 --- /dev/null +++ b/_examples/http-client/wit/deps/io/streams.wit @@ -0,0 +1,262 @@ +package wasi:io@0.2.0; + +/// WASI I/O is an I/O abstraction API which is currently focused on providing +/// stream types. +/// +/// In the future, the component model is expected to add built-in stream types; +/// when it does, they are expected to subsume this API. +interface streams { + use error.{error}; + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + resource input-stream { + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + blocking-read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + blocking-skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + } + + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + resource output-stream { + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + check-write: func() -> result; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + write: func( + contents: list + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occured. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + subscribe: func() -> pollable; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivelant to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/_examples/http-client/wit/deps/io/world.wit b/_examples/http-client/wit/deps/io/world.wit new file mode 100644 index 0000000..5f0b43f --- /dev/null +++ b/_examples/http-client/wit/deps/io/world.wit @@ -0,0 +1,6 @@ +package wasi:io@0.2.0; + +world imports { + import streams; + import poll; +} diff --git a/_examples/http-server/wit/deps/wasmcloud/bus.wit b/_examples/http-client/wit/deps/lattice/bus.wit similarity index 100% rename from _examples/http-server/wit/deps/wasmcloud/bus.wit rename to _examples/http-client/wit/deps/lattice/bus.wit diff --git a/_examples/http-client/wit/deps/logging/logging.wit b/_examples/http-client/wit/deps/logging/logging.wit new file mode 100644 index 0000000..8c0bdf8 --- /dev/null +++ b/_examples/http-client/wit/deps/logging/logging.wit @@ -0,0 +1,35 @@ +/// 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); +} diff --git a/_examples/http-client/wit/deps/logging/world.wit b/_examples/http-client/wit/deps/logging/world.wit new file mode 100644 index 0000000..ede6286 --- /dev/null +++ b/_examples/http-client/wit/deps/logging/world.wit @@ -0,0 +1,5 @@ +package wasi:logging; + +world imports { + import logging; +} diff --git a/_examples/http-client/wit/deps/messaging/messaging.wit b/_examples/http-client/wit/deps/messaging/messaging.wit new file mode 100644 index 0000000..239d289 --- /dev/null +++ b/_examples/http-client/wit/deps/messaging/messaging.wit @@ -0,0 +1,27 @@ +package wasmcloud:messaging@0.2.0; + +// Types common to message broker interactions +interface types { + // A message sent to or received from a broker + record broker-message { + subject: string, + body: list, + reply-to: option, + } +} + +interface handler { + use types.{broker-message}; + + // Callback handled to invoke a function when a message is received from a subscription + handle-message: func(msg: broker-message) -> result<_, string>; +} + +interface consumer { + use types.{broker-message}; + + // Perform a request operation on a subject + request: func(subject: string, body: list, timeout-ms: u32) -> result; + // Publish a message to a subject without awaiting a response + publish: func(msg: broker-message) -> result<_, string>; +} diff --git a/_examples/http-client/wit/deps/random/insecure-seed.wit b/_examples/http-client/wit/deps/random/insecure-seed.wit new file mode 100644 index 0000000..47210ac --- /dev/null +++ b/_examples/http-client/wit/deps/random/insecure-seed.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.0; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + insecure-seed: func() -> tuple; +} diff --git a/_examples/http-client/wit/deps/random/insecure.wit b/_examples/http-client/wit/deps/random/insecure.wit new file mode 100644 index 0000000..c58f4ee --- /dev/null +++ b/_examples/http-client/wit/deps/random/insecure.wit @@ -0,0 +1,22 @@ +package wasi:random@0.2.0; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + get-insecure-random-u64: func() -> u64; +} diff --git a/_examples/http-client/wit/deps/random/random.wit b/_examples/http-client/wit/deps/random/random.wit new file mode 100644 index 0000000..0c017f0 --- /dev/null +++ b/_examples/http-client/wit/deps/random/random.wit @@ -0,0 +1,26 @@ +package wasi:random@0.2.0; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + get-random-u64: func() -> u64; +} diff --git a/_examples/http-client/wit/deps/random/world.wit b/_examples/http-client/wit/deps/random/world.wit new file mode 100644 index 0000000..3da3491 --- /dev/null +++ b/_examples/http-client/wit/deps/random/world.wit @@ -0,0 +1,7 @@ +package wasi:random@0.2.0; + +world imports { + import random; + import insecure; + import insecure-seed; +} diff --git a/_examples/http-client/wit/deps/secrets/secrets.wit b/_examples/http-client/wit/deps/secrets/secrets.wit new file mode 100644 index 0000000..da6f4ad --- /dev/null +++ b/_examples/http-client/wit/deps/secrets/secrets.wit @@ -0,0 +1,56 @@ +/// This WIT interface powers secret support in wasmCloud +/// +/// See RFC #2190 https://github.com/wasmCloud/wasmCloud/issues/2190 + +package wasmcloud:secrets@0.1.0-draft; + +interface store { + // An error type that encapsulates the different errors that can occur fetching secrets + variant secrets-error { + // This indicates an error from an "upstream" secrets source. + // As this could be almost _anything_ (such as Vault, Kubernetes Secrets, 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), + // This indicates that the secret was not found. Generally "not found" errors will + // be handled by the upstream secrets backend, but there are cases where the host + // may need to return this error. + not-found, + } + + // A secret value can be either a string or a byte array, which lets you + // store binary data as a secret. + variant secret-value { + // A string value + %string(string), + // A byte array value + bytes(list), + } + + // A secret is a resource that can only be borrowed. This allows you to + // pass around handles to secrets and not reveal the values until a + // component needs them. + // You need to use the reveal interface to get the value. + resource secret; + + // Gets a single opaque secrets value set at the given key if it exists + get: func( + // A string key to fetch + key: string, + ) -> result; + +} + +interface reveal { + use store.{secret, secret-value}; + + // Reveals the value of a secret to the caller. + // This lets you easily audit your code to discover where secrets are being used. + reveal: func(s: borrow) -> secret-value; +} diff --git a/_examples/http-client/wit/deps/sockets/instance-network.wit b/_examples/http-client/wit/deps/sockets/instance-network.wit new file mode 100644 index 0000000..e455d0f --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/instance-network.wit @@ -0,0 +1,9 @@ + +/// This interface provides a value-export of the default network handle.. +interface instance-network { + use network.{network}; + + /// Get a handle to the default network. + instance-network: func() -> network; + +} diff --git a/_examples/http-client/wit/deps/sockets/ip-name-lookup.wit b/_examples/http-client/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 0000000..8e639ec --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,51 @@ + +interface ip-name-lookup { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network, error-code, ip-address}; + + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + resolve-addresses: func(network: borrow, name: string) -> result; + + resource resolve-address-stream { + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } +} diff --git a/_examples/http-client/wit/deps/sockets/network.wit b/_examples/http-client/wit/deps/sockets/network.wit new file mode 100644 index 0000000..9cadf06 --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/network.wit @@ -0,0 +1,145 @@ + +interface network { + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + + /// The operation timed out before it could finish completely. + timeout, + + /// This operation is incompatible with another asynchronous operation that is already in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + + /// A bind operation failed because the provided address is not an address that the `network` can bind to. + address-not-bindable, + + /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. + address-in-use, + + /// The remote address is not reachable + remote-unreachable, + + + /// The TCP connection was forcefully rejected + connection-refused, + + /// The TCP connection was reset. + connection-reset, + + /// A TCP connection was aborted. + connection-aborted, + + + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + + + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + permanent-resolver-failure, + } + + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + type ipv4-address = tuple; + type ipv6-address = tuple; + + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } + +} diff --git a/_examples/http-client/wit/deps/sockets/tcp-create-socket.wit b/_examples/http-client/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 0000000..c7ddf1f --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,27 @@ + +interface tcp-create-socket { + use network.{network, error-code, ip-address-family}; + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/_examples/http-client/wit/deps/sockets/tcp.wit b/_examples/http-client/wit/deps/sockets/tcp.wit new file mode 100644 index 0000000..5902b9e --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/tcp.wit @@ -0,0 +1,353 @@ + +interface tcp { + use wasi:io/streams@0.2.0.{input-stream, output-stream}; + use wasi:io/poll@0.2.0.{pollable}; + use wasi:clocks/monotonic-clock@0.2.0.{duration}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + + /// Similar to `SHUT_WR` in POSIX. + send, + + /// Similar to `SHUT_RDWR` in POSIX. + both, + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for a more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + resource tcp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connection` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + finish-connect: func() -> result, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + start-listen: func() -> result<_, error-code>; + finish-listen: func() -> result<_, error-code>; + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + accept: func() -> result, error-code>; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` state. + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + keep-alive-enabled: func() -> result; + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-idle-time: func() -> result; + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-interval: func() -> result; + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + keep-alive-count: func() -> result; + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + hop-limit: func() -> result; + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for a more information. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent. Shutting a down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/_examples/http-client/wit/deps/sockets/udp-create-socket.wit b/_examples/http-client/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 0000000..0482d1f --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,27 @@ + +interface udp-create-socket { + use network.{network, error-code, ip-address-family}; + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/_examples/http-client/wit/deps/sockets/udp.wit b/_examples/http-client/wit/deps/sockets/udp.wit new file mode 100644 index 0000000..d987a0a --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/udp.wit @@ -0,0 +1,266 @@ + +interface udp { + use wasi:io/poll@0.2.0.{pollable}; + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + record outgoing-datagram { + /// The payload. + data: list, + + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. + remote-address: option, + } + + + + /// A UDP socket handle. + resource udp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + finish-bind: func() -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, but + /// only the most recently returned pair of streams will be operational. Implementations may trap if + /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + %stream: func(remote-address: option) -> result, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + local-address: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + address-family: func() -> ip-address-family; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + unicast-hop-limit: func() -> result; + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + receive-buffer-size: func() -> result; + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + send-buffer-size: func() -> result; + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource incoming-datagram-stream { + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } + + resource outgoing-datagram-stream { + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without blocking and + /// returns how many messages were actually sent (or queued for sending). This function never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list and sequentially + /// sending each individual datagram until either the end of the list has been reached or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI Preview2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + subscribe: func() -> pollable; + } +} diff --git a/_examples/http-client/wit/deps/sockets/world.wit b/_examples/http-client/wit/deps/sockets/world.wit new file mode 100644 index 0000000..f8bb92a --- /dev/null +++ b/_examples/http-client/wit/deps/sockets/world.wit @@ -0,0 +1,11 @@ +package wasi:sockets@0.2.0; + +world imports { + import instance-network; + import network; + import udp; + import udp-create-socket; + import tcp; + import tcp-create-socket; + import ip-name-lookup; +} diff --git a/_examples/http-client/wit/world.wit b/_examples/http-client/wit/world.wit new file mode 100644 index 0000000..2156a0e --- /dev/null +++ b/_examples/http-client/wit/world.wit @@ -0,0 +1,8 @@ +package example:http-client; + +world example { + include wasmcloud:component/imports; + + import wasi:http/outgoing-handler@0.2.0; + export wasi:http/incoming-handler@0.2.0; +} diff --git a/_examples/http-server/gen/wasi/config/runtime/abi.go b/_examples/http-server/gen/wasi/config/runtime/abi.go new file mode 100644 index 0000000..9e4d898 --- /dev/null +++ b/_examples/http-server/gen/wasi/config/runtime/abi.go @@ -0,0 +1,18 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package runtime + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "unsafe" +) + +// OptionStringShape is used for storage in variant or result types. +type OptionStringShape struct { + shape [unsafe.Sizeof(cm.Option[string]{})]byte +} + +// ConfigErrorShape is used for storage in variant or result types. +type ConfigErrorShape struct { + shape [unsafe.Sizeof(ConfigError{})]byte +} diff --git a/_examples/http-server/gen/wasi/config/runtime/empty.s b/_examples/http-server/gen/wasi/config/runtime/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-server/gen/wasi/config/runtime/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-server/gen/wasi/config/runtime/runtime.wit.go b/_examples/http-server/gen/wasi/config/runtime/runtime.wit.go new file mode 100644 index 0000000..edf169f --- /dev/null +++ b/_examples/http-server/gen/wasi/config/runtime/runtime.wit.go @@ -0,0 +1,84 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package runtime represents the imported interface "wasi:config/runtime@0.2.0-draft". +package runtime + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// ConfigError represents the variant "wasi:config/runtime@0.2.0-draft#config-error". +// +// An error type that encapsulates the different errors that can occur fetching config +// +// variant config-error { +// upstream(string), +// io(string), +// } +type ConfigError cm.Variant[uint8, string, string] + +// ConfigErrorUpstream returns a [ConfigError] of case "upstream". +// +// 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. +func ConfigErrorUpstream(data string) ConfigError { + return cm.New[ConfigError](0, data) +} + +// Upstream returns a non-nil *[string] if [ConfigError] represents the variant case "upstream". +func (self *ConfigError) Upstream() *string { + return cm.Case[string](self, 0) +} + +// ConfigErrorIO returns a [ConfigError] of case "io". +// +// 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. +func ConfigErrorIO(data string) ConfigError { + return cm.New[ConfigError](1, data) +} + +// IO returns a non-nil *[string] if [ConfigError] represents the variant case "io". +func (self *ConfigError) IO() *string { + return cm.Case[string](self, 1) +} + +// Get represents the imported function "get". +// +// Gets a single opaque config value set at the given key if it exists +// +// get: func(key: string) -> result, config-error> +// +//go:nosplit +func Get(key string) (result cm.Result[OptionStringShape, cm.Option[string], ConfigError]) { + key0, key1 := cm.LowerString(key) + wasmimport_Get((*uint8)(key0), (uint32)(key1), &result) + return +} + +//go:wasmimport wasi:config/runtime@0.2.0-draft get +//go:noescape +func wasmimport_Get(key0 *uint8, key1 uint32, result *cm.Result[OptionStringShape, cm.Option[string], ConfigError]) + +// GetAll represents the imported function "get-all". +// +// Gets a list of all set config data +// +// get-all: func() -> result>, config-error> +// +//go:nosplit +func GetAll() (result cm.Result[ConfigErrorShape, cm.List[[2]string], ConfigError]) { + wasmimport_GetAll(&result) + return +} + +//go:wasmimport wasi:config/runtime@0.2.0-draft get-all +//go:noescape +func wasmimport_GetAll(result *cm.Result[ConfigErrorShape, cm.List[[2]string], ConfigError]) diff --git a/_examples/http-server/gen/wasmcloud/messaging/consumer/abi.go b/_examples/http-server/gen/wasmcloud/messaging/consumer/abi.go new file mode 100644 index 0000000..70f60eb --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/messaging/consumer/abi.go @@ -0,0 +1,32 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package consumer + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-server/gen/wasmcloud/messaging/types" + "unsafe" +) + +// BrokerMessageShape is used for storage in variant or result types. +type BrokerMessageShape struct { + shape [unsafe.Sizeof(types.BrokerMessage{})]byte +} + +func lower_OptionString(v cm.Option[string]) (f0 uint32, f1 *uint8, f2 uint32) { + some := v.Some() + if some != nil { + f0 = 1 + v1, v2 := cm.LowerString(*some) + f1 = (*uint8)(v1) + f2 = (uint32)(v2) + } + return +} + +func lower_BrokerMessage(v types.BrokerMessage) (f0 *uint8, f1 uint32, f2 *uint8, f3 uint32, f4 uint32, f5 *uint8, f6 uint32) { + f0, f1 = cm.LowerString(v.Subject) + f2, f3 = cm.LowerList(v.Body) + f4, f5, f6 = lower_OptionString(v.ReplyTo) + return +} diff --git a/_examples/http-server/gen/wasmcloud/messaging/consumer/consumer.wit.go b/_examples/http-server/gen/wasmcloud/messaging/consumer/consumer.wit.go new file mode 100644 index 0000000..3d360f4 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/messaging/consumer/consumer.wit.go @@ -0,0 +1,46 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package consumer represents the imported interface "wasmcloud:messaging/consumer@0.2.0". +package consumer + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-server/gen/wasmcloud/messaging/types" +) + +// Request represents the imported function "request". +// +// Perform a request operation on a subject +// +// request: func(subject: string, body: list, timeout-ms: u32) -> result +// +//go:nosplit +func Request(subject string, body cm.List[uint8], timeoutMs uint32) (result cm.Result[BrokerMessageShape, types.BrokerMessage, string]) { + subject0, subject1 := cm.LowerString(subject) + body0, body1 := cm.LowerList(body) + timeoutMs0 := (uint32)(timeoutMs) + wasmimport_Request((*uint8)(subject0), (uint32)(subject1), (*uint8)(body0), (uint32)(body1), (uint32)(timeoutMs0), &result) + return +} + +//go:wasmimport wasmcloud:messaging/consumer@0.2.0 request +//go:noescape +func wasmimport_Request(subject0 *uint8, subject1 uint32, body0 *uint8, body1 uint32, timeoutMs0 uint32, result *cm.Result[BrokerMessageShape, types.BrokerMessage, string]) + +// Publish represents the imported function "publish". +// +// Publish a message to a subject without awaiting a response +// +// publish: func(msg: broker-message) -> result<_, string> +// +//go:nosplit +func Publish(msg types.BrokerMessage) (result cm.Result[string, struct{}, string]) { + msg0, msg1, msg2, msg3, msg4, msg5, msg6 := lower_BrokerMessage(msg) + wasmimport_Publish((*uint8)(msg0), (uint32)(msg1), (*uint8)(msg2), (uint32)(msg3), (uint32)(msg4), (*uint8)(msg5), (uint32)(msg6), &result) + return +} + +//go:wasmimport wasmcloud:messaging/consumer@0.2.0 publish +//go:noescape +func wasmimport_Publish(msg0 *uint8, msg1 uint32, msg2 *uint8, msg3 uint32, msg4 uint32, msg5 *uint8, msg6 uint32, result *cm.Result[string, struct{}, string]) diff --git a/_examples/http-server/gen/wasmcloud/messaging/consumer/empty.s b/_examples/http-server/gen/wasmcloud/messaging/consumer/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/messaging/consumer/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-server/gen/wasmcloud/messaging/types/types.wit.go b/_examples/http-server/gen/wasmcloud/messaging/types/types.wit.go new file mode 100644 index 0000000..6fbc9e9 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/messaging/types/types.wit.go @@ -0,0 +1,25 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package types represents the imported interface "wasmcloud:messaging/types@0.2.0". +// +// Types common to message broker interactions +package types + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// BrokerMessage represents the record "wasmcloud:messaging/types@0.2.0#broker-message". +// +// A message sent to or received from a broker +// +// record broker-message { +// subject: string, +// body: list, +// reply-to: option, +// } +type BrokerMessage struct { + Subject string + Body cm.List[uint8] + ReplyTo cm.Option[string] +} diff --git a/_examples/http-server/gen/wasmcloud/secrets/reveal/empty.s b/_examples/http-server/gen/wasmcloud/secrets/reveal/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/secrets/reveal/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-server/gen/wasmcloud/secrets/reveal/reveal.wit.go b/_examples/http-server/gen/wasmcloud/secrets/reveal/reveal.wit.go new file mode 100644 index 0000000..b209d91 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/secrets/reveal/reveal.wit.go @@ -0,0 +1,27 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package reveal represents the imported interface "wasmcloud:secrets/reveal@0.1.0-draft". +package reveal + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" + "github.com/wasmCloud/component-sdk-go/_examples/http-server/gen/wasmcloud/secrets/store" +) + +// Reveal represents the imported function "reveal". +// +// Reveals the value of a secret to the caller. +// This lets you easily audit your code to discover where secrets are being used. +// +// reveal: func(s: borrow) -> secret-value +// +//go:nosplit +func Reveal(s store.Secret) (result store.SecretValue) { + s0 := cm.Reinterpret[uint32](s) + wasmimport_Reveal((uint32)(s0), &result) + return +} + +//go:wasmimport wasmcloud:secrets/reveal@0.1.0-draft reveal +//go:noescape +func wasmimport_Reveal(s0 uint32, result *store.SecretValue) diff --git a/_examples/http-server/gen/wasmcloud/secrets/store/abi.go b/_examples/http-server/gen/wasmcloud/secrets/store/abi.go new file mode 100644 index 0000000..71add12 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/secrets/store/abi.go @@ -0,0 +1,12 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +package store + +import ( + "unsafe" +) + +// SecretsErrorShape is used for storage in variant or result types. +type SecretsErrorShape struct { + shape [unsafe.Sizeof(SecretsError{})]byte +} diff --git a/_examples/http-server/gen/wasmcloud/secrets/store/empty.s b/_examples/http-server/gen/wasmcloud/secrets/store/empty.s new file mode 100644 index 0000000..5444f20 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/secrets/store/empty.s @@ -0,0 +1,3 @@ +// This file exists for testing this package without WebAssembly, +// allowing empty function bodies with a //go:wasmimport directive. +// See https://pkg.go.dev/cmd/compile for more information. diff --git a/_examples/http-server/gen/wasmcloud/secrets/store/store.wit.go b/_examples/http-server/gen/wasmcloud/secrets/store/store.wit.go new file mode 100644 index 0000000..06891e7 --- /dev/null +++ b/_examples/http-server/gen/wasmcloud/secrets/store/store.wit.go @@ -0,0 +1,144 @@ +// Code generated by wit-bindgen-go. DO NOT EDIT. + +// Package store represents the imported interface "wasmcloud:secrets/store@0.1.0-draft". +package store + +import ( + "github.com/bytecodealliance/wasm-tools-go/cm" +) + +// SecretsError represents the variant "wasmcloud:secrets/store@0.1.0-draft#secrets-error". +// +// An error type that encapsulates the different errors that can occur fetching secrets +// +// variant secrets-error { +// upstream(string), +// io(string), +// not-found, +// } +type SecretsError cm.Variant[uint8, string, string] + +// SecretsErrorUpstream returns a [SecretsError] of case "upstream". +// +// This indicates an error from an "upstream" secrets source. +// As this could be almost _anything_ (such as Vault, Kubernetes Secrets, KeyValue +// buckets, etc), +// the error message is a string. +func SecretsErrorUpstream(data string) SecretsError { + return cm.New[SecretsError](0, data) +} + +// Upstream returns a non-nil *[string] if [SecretsError] represents the variant case "upstream". +func (self *SecretsError) Upstream() *string { + return cm.Case[string](self, 0) +} + +// SecretsErrorIO returns a [SecretsError] of case "io". +// +// 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. +func SecretsErrorIO(data string) SecretsError { + return cm.New[SecretsError](1, data) +} + +// IO returns a non-nil *[string] if [SecretsError] represents the variant case "io". +func (self *SecretsError) IO() *string { + return cm.Case[string](self, 1) +} + +// SecretsErrorNotFound returns a [SecretsError] of case "not-found". +// +// This indicates that the secret was not found. Generally "not found" errors will +// be handled by the upstream secrets backend, but there are cases where the host +// may need to return this error. +func SecretsErrorNotFound() SecretsError { + var data struct{} + return cm.New[SecretsError](2, data) +} + +// NotFound returns true if [SecretsError] represents the variant case "not-found". +func (self *SecretsError) NotFound() bool { + return self.Tag() == 2 +} + +// SecretValue represents the variant "wasmcloud:secrets/store@0.1.0-draft#secret-value". +// +// A secret value can be either a string or a byte array, which lets you +// store binary data as a secret. +// +// variant secret-value { +// string(string), +// bytes(list), +// } +type SecretValue cm.Variant[uint8, string, cm.List[uint8]] + +// SecretValueString returns a [SecretValue] of case "string". +// +// A string value +func SecretValueString(data string) SecretValue { + return cm.New[SecretValue](0, data) +} + +// String returns a non-nil *[string] if [SecretValue] represents the variant case "string". +func (self *SecretValue) String() *string { + return cm.Case[string](self, 0) +} + +// SecretValueBytes returns a [SecretValue] of case "bytes". +// +// A byte array value +func SecretValueBytes(data cm.List[uint8]) SecretValue { + return cm.New[SecretValue](1, data) +} + +// Bytes returns a non-nil *[cm.List[uint8]] if [SecretValue] represents the variant case "bytes". +func (self *SecretValue) Bytes() *cm.List[uint8] { + return cm.Case[cm.List[uint8]](self, 1) +} + +// Secret represents the imported resource "wasmcloud:secrets/store@0.1.0-draft#secret". +// +// A secret is a resource that can only be borrowed. This allows you to +// pass around handles to secrets and not reveal the values until a +// component needs them. +// You need to use the reveal interface to get the value. +// +// resource secret +type Secret cm.Resource + +// ResourceDrop represents the imported resource-drop for resource "secret". +// +// Drops a resource handle. +// +//go:nosplit +func (self Secret) ResourceDrop() { + self0 := cm.Reinterpret[uint32](self) + wasmimport_SecretResourceDrop((uint32)(self0)) + return +} + +//go:wasmimport wasmcloud:secrets/store@0.1.0-draft [resource-drop]secret +//go:noescape +func wasmimport_SecretResourceDrop(self0 uint32) + +// Get represents the imported function "get". +// +// Gets a single opaque secrets value set at the given key if it exists +// +// get: func(key: string) -> result +// +//go:nosplit +func Get(key string) (result cm.Result[SecretsErrorShape, Secret, SecretsError]) { + key0, key1 := cm.LowerString(key) + wasmimport_Get((*uint8)(key0), (uint32)(key1), &result) + return +} + +//go:wasmimport wasmcloud:secrets/store@0.1.0-draft get +//go:noescape +func wasmimport_Get(key0 *uint8, key1 uint32, result *cm.Result[SecretsErrorShape, Secret, SecretsError]) diff --git a/_examples/http-server/main.go b/_examples/http-server/main.go index e21a1d7..16dcde5 100644 --- a/_examples/http-server/main.go +++ b/_examples/http-server/main.go @@ -46,16 +46,16 @@ func entryHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add("content-type", "text/plain") w.Header().Add("X-Requested-Path", r.URL.Path) w.Header().Add("X-Existing-Paths", strings.Join(keys, ",")) - w.Write([]byte(Index)) + _, _ = w.Write([]byte(Index)) } func headersHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add("X-Your-User-Agent", r.Header.Get("User-Agent")) - w.Write([]byte("Check headers!")) + _, _ = w.Write([]byte("Check headers!")) } -func errorHandler(w http.ResponseWriter, r *http.Request) { +func errorHandler(w http.ResponseWriter, _ *http.Request) { http.Error(w, "Something went wrong", http.StatusInternalServerError) } @@ -66,7 +66,7 @@ func formHandler(w http.ResponseWriter, r *http.Request) { } for key, values := range r.Form { - w.Write([]byte(key + ": " + strings.Join(values, ",") + "\n")) + _, _ = w.Write([]byte(key + ": " + strings.Join(values, ",") + "\n")) } } diff --git a/_examples/http-server/wit/deps.lock b/_examples/http-server/wit/deps.lock index a7927d4..9b4d85b 100644 --- a/_examples/http-server/wit/deps.lock +++ b/_examples/http-server/wit/deps.lock @@ -8,9 +8,13 @@ sha512 = "e6b53a07221f1413953c9797c68f08b815fdaebf66419bbc1ea3e8b7dece7373106269 [component] path = "../../../wit" -sha256 = "daaab744fe06a2ee87e4d183de50c7660e08cd9af1af796d997771e0af09204f" -sha512 = "3f18283f5fac610a71cbc67a548596f2f75cf61b795bf21a7d51b31f56ea404dd39390e20da1cf3cbe007a9a6607e3c1832d72f45881cf06c3035beb79df4d1b" -deps = ["cli", "clocks", "filesystem", "io", "logging", "random", "sockets", "wasmcloud"] +sha256 = "ec5b1fc6183ecd80b8328e2345d96d2b7e9fc8c2085300389d21c078ab03729f" +sha512 = "5b1488b7be9f9e05b713aa9cc5465eb730550eab3ae3a9a5ca8a243947a6ae9b90e4a4f06ecd9cc9a375306bb619c54b16856a73d25aa227c45352b88ec741db" +deps = ["cli", "clocks", "config", "filesystem", "io", "lattice", "logging", "messaging", "random", "secrets", "sockets"] + +[config] +sha256 = "9148c06861712b69170af7b8ec37896b4104297d920fdec9f3bcc0b1eee4a5c8" +sha512 = "25a54101620f279c835b39f56f6dbf8a92b374b6faaf6cf6aaa1ea06d8b97b9b79788cf8abd9c2ad0c11e3629dba6a2513b71f2c54b9f95027054ae54a4615b8" [filesystem] sha256 = "498c465cfd04587db40f970fff2185daa597d074c20b68a8bcbae558f261499b" @@ -26,18 +30,26 @@ deps = ["cli", "clocks", "filesystem", "io", "random", "sockets"] sha256 = "7210e5653539a15478f894d4da24cc69d61924cbcba21d2804d69314a88e5a4c" sha512 = "49184a1b0945a889abd52d25271172ed3dc2db6968fcdddb1bab7ee0081f4a3eeee0977ad2291126a37631c0d86eeea75d822fa8af224c422134500bf9f0f2bb" +[lattice] +sha256 = "b4946a8bfa48b2f4ac404de03617d25712879596be5417bde3de09ca9c369462" +sha512 = "09918bb2fa8f7af022f71453348be38ec7fd1a35df6809b8d0c5f246856712f969557ff65d9e5d4619e905191e27fba2fbbcc9f38c777a7b09eb73c30909d33f" + [logging] sha256 = "9676b482485bb0fd2751a390374c1108865a096b7037f4b5dbe524f066bfb06e" sha512 = "30a621a6d48a0175e8047c062e618523a85f69c45a7c31918da2b888f7527fce1aca67fa132552222725d0f6cdcaed95be7f16c28488d9468c0fad00cb7450b9" +[messaging] +sha256 = "41ada083aceb2b4ba92d9bd16d19b6462cc02b10378c9a49135c3447f9138a44" +sha512 = "aa9c819dfd9e85b19661f6087ffd824c44fc38c8a4bc1005c4e7fd34fe844633c52cae7a0412e9ea90f71826e0660e8a3b5672a0f0303c524e4139643ae675ac" + [random] sha256 = "7371d03c037d924caba2587fb2e7c5773a0d3c5fcecbf7971e0e0ba57973c53d" sha512 = "964c4e8925a53078e4d94ba907b54f89a0b7e154f46823a505391471466c17f53c8692682e5c85771712acd88b348686173fc07c53a3cfe3d301b8cd8ddd0de4" +[secrets] +sha256 = "4c965f81e4f8510e917976dc7017b070d23b964724e3ca058f28ec9e3d691854" +sha512 = "c23d3d86846b7f35238347974c104a3056e5871db85a8e17c607cf2c48c5fc6dc550fa698a233b78de2c7b25e80ff6c590d0a4bf8c8892b48b3cec52bc141d32" + [sockets] sha256 = "622bd28bbeb43736375dc02bd003fd3a016ff8ee91e14bab488325c6b38bf966" sha512 = "5a63c1f36de0c4548e1d2297bdbededb28721cbad94ef7825c469eae29d7451c97e00b4c1d6730ee1ec0c4a5aac922961a2795762d4a0c3bb54e30a391a84bae" - -[wasmcloud] -sha256 = "b4946a8bfa48b2f4ac404de03617d25712879596be5417bde3de09ca9c369462" -sha512 = "09918bb2fa8f7af022f71453348be38ec7fd1a35df6809b8d0c5f246856712f969557ff65d9e5d4619e905191e27fba2fbbcc9f38c777a7b09eb73c30909d33f" diff --git a/_examples/http-server/wit/deps/component/world.wit b/_examples/http-server/wit/deps/component/world.wit index 8a40ed3..186845a 100644 --- a/_examples/http-server/wit/deps/component/world.wit +++ b/_examples/http-server/wit/deps/component/world.wit @@ -1,14 +1,30 @@ package wasmcloud:component; +world exports { + // wasi + export wasi:http/incoming-handler@0.2.0; + + // wasmcloud + export wasmcloud:messaging/handler@0.2.0; +} + world imports { // tinygo include wasi:cli/imports@0.2.0; // wasi import wasi:logging/logging; - export wasi:http/incoming-handler@0.2.0; + import wasi:config/runtime@0.2.0-draft; import wasi:http/outgoing-handler@0.2.0; // wasmcloud import wasmcloud:bus/lattice@1.0.0; + import wasmcloud:messaging/consumer@0.2.0; + import wasmcloud:secrets/store@0.1.0-draft; + import wasmcloud:secrets/reveal@0.1.0-draft; +} + +world sdk { + include exports; + include imports; } diff --git a/_examples/http-server/wit/deps/config/runtime_config.wit b/_examples/http-server/wit/deps/config/runtime_config.wit new file mode 100644 index 0000000..29d53b1 --- /dev/null +++ b/_examples/http-server/wit/deps/config/runtime_config.wit @@ -0,0 +1,25 @@ +interface runtime { + /// An error type that encapsulates the different errors that can occur fetching config + variant config-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 single opaque config value set at the given key if it exists + get: func( + /// A string key to fetch + key: string + ) -> result, config-error>; + + /// Gets a list of all set config data + get-all: func() -> result>, config-error>; +} diff --git a/_examples/http-server/wit/deps/config/world.wit b/_examples/http-server/wit/deps/config/world.wit new file mode 100644 index 0000000..378c4a7 --- /dev/null +++ b/_examples/http-server/wit/deps/config/world.wit @@ -0,0 +1,6 @@ +package wasi:config@0.2.0-draft; + +world imports { + /// The runtime interface for config + import runtime; +} \ No newline at end of file diff --git a/_examples/http-server/wit/deps/lattice/bus.wit b/_examples/http-server/wit/deps/lattice/bus.wit new file mode 100644 index 0000000..9275448 --- /dev/null +++ b/_examples/http-server/wit/deps/lattice/bus.wit @@ -0,0 +1,14 @@ +package wasmcloud:bus@1.0.0; + +interface lattice { + /// Interface target. This represents an interface, which can be selected by `set-link-name`. + resource call-target-interface { + constructor(namespace: string, %package: string, %interface: string); + } + + /// Set an optional link name to use for all interfaces specified. This is advanced + /// functionality only available within wasmcloud and, as such, is exposed here as part of the + /// wasmcloud:bus package. This is used when you are linking multiple of the same interfaces + /// (i.e. a keyvalue implementation for caching and another one for secrets) to a component + set-link-name: func(name: string, interfaces: list); +} diff --git a/_examples/http-server/wit/deps/messaging/messaging.wit b/_examples/http-server/wit/deps/messaging/messaging.wit new file mode 100644 index 0000000..239d289 --- /dev/null +++ b/_examples/http-server/wit/deps/messaging/messaging.wit @@ -0,0 +1,27 @@ +package wasmcloud:messaging@0.2.0; + +// Types common to message broker interactions +interface types { + // A message sent to or received from a broker + record broker-message { + subject: string, + body: list, + reply-to: option, + } +} + +interface handler { + use types.{broker-message}; + + // Callback handled to invoke a function when a message is received from a subscription + handle-message: func(msg: broker-message) -> result<_, string>; +} + +interface consumer { + use types.{broker-message}; + + // Perform a request operation on a subject + request: func(subject: string, body: list, timeout-ms: u32) -> result; + // Publish a message to a subject without awaiting a response + publish: func(msg: broker-message) -> result<_, string>; +} diff --git a/_examples/http-server/wit/deps/secrets/secrets.wit b/_examples/http-server/wit/deps/secrets/secrets.wit new file mode 100644 index 0000000..da6f4ad --- /dev/null +++ b/_examples/http-server/wit/deps/secrets/secrets.wit @@ -0,0 +1,56 @@ +/// This WIT interface powers secret support in wasmCloud +/// +/// See RFC #2190 https://github.com/wasmCloud/wasmCloud/issues/2190 + +package wasmcloud:secrets@0.1.0-draft; + +interface store { + // An error type that encapsulates the different errors that can occur fetching secrets + variant secrets-error { + // This indicates an error from an "upstream" secrets source. + // As this could be almost _anything_ (such as Vault, Kubernetes Secrets, 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), + // This indicates that the secret was not found. Generally "not found" errors will + // be handled by the upstream secrets backend, but there are cases where the host + // may need to return this error. + not-found, + } + + // A secret value can be either a string or a byte array, which lets you + // store binary data as a secret. + variant secret-value { + // A string value + %string(string), + // A byte array value + bytes(list), + } + + // A secret is a resource that can only be borrowed. This allows you to + // pass around handles to secrets and not reveal the values until a + // component needs them. + // You need to use the reveal interface to get the value. + resource secret; + + // Gets a single opaque secrets value set at the given key if it exists + get: func( + // A string key to fetch + key: string, + ) -> result; + +} + +interface reveal { + use store.{secret, secret-value}; + + // Reveals the value of a secret to the caller. + // This lets you easily audit your code to discover where secrets are being used. + reveal: func(s: borrow) -> secret-value; +} diff --git a/go.mod b/go.mod index b5358fb..95eeb6d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module go.wasmcloud.dev/component -go 1.22.5 +go 1.23.0 require ( github.com/bytecodealliance/wasm-tools-go v0.2.0 diff --git a/net/wasihttp/adapter.go b/net/wasihttp/adapter.go index 74ed0f7..c8d20b8 100644 --- a/net/wasihttp/adapter.go +++ b/net/wasihttp/adapter.go @@ -11,11 +11,11 @@ import ( "go.wasmcloud.dev/component/gen/wasi/io/streams" ) -var _ http.ResponseWriter = (*responseOutparamWriter)(nil) +var _ http.ResponseWriter = (*ResponseOutparamWriter)(nil) type IncomingRequest = types.IncomingRequest -type responseOutparamWriter struct { +type ResponseOutparamWriter struct { outparam types.ResponseOutparam response types.OutgoingResponse wasiHeaders types.Fields @@ -29,11 +29,11 @@ type responseOutparamWriter struct { statuscode int } -func (row *responseOutparamWriter) Header() http.Header { +func (row *ResponseOutparamWriter) Header() http.Header { return row.httpHeaders } -func (row *responseOutparamWriter) Write(buf []byte) (int, error) { +func (row *ResponseOutparamWriter) Write(buf []byte) (int, error) { // NOTE(lxf): If this is the first write, make sure we set the headers/statuscode row.headerOnce.Do(row.reconcile) if row.headerErr != nil { @@ -55,7 +55,7 @@ func (row *responseOutparamWriter) Write(buf []byte) (int, error) { return int(contents.Len()), nil } -func (row *responseOutparamWriter) WriteHeader(statusCode int) { +func (row *ResponseOutparamWriter) WriteHeader(statusCode int) { row.headerOnce.Do(func() { row.statuscode = statusCode row.reconcile() @@ -63,7 +63,7 @@ func (row *responseOutparamWriter) WriteHeader(statusCode int) { } // reconcile headers from go to wasi -func (row *responseOutparamWriter) reconcileHeaders() error { +func (row *ResponseOutparamWriter) reconcileHeaders() error { for key, vals := range row.httpHeaders { fieldVals := []types.FieldValue{} for _, val := range vals { @@ -81,7 +81,7 @@ func (row *responseOutparamWriter) reconcileHeaders() error { return nil } -func (row *responseOutparamWriter) reconcile() { +func (row *ResponseOutparamWriter) reconcile() { if row.headerErr = row.reconcileHeaders(); row.headerErr != nil { return } @@ -107,13 +107,14 @@ func (row *responseOutparamWriter) reconcile() { types.ResponseOutparamSet(row.outparam, result) } -func (row *responseOutparamWriter) Close() error { +func (row *ResponseOutparamWriter) Close() error { if row.stream == nil { return nil } row.stream.BlockingFlush() row.stream.ResourceDrop() + row.stream = nil var maybeTrailers cm.Option[types.Fields] wasiTrailers := types.NewFields() @@ -141,8 +142,8 @@ func (row *responseOutparamWriter) Close() error { } // convert the ResponseOutparam to http.ResponseWriter -func NewHttpResponseWriter(out types.ResponseOutparam) *responseOutparamWriter { - return &responseOutparamWriter{ +func WASItoHTTPResponseWriter(out types.ResponseOutparam) *ResponseOutparamWriter { + return &ResponseOutparamWriter{ outparam: out, httpHeaders: http.Header{}, wasiHeaders: types.NewFields(), @@ -151,7 +152,7 @@ func NewHttpResponseWriter(out types.ResponseOutparam) *responseOutparamWriter { } // convert the IncomingRequest to http.Request -func NewHttpRequest(ir IncomingRequest) (req *http.Request, err error) { +func WASItoHTTPRequest(ir IncomingRequest) (req *http.Request, err error) { method, err := methodToString(ir.Method()) if err != nil { return nil, err @@ -188,7 +189,9 @@ func NewHttpRequest(ir IncomingRequest) (req *http.Request, err error) { } req.Trailer = trailers - toHttpHeader(ir.Headers(), &req.Header) + headers := ir.Headers() + WASItoHTTPHeader(headers, &req.Header) + headers.ResourceDrop() req.Host = authority req.URL.Host = authority @@ -222,7 +225,7 @@ func methodToString(m types.Method) (string, error) { return "", fmt.Errorf("failed to convert http method") } -func toHttpHeader(src types.Fields, dest *http.Header) { +func WASItoHTTPHeader(src types.Fields, dest *http.Header) { for _, f := range src.Entries().Slice() { key := string(f.F0) value := string(cm.List[uint8](f.F1).Slice()) @@ -230,32 +233,7 @@ func toHttpHeader(src types.Fields, dest *http.Header) { } } -// convert the IncomingRequest to http.Request -func NewOutgoingHttpRequest(req *http.Request) (types.OutgoingRequest, error) { - headers := types.NewFields() - if err := toWasiHeader(req.Header, headers); err != nil { - return types.NewOutgoingRequest(headers), err - } - - or := types.NewOutgoingRequest(headers) - - or.SetAuthority(cm.Some(req.Host)) - or.SetMethod(toWasiMethod(req.Method)) - or.SetPathWithQuery(cm.Some(req.URL.Path + "?" + req.URL.Query().Encode())) - - switch req.URL.Scheme { - case "http": - or.SetScheme(cm.Some(types.SchemeHTTP())) - case "https": - or.SetScheme(cm.Some(types.SchemeHTTPS())) - default: - or.SetScheme(cm.Some(types.SchemeOther(req.URL.Scheme))) - } - - return or, nil -} - -func toWasiHeader(src http.Header, dest types.Fields) error { +func HTTPtoWASIHeader(src http.Header, dest types.Fields) error { for k, v := range src { key := types.FieldKey(k) fieldVals := []types.FieldValue{} diff --git a/net/wasihttp/roundtripper.go b/net/wasihttp/roundtripper.go index 349d75b..731399a 100644 --- a/net/wasihttp/roundtripper.go +++ b/net/wasihttp/roundtripper.go @@ -33,52 +33,72 @@ func (r *Transport) requestOptions() types.RequestOptions { return options } -func (r *Transport) RoundTrip(req *http.Request) (*http.Response, error) { - or, err := NewOutgoingHttpRequest(req) - if err != nil { +func (r *Transport) RoundTrip(incomingRequest *http.Request) (*http.Response, error) { + var err error + + outHeaders := types.NewFields() + if err := HTTPtoWASIHeader(incomingRequest.Header, outHeaders); err != nil { return nil, err } + outRequest := types.NewOutgoingRequest(outHeaders) + + outRequest.SetAuthority(cm.Some(incomingRequest.Host)) + outRequest.SetMethod(toWasiMethod(incomingRequest.Method)) + outRequest.SetPathWithQuery(cm.Some(incomingRequest.URL.Path + "?" + incomingRequest.URL.Query().Encode())) + + switch incomingRequest.URL.Scheme { + case "http": + outRequest.SetScheme(cm.Some(types.SchemeHTTP())) + case "https": + outRequest.SetScheme(cm.Some(types.SchemeHTTPS())) + default: + outRequest.SetScheme(cm.Some(types.SchemeOther(incomingRequest.URL.Scheme))) + } + var adaptedBody io.WriteCloser - var body types.OutgoingBody - if req.Body != nil { - bodyRes := or.Body() + var body *types.OutgoingBody + if incomingRequest.Body != nil { + bodyRes := outRequest.Body() if bodyRes.IsErr() { return nil, fmt.Errorf("failed to acquire resource handle to request body: %s", bodyRes.Err()) } - - body = *bodyRes.OK() - + body = bodyRes.OK() adaptedBody, err = NewOutgoingBody(body) if err != nil { return nil, fmt.Errorf("failed to adapt body: %s", err) } } - handleResp := outgoinghandler.Handle(or, cm.Some(r.requestOptions())) + handleResp := outgoinghandler.Handle(outRequest, cm.Some(r.requestOptions())) if handleResp.Err() != nil { return nil, fmt.Errorf("%v", handleResp.Err()) } - if adaptedBody != nil { - if _, err := io.Copy(adaptedBody, req.Body); err != nil { - return nil, fmt.Errorf("failed to copy body: %s", err) + // NOTE(lxf): If request includes a body, copy it to the adapted wasi body + if body != nil { + if _, err := io.Copy(adaptedBody, incomingRequest.Body); err != nil { + return nil, fmt.Errorf("failed to copy body: %v", err) } - trailers := types.NewFields() - if err := toWasiHeader(req.Trailer, trailers); err != nil { + outTrailers := types.NewFields() + if err := HTTPtoWASIHeader(incomingRequest.Trailer, outTrailers); err != nil { return nil, err } - types.OutgoingBodyFinish(body, cm.Some(trailers)) + + outFinish := types.OutgoingBodyFinish(*body, cm.Some(outTrailers)) + if outFinish.IsErr() { + return nil, fmt.Errorf("failed to set trailer: %v", outFinish.Err()) + } } - top := *handleResp.OK() + // NOTE(lxf): Request is fully sent. Processing response. + futureResponse := handleResp.OK() + // wait until resp is returned - subscription := top.Subscribe() - subscription.Block() - subscription.ResourceDrop() + futureResponse.Subscribe().Block() - pollableOption := top.Get() + pollableOption := futureResponse.Get() if pollableOption.None() { return nil, fmt.Errorf("incoming resp is None") } @@ -93,16 +113,24 @@ func (r *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return nil, fmt.Errorf("%v", resultOption.Err()) } - incomingBodyTrailer := *resultOption.OK() - respBody, trailers, err := NewIncomingBodyTrailer(incomingBodyTrailer) + incomingResponse := resultOption.OK() + incomingBody, incomingTrailers, err := NewIncomingBodyTrailer(incomingResponse) if err != nil { return nil, fmt.Errorf("failed to consume incoming request %s", err) } + incomingHeaders := http.Header{} + headers := incomingResponse.Headers() + WASItoHTTPHeader(headers, &incomingHeaders) + headers.ResourceDrop() + resp := &http.Response{ - StatusCode: int(incomingBodyTrailer.Status()), - Body: respBody, - Trailer: trailers, + StatusCode: int(incomingResponse.Status()), + Status: http.StatusText(int(incomingResponse.Status())), + Request: incomingRequest, + Header: incomingHeaders, + Body: incomingBody, + Trailer: incomingTrailers, } return resp, nil diff --git a/net/wasihttp/server.go b/net/wasihttp/server.go index beac19a..6e9f20e 100644 --- a/net/wasihttp/server.go +++ b/net/wasihttp/server.go @@ -30,7 +30,7 @@ func HandleFunc(h http.HandlerFunc) { } func wasiHandle(request types.IncomingRequest, responseOut types.ResponseOutparam) { - httpReq, err := NewHttpRequest(request) + httpReq, err := WASItoHTTPRequest(request) if err != nil { types.ResponseOutparamSet(responseOut, cm.Err[cm.Result[types.ErrorCodeShape, types.OutgoingResponse, types.ErrorCode]]( types.ErrorCodeInternalError(cm.Some(err.Error()))), @@ -41,7 +41,7 @@ func wasiHandle(request types.IncomingRequest, responseOut types.ResponseOutpara defer httpReq.Body.Close() } - httpRes := NewHttpResponseWriter(responseOut) + httpRes := WASItoHTTPResponseWriter(responseOut) defer httpRes.Close() handler(httpRes, httpReq) diff --git a/net/wasihttp/streams.go b/net/wasihttp/streams.go index 6e26832..5f091c9 100644 --- a/net/wasihttp/streams.go +++ b/net/wasihttp/streams.go @@ -19,18 +19,24 @@ type BodyConsumer interface { type inputStreamReader struct { consumer BodyConsumer - body types.IncomingBody - stream streams.InputStream + body *types.IncomingBody + stream *streams.InputStream trailerLock sync.Mutex trailers http.Header trailerOnce sync.Once - dropOnce sync.Once } func (r *inputStreamReader) Close() error { - r.dropOnce.Do(func() { + r.trailerOnce.Do(r.parseTrailers) + + if r.stream != nil { r.stream.ResourceDrop() - }) + } + + if r.body != nil { + r.body.ResourceDrop() + r.body = nil + } return nil } @@ -40,10 +46,11 @@ func (r *inputStreamReader) parseTrailers() { defer r.trailerLock.Unlock() // if we got this far, then we release ownership from body, otherwise it is our responsibility to drop it - r.dropOnce.Do(func() {}) - r.stream.ResourceDrop() - futureTrailers := types.IncomingBodyFinish(r.body) + r.stream = nil + + futureTrailers := types.IncomingBodyFinish(*r.body) + defer futureTrailers.ResourceDrop() trailersResult := futureTrailers.Get() @@ -72,7 +79,11 @@ func (r *inputStreamReader) parseTrailers() { } func (r *inputStreamReader) Read(p []byte) (n int, err error) { - readResult := r.stream.BlockingRead(uint64(len(p))) + pollable := r.stream.Subscribe() + pollable.Block() + pollable.ResourceDrop() + + readResult := r.stream.Read(uint64(len(p))) if err := readResult.Err(); err != nil { if err.Closed() { r.trailerOnce.Do(r.parseTrailers) @@ -87,47 +98,50 @@ func (r *inputStreamReader) Read(p []byte) (n int, err error) { } func NewIncomingBodyTrailer(consumer BodyConsumer) (io.ReadCloser, http.Header, error) { - trailers := http.Header{} consumeResult := consumer.Consume() if consumeResult.IsErr() { return nil, nil, errors.New("failed to consume incoming request") } - body := *consumeResult.OK() + + body := consumeResult.OK() streamResult := body.Stream() if streamResult.IsErr() { return nil, nil, errors.New("failed to consume incoming request body stream") } + + stream := streamResult.OK() + + trailers := http.Header{} return &inputStreamReader{ consumer: consumer, trailers: trailers, body: body, - stream: *streamResult.OK(), + stream: stream, }, trailers, nil } -type outputStreamReader struct { - body types.OutgoingBody - stream streams.OutputStream +type outgoingBody struct { + body *types.OutgoingBody + stream *streams.OutputStream } -func NewOutgoingBody(body types.OutgoingBody) (io.WriteCloser, error) { +func NewOutgoingBody(body *types.OutgoingBody) (io.WriteCloser, error) { stream := body.Write() if stream.IsErr() { return nil, errors.New("failed to acquire resource handle to request body") } - return &outputStreamReader{ + return &outgoingBody{ body: body, - stream: *stream.OK(), + stream: stream.OK(), }, nil } -func (r *outputStreamReader) Close() error { +func (r *outgoingBody) Close() error { r.stream.ResourceDrop() - r.body.ResourceDrop() return nil } -func (r *outputStreamReader) Write(p []byte) (n int, err error) { +func (r *outgoingBody) Write(p []byte) (n int, err error) { contents := cm.ToList(p) writeResult := r.stream.BlockingWriteAndFlush(contents) if err := writeResult.Err(); err != nil {