From 277ae0bb1f42afed36c45e2c28370796000e6246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Sat, 18 Jan 2025 12:23:41 +0100 Subject: [PATCH 01/17] Update for composable app manifests (#1243) * update golem-exmaples and extend app dynamic help with components and dependencies * add new-app-component command * update app manifest schema refs * make fix --- Cargo.lock | 110 ++++++-------- golem-cli/Cargo.toml | 2 +- golem-cli/src/command.rs | 57 ++++++-- golem-cli/src/diagnose.rs | 2 +- golem-cli/src/examples.rs | 58 +++++++- golem-cli/src/model.rs | 2 +- golem-cli/src/model/text.rs | 2 +- .../auction-registry/golem.yaml | 4 +- .../auction-example/auction/golem.yaml | 4 +- test-components/auction-example/golem.yaml | 4 +- test-components/rpc/caller/golem.yaml | 4 +- test-components/rpc/counters/golem.yaml | 4 +- test-components/rpc/ephemeral/golem.yaml | 4 +- test-components/rpc/golem.yaml | 4 +- .../rpc/child-component/golem.yaml | 4 +- test-components/rust-service/rpc/golem.yaml | 4 +- .../rpc/parent-component/golem.yaml | 4 +- test-components/ts-rpc/caller/golem.yaml | 4 +- test-components/ts-rpc/counter/golem.yaml | 4 +- test-components/ts-rpc/golem.yaml | 4 +- wasm-rpc-stubgen/src/commands/app.rs | 137 +++++++++++++++--- wasm-rpc-stubgen/src/lib.rs | 38 +---- wasm-rpc-stubgen/src/log.rs | 4 + wasm-rpc-stubgen/src/model/app.rs | 40 ++++- 24 files changed, 331 insertions(+), 173 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bac742953a..e93a1caddf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1170,30 +1170,15 @@ dependencies = [ "which 4.4.2", ] -[[package]] -name = "bit-set" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" -dependencies = [ - "bit-vec 0.6.3", -] - [[package]] name = "bit-set" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" dependencies = [ - "bit-vec 0.8.0", + "bit-vec", ] -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - [[package]] name = "bit-vec" version = "0.8.0" @@ -1465,7 +1450,7 @@ dependencies = [ "bytes 1.9.0", "cargo-component-core", "cargo-config2", - "cargo_metadata 0.19.1", + "cargo_metadata", "clap", "futures", "heck 0.5.0", @@ -1545,20 +1530,6 @@ dependencies = [ "serde", ] -[[package]] -name = "cargo_metadata" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d886547e41f740c616ae73108f6eb70afe6d940c7bc697cb30f13daec073037" -dependencies = [ - "camino", - "cargo-platform", - "semver", - "serde", - "serde_json", - "thiserror 1.0.69", -] - [[package]] name = "cargo_metadata" version = "0.19.1" @@ -1865,7 +1836,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68578f196d2a33ff61b27fae256c3164f65e36382648e30666dde05b8cc9dfdf" dependencies = [ "async-trait", - "convert_case 0.6.0", + "convert_case", "json5", "nom", "pathdiff", @@ -1961,12 +1932,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" -[[package]] -name = "convert_case" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" - [[package]] name = "convert_case" version = "0.6.0" @@ -2620,19 +2585,6 @@ dependencies = [ "syn 2.0.96", ] -[[package]] -name = "derive_more" -version = "0.99.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" -dependencies = [ - "convert_case 0.4.0", - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.96", -] - [[package]] name = "derive_more" version = "1.0.0" @@ -3172,11 +3124,11 @@ checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" [[package]] name = "fancy-regex" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "531e46835a22af56d1e3b66f04844bed63158bc094a628bec1d321d9b4c44bf2" +checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" dependencies = [ - "bit-set 0.5.3", + "bit-set", "regex-automata 0.4.9", "regex-syntax 0.8.5", ] @@ -3799,7 +3751,7 @@ dependencies = [ "async-trait", "bincode", "bytes 1.9.0", - "cargo_metadata 0.19.1", + "cargo_metadata", "futures-core", "golem-wasm-ast", "golem-wasm-rpc", @@ -3830,7 +3782,7 @@ dependencies = [ "clap_complete", "cli-table", "colored", - "derive_more 1.0.0", + "derive_more", "dirs 5.0.1", "env_logger 0.11.6", "futures-util", @@ -3925,7 +3877,7 @@ dependencies = [ "combine", "console-subscriber", "dashmap", - "derive_more 1.0.0", + "derive_more", "figment", "fred", "git-version", @@ -4082,20 +4034,22 @@ dependencies = [ [[package]] name = "golem-examples" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c0bcbbedbbecc9c66f2349150cbeb1b9e9704958611af624fbf11ea7202c4d9" +checksum = "f0ae4fa06a19377a53f113c47c70724416fd9cf6b9f655749250ded3f81de616" dependencies = [ "Inflector", - "cargo_metadata 0.18.1", + "cargo_metadata", "clap", "colored", "copy_dir", - "derive_more 0.99.18", + "derive_more", "dir-diff", "fancy-regex", "golem-wit", "include_dir", + "itertools 0.14.0", + "nanoid", "once_cell", "regex", "serde", @@ -4111,7 +4065,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b33e98f6cc141902ffcc13d027d0bb9a4d3310e51ff182f67236384e8dfeb3ac" dependencies = [ "clap", - "convert_case 0.6.0", + "convert_case", "fmt", "indexmap 2.7.0", "indoc", @@ -4311,7 +4265,7 @@ dependencies = [ "async-trait", "bigdecimal", "bincode", - "cargo_metadata 0.19.1", + "cargo_metadata", "git-version", "golem-wasm-ast", "poem-openapi", @@ -4433,7 +4387,7 @@ dependencies = [ "cap-fs-ext", "cap-std", "cap-time-ext", - "cargo_metadata 0.19.1", + "cargo_metadata", "chrono", "console-subscriber", "dashmap", @@ -4513,7 +4467,7 @@ dependencies = [ "bincode", "bytes 1.9.0", "console-subscriber", - "derive_more 1.0.0", + "derive_more", "figment", "futures", "futures-util", @@ -4568,7 +4522,7 @@ dependencies = [ "chrono", "conditional-trait-gen", "criterion", - "derive_more 1.0.0", + "derive_more", "fastrand", "figment", "fred", @@ -5573,6 +5527,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.14" @@ -6216,6 +6179,15 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03" +[[package]] +name = "nanoid" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" +dependencies = [ + "rand", +] + [[package]] name = "nanorand" version = "0.7.0" @@ -7349,7 +7321,7 @@ dependencies = [ "base64 0.22.1", "bytes 1.9.0", "chrono", - "derive_more 1.0.0", + "derive_more", "futures-util", "humantime", "indexmap 2.7.0", @@ -7681,8 +7653,8 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14cae93065090804185d3b75f0bf93b8eeda30c7a9b4a33d3bdb3988d6229e50" dependencies = [ - "bit-set 0.8.0", - "bit-vec 0.8.0", + "bit-set", + "bit-vec", "bitflags 2.7.0", "lazy_static 1.5.0", "num-traits", diff --git a/golem-cli/Cargo.toml b/golem-cli/Cargo.toml index 81b143e9ea..cc2c7fbd84 100644 --- a/golem-cli/Cargo.toml +++ b/golem-cli/Cargo.toml @@ -45,7 +45,7 @@ derive_more = { workspace = true } dirs = "5.0.1" futures-util = { workspace = true } glob = "0.3.1" -golem-examples = "1.1.0" +golem-examples = "1.1.1" h2 = "0.4.7" http = { workspace = true } humansize = { workspace = true } diff --git a/golem-cli/src/command.rs b/golem-cli/src/command.rs index 746c1acefd..9023371f78 100644 --- a/golem-cli/src/command.rs +++ b/golem-cli/src/command.rs @@ -32,6 +32,8 @@ use api_deployment::ApiDeploymentSubcommand; use clap::{self, Command, Subcommand}; use component::ComponentSubCommand; use golem_common::uri::oss::uri::ComponentUri; +use golem_examples::cli::NameOrLanguage; +use golem_examples::model::{ComponentName, GuestLanguage, GuestLanguageTier, PackageName}; use golem_wasm_rpc_stubgen::App; use plugin::PluginSubcommand; use profile::{ProfileSubCommand, UniversalProfileAdd}; @@ -104,9 +106,43 @@ pub enum StaticSharedCommand { #[command(flatten)] command: diagnose::cli::Command, }, - /// Create a new Golem component from built-in examples - #[command(flatten)] - Examples(golem_examples::cli::Command), + + /// Create a new Golem standalone component example project from built-in examples + #[command()] + New { + #[command(flatten)] + name_or_language: NameOrLanguage, + + /// The package name of the generated component (in namespace:name format) + #[arg(short, long)] + package_name: Option, + + /// The new component's name + component_name: ComponentName, + }, + + /// Add a new Golem component to a project using Golem Application Manifest + #[command()] + NewAppComponent { + /// The component name (and package name) of the generated component (in namespace:name format) + component_name: PackageName, + + /// Component language + #[arg(short, long, alias = "lang")] + language: GuestLanguage, + }, + + /// Lists the built-in examples available for creating new components + #[command()] + ListExamples { + /// The minimum language tier to include in the list + #[arg(short, long)] + min_tier: Option, + + /// Filter examples by a given guest language + #[arg(short, long, alias = "lang")] + language: Option, + }, } impl CliCommand for StaticSharedCommand { @@ -116,19 +152,22 @@ impl CliCommand for StaticSharedCommand { diagnose(command); Ok(GolemResult::Empty) } - StaticSharedCommand::Examples(golem_examples::cli::Command::ListExamples { - min_tier, - language, - }) => examples::process_list_examples(min_tier, language), - StaticSharedCommand::Examples(golem_examples::cli::Command::New { + StaticSharedCommand::ListExamples { min_tier, language } => { + examples::list_standalone_examples(min_tier, language) + } + StaticSharedCommand::New { name_or_language, package_name, component_name, - }) => examples::process_new( + } => examples::new( name_or_language.example_name(), component_name, package_name, ), + StaticSharedCommand::NewAppComponent { + component_name, + language, + } => examples::new_app_component(component_name, language), } } } diff --git a/golem-cli/src/diagnose.rs b/golem-cli/src/diagnose.rs index a4a194d742..5d61f9f63f 100644 --- a/golem-cli/src/diagnose.rs +++ b/golem-cli/src/diagnose.rs @@ -716,7 +716,7 @@ impl DetectedTool { pub fn diagnose(command: cli::Command) { let selected_language = match &command.language { - Some(language) => SelectedLanguage::from_flag(language.clone()), + Some(language) => SelectedLanguage::from_flag(*language), None => SelectedLanguage::from_env(), }; diff --git a/golem-cli/src/examples.rs b/golem-cli/src/examples.rs index 39aa9ecb7a..94a27af434 100644 --- a/golem-cli/src/examples.rs +++ b/golem-cli/src/examples.rs @@ -14,24 +14,25 @@ use std::env; +use crate::model::{ExampleDescription, GolemError, GolemResult}; use golem_examples::model::{ - ComponentName, ExampleName, ExampleParameters, GuestLanguage, GuestLanguageTier, PackageName, + ComponentName, ComposableAppGroupName, ExampleName, ExampleParameters, GuestLanguage, + GuestLanguageTier, PackageName, TargetExistsResolveMode, }; use golem_examples::*; +use itertools::Itertools; -use crate::model::{ExampleDescription, GolemError, GolemResult}; - -pub fn process_new( +pub fn new( example_name: ExampleName, component_name: ComponentName, package_name: Option, ) -> Result { - let examples = GolemExamples::list_all_examples(); + let examples = all_standalone_examples(); let example = examples.iter().find(|example| example.name == example_name); match example { Some(example) => { let cwd = env::current_dir().expect("Failed to get current working directory"); - match GolemExamples::instantiate( + match instantiate_example( example, &ExampleParameters { component_name, @@ -39,6 +40,7 @@ pub fn process_new( .unwrap_or(PackageName::from_string("golem:component").unwrap()), target_path: cwd, }, + TargetExistsResolveMode::Fail, ) { Ok(instructions) => Ok(GolemResult::Str(instructions.to_string())), Err(err) => GolemResult::err(format!("Failed to instantiate component: {err}")), @@ -50,11 +52,11 @@ pub fn process_new( } } -pub fn process_list_examples( +pub fn list_standalone_examples( min_tier: Option, language: Option, ) -> Result { - let examples = GolemExamples::list_all_examples() + let examples = all_standalone_examples() .iter() .filter(|example| match &language { Some(language) => example.language == *language, @@ -69,3 +71,43 @@ pub fn process_list_examples( Ok(GolemResult::Ok(Box::new(examples))) } + +pub fn new_app_component( + component_name: PackageName, + language: GuestLanguage, +) -> Result { + let all_examples = all_composable_app_examples(); + + let Some(language_examples) = all_examples.get(&language) else { + return Err(GolemError(format!( + "No template found for {}, currently supported languages: {}", + language, + all_examples.keys().join(", ") + ))); + }; + + let default_examples = language_examples + .get(&ComposableAppGroupName::default()) + .expect("No default template found for the selected language"); + + assert_eq!( + default_examples.components.len(), + 1, + "Expected exactly one default component template" + ); + + let default_component_example = &default_examples.components[0]; + + match add_component_by_example( + default_examples.common.as_ref(), + default_component_example, + &env::current_dir().expect("Failed to get current working directory"), + &component_name, + ) { + Ok(_) => Ok(GolemResult::Str(format!( + "Added new app component {}", + component_name.to_string_with_colon() + ))), + Err(err) => Err(GolemError(format!("Failed to add component: {err}"))), + } +} diff --git a/golem-cli/src/model.rs b/golem-cli/src/model.rs index 460cf24733..445ad053d4 100644 --- a/golem-cli/src/model.rs +++ b/golem-cli/src/model.rs @@ -596,7 +596,7 @@ impl ExampleDescription { pub fn from_example(example: &Example) -> Self { Self { name: example.name.clone(), - language: example.language.clone(), + language: example.language, description: example.description.clone(), tier: example.language.tier(), } diff --git a/golem-cli/src/model/text.rs b/golem-cli/src/model/text.rs index 38fba00540..2ac5c17ba3 100644 --- a/golem-cli/src/model/text.rs +++ b/golem-cli/src/model/text.rs @@ -695,7 +695,7 @@ pub mod example { fn from(value: &ExampleDescription) -> Self { Self { name: value.name.clone(), - language: value.language.clone(), + language: value.language, tier: value.tier.clone(), description: textwrap::wrap(&value.description, 30).join("\n"), } diff --git a/test-components/auction-example/auction-registry/golem.yaml b/test-components/auction-example/auction-registry/golem.yaml index c7a3ca0b61..b7cda62f1b 100644 --- a/test-components/auction-example/auction-registry/golem.yaml +++ b/test-components/auction-example/auction-registry/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: auction-registry: diff --git a/test-components/auction-example/auction/golem.yaml b/test-components/auction-example/auction/golem.yaml index 6852fdd359..dd5ba8c541 100644 --- a/test-components/auction-example/auction/golem.yaml +++ b/test-components/auction-example/auction/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: auction: diff --git a/test-components/auction-example/golem.yaml b/test-components/auction-example/golem.yaml index fc14644feb..5f051e3e6a 100644 --- a/test-components/auction-example/golem.yaml +++ b/test-components/auction-example/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json tempDir: target/golem-temp templates: diff --git a/test-components/rpc/caller/golem.yaml b/test-components/rpc/caller/golem.yaml index 256d497f08..70bf7a944f 100644 --- a/test-components/rpc/caller/golem.yaml +++ b/test-components/rpc/caller/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: caller: diff --git a/test-components/rpc/counters/golem.yaml b/test-components/rpc/counters/golem.yaml index 0ca0ef07eb..b3e6819c09 100644 --- a/test-components/rpc/counters/golem.yaml +++ b/test-components/rpc/counters/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: counters: diff --git a/test-components/rpc/ephemeral/golem.yaml b/test-components/rpc/ephemeral/golem.yaml index 5484ccedf1..499373bd50 100644 --- a/test-components/rpc/ephemeral/golem.yaml +++ b/test-components/rpc/ephemeral/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: ephemeral: diff --git a/test-components/rpc/golem.yaml b/test-components/rpc/golem.yaml index fc14644feb..5f051e3e6a 100644 --- a/test-components/rpc/golem.yaml +++ b/test-components/rpc/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json tempDir: target/golem-temp templates: diff --git a/test-components/rust-service/rpc/child-component/golem.yaml b/test-components/rust-service/rpc/child-component/golem.yaml index dad604c8c0..04b3b06b2a 100644 --- a/test-components/rust-service/rpc/child-component/golem.yaml +++ b/test-components/rust-service/rpc/child-component/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: child-component: diff --git a/test-components/rust-service/rpc/golem.yaml b/test-components/rust-service/rpc/golem.yaml index c579ae6dda..1019c8be30 100644 --- a/test-components/rust-service/rpc/golem.yaml +++ b/test-components/rust-service/rpc/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json tempDir: target/golem-temp templates: diff --git a/test-components/rust-service/rpc/parent-component/golem.yaml b/test-components/rust-service/rpc/parent-component/golem.yaml index 86e960b83e..7d507d0c9e 100644 --- a/test-components/rust-service/rpc/parent-component/golem.yaml +++ b/test-components/rust-service/rpc/parent-component/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: parent-component: diff --git a/test-components/ts-rpc/caller/golem.yaml b/test-components/ts-rpc/caller/golem.yaml index 375321e37d..e7ebfaacfc 100644 --- a/test-components/ts-rpc/caller/golem.yaml +++ b/test-components/ts-rpc/caller/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: caller: diff --git a/test-components/ts-rpc/counter/golem.yaml b/test-components/ts-rpc/counter/golem.yaml index 5603d26bcb..bdd48e8e7b 100644 --- a/test-components/ts-rpc/counter/golem.yaml +++ b/test-components/ts-rpc/counter/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json components: counter: diff --git a/test-components/ts-rpc/golem.yaml b/test-components/ts-rpc/golem.yaml index 0155947ee9..7d1960795e 100644 --- a/test-components/ts-rpc/golem.yaml +++ b/test-components/ts-rpc/golem.yaml @@ -1,7 +1,7 @@ # Schema for IDEA: -# $schema: https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# $schema: https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json # Schema for vscode-yaml -# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.0/golem.schema.json +# yaml-language-server: $schema=https://schema.golem.cloud/app/golem/1.1.1/golem.schema.json tempDir: dist/golem-temp witDeps: diff --git a/wasm-rpc-stubgen/src/commands/app.rs b/wasm-rpc-stubgen/src/commands/app.rs index 6122735f7a..e2ea8185b2 100644 --- a/wasm-rpc-stubgen/src/commands/app.rs +++ b/wasm-rpc-stubgen/src/commands/app.rs @@ -20,6 +20,7 @@ use crate::wit_generate::{ use crate::wit_resolve::{ResolvedWitApplication, WitDepsResolver}; use crate::{commands, naming, WasmRpcOverride}; use anyhow::{anyhow, bail, Context, Error}; +use colored::control::SHOULD_COLORIZE; use colored::Colorize; use glob::{glob_with, MatchOptions}; use golem_wasm_rpc::WASM_RPC_VERSION; @@ -559,36 +560,128 @@ pub fn clean(config: Config) -> anyhow: Ok(()) } -// TODO: collect_custom_commands is not selected_component_names aware yet -pub fn collect_custom_commands( +pub fn print_dynamic_help( config: Config, -) -> anyhow::Result>> { - set_log_output(config.log_output); +) -> anyhow::Result<()> { + static LABEL_SOURCE: &str = "Source"; + static LABEL_SELECTED: &str = "Selected"; + static LABEL_TEMPLATE: &str = "Template"; + static LABEL_PROFILES: &str = "Profiles"; + static LABEL_DEPENDENCIES: &str = "Dependencies"; + + let label_padding = { + [ + &LABEL_SOURCE, + &LABEL_SELECTED, + &LABEL_TEMPLATE, + &LABEL_PROFILES, + &LABEL_DEPENDENCIES, + ] + .map(|label| label.len()) + .into_iter() + .max() + .unwrap_or(0) + + 1 + }; - let (app, _selected_component_names) = to_anyhow( - config.log_output, - "Failed to load application manifest(s), see problems above", - load_app(&config), - )?; + let print_field = |label: &'static str, value: String| { + println!(" {:>::new(); - for profile in &all_profiles { - for command in app.all_custom_commands(profile.as_ref()) { - if !commands.contains_key(command.as_str()) { - commands.insert(command.clone(), BTreeSet::new()); + match profile { + None => { + println!("{}", "Custom commands:".log_color_help_group()) + } + Some(profile) => { + println!( + "{}{}{}", + "Custom commands for ".log_color_help_group(), + profile.as_str().log_color_help_group(), + " profile:".log_color_help_group() + ) } - profile.iter().for_each(|profile| { - commands - .get_mut(command.as_str()) - .unwrap() - .insert(profile.clone()); - }); } + for command in commands { + println!(" {}", command.bold()) + } + println!() } - Ok(commands) + Ok(()) } pub fn custom_command( diff --git a/wasm-rpc-stubgen/src/lib.rs b/wasm-rpc-stubgen/src/lib.rs index 075d75a16f..2fe51bdf5c 100644 --- a/wasm-rpc-stubgen/src/lib.rs +++ b/wasm-rpc-stubgen/src/lib.rs @@ -33,8 +33,6 @@ use crate::stub::{StubConfig, StubDefinition}; use crate::wit_generate::UpdateCargoToml; use anyhow::Context; use clap::Subcommand; -use colored::Colorize; -use itertools::Itertools; use std::collections::HashSet; use std::marker::PhantomData; use std::path::PathBuf; @@ -194,7 +192,7 @@ pub struct App { #[derive(Subcommand, Debug)] pub enum AppSubCommand { - /// Runs component build steps + /// Run component build steps Build(AppBuildArgs), /// Clean outputs Clean, @@ -290,7 +288,7 @@ pub async fn run_app_command( None => { clap_command.print_help()?; println!(); - print_app_custom_commands_help(config); + print_dynamic_help(config); exit(2); } } @@ -336,34 +334,10 @@ fn app_manifest_sources_to_resolve_mode( } } -fn print_app_custom_commands_help( - mut config: commands::app::Config, -) { +fn print_dynamic_help(mut config: commands::app::Config) { config.log_output = Output::None; - match commands::app::collect_custom_commands(config) { - Ok(commands) => { - if !commands.is_empty() { - println!("{}", "Custom commands:".bold().underline()); - for (command, profiles) in commands { - if profiles.is_empty() { - println!(" {}", command); - } else { - println!( - " {} ({})", - command, - profiles.iter().map(|s| s.to_string()).join(", ") - ); - } - } - println!(); - } - } - Err(err) => { - println!( - "{}\n{:?}", - "Cannot show custom commands:".log_color_warn(), - err - ); - } + + if let Some(err) = commands::app::print_dynamic_help(config).err() { + println!("{}\n{}", "Cannot show dynamic help:".log_color_warn(), err); } } diff --git a/wasm-rpc-stubgen/src/log.rs b/wasm-rpc-stubgen/src/log.rs index b9f361758c..37b244b617 100644 --- a/wasm-rpc-stubgen/src/log.rs +++ b/wasm-rpc-stubgen/src/log.rs @@ -253,6 +253,10 @@ pub trait LogColorize { self.as_str().bold() } + fn log_color_help_group(&self) -> ColoredString { + self.as_str().bold().underline() + } + fn log_color_error_highlight(&self) -> ColoredString { self.as_str().bold().red().underline() } diff --git a/wasm-rpc-stubgen/src/model/app.rs b/wasm-rpc-stubgen/src/model/app.rs index a380eda3ec..bb9ea0e8e1 100644 --- a/wasm-rpc-stubgen/src/model/app.rs +++ b/wasm-rpc-stubgen/src/model/app.rs @@ -6,7 +6,7 @@ use crate::validation::{ValidatedResult, ValidationBuilder}; use crate::{fs, naming}; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; -use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt::Formatter; use std::fmt::{Debug, Display}; use std::hash::Hash; @@ -232,6 +232,10 @@ impl Application { self.components.keys() } + pub fn has_any_component(&self) -> bool { + !self.components.is_empty() + } + pub fn contains_component(&self, component_name: &ComponentName) -> bool { self.components.contains_key(component_name) } @@ -282,6 +286,36 @@ impl Application { custom_commands } + pub fn all_custom_commands_for_all_profiles( + &self, + ) -> BTreeMap, BTreeSet> { + let mut custom_commands = BTreeMap::, BTreeSet>::new(); + + custom_commands + .entry(None) + .or_default() + .extend(self.custom_commands.keys().cloned()); + + for profile in self.all_option_profiles() { + let profile_commands: &mut BTreeSet = { + if custom_commands.contains_key(&profile) { + custom_commands.get_mut(&profile).unwrap() + } else { + custom_commands.entry(profile.clone()).or_default() + } + }; + + profile_commands.extend(self.component_names().flat_map(|component_name| { + self.component_properties(component_name, profile.as_ref()) + .custom_commands + .keys() + .cloned() + })); + } + + custom_commands + } + pub fn temp_dir(&self) -> PathBuf { match self.temp_dir.as_ref() { Some(temp_dir) => temp_dir.source.as_path().join(&temp_dir.value), @@ -316,9 +350,9 @@ impl Application { .unwrap_or(&self.no_dependencies) } - fn component_profiles(&self, component_name: &ComponentName) -> HashSet { + pub fn component_profiles(&self, component_name: &ComponentName) -> BTreeSet { match &self.component(component_name).properties { - ResolvedComponentProperties::Properties { .. } => HashSet::new(), + ResolvedComponentProperties::Properties { .. } => BTreeSet::new(), ResolvedComponentProperties::Profiles { profiles, .. } => { profiles.keys().cloned().collect() } From c922868afced160c4d9ac01f6f42f1e87a47e634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Sat, 18 Jan 2025 13:56:04 +0100 Subject: [PATCH 02/17] Remove unused font-config and related deps (#1244) --- .github/workflows/ci.yaml | 24 -- Cargo.lock | 265 +----------------- Cross.toml | 2 +- .../docker/Dockerfile | 2 +- golem-component-service/docker/Dockerfile | 2 +- golem-shard-manager/docker/Dockerfile | 2 +- golem-worker-executor/docker/Dockerfile | 2 +- golem-worker-service/docker/Dockerfile | 2 +- integration-tests/Cargo.toml | 1 - 9 files changed, 8 insertions(+), 294 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ee61f12afd..3a4274c863 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -218,10 +218,6 @@ jobs: submodules: recursive - name: Fetch tag run: git fetch origin --deepen=1 - - name: Install Fontconfig - run: | - sudo apt-get update - sudo apt-get install libfontconfig1-dev - name: Setup Rust run: rustup update stable --no-self-update && rustup default stable - uses: Swatinem/rust-cache@v2 @@ -291,10 +287,6 @@ jobs: submodules: recursive - name: Fetch tag run: git fetch origin --deepen=1 - - name: Install Fontconfig - run: | - sudo apt-get update - sudo apt-get install libfontconfig1-dev - name: Setup Rust run: rustup update stable --no-self-update && rustup default stable - uses: Swatinem/rust-cache@v2 @@ -344,10 +336,6 @@ jobs: submodules: recursive - name: Fetch tag run: git fetch origin --deepen=1 - - name: Install Fontconfig - run: | - sudo apt-get update - sudo apt-get install libfontconfig1-dev - name: Setup Rust run: rustup update stable --no-self-update && rustup default stable - uses: Swatinem/rust-cache@v2 @@ -387,10 +375,6 @@ jobs: submodules: recursive - name: Fetch tag run: git fetch origin --deepen=1 - - name: Install Fontconfig - run: | - sudo apt-get update - sudo apt-get install libfontconfig1-dev - name: Setup Rust run: rustup update stable --no-self-update && rustup default stable - uses: cargo-bins/cargo-binstall@main @@ -433,10 +417,6 @@ jobs: submodules: recursive - name: Fetch tag run: git fetch origin --deepen=1 - - name: Install Fontconfig - run: | - sudo apt-get update - sudo apt-get install libfontconfig1-dev - name: Setup Rust run: rustup update stable --no-self-update && rustup default stable - uses: Swatinem/rust-cache@v2 @@ -478,10 +458,6 @@ jobs: submodules: recursive - name: Fetch tag run: git fetch origin --deepen=1 - - name: Install Fontconfig - run: | - sudo apt-get update - sudo apt-get install libfontconfig1-dev - name: Setup Rust run: rustup update stable --no-self-update && rustup default stable - uses: Swatinem/rust-cache@v2 diff --git a/Cargo.lock b/Cargo.lock index e93a1caddf..43cd840e8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1761,12 +1761,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67ba02a97a2bd10f4b59b25c7973101c79642302776489e030cd13cdab09ed15" -[[package]] -name = "color_quant" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" - [[package]] name = "colorchoice" version = "1.0.3" @@ -2003,42 +1997,6 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "core-graphics" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "core-graphics-types", - "foreign-types 0.5.0", - "libc", -] - -[[package]] -name = "core-graphics-types" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" -dependencies = [ - "bitflags 1.3.2", - "core-foundation 0.9.4", - "libc", -] - -[[package]] -name = "core-text" -version = "20.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9d2790b5c08465d49f8dc05c8bcae9fea467855947db39b0f8145c091aaced5" -dependencies = [ - "core-foundation 0.9.4", - "core-graphics", - "foreign-types 0.5.0", - "libc", -] - [[package]] name = "cpp_demangle" version = "0.4.4" @@ -2744,15 +2702,6 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59f8e79d1fbf76bdfbde321e902714bf6c49df88a7dda6fc682fc2979226962d" -[[package]] -name = "dlib" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" -dependencies = [ - "libloading", -] - [[package]] name = "dlv-list" version = "0.5.2" @@ -2801,18 +2750,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" -[[package]] -name = "dwrote" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70182709525a3632b2ba96b6569225467b18ecb4a77f46d255f713a6bebf05fd" -dependencies = [ - "lazy_static 1.5.0", - "libc", - "winapi", - "wio", -] - [[package]] name = "dyn-clone" version = "1.0.17" @@ -3150,15 +3087,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - [[package]] name = "ff" version = "0.12.1" @@ -3236,12 +3164,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "float-ord" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" - [[package]] name = "flume" version = "0.11.1" @@ -3272,59 +3194,13 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" -[[package]] -name = "font-kit" -version = "0.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b64b34f4efd515f905952d91bc185039863705592c0c53ae6d979805dd154520" -dependencies = [ - "bitflags 2.7.0", - "byteorder", - "core-foundation 0.9.4", - "core-graphics", - "core-text", - "dirs 5.0.1", - "dwrote", - "float-ord", - "freetype-sys", - "lazy_static 1.5.0", - "libc", - "log 0.4.22", - "pathfinder_geometry", - "pathfinder_simd", - "walkdir", - "winapi", - "yeslogic-fontconfig-sys", -] - [[package]] name = "foreign-types" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" dependencies = [ - "foreign-types-shared 0.1.1", -] - -[[package]] -name = "foreign-types" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" -dependencies = [ - "foreign-types-macros", - "foreign-types-shared 0.3.1", -] - -[[package]] -name = "foreign-types-macros" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.96", + "foreign-types-shared", ] [[package]] @@ -3333,12 +3209,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" -[[package]] -name = "foreign-types-shared" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" - [[package]] name = "form_urlencoded" version = "1.2.1" @@ -3389,17 +3259,6 @@ dependencies = [ "syn 2.0.96", ] -[[package]] -name = "freetype-sys" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - [[package]] name = "fs-set-times" version = "0.20.2" @@ -3644,16 +3503,6 @@ dependencies = [ "polyval", ] -[[package]] -name = "gif" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80792593675e051cf94a4b111980da2ba60d4a83e43e0048c5693baab3977045" -dependencies = [ - "color_quant", - "weezl", -] - [[package]] name = "gimli" version = "0.31.1" @@ -5277,20 +5126,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "image" -version = "0.24.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5690139d2f55868e080017335e4b94cb7414274c74f1669c84fb5feba2c9f69d" -dependencies = [ - "bytemuck", - "byteorder", - "color_quant", - "jpeg-decoder", - "num-traits", - "png", -] - [[package]] name = "include_dir" version = "0.7.4" @@ -5394,7 +5229,6 @@ dependencies = [ "golem-common", "golem-test-framework", "golem-wasm-rpc", - "plotters", "poem", "rand", "reqwest 0.12.12", @@ -5571,12 +5405,6 @@ dependencies = [ "libc", ] -[[package]] -name = "jpeg-decoder" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d4a7da358eff58addd2877a45865158f0d78c911d43a5784ceb7bbf52833b0" - [[package]] name = "js-sys" version = "0.3.77" @@ -6128,7 +5956,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8402cab7aefae129c6977bb0ff1b8fd9a04eb5b51efc50a70bea51cda0c7924" dependencies = [ "adler2", - "simd-adler32", ] [[package]] @@ -6578,7 +6405,7 @@ checksum = "6174bc48f102d208783c2c84bf931bb75927a617866870de8a4ea85597f871f5" dependencies = [ "bitflags 2.7.0", "cfg-if", - "foreign-types 0.3.2", + "foreign-types", "libc", "once_cell", "openssl-macros", @@ -6891,25 +6718,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" -[[package]] -name = "pathfinder_geometry" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3" -dependencies = [ - "log 0.4.22", - "pathfinder_simd", -] - -[[package]] -name = "pathfinder_simd" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cf07ef4804cfa9aea3b04a7bbdd5a40031dbb6b4f2cbaf2b011666c80c5b4f2" -dependencies = [ - "rustc_version", -] - [[package]] name = "pbjson" version = "0.6.0" @@ -7198,16 +7006,9 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" dependencies = [ - "chrono", - "font-kit", - "image", - "lazy_static 1.5.0", "num-traits", - "pathfinder_geometry", "plotters-backend", - "plotters-bitmap", "plotters-svg", - "ttf-parser", "wasm-bindgen", "web-sys", ] @@ -7218,17 +7019,6 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" -[[package]] -name = "plotters-bitmap" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ce181e3f6bf82d6c1dc569103ca7b1bd964c60ba03d7e6cdfbb3e3eb7f7405" -dependencies = [ - "gif", - "image", - "plotters-backend", -] - [[package]] name = "plotters-svg" version = "0.3.7" @@ -7238,19 +7028,6 @@ dependencies = [ "plotters-backend", ] -[[package]] -name = "png" -version = "0.17.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide", -] - [[package]] name = "poem" version = "3.1.6" @@ -9099,12 +8876,6 @@ dependencies = [ "rand_core", ] -[[package]] -name = "simd-adler32" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" - [[package]] name = "similar" version = "2.6.0" @@ -10452,12 +10223,6 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" -[[package]] -name = "ttf-parser" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4" - [[package]] name = "tungstenite" version = "0.24.0" @@ -11760,12 +11525,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "weezl" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53a85b86a771b1c87058196170769dd264f66c0782acf1ae6cc51bfd64b39082" - [[package]] name = "which" version = "4.4.2" @@ -12184,15 +11943,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "wio" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" -dependencies = [ - "winapi", -] - [[package]] name = "wit-bindgen-core" version = "0.26.0" @@ -12505,17 +12255,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" -[[package]] -name = "yeslogic-fontconfig-sys" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "503a066b4c037c440169d995b869046827dbc71263f6e8f3be6d77d4f3229dbd" -dependencies = [ - "dlib", - "once_cell", - "pkg-config", -] - [[package]] name = "yoke" version = "0.7.5" diff --git a/Cross.toml b/Cross.toml index 3e61b531f8..055d9d15e3 100644 --- a/Cross.toml +++ b/Cross.toml @@ -1,7 +1,7 @@ [target.aarch64-unknown-linux-gnu] pre-build = [ "dpkg --add-architecture $CROSS_DEB_ARCH", - "apt-get update && apt-get --assume-yes install libssl-dev:$CROSS_DEB_ARCH libfontconfig1-dev:$CROSS_DEB_ARCH unzip curl", + "apt-get update && apt-get --assume-yes install libssl-dev:$CROSS_DEB_ARCH unzip curl", "curl -LO https://github.com/protocolbuffers/protobuf/releases/download/v27.3/protoc-27.3-linux-x86_64.zip", "unzip protoc-27.3-linux-x86_64.zip -d /usr/local", "chmod +x /usr/local/bin/protoc" diff --git a/golem-component-compilation-service/docker/Dockerfile b/golem-component-compilation-service/docker/Dockerfile index d4bbc8f5d5..89636e5624 100644 --- a/golem-component-compilation-service/docker/Dockerfile +++ b/golem-component-compilation-service/docker/Dockerfile @@ -16,7 +16,7 @@ WORKDIR /app COPY /target/$RUST_TARGET/release/golem-component-compilation-service ./ COPY /golem-component-compilation-service/config/ ./config/ -RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates libfontconfig1-dev +RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates RUN update-ca-certificates EXPOSE 8080 diff --git a/golem-component-service/docker/Dockerfile b/golem-component-service/docker/Dockerfile index 8c18cc8a5a..1d988954f7 100644 --- a/golem-component-service/docker/Dockerfile +++ b/golem-component-service/docker/Dockerfile @@ -17,7 +17,7 @@ COPY /target/$RUST_TARGET/release/golem-component-service ./ COPY /golem-component-service/config/component-service.toml ./config/component-service.toml COPY /golem-component-service/db ./db -RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates libfontconfig1-dev +RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates RUN update-ca-certificates EXPOSE 8080 diff --git a/golem-shard-manager/docker/Dockerfile b/golem-shard-manager/docker/Dockerfile index b881cbf28f..0431445537 100644 --- a/golem-shard-manager/docker/Dockerfile +++ b/golem-shard-manager/docker/Dockerfile @@ -16,7 +16,7 @@ WORKDIR /app COPY /target/$RUST_TARGET/release/golem-shard-manager ./ COPY /golem-shard-manager/config/shard-manager.toml ./config/shard-manager.toml -RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates libfontconfig1-dev +RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates RUN update-ca-certificates EXPOSE 8081 diff --git a/golem-worker-executor/docker/Dockerfile b/golem-worker-executor/docker/Dockerfile index 7d260dcae9..6ffdd769c0 100644 --- a/golem-worker-executor/docker/Dockerfile +++ b/golem-worker-executor/docker/Dockerfile @@ -16,7 +16,7 @@ WORKDIR /app COPY /target/$RUST_TARGET/release/worker-executor ./ COPY /golem-worker-executor/config/worker-executor.toml ./config/worker-executor.toml -RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates libfontconfig1-dev +RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates RUN update-ca-certificates EXPOSE 9000 diff --git a/golem-worker-service/docker/Dockerfile b/golem-worker-service/docker/Dockerfile index 31857945a0..6cc9d89226 100644 --- a/golem-worker-service/docker/Dockerfile +++ b/golem-worker-service/docker/Dockerfile @@ -17,7 +17,7 @@ COPY /target/$RUST_TARGET/release/golem-worker-service ./ COPY /golem-worker-service/config/worker-service.toml ./config/worker-service.toml COPY /golem-worker-service/db ./db -RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates libfontconfig1-dev +RUN apt-get update && apt-get install -y pkg-config libssl-dev ca-certificates RUN update-ca-certificates EXPOSE 9005 diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 302a3f5498..fc2854bdc6 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -21,7 +21,6 @@ async-trait = { workspace = true } axum = { workspace = true } clap = { workspace = true } console-subscriber = { workspace = true } -plotters = "0.3.7" poem = { workspace = true } rand = { workspace = true } reqwest = { workspace = true } From df51498d535022f906bb90fd89df17876a3ad885 Mon Sep 17 00:00:00 2001 From: Afsal Thaj Date: Sun, 19 Jan 2025 01:33:35 +1100 Subject: [PATCH 03/17] Fix dependency order in publish task (#1246) --- Makefile.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile.toml b/Makefile.toml index 49d0289d5a..d483563d93 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -382,8 +382,8 @@ dependencies = [ "publish-golem-rib", "publish-golem-common", "publish-golem-client", - "publish-golem-service-base", "publish-golem-test-framework", + "publish-golem-service-base", "publish-golem-cli", ] From 38374782dc7dc4d6fd7fba78d134f16cb20bd352 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Sat, 18 Jan 2025 17:37:16 +0100 Subject: [PATCH 04/17] fix deps and publish order (#1248) --- Cargo.lock | 1 - Makefile.toml | 2 +- golem-service-base/Cargo.toml | 2 -- 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 43cd840e8a..3c4c2c6e24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3963,7 +3963,6 @@ dependencies = [ "futures", "golem-api-grpc", "golem-common", - "golem-test-framework", "golem-wasm-ast", "golem-wasm-rpc", "hex", diff --git a/Makefile.toml b/Makefile.toml index d483563d93..49d0289d5a 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -382,8 +382,8 @@ dependencies = [ "publish-golem-rib", "publish-golem-common", "publish-golem-client", - "publish-golem-test-framework", "publish-golem-service-base", + "publish-golem-test-framework", "publish-golem-cli", ] diff --git a/golem-service-base/Cargo.toml b/golem-service-base/Cargo.toml index 9ca20d5368..96f4726612 100644 --- a/golem-service-base/Cargo.toml +++ b/golem-service-base/Cargo.toml @@ -70,8 +70,6 @@ uuid = { workspace = true } wasmtime = { workspace = true } [dev-dependencies] -golem-test-framework = { path = "../golem-test-framework", version = "0.0.0" } - assert2 = { workspace = true } proptest = { workspace = true } tempfile = { workspace = true } From de0f29306d4af7681c574cad4b791e53943ba618 Mon Sep 17 00:00:00 2001 From: Daniel Vigovszky Date: Mon, 20 Jan 2025 16:48:18 +0100 Subject: [PATCH 05/17] Fix dynamic linking metadata propagation (#1251) --- .../src/service/component.rs | 6 ++- .../src/services/component.rs | 44 ++++++++++++++----- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/golem-component-service-base/src/service/component.rs b/golem-component-service-base/src/service/component.rs index f767241ff7..19f4f02b41 100644 --- a/golem-component-service-base/src/service/component.rs +++ b/golem-component-service-base/src/service/component.rs @@ -667,8 +667,9 @@ impl ComponentServiceDefault ComponentServiceDefault> = - export.into_iter().map(AnalysedExport::try_from).collect(); + let export = &metadata.exports; + let vec: Vec> = export + .iter() + .cloned() + .map(AnalysedExport::try_from) + .collect(); vec.into_iter().collect() }) .unwrap_or_else(|| Ok(Vec::new())) - .map_err(|_| { - GrpcError::Unexpected("Failed to get the exports".to_string()) + .map_err(|err| { + GrpcError::Unexpected(format!("Failed to get the exports: {err}")) })?, files: component .files .into_iter() .map(|file| file.try_into()) .collect::, _>>() - .map_err(|_| { - GrpcError::Unexpected("Failed to get the files".to_string()) + .map_err(|err| { + GrpcError::Unexpected(format!("Failed to get the files: {err}")) })?, plugin_installations: component .installed_plugins .into_iter() .map(|plugin| plugin.try_into()) .collect::, _>>() - .map_err(|_| { - GrpcError::Unexpected( - "Failed to get the plugin installations".to_string(), - ) + .map_err(|err| { + GrpcError::Unexpected(format!( + "Failed to get the plugin installations: {err}" + )) })?, - dynamic_linking: HashMap::new(), // TODO + dynamic_linking: HashMap::from_iter( + component + .metadata + .map(|metadata| { + metadata + .dynamic_linking + .into_iter() + .map(|(k, v)| v.try_into().map(|v| (k.clone(), v))) + .collect::, String>>() + }) + .unwrap_or_else(|| Ok(Vec::new())) + .map_err(|err| { + GrpcError::Unexpected(format!( + "Failed to get the dynamic linking information: {err}" + )) + })?, + ), }; record_external_call_response_size_bytes("components", "get_metadata", len); From 3b373c7b6b0ba4556f27f36b4331a0a4da7efe26 Mon Sep 17 00:00:00 2001 From: Afsal Thaj Date: Tue, 21 Jan 2025 20:51:29 +1100 Subject: [PATCH 06/17] Resume replay for debugging service (#1242) * Make oplog constructor public * update golem examples * Make openoplogs public for debugging service * Add resume replay to external operations * Add resume replay to worker * Fix store passed to resume * Fix compilation errors * Fix count * Make return type of resume sensible * Add comments in resume_replay * Handle resuming the replay of error * Throw when unable to send resume command --- .../src/durable_host/mod.rs | 348 +++++++++--------- .../src/services/oplog/mod.rs | 8 +- golem-worker-executor-base/src/worker.rs | 41 +++ golem-worker-executor-base/src/workerctx.rs | 10 +- .../tests/common/mod.rs | 7 + golem-worker-executor/src/context.rs | 7 + 6 files changed, 245 insertions(+), 176 deletions(-) diff --git a/golem-worker-executor-base/src/durable_host/mod.rs b/golem-worker-executor-base/src/durable_host/mod.rs index 14589458d8..66d6272e56 100644 --- a/golem-worker-executor-base/src/durable_host/mod.rs +++ b/golem-worker-executor-base/src/durable_host/mod.rs @@ -1206,6 +1206,182 @@ impl> ExternalOperations for Dur calculate_last_known_status(this, owned_worker_id, metadata).await } + async fn resume_replay( + store: &mut (impl AsContextMut + Send), + instance: &Instance, + ) -> Result { + let mut number_of_replayed_functions = 0; + + let resume_result = loop { + let cont = store.as_context().data().durable_ctx().state.is_replay(); + + if cont { + let oplog_entry = store + .as_context_mut() + .data_mut() + .durable_ctx_mut() + .state + .replay_state + .get_oplog_entry_exported_function_invoked() + .await; + match oplog_entry { + Err(error) => break Err(error), + Ok(None) => break Ok(RetryDecision::None), + Ok(Some((function_name, function_input, idempotency_key))) => { + debug!("Replaying function {function_name}"); + let span = span!(Level::INFO, "replaying", function = function_name); + store + .as_context_mut() + .data_mut() + .set_current_idempotency_key(idempotency_key) + .await; + + let full_function_name = function_name.to_string(); + let invoke_result = invoke_worker( + full_function_name.clone(), + function_input.clone(), + store, + instance, + ) + .instrument(span) + .await; + + match invoke_result { + Ok(InvokeResult::Succeeded { + output, + consumed_fuel, + }) => { + let component_metadata = + store.as_context().data().component_metadata(); + + match exports::function_by_name( + &component_metadata.exports, + &full_function_name, + ) { + Ok(value) => { + if let Some(value) = value { + let result = + interpret_function_results(output, value.results) + .map_err(|e| GolemError::ValueMismatch { + details: e.join(", "), + })?; + if let Err(err) = store + .as_context_mut() + .data_mut() + .on_invocation_success( + &full_function_name, + &function_input, + consumed_fuel, + result, + ) + .await + { + break Err(err); + } + } else { + let trap_type = TrapType::Error( + WorkerError::InvalidRequest(format!( + "Function {full_function_name} not found" + )), + ); + + let _ = store + .as_context_mut() + .data_mut() + .on_invocation_failure(&trap_type) + .await; + + break Err(GolemError::invalid_request(format!( + "Function {full_function_name} not found" + ))); + } + } + Err(err) => { + let trap_type = + TrapType::Error(WorkerError::InvalidRequest(format!( + "Function {full_function_name} not found: {err}" + ))); + + let _ = store + .as_context_mut() + .data_mut() + .on_invocation_failure(&trap_type) + .await; + + break Err(GolemError::invalid_request(format!( + "Function {full_function_name} not found: {err}" + ))); + } + } + number_of_replayed_functions += 1; + continue; + } + _ => { + let trap_type = match invoke_result { + Ok(invoke_result) => invoke_result.as_trap_type::(), + Err(error) => { + Some(TrapType::from_error::(&anyhow!(error))) + } + }; + let decision = match trap_type { + Some(trap_type) => { + let decision = store + .as_context_mut() + .data_mut() + .on_invocation_failure(&trap_type) + .await; + + if decision == RetryDecision::None { + // Cannot retry so we need to fail + match trap_type { + TrapType::Interrupt(interrupt_kind) => { + if interrupt_kind == InterruptKind::Interrupt { + break Err(GolemError::runtime( + "Interrupted via the Golem API", + )); + } else { + break Err(GolemError::runtime("The worker could not finish replaying a function {function_name}")); + } + } + TrapType::Exit => { + break Err(GolemError::runtime( + "Process exited", + )) + } + TrapType::Error(error) => { + let stderr = store + .as_context() + .data() + .get_public_state() + .event_service() + .get_last_invocation_errors(); + break Err(GolemError::runtime( + error.to_string(&stderr), + )); + } + } + } + + decision + } + None => RetryDecision::None, + }; + + break Ok(decision); + } + } + } + } + } else { + break Ok(RetryDecision::None); + } + }; + + record_number_of_replayed_functions(number_of_replayed_functions); + + resume_result + } + async fn prepare_instance( worker_id: &WorkerId, instance: &Instance, @@ -1213,8 +1389,6 @@ impl> ExternalOperations for Dur ) -> Result { debug!("Starting prepare_instance"); let start = Instant::now(); - let mut count = 0; - store.as_context_mut().data_mut().set_running(); if store @@ -1257,177 +1431,9 @@ impl> ExternalOperations for Dur .get_out_of_deleted_region() .await; - let result = loop { - let cont = store.as_context().data().durable_ctx().state.is_replay(); - - if cont { - let oplog_entry = store - .as_context_mut() - .data_mut() - .durable_ctx_mut() - .state - .replay_state - .get_oplog_entry_exported_function_invoked() - .await; - match oplog_entry { - Err(error) => break Err(error), - Ok(None) => break Ok(RetryDecision::None), - Ok(Some((function_name, function_input, idempotency_key))) => { - debug!("Replaying function {function_name}"); - let span = span!(Level::INFO, "replaying", function = function_name); - store - .as_context_mut() - .data_mut() - .set_current_idempotency_key(idempotency_key) - .await; - - let full_function_name = function_name.to_string(); - let invoke_result = invoke_worker( - full_function_name.clone(), - function_input.clone(), - store, - instance, - ) - .instrument(span) - .await; - - match invoke_result { - Ok(InvokeResult::Succeeded { - output, - consumed_fuel, - }) => { - let component_metadata = - store.as_context().data().component_metadata(); - - match exports::function_by_name( - &component_metadata.exports, - &full_function_name, - ) { - Ok(value) => { - if let Some(value) = value { - let result = interpret_function_results( - output, - value.results, - ) - .map_err(|e| GolemError::ValueMismatch { - details: e.join(", "), - })?; - if let Err(err) = store - .as_context_mut() - .data_mut() - .on_invocation_success( - &full_function_name, - &function_input, - consumed_fuel, - result, - ) - .await - { - break Err(err); - } - } else { - let trap_type = TrapType::Error( - WorkerError::InvalidRequest(format!( - "Function {full_function_name} not found" - )), - ); - - let _ = store - .as_context_mut() - .data_mut() - .on_invocation_failure(&trap_type) - .await; - - break Err(GolemError::invalid_request(format!( - "Function {full_function_name} not found" - ))); - } - } - Err(err) => { - let trap_type = TrapType::Error( - WorkerError::InvalidRequest(format!( - "Function {full_function_name} not found: {err}" - )), - ); - - let _ = store - .as_context_mut() - .data_mut() - .on_invocation_failure(&trap_type) - .await; - - break Err(GolemError::invalid_request(format!( - "Function {full_function_name} not found: {err}" - ))); - } - } - count += 1; - continue; - } - _ => { - let trap_type = match invoke_result { - Ok(invoke_result) => invoke_result.as_trap_type::(), - Err(error) => { - Some(TrapType::from_error::(&anyhow!(error))) - } - }; - let decision = match trap_type { - Some(trap_type) => { - let decision = store - .as_context_mut() - .data_mut() - .on_invocation_failure(&trap_type) - .await; - - if decision == RetryDecision::None { - // Cannot retry so we need to fail - match trap_type { - TrapType::Interrupt(interrupt_kind) => { - if interrupt_kind - == InterruptKind::Interrupt - { - break Err(GolemError::runtime( - "Interrupted via the Golem API", - )); - } else { - break Err(GolemError::runtime("The worker could not finish replaying a function {function_name}")); - } - } - TrapType::Exit => { - break Err(GolemError::runtime( - "Process exited", - )) - } - TrapType::Error(error) => { - let stderr = store - .as_context() - .data() - .get_public_state() - .event_service() - .get_last_invocation_errors(); - break Err(GolemError::runtime( - error.to_string(&stderr), - )); - } - } - } - - decision - } - None => RetryDecision::None, - }; + let result = Self::resume_replay(store, instance).await; - break Ok(decision); - } - } - } - } - } else { - break Ok(RetryDecision::None); - } - }; record_resume_worker(start.elapsed()); - record_number_of_replayed_functions(count); let final_decision = Self::finalize_pending_update(&result, instance, store).await; diff --git a/golem-worker-executor-base/src/services/oplog/mod.rs b/golem-worker-executor-base/src/services/oplog/mod.rs index d7d3dc0000..a9f8e647b0 100644 --- a/golem-worker-executor-base/src/services/oplog/mod.rs +++ b/golem-worker-executor-base/src/services/oplog/mod.rs @@ -367,12 +367,12 @@ impl OpenOplogEntry { } #[derive(Clone)] -struct OpenOplogs { +pub struct OpenOplogs { oplogs: Cache, } impl OpenOplogs { - fn new(name: &'static str) -> Self { + pub fn new(name: &'static str) -> Self { Self { oplogs: Cache::new( None, @@ -383,7 +383,7 @@ impl OpenOplogs { } } - async fn get_or_open( + pub async fn get_or_open( &self, worker_id: &WorkerId, constructor: impl OplogConstructor + Send + 'static, @@ -446,7 +446,7 @@ impl Debug for OpenOplogs { } #[async_trait] -trait OplogConstructor: Clone { +pub trait OplogConstructor: Clone { async fn create_oplog( self, close: Box, diff --git a/golem-worker-executor-base/src/worker.rs b/golem-worker-executor-base/src/worker.rs index 37f6e618d6..9622f47d0c 100644 --- a/golem-worker-executor-base/src/worker.rs +++ b/golem-worker-executor-base/src/worker.rs @@ -452,6 +452,24 @@ impl Worker { } } + pub async fn resume_replay(&self) -> Result<(), GolemError> { + match &*self.instance.lock().await { + WorkerInstance::Running(running) => { + running + .sender + .send(WorkerCommand::ResumeReplay) + .expect("Failed to send resume command"); + + Ok(()) + } + WorkerInstance::Unloaded | WorkerInstance::WaitingForPermit(_) => { + Err(GolemError::invalid_request( + "Explicit resume is not supported for uninitialized workers", + )) + } + } + } + pub async fn invoke( &self, idempotency_key: IdempotencyKey, @@ -1485,6 +1503,28 @@ impl RunningWorker { while let Some(cmd) = receiver.recv().await { waiting_for_command.store(false, Ordering::Release); match cmd { + WorkerCommand::ResumeReplay => { + let mut store = store.lock().await; + + let resume_replay_result = + Ctx::resume_replay(&mut *store, &instance).await; + + match resume_replay_result { + Ok(decision) => { + final_decision = decision; + } + + Err(err) => { + warn!("Failed to resume replay: {err}"); + if let Err(err2) = store.data_mut().set_suspended().await { + warn!("Additional error during resume of replay of worker: {err2}"); + } + + parent.stop_internal(true, Some(err)).await; + break; + } + } + } WorkerCommand::Invocation => { let message = active .write() @@ -1989,6 +2029,7 @@ pub enum RetryDecision { #[derive(Debug)] enum WorkerCommand { Invocation, + ResumeReplay, Interrupt(InterruptKind), } diff --git a/golem-worker-executor-base/src/workerctx.rs b/golem-worker-executor-base/src/workerctx.rs index 765e478bbb..72f4b48e30 100644 --- a/golem-worker-executor-base/src/workerctx.rs +++ b/golem-worker-executor-base/src/workerctx.rs @@ -50,7 +50,7 @@ use golem_common::model::{ use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; use golem_wasm_rpc::wasmtime::ResourceStore; use golem_wasm_rpc::Value; -use wasmtime::component::{Component, Linker}; +use wasmtime::component::{Component, Instance, Linker}; use wasmtime::{AsContextMut, Engine, ResourceLimiterAsync}; use wasmtime_wasi::WasiView; use wasmtime_wasi_http::WasiHttpView; @@ -366,6 +366,14 @@ pub trait ExternalOperations { metadata: &Option, ) -> Result; + /// Resume the replay of a worker instance. Note that if the previous replay + /// hasn't reached the end of the replay (which is usually last index in oplog) + /// resume_replay will ensure to start replay from the last replayed index. + async fn resume_replay( + store: &mut (impl AsContextMut + Send), + instance: &Instance, + ) -> Result; + /// Prepares a wasmtime instance after it has been created, but before it can be invoked. /// This can be used to restore the previous state of the worker but by general it can be no-op. /// diff --git a/golem-worker-executor-base/tests/common/mod.rs b/golem-worker-executor-base/tests/common/mod.rs index acbe36a5f1..8655c1ae6e 100644 --- a/golem-worker-executor-base/tests/common/mod.rs +++ b/golem-worker-executor-base/tests/common/mod.rs @@ -461,6 +461,13 @@ impl ExternalOperations for TestWorkerCtx { .await } + async fn resume_replay( + store: &mut (impl AsContextMut + Send), + instance: &Instance, + ) -> Result { + DurableWorkerCtx::::resume_replay(store, instance).await + } + async fn prepare_instance( worker_id: &WorkerId, instance: &Instance, diff --git a/golem-worker-executor/src/context.rs b/golem-worker-executor/src/context.rs index 28585f6bb3..3752aabee8 100644 --- a/golem-worker-executor/src/context.rs +++ b/golem-worker-executor/src/context.rs @@ -116,6 +116,13 @@ impl ExternalOperations for Context { DurableWorkerCtx::::compute_latest_worker_status(this, worker_id, metadata).await } + async fn resume_replay( + store: &mut (impl AsContextMut + Send), + instance: &Instance, + ) -> Result { + DurableWorkerCtx::::resume_replay(store, instance).await + } + async fn prepare_instance( worker_id: &WorkerId, instance: &Instance, From d22a30c922d2e8e9def903965bd5aae4c087cfcb Mon Sep 17 00:00:00 2001 From: Maxim Schuwalow Date: Tue, 21 Jan 2025 12:00:14 +0100 Subject: [PATCH 07/17] Support invoking wasi:http/incoming-handler (#1249) * Support invoking wasi:http/incoming-handler * unsafety comment * Update golem-common/src/virtual_exports/http_incoming_handler.rs Co-authored-by: Daniel Vigovszky * comments * test using wasm echo server * test restore of state when implementing wasi:http/incoming-handler * remove debug log --------- Co-authored-by: Daniel Vigovszky --- Cargo.lock | 3 + Cargo.toml | 3 + golem-common/Cargo.toml | 1 + golem-common/src/lib.rs | 2 + golem-common/src/model/component_metadata.rs | 14 +- golem-common/src/model/exports.rs | 21 +- .../virtual_exports/http_incoming_handler.rs | 529 ++ golem-common/src/virtual_exports/mod.rs | 15 + golem-worker-executor-base/Cargo.toml | 2 + .../src/durable_host/http/types.rs | 137 +- .../src/durable_host/io/streams.rs | 27 +- golem-worker-executor-base/src/invocation.rs | 253 +- golem-worker-executor-base/src/lib.rs | 1 + .../http_incoming_handler.rs | 142 + .../src/virtual_export_compat/mod.rs | 15 + golem-worker-executor-base/tests/wasi.rs | 313 + ...si-http-incoming-request-handler-echo.wasm | Bin 0 -> 103873 bytes .../Cargo.lock | 25 + .../Cargo.toml | 25 + .../src/bindings.rs | 7502 +++++++++++++++++ .../src/lib.rs | 95 + .../wit/deps.lock | 29 + .../wit/deps.toml | 1 + .../wit/deps/cli/command.wit | 10 + .../wit/deps/cli/environment.wit | 22 + .../wit/deps/cli/exit.wit | 17 + .../wit/deps/cli/imports.wit | 36 + .../wit/deps/cli/run.wit | 6 + .../wit/deps/cli/stdio.wit | 26 + .../wit/deps/cli/terminal.wit | 62 + .../wit/deps/clocks/monotonic-clock.wit | 50 + .../wit/deps/clocks/timezone.wit | 55 + .../wit/deps/clocks/wall-clock.wit | 46 + .../wit/deps/clocks/world.wit | 11 + .../wit/deps/filesystem/preopens.wit | 11 + .../wit/deps/filesystem/types.wit | 672 ++ .../wit/deps/filesystem/world.wit | 9 + .../wit/deps/http/handler.wit | 49 + .../wit/deps/http/proxy.wit | 50 + .../wit/deps/http/types.wit | 673 ++ .../wit/deps/io/error.wit | 34 + .../wit/deps/io/poll.wit | 47 + .../wit/deps/io/streams.wit | 290 + .../wit/deps/io/world.wit | 10 + .../wit/deps/random/insecure-seed.wit | 27 + .../wit/deps/random/insecure.wit | 25 + .../wit/deps/random/random.wit | 29 + .../wit/deps/random/world.wit | 13 + .../wit/deps/sockets/instance-network.wit | 11 + .../wit/deps/sockets/ip-name-lookup.wit | 56 + .../wit/deps/sockets/network.wit | 169 + .../wit/deps/sockets/tcp-create-socket.wit | 30 + .../wit/deps/sockets/tcp.wit | 387 + .../wit/deps/sockets/udp-create-socket.wit | 30 + .../wit/deps/sockets/udp.wit | 288 + .../wit/deps/sockets/world.wit | 19 + .../wit/world.wit | 6 + ...i-http-incoming-request-handler-state.wasm | Bin 0 -> 115473 bytes .../Cargo.lock | 25 + .../Cargo.toml | 25 + .../src/bindings.rs | 7502 +++++++++++++++++ .../src/lib.rs | 73 + .../wit/deps.lock | 29 + .../wit/deps.toml | 1 + .../wit/deps/cli/command.wit | 10 + .../wit/deps/cli/environment.wit | 22 + .../wit/deps/cli/exit.wit | 17 + .../wit/deps/cli/imports.wit | 36 + .../wit/deps/cli/run.wit | 6 + .../wit/deps/cli/stdio.wit | 26 + .../wit/deps/cli/terminal.wit | 62 + .../wit/deps/clocks/monotonic-clock.wit | 50 + .../wit/deps/clocks/timezone.wit | 55 + .../wit/deps/clocks/wall-clock.wit | 46 + .../wit/deps/clocks/world.wit | 11 + .../wit/deps/filesystem/preopens.wit | 11 + .../wit/deps/filesystem/types.wit | 672 ++ .../wit/deps/filesystem/world.wit | 9 + .../wit/deps/http/handler.wit | 49 + .../wit/deps/http/proxy.wit | 50 + .../wit/deps/http/types.wit | 673 ++ .../wit/deps/io/error.wit | 34 + .../wit/deps/io/poll.wit | 47 + .../wit/deps/io/streams.wit | 290 + .../wit/deps/io/world.wit | 10 + .../wit/deps/random/insecure-seed.wit | 27 + .../wit/deps/random/insecure.wit | 25 + .../wit/deps/random/random.wit | 29 + .../wit/deps/random/world.wit | 13 + .../wit/deps/sockets/instance-network.wit | 11 + .../wit/deps/sockets/ip-name-lookup.wit | 56 + .../wit/deps/sockets/network.wit | 169 + .../wit/deps/sockets/tcp-create-socket.wit | 30 + .../wit/deps/sockets/tcp.wit | 387 + .../wit/deps/sockets/udp-create-socket.wit | 30 + .../wit/deps/sockets/udp.wit | 288 + .../wit/deps/sockets/world.wit | 19 + .../wit/world.wit | 6 + .../wasi-http-incoming-request-handler.wasm | Bin 0 -> 54995 bytes .../Cargo.lock | 25 + .../Cargo.toml | 25 + .../src/bindings.rs | 7502 +++++++++++++++++ .../src/lib.rs | 19 + .../wit/deps.lock | 29 + .../wit/deps.toml | 1 + .../wit/deps/cli/command.wit | 10 + .../wit/deps/cli/environment.wit | 22 + .../wit/deps/cli/exit.wit | 17 + .../wit/deps/cli/imports.wit | 36 + .../wit/deps/cli/run.wit | 6 + .../wit/deps/cli/stdio.wit | 26 + .../wit/deps/cli/terminal.wit | 62 + .../wit/deps/clocks/monotonic-clock.wit | 50 + .../wit/deps/clocks/timezone.wit | 55 + .../wit/deps/clocks/wall-clock.wit | 46 + .../wit/deps/clocks/world.wit | 11 + .../wit/deps/filesystem/preopens.wit | 11 + .../wit/deps/filesystem/types.wit | 672 ++ .../wit/deps/filesystem/world.wit | 9 + .../wit/deps/http/handler.wit | 49 + .../wit/deps/http/proxy.wit | 50 + .../wit/deps/http/types.wit | 673 ++ .../wit/deps/io/error.wit | 34 + .../wit/deps/io/poll.wit | 47 + .../wit/deps/io/streams.wit | 290 + .../wit/deps/io/world.wit | 10 + .../wit/deps/random/insecure-seed.wit | 27 + .../wit/deps/random/insecure.wit | 25 + .../wit/deps/random/random.wit | 29 + .../wit/deps/random/world.wit | 13 + .../wit/deps/sockets/instance-network.wit | 11 + .../wit/deps/sockets/ip-name-lookup.wit | 56 + .../wit/deps/sockets/network.wit | 169 + .../wit/deps/sockets/tcp-create-socket.wit | 30 + .../wit/deps/sockets/tcp.wit | 387 + .../wit/deps/sockets/udp-create-socket.wit | 30 + .../wit/deps/sockets/udp.wit | 288 + .../wit/deps/sockets/world.wit | 19 + .../wit/world.wit | 6 + 139 files changed, 34092 insertions(+), 147 deletions(-) create mode 100644 golem-common/src/virtual_exports/http_incoming_handler.rs create mode 100644 golem-common/src/virtual_exports/mod.rs create mode 100644 golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs create mode 100644 golem-worker-executor-base/src/virtual_export_compat/mod.rs create mode 100644 test-components/wasi-http-incoming-request-handler-echo.wasm create mode 100644 test-components/wasi-http-incoming-request-handler-echo/Cargo.lock create mode 100644 test-components/wasi-http-incoming-request-handler-echo/Cargo.toml create mode 100644 test-components/wasi-http-incoming-request-handler-echo/src/bindings.rs create mode 100644 test-components/wasi-http-incoming-request-handler-echo/src/lib.rs create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps.lock create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps.toml create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/command.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/environment.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/exit.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/imports.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/run.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/stdio.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/terminal.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/monotonic-clock.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/timezone.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/wall-clock.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/preopens.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/types.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/handler.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/proxy.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/types.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/error.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/poll.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/streams.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure-seed.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/random.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/instance-network.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/ip-name-lookup.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/network.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp-create-socket.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp-create-socket.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-echo/wit/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state.wasm create mode 100644 test-components/wasi-http-incoming-request-handler-state/Cargo.lock create mode 100644 test-components/wasi-http-incoming-request-handler-state/Cargo.toml create mode 100644 test-components/wasi-http-incoming-request-handler-state/src/bindings.rs create mode 100644 test-components/wasi-http-incoming-request-handler-state/src/lib.rs create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps.lock create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps.toml create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/command.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/environment.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/exit.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/imports.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/run.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/stdio.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/terminal.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/monotonic-clock.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/timezone.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/wall-clock.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/preopens.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/types.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/http/handler.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/http/proxy.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/http/types.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/io/error.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/io/poll.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/io/streams.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/io/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure-seed.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/random/random.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/random/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/instance-network.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/ip-name-lookup.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/network.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp-create-socket.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp-create-socket.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler-state/wit/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler.wasm create mode 100644 test-components/wasi-http-incoming-request-handler/Cargo.lock create mode 100644 test-components/wasi-http-incoming-request-handler/Cargo.toml create mode 100644 test-components/wasi-http-incoming-request-handler/src/bindings.rs create mode 100644 test-components/wasi-http-incoming-request-handler/src/lib.rs create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps.lock create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps.toml create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/cli/command.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/cli/environment.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/cli/exit.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/cli/imports.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/cli/run.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/cli/stdio.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/cli/terminal.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/clocks/monotonic-clock.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/clocks/timezone.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/clocks/wall-clock.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/clocks/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/preopens.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/types.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/http/handler.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/http/proxy.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/http/types.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/io/error.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/io/poll.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/io/streams.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/io/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure-seed.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/random/random.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/random/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/instance-network.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/ip-name-lookup.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/network.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp-create-socket.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp-create-socket.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/deps/sockets/world.wit create mode 100644 test-components/wasi-http-incoming-request-handler/wit/world.wit diff --git a/Cargo.lock b/Cargo.lock index 3c4c2c6e24..02f5a3c779 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3747,6 +3747,7 @@ dependencies = [ "rand", "range-set-blaze", "regex", + "semver", "serde", "serde_json", "serde_yaml", @@ -4224,6 +4225,7 @@ dependencies = [ "async-fs", "async-lock", "async-mutex", + "async-scoped", "async-stream", "async-trait", "aws-config", @@ -4260,6 +4262,7 @@ dependencies = [ "hex", "http 1.2.0", "http-body 1.0.1", + "http-body-util", "humansize", "humantime-serde", "hyper 1.5.2", diff --git a/Cargo.toml b/Cargo.toml index 1578ab232a..618edab19b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,6 +64,9 @@ exclude = [ "test-components/update-test-v3-11", "test-components/update-test-v4", "test-components/variant-service", + "test-components/wasi-http-incoming-request-handler", + "test-components/wasi-http-incoming-request-handler-echo", + "test-components/wasi-http-incoming-request-handler-state", "test-components/write-stderr", "test-components/write-stdout", ] diff --git a/golem-common/Cargo.toml b/golem-common/Cargo.toml index 0c0be48346..eb5cba0020 100644 --- a/golem-common/Cargo.toml +++ b/golem-common/Cargo.toml @@ -52,6 +52,7 @@ prost-types = { workspace = true, optional = true } rand = { workspace = true } range-set-blaze = "0.1.16" regex = { workspace = true } +semver = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } serde_yaml = { workspace = true } diff --git a/golem-common/src/lib.rs b/golem-common/src/lib.rs index 5d084defe4..d7581adf7b 100644 --- a/golem-common/src/lib.rs +++ b/golem-common/src/lib.rs @@ -56,6 +56,8 @@ pub mod tracing; pub mod uri; +pub mod virtual_exports; + #[cfg(test)] test_r::enable!(); diff --git a/golem-common/src/model/component_metadata.rs b/golem-common/src/model/component_metadata.rs index 138321e593..980e19ade2 100644 --- a/golem-common/src/model/component_metadata.rs +++ b/golem-common/src/model/component_metadata.rs @@ -16,7 +16,7 @@ use bincode::{Decode, Encode}; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; -use crate::SafeDisplay; +use crate::{virtual_exports, SafeDisplay}; use golem_wasm_ast::analysis::AnalysedFunctionParameter; use golem_wasm_ast::core::Mem; use golem_wasm_ast::metadata::Producers as WasmAstProducers; @@ -182,6 +182,7 @@ impl RawComponentMetadata { .map_err(ComponentProcessingError::Analysis)?; add_resource_drops(&mut exports); + add_virtual_exports(&mut exports); let exports = exports.into_iter().collect::>(); @@ -327,6 +328,17 @@ fn drop_from_constructor(constructor: &AnalysedFunction) -> AnalysedFunction { } } +fn add_virtual_exports(exports: &mut Vec) { + // Some interfaces like the golem/http:incoming-handler do not exist on the component, + // but are dynamically created by the worker executor based on other existing interfaces. + + if virtual_exports::http_incoming_handler::implements_required_interfaces(exports) { + exports.extend(vec![ + virtual_exports::http_incoming_handler::ANALYZED_EXPORT.clone(), + ]); + }; +} + #[cfg(feature = "protobuf")] mod protobuf { use crate::model::component_metadata::{ diff --git a/golem-common/src/model/exports.rs b/golem-common/src/model/exports.rs index 0675da80cf..adc7c6d2c2 100644 --- a/golem-common/src/model/exports.rs +++ b/golem-common/src/model/exports.rs @@ -16,24 +16,7 @@ use golem_wasm_ast::analysis::{AnalysedExport, AnalysedFunction, AnalysedInstanc use rib::{ParsedFunctionName, ParsedFunctionReference, ParsedFunctionSite}; -pub trait AnalysedExportExtensions { - fn function_names(&self) -> Vec; -} - -impl AnalysedExportExtensions for AnalysedExport { - fn function_names(&self) -> Vec { - match self { - AnalysedExport::Instance(instance) => instance - .functions - .iter() - .map(|function| format!("{}.{{{}}}", instance.name, function.name)) - .collect(), - AnalysedExport::Function(function) => vec![function.name.clone()], - } - } -} - -pub fn instances(exports: &Vec) -> Vec { +fn instances(exports: &Vec) -> Vec { let mut instances = vec![]; for export in exports { if let AnalysedExport::Instance(instance) = export { @@ -43,7 +26,7 @@ pub fn instances(exports: &Vec) -> Vec { instances } -pub fn functions(exports: &Vec) -> Vec { +fn functions(exports: &Vec) -> Vec { let mut functions = vec![]; for export in exports { if let AnalysedExport::Function(function) = export { diff --git a/golem-common/src/virtual_exports/http_incoming_handler.rs b/golem-common/src/virtual_exports/http_incoming_handler.rs new file mode 100644 index 0000000000..ef3b6333b2 --- /dev/null +++ b/golem-common/src/virtual_exports/http_incoming_handler.rs @@ -0,0 +1,529 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use bytes::Bytes; +use golem_wasm_ast::analysis::AnalysedType; +use golem_wasm_ast::analysis::{AnalysedExport, AnalysedFunction, AnalysedInstance}; +use golem_wasm_rpc::Value; +use lazy_static::lazy_static; +use semver::Version; + +// The following wit is modelled here: +// +// type fields = list>>; +// type body = list; +// +// record body-and-trailers { +// body: body, +// trailers: option +// } +// +// record request { +// uri: string +// method: method, +// headers: fields, +// body-and-trailers: option +// } +// +// record response { +// status: status-code, +// headers: fields, +// body: option +// } +// +// handle: func(request: request) -> response; +// + +lazy_static! { + pub static ref REQUIRED_FUNCTIONS: Vec = vec![ + rib::ParsedFunctionName { + site: rib::ParsedFunctionSite::PackagedInterface { + namespace: "wasi".to_string(), + package: "http".to_string(), + interface: "incoming-handler".to_string(), + version: Some(rib::SemVer(Version::new(0, 2, 0))) + }, + function: rib::ParsedFunctionReference::Function { + function: "handle".to_string() + } + }, + rib::ParsedFunctionName { + site: rib::ParsedFunctionSite::PackagedInterface { + namespace: "wasi".to_string(), + package: "http".to_string(), + interface: "incoming-handler".to_string(), + version: Some(rib::SemVer(Version::new(0, 2, 1))) + }, + function: rib::ParsedFunctionReference::Function { + function: "handle".to_string() + } + }, + rib::ParsedFunctionName { + site: rib::ParsedFunctionSite::PackagedInterface { + namespace: "wasi".to_string(), + package: "http".to_string(), + interface: "incoming-handler".to_string(), + version: Some(rib::SemVer(Version::new(0, 2, 2))) + }, + function: rib::ParsedFunctionReference::Function { + function: "handle".to_string() + } + }, + rib::ParsedFunctionName { + site: rib::ParsedFunctionSite::PackagedInterface { + namespace: "wasi".to_string(), + package: "http".to_string(), + interface: "incoming-handler".to_string(), + version: Some(rib::SemVer(Version::new(0, 2, 3))) + }, + function: rib::ParsedFunctionReference::Function { + function: "handle".to_string() + } + } + ]; + pub static ref PARSED_FUNCTION_NAME: rib::ParsedFunctionName = rib::ParsedFunctionName { + site: rib::ParsedFunctionSite::PackagedInterface { + namespace: "golem".to_string(), + package: "http".to_string(), + interface: "incoming-handler".to_string(), + version: None + }, + function: rib::ParsedFunctionReference::Function { + function: "handle".to_string() + } + }; + pub static ref ANALYZED_FUNCTION_PARAMETERS: Vec = { + use golem_wasm_ast::analysis::*; + vec![AnalysedFunctionParameter { + name: "request".to_string(), + typ: IncomingHttpRequest::analysed_type(), + }] + }; + pub static ref ANALYZED_FUNCTION_RESULTS: Vec = { + use golem_wasm_ast::analysis::*; + vec![AnalysedFunctionResult { + name: None, + typ: HttpResponse::analysed_type(), + }] + }; + pub static ref ANALYZED_FUNCTION: AnalysedFunction = { + use golem_wasm_ast::analysis::*; + + AnalysedFunction { + name: "handle".to_string(), + parameters: ANALYZED_FUNCTION_PARAMETERS.clone(), + results: ANALYZED_FUNCTION_RESULTS.clone(), + } + }; + pub static ref ANALYZED_EXPORT: AnalysedExport = AnalysedExport::Instance(AnalysedInstance { + name: "golem:http/incoming-handler".to_string(), + functions: vec![ANALYZED_FUNCTION.clone()] + }); +} + +pub fn implements_required_interfaces(exports: &[AnalysedExport]) -> bool { + let compatible_interfaces = [ + "wasi:http/incoming-handler@0.2.0".to_string(), + "wasi:http/incoming-handler@0.2.1".to_string(), + "wasi:http/incoming-handler@0.2.2".to_string(), + "wasi:http/incoming-handler@0.2.3".to_string(), + ]; + + exports.iter().any(|ae| match ae { + AnalysedExport::Instance(AnalysedInstance { name, .. }) => { + compatible_interfaces.contains(name) + } + _ => false, + }) +} + +macro_rules! extract { + ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?, $ret:expr, $err:expr) => { + match $expression { + $pattern $(if $guard)? => Ok($ret), + _ => Err($err) + } + }; +} + +pub enum HttpMethod { + GET, + HEAD, + POST, + PUT, + DELETE, + CONNECT, + OPTIONS, + TRACE, + PATCH, + Custom(String), +} + +impl HttpMethod { + pub fn analyzed_type() -> AnalysedType { + use golem_wasm_ast::analysis::*; + AnalysedType::Variant(TypeVariant { + cases: vec![ + NameOptionTypePair { + name: "GET".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "HEAD".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "POST".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "PUT".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "DELETE".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "CONNECT".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "OPTIONS".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "TRACE".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "PATCH".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "Custom".to_string(), + typ: Some(AnalysedType::Str(TypeStr)), + }, + ], + }) + } + + pub fn from_value(value: &Value) -> Result { + let (case_idx, case_value) = extract!( + value, + Value::Variant { + case_idx, + case_value + }, + (case_idx, case_value), + "not a variant" + )?; + + match case_idx { + 0 => Ok(HttpMethod::GET), + 1 => Ok(HttpMethod::HEAD), + 2 => Ok(HttpMethod::POST), + 3 => Ok(HttpMethod::PUT), + 4 => Ok(HttpMethod::DELETE), + 5 => Ok(HttpMethod::CONNECT), + 6 => Ok(HttpMethod::OPTIONS), + 7 => Ok(HttpMethod::TRACE), + 8 => Ok(HttpMethod::PATCH), + 9 => { + let value = case_value.as_ref().ok_or("no case_value provided")?; + let custom_method = + extract!(*value.clone(), Value::String(inner), inner, "not a string")?; + Ok(HttpMethod::Custom(custom_method)) + } + _ => Err("unknown case")?, + } + } +} + +impl TryInto for HttpMethod { + type Error = http::method::InvalidMethod; + + fn try_into(self) -> Result { + match self { + Self::GET => Ok(http::Method::GET), + Self::HEAD => Ok(http::Method::HEAD), + Self::POST => Ok(http::Method::POST), + Self::PUT => Ok(http::Method::PUT), + Self::DELETE => Ok(http::Method::DELETE), + Self::CONNECT => Ok(http::Method::CONNECT), + Self::OPTIONS => Ok(http::Method::OPTIONS), + Self::TRACE => Ok(http::Method::TRACE), + Self::PATCH => Ok(http::Method::PATCH), + Self::Custom(method) => http::Method::from_bytes(method.as_bytes()), + } + } +} + +pub struct HttpFields(pub Vec<(String, Bytes)>); + +impl HttpFields { + pub fn analyzed_type() -> AnalysedType { + use golem_wasm_ast::analysis::*; + AnalysedType::List(TypeList { + inner: Box::new(AnalysedType::Tuple(TypeTuple { + items: vec![ + AnalysedType::Str(TypeStr), + AnalysedType::List(TypeList { + inner: Box::new(AnalysedType::U8(TypeU8)), + }), + ], + })), + }) + } + + pub fn from_value(value: &Value) -> Result { + let mut result = Vec::new(); + + let list_values = extract!(value, Value::List(inner), inner, "not a list")?; + + for lv in list_values { + let tuple_value = extract!(lv, Value::Tuple(inner), inner, "not a tuple")?; + + let (name, values) = extract!( + tuple_value.as_slice(), + [Value::String(name), Value::List(values)], + (name.clone(), values), + "incompatible types" + )?; + + let mut result_value = Vec::new(); + + for v in values { + let v = extract!(v, Value::U8(inner), *inner, "not a byte")?; + result_value.push(v); + } + + result.push((name, Bytes::from(result_value))); + } + + Ok(HttpFields(result)) + } + + pub fn to_value(self) -> Value { + let mut list_values = Vec::new(); + + for (name, value) in self.0 { + let converted_bytes: Vec = value.into_iter().map(Value::U8).collect::>(); + + list_values.push(Value::Tuple(vec![ + Value::String(name), + Value::List(converted_bytes), + ])); + } + Value::List(list_values) + } +} + +pub struct HttpBodyContent(pub Bytes); + +impl HttpBodyContent { + pub fn analyzed_type() -> AnalysedType { + use golem_wasm_ast::analysis::*; + AnalysedType::List(TypeList { + inner: Box::new(AnalysedType::U8(TypeU8)), + }) + } + + pub fn from_value(value: &Value) -> Result { + let mut result = Vec::new(); + + let list_values = extract!(value, Value::List(inner), inner, "not a list")?; + + for lv in list_values { + let byte_value = extract!(lv, Value::U8(inner), *inner, "not a byte")?; + result.push(byte_value); + } + + Ok(HttpBodyContent(Bytes::from(result))) + } + + pub fn to_value(self) -> Value { + let converted = self.0.into_iter().map(Value::U8).collect::>(); + Value::List(converted) + } +} + +pub struct HttpBodyAndTrailers { + pub content: HttpBodyContent, + pub trailers: Option, +} + +impl HttpBodyAndTrailers { + pub fn analysed_type() -> AnalysedType { + use golem_wasm_ast::analysis::*; + + AnalysedType::Record(TypeRecord { + fields: vec![ + NameTypePair { + name: "content".to_string(), + typ: HttpBodyContent::analyzed_type(), + }, + NameTypePair { + name: "trailers".to_string(), + typ: AnalysedType::Option(TypeOption { + inner: Box::new(HttpFields::analyzed_type()), + }), + }, + ], + }) + } + + pub fn from_value(value: &Value) -> Result { + let record_values = extract!(value, Value::Record(inner), inner, "not a record")?; + + if record_values.len() != 2 { + Err("wrong length of record data")?; + }; + + let content = HttpBodyContent::from_value(&record_values[0])?; + let trailers = extract!( + &record_values[1], + Value::Option(inner), + match inner { + Some(inner) => Some(HttpFields::from_value(inner)?), + None => None, + }, + "not an option" + )?; + + Ok(HttpBodyAndTrailers { content, trailers }) + } + pub fn to_value(self) -> Value { + let converted_content = self.content.to_value(); + let converted_trailers = Value::Option(self.trailers.map(|t| Box::new(t.to_value()))); + + Value::Record(vec![converted_content, converted_trailers]) + } +} + +pub struct IncomingHttpRequest { + pub uri: String, + pub method: HttpMethod, + pub headers: HttpFields, + pub body: Option, +} + +impl IncomingHttpRequest { + pub fn analysed_type() -> AnalysedType { + use golem_wasm_ast::analysis::*; + + AnalysedType::Record(TypeRecord { + fields: vec![ + NameTypePair { + name: "uri".to_string(), + typ: AnalysedType::Str(TypeStr), + }, + NameTypePair { + name: "method".to_string(), + typ: HttpMethod::analyzed_type(), + }, + NameTypePair { + name: "headers".to_string(), + typ: HttpFields::analyzed_type(), + }, + NameTypePair { + name: "body-and-trailers".to_string(), + typ: AnalysedType::Option(TypeOption { + inner: Box::new(HttpBodyAndTrailers::analysed_type()), + }), + }, + ], + }) + } + + pub fn from_function_input(inputs: &[Value]) -> Result { + if inputs.len() != 1 { + Err("invalid number of inputs")?; + }; + Self::from_value(&inputs[0]) + .map_err(|e| format!("Failed parsing input as http request: {e}")) + } + + fn from_value(value: &Value) -> Result { + let record_values = extract!(value, Value::Record(inner), inner, "not a record")?; + + if record_values.len() != 4 { + Err("wrong length of record data")?; + }; + + let uri = extract!( + record_values[0].clone(), + Value::String(inner), + inner, + "not a string" + )?; + let method = HttpMethod::from_value(&record_values[1])?; + let headers = HttpFields::from_value(&record_values[2])?; + let body = extract!( + &record_values[3], + Value::Option(inner), + match inner { + Some(v) => Some(HttpBodyAndTrailers::from_value(v)?), + None => None, + }, + "not an option" + )?; + + Ok(IncomingHttpRequest { + uri, + method, + headers, + body, + }) + } +} + +pub struct HttpResponse { + pub status: u16, + pub headers: HttpFields, + pub body: Option, +} + +impl HttpResponse { + pub fn analysed_type() -> AnalysedType { + use golem_wasm_ast::analysis::*; + + AnalysedType::Record(TypeRecord { + fields: vec![ + NameTypePair { + name: "status".to_string(), + typ: AnalysedType::U16(TypeU16), + }, + NameTypePair { + name: "headers".to_string(), + typ: HttpFields::analyzed_type(), + }, + NameTypePair { + name: "body-and-trailers".to_string(), + typ: AnalysedType::Option(TypeOption { + inner: Box::new(HttpBodyAndTrailers::analysed_type()), + }), + }, + ], + }) + } + + pub fn to_value(self) -> Value { + let converted_status: Value = Value::U16(self.status); + let converted_headers: Value = self.headers.to_value(); + let converted_body: Value = Value::Option(self.body.map(|b| Box::new(b.to_value()))); + + Value::Record(vec![converted_status, converted_headers, converted_body]) + } +} diff --git a/golem-common/src/virtual_exports/mod.rs b/golem-common/src/virtual_exports/mod.rs new file mode 100644 index 0000000000..a3d76a162c --- /dev/null +++ b/golem-common/src/virtual_exports/mod.rs @@ -0,0 +1,15 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod http_incoming_handler; diff --git a/golem-worker-executor-base/Cargo.toml b/golem-worker-executor-base/Cargo.toml index 56ed5b0352..bfecadd834 100644 --- a/golem-worker-executor-base/Cargo.toml +++ b/golem-worker-executor-base/Cargo.toml @@ -25,6 +25,7 @@ golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } +async-scoped = "0.9.0" async-fs = { workspace = true } async-lock = "3.4.0" async-mutex = "1.4.0" @@ -52,6 +53,7 @@ gethostname = "0.5.0" hex = { workspace = true } http = { workspace = true } http-body = "1.0.1" # keep in sync with wasmtime +http-body-util = "0.1.0" # keep in sync with wasmtime humansize = { workspace = true } humantime-serde = { workspace = true } hyper = { workspace = true } diff --git a/golem-worker-executor-base/src/durable_host/http/types.rs b/golem-worker-executor-base/src/durable_host/http/types.rs index 1ca6d2e0ef..3b3e32cb4a 100644 --- a/golem-worker-executor-base/src/durable_host/http/types.rs +++ b/golem-worker-executor-base/src/durable_host/http/types.rs @@ -441,78 +441,81 @@ impl HostFutureTrailers for DurableWorkerCtx { &mut self, self_: Resource, ) -> anyhow::Result>, ErrorCode>, ()>>> { - self.observe_function_call("http::types::future_trailers", "get"); + // Trailers might be associated with an incoming http request or an http response. + // Only in the second case do we need to add durability. We can distinguish these + // two cases by checking for presence of an associated open http request. + if let Some(request_state) = self.state.open_http_requests.get(&self_.rep()) { + let begin_idx = self + .state + .open_function_table + .get(&request_state.root_handle) + .ok_or_else(|| { + anyhow!( + "No matching BeginRemoteWrite index was found for the open HTTP request" + ) + })?; - let request_state = self - .state - .open_http_requests - .get(&self_.rep()) - .ok_or_else(|| { - anyhow!("No matching HTTP request is associated with resource handle") - })?; - let begin_idx = self - .state - .open_function_table - .get(&request_state.root_handle) - .ok_or_else(|| { - anyhow!("No matching BeginRemoteWrite index was found for the open HTTP request") - })?; - let request = request_state.request.clone(); - - let durability = Durability::< - Option>>, SerializableErrorCode>, ()>>, - SerializableError, - >::new( - self, - "golem http::types::future_trailers", - "get", - DurableFunctionType::WriteRemoteBatched(Some(*begin_idx)), - ) - .await?; - - if durability.is_live() { - let result = HostFutureTrailers::get(&mut self.as_wasi_http_view(), self_).await; - let to_serialize = match &result { - Ok(Some(Ok(Ok(None)))) => Ok(Some(Ok(Ok(None)))), - Ok(Some(Ok(Ok(Some(trailers))))) => { - let mut serialized_trailers = HashMap::new(); - let host_fields: &Resource = - unsafe { std::mem::transmute(trailers) }; - - for (key, value) in get_fields(self.table(), host_fields)? { - serialized_trailers - .insert(key.as_str().to_string(), value.as_bytes().to_vec()); + let request = request_state.request.clone(); + + let durability = Durability::< + Option>>, SerializableErrorCode>, ()>>, + SerializableError, + >::new( + self, + "golem http::types::future_trailers", + "get", + DurableFunctionType::WriteRemoteBatched(Some(*begin_idx)), + ) + .await?; + + if durability.is_live() { + let result = HostFutureTrailers::get(&mut self.as_wasi_http_view(), self_).await; + let to_serialize = match &result { + Ok(Some(Ok(Ok(None)))) => Ok(Some(Ok(Ok(None)))), + Ok(Some(Ok(Ok(Some(trailers))))) => { + let mut serialized_trailers = HashMap::new(); + let host_fields: &Resource = + unsafe { std::mem::transmute(trailers) }; + + for (key, value) in get_fields(self.table(), host_fields)? { + serialized_trailers + .insert(key.as_str().to_string(), value.as_bytes().to_vec()); + } + Ok(Some(Ok(Ok(Some(serialized_trailers))))) } - Ok(Some(Ok(Ok(Some(serialized_trailers))))) - } - Ok(Some(Ok(Err(error_code)))) => Ok(Some(Ok(Err(error_code.into())))), - Ok(Some(Err(_))) => Ok(Some(Err(()))), - Ok(None) => Ok(None), - Err(err) => Err(SerializableError::from(err)), - }; - let _ = durability - .persist_serializable(self, request, to_serialize) - .await; - result - } else { - let serialized = durability.replay(self).await; - match serialized { - Ok(Some(Ok(Ok(None)))) => Ok(Some(Ok(Ok(None)))), - Ok(Some(Ok(Ok(Some(serialized_trailers))))) => { - let mut fields = FieldMap::new(); - for (key, value) in serialized_trailers { - fields.insert(HeaderName::from_str(&key)?, HeaderValue::try_from(value)?); + Ok(Some(Ok(Err(error_code)))) => Ok(Some(Ok(Err(error_code.into())))), + Ok(Some(Err(_))) => Ok(Some(Err(()))), + Ok(None) => Ok(None), + Err(err) => Err(SerializableError::from(err)), + }; + let _ = durability + .persist_serializable(self, request, to_serialize) + .await; + result + } else { + let serialized = durability.replay(self).await; + match serialized { + Ok(Some(Ok(Ok(None)))) => Ok(Some(Ok(Ok(None)))), + Ok(Some(Ok(Ok(Some(serialized_trailers))))) => { + let mut fields = FieldMap::new(); + for (key, value) in serialized_trailers { + fields + .insert(HeaderName::from_str(&key)?, HeaderValue::try_from(value)?); + } + let hdrs = self + .table() + .push(wasmtime_wasi_http::types::HostFields::Owned { fields })?; + Ok(Some(Ok(Ok(Some(hdrs))))) } - let hdrs = self - .table() - .push(wasmtime_wasi_http::types::HostFields::Owned { fields })?; - Ok(Some(Ok(Ok(Some(hdrs))))) + Ok(Some(Ok(Err(error_code)))) => Ok(Some(Ok(Err(error_code.into())))), + Ok(Some(Err(_))) => Ok(Some(Err(()))), + Ok(None) => Ok(None), + Err(error) => Err(error), } - Ok(Some(Ok(Err(error_code)))) => Ok(Some(Ok(Err(error_code.into())))), - Ok(Some(Err(_))) => Ok(Some(Err(()))), - Ok(None) => Ok(None), - Err(error) => Err(error), } + } else { + self.observe_function_call("http::types::future_trailers", "get"); + HostFutureTrailers::get(&mut self.as_wasi_http_view(), self_).await } } diff --git a/golem-worker-executor-base/src/durable_host/io/streams.rs b/golem-worker-executor-base/src/durable_host/io/streams.rs index fe3b45de57..c4f4acb9f2 100644 --- a/golem-worker-executor-base/src/durable_host/io/streams.rs +++ b/golem-worker-executor-base/src/durable_host/io/streams.rs @@ -15,7 +15,7 @@ use anyhow::anyhow; use async_trait::async_trait; use wasmtime::component::Resource; -use wasmtime_wasi::{ResourceTable, StreamError}; +use wasmtime_wasi::StreamError; use crate::durable_host::http::end_http_request; use crate::durable_host::http::serialized::SerializableHttpRequest; @@ -38,8 +38,8 @@ impl HostInputStream for DurableWorkerCtx { self_: Resource, len: u64, ) -> Result, StreamError> { - if is_incoming_http_body_stream(self.table(), &self_) { - let handle = self_.rep(); + let handle = self_.rep(); + if is_incoming_http_body_stream(self, &self_) { let begin_idx = get_http_request_begin_idx(self, handle)?; let durability = Durability::, SerializableStreamError>::new( @@ -71,7 +71,7 @@ impl HostInputStream for DurableWorkerCtx { self_: Resource, len: u64, ) -> Result, StreamError> { - if is_incoming_http_body_stream(self.table(), &self_) { + if is_incoming_http_body_stream(self, &self_) { let handle = self_.rep(); let begin_idx = get_http_request_begin_idx(self, handle)?; @@ -100,7 +100,7 @@ impl HostInputStream for DurableWorkerCtx { } async fn skip(&mut self, self_: Resource, len: u64) -> Result { - if is_incoming_http_body_stream(self.table(), &self_) { + if is_incoming_http_body_stream(self, &self_) { let handle = self_.rep(); let begin_idx = get_http_request_begin_idx(self, handle)?; @@ -132,7 +132,7 @@ impl HostInputStream for DurableWorkerCtx { self_: Resource, len: u64, ) -> Result { - if is_incoming_http_body_stream(self.table(), &self_) { + if is_incoming_http_body_stream(self, &self_) { let handle = self_.rep(); let begin_idx = get_http_request_begin_idx(self, handle)?; @@ -168,7 +168,7 @@ impl HostInputStream for DurableWorkerCtx { async fn drop(&mut self, rep: Resource) -> anyhow::Result<()> { self.observe_function_call("io::streams::input_stream", "drop"); - if is_incoming_http_body_stream(self.table(), &rep) { + if is_incoming_http_body_stream(self, &rep) { let handle = rep.rep(); if let Some(state) = self.state.open_http_requests.get(&handle) { if state.close_owner == HttpRequestCloseOwner::InputStreamClosed { @@ -297,8 +297,17 @@ impl Host for DurableWorkerCtx { } } -fn is_incoming_http_body_stream(table: &ResourceTable, stream: &Resource) -> bool { - let stream = table.get::(stream).unwrap(); +fn is_incoming_http_body_stream( + ctx: &mut DurableWorkerCtx, + stream: &Resource, +) -> bool { + // incoming-body is used for both incoming http bodies (which don't need durability), + // and response bodies. Only in the second case will there be an associated open http request. + if !ctx.state.open_http_requests.contains_key(&stream.rep()) { + return false; + }; + + let stream = ctx.table().get::(stream).unwrap(); stream .as_any() .downcast_ref::() diff --git a/golem-worker-executor-base/src/invocation.rs b/golem-worker-executor-base/src/invocation.rs index 5f50de7f79..d411765e51 100644 --- a/golem-worker-executor-base/src/invocation.rs +++ b/golem-worker-executor-base/src/invocation.rs @@ -12,19 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::error::GolemError; +use crate::metrics::wasm::{record_invocation, record_invocation_consumption}; +use crate::model::{InterruptKind, TrapType}; +use crate::virtual_export_compat; +use crate::workerctx::{PublicWorkerIo, WorkerCtx}; +use anyhow::anyhow; use golem_common::model::oplog::{WorkerError, WorkerResourceId}; -use golem_common::model::WorkerStatus; +use golem_common::model::{IdempotencyKey, WorkerStatus}; +use golem_common::virtual_exports; use golem_wasm_rpc::wasmtime::{decode_param, encode_output, type_to_analysed_type}; use golem_wasm_rpc::Value; use rib::{ParsedFunctionName, ParsedFunctionReference}; use tracing::{debug, error}; use wasmtime::component::{Func, Val}; use wasmtime::{AsContextMut, StoreContextMut}; - -use crate::error::GolemError; -use crate::metrics::wasm::{record_invocation, record_invocation_consumption}; -use crate::model::{InterruptKind, TrapType}; -use crate::workerctx::{PublicWorkerIo, WorkerCtx}; +use wasmtime_wasi_http::bindings::Proxy; +use wasmtime_wasi_http::WasiHttpView; /// Invokes a function on a worker. /// @@ -108,10 +112,9 @@ pub fn find_first_available_function( let mut store = store.as_context_mut(); for name in names { let parsed = ParsedFunctionName::parse(&name).ok()?; - if find_function(&mut store, instance, &parsed) - .ok() - .flatten() - .is_some() + + if let Ok(FindFunctionResult::ExportedFunction(_)) = + find_function(&mut store, instance, &parsed) { return Some(name); } @@ -123,7 +126,21 @@ fn find_function<'a, Ctx: WorkerCtx>( mut store: &mut StoreContextMut<'a, Ctx>, instance: &'a wasmtime::component::Instance, parsed_function_name: &ParsedFunctionName, -) -> Result, GolemError> { +) -> Result { + if *parsed_function_name == *virtual_exports::http_incoming_handler::PARSED_FUNCTION_NAME { + return Ok(FindFunctionResult::IncomingHttpHandlerBridge); + }; + + let parsed_function_ref = parsed_function_name.function(); + + if matches!( + parsed_function_ref, + ParsedFunctionReference::RawResourceDrop { .. } + | ParsedFunctionReference::IndexedResourceDrop { .. } + ) { + return Ok(FindFunctionResult::ResourceDrop); + } + match &parsed_function_name.site().interface_name() { Some(interface_name) => { let exported_instance_idx = instance @@ -132,6 +149,7 @@ fn find_function<'a, Ctx: WorkerCtx>( "could not load exports for interface {}", interface_name )))?; + let func = instance .get_export( &mut store, @@ -141,38 +159,28 @@ fn find_function<'a, Ctx: WorkerCtx>( .and_then(|idx| instance.get_func(&mut store, idx)); match func { - Some(func) => Ok(Some(func)), - None => { - if matches!( - parsed_function_name.function(), - ParsedFunctionReference::RawResourceDrop { .. } - | ParsedFunctionReference::IndexedResourceDrop { .. } - ) { - Ok(None) - } else { - match parsed_function_name.method_as_static() { - None => Err(GolemError::invalid_request(format!( - "could not load function {} for interface {}", - &parsed_function_name.function().function_name(), - interface_name - ))), - Some(parsed_static) => instance - .get_export( - &mut store, - Some(&exported_instance_idx), - &parsed_static.function().function_name(), - ) - .and_then(|idx| instance.get_func(&mut store, idx)) - .ok_or(GolemError::invalid_request(format!( - "could not load function {} or {} for interface {}", - &parsed_function_name.function().function_name(), - &parsed_static.function().function_name(), - interface_name - ))) - .map(Some), - } - } - } + Some(func) => Ok(FindFunctionResult::ExportedFunction(func)), + None => match parsed_function_name.method_as_static() { + None => Err(GolemError::invalid_request(format!( + "could not load function {} for interface {}", + &parsed_function_name.function().function_name(), + interface_name + ))), + Some(parsed_static) => instance + .get_export( + &mut store, + Some(&exported_instance_idx), + &parsed_static.function().function_name(), + ) + .and_then(|idx| instance.get_func(&mut store, idx)) + .ok_or(GolemError::invalid_request(format!( + "could not load function {} or {} for interface {}", + &parsed_function_name.function().function_name(), + &parsed_static.function().function_name(), + interface_name + ))) + .map(FindFunctionResult::ExportedFunction), + }, } } None => instance @@ -181,7 +189,7 @@ fn find_function<'a, Ctx: WorkerCtx>( "could not load function {}", &parsed_function_name.function().function_name() ))) - .map(Some), + .map(FindFunctionResult::ExportedFunction), } } @@ -235,11 +243,16 @@ async fn invoke_or_fail( } let mut call_result = match function { - Some(function) => invoke(&mut store, function, &function_input, &full_function_name).await, - None => { + FindFunctionResult::ExportedFunction(function) => { + invoke(&mut store, function, &function_input, &full_function_name).await + } + FindFunctionResult::ResourceDrop => { // Special function: drop drop_resource(&mut store, &parsed, &function_input, &full_function_name).await } + FindFunctionResult::IncomingHttpHandlerBridge => { + invoke_http_handler(&mut store, instance, &function_input, &full_function_name).await + } }; if let Ok(r) = call_result.as_mut() { r.add_fuel(extra_fuel); @@ -270,12 +283,17 @@ async fn get_or_create_indexed_resource<'a, Ctx: WorkerCtx>( resource: resource_name.clone(), }, ); - let resource_constructor = find_function(store, instance, &resource_constructor_name)?.ok_or( - GolemError::invalid_request(format!( + + let resource_constructor = if let FindFunctionResult::ExportedFunction(func) = + find_function(store, instance, &resource_constructor_name)? + { + func + } else { + Err(GolemError::invalid_request(format!( "could not find resource constructor for resource {}", resource_name - )), - )?; + )))? + }; let constructor_param_types = resource_constructor.params(store as &StoreContextMut<'a, Ctx>).iter().map(type_to_analysed_type).collect::, _>>() .map_err(|err| GolemError::invalid_request(format!("Indexed resource invocation cannot be used with owned or borrowed resource handles in constructor parameter position! ({err})")))?; @@ -407,6 +425,103 @@ async fn invoke( } } +async fn invoke_http_handler( + store: &mut impl AsContextMut, + instance: &wasmtime::component::Instance, + function_input: &[Value], + raw_function_name: &str, +) -> Result { + let (sender, receiver) = tokio::sync::oneshot::channel(); + + let proxy = Proxy::new(&mut *store, instance).unwrap(); + let mut store_context = store.as_context_mut(); + + store_context.data_mut().borrow_fuel().await?; + + let idempotency_key = store_context.data().get_current_idempotency_key().await; + if let Some(idempotency_key) = &idempotency_key { + store_context + .data() + .get_public_state() + .event_service() + .emit_invocation_start( + raw_function_name, + idempotency_key, + store_context.data().is_live(), + ); + } + + tracing::debug!("Invoking wasi:http/incoming-http-handler handle"); + + let (_, mut task_exits) = { + let hyper_request = + virtual_export_compat::http_incoming_handler::input_to_hyper_request(function_input)?; + let scheme = wasi_http_scheme_from_request(&hyper_request)?; + let incoming = store_context + .data_mut() + .as_wasi_http_view() + .new_incoming_request(scheme, hyper_request) + .unwrap(); + let outgoing = store_context + .data_mut() + .as_wasi_http_view() + .new_response_outparam(sender) + .unwrap(); + + // unsafety comes from scope_and_collect: + // + // This function is not completely safe: + // please see cancellation_soundness in [tests.rs](https://github.com/rmanoka/async-scoped/blob/master/src/tests.rs) for a test-case that suggests how this can lead to invalid memory access if not dealt with care. + // The caller must ensure that the lifetime ’a is valid until the returned future is fully driven. Dropping the future is okay, but blocks the current thread until all spawned futures complete. + unsafe { + async_scoped::TokioScope::scope_and_collect(|s| { + s.spawn(proxy.wasi_http_incoming_handler().call_handle( + store_context, + incoming, + outgoing, + )); + }) + .await + } + }; + + let out = receiver.await; + + let res_or_error = match out { + Ok(Ok(resp)) => { + Ok(virtual_export_compat::http_incoming_handler::http_response_to_output(resp).await?) + } + Ok(Err(e)) => Err(anyhow::Error::from(e)), + Err(_) => { + // An error in the receiver (`RecvError`) only indicates that the + // task exited before a response was sent (i.e., the sender was + // dropped); it does not describe the underlying cause of failure. + // Instead we retrieve and propagate the error from inside the task + // which should more clearly tell the user what went wrong. Note + // that we assume the task has already exited at this point so the + // `await` should resolve immediately. + let task_exit = task_exits.remove(0); + let e = match task_exit { + Ok(r) => r.expect_err("if the receiver has an error, the task must have failed"), + Err(_e) => anyhow!("failed joining wasm task"), + }; + Err(e)? + } + }; + + let consumed_fuel = finish_invocation_and_get_fuel_consumption( + &mut store.as_context_mut(), + raw_function_name, + idempotency_key, + ) + .await?; + + match res_or_error { + Ok(resp) => Ok(InvokeResult::from_success(consumed_fuel, vec![resp])), + Err(e) => Ok(InvokeResult::from_error::(consumed_fuel, &e)), + } +} + async fn drop_resource( store: &mut impl AsContextMut, parsed_function_name: &ParsedFunctionName, @@ -508,6 +623,18 @@ async fn call_exported_function( result }; + let consumed_fuel_for_call = + finish_invocation_and_get_fuel_consumption(&mut store, raw_function_name, idempotency_key) + .await?; + + Ok((result.map(|_| results), consumed_fuel_for_call)) +} + +async fn finish_invocation_and_get_fuel_consumption( + store: &mut StoreContextMut<'_, Ctx>, + raw_function_name: &str, + idempotency_key: Option, +) -> Result { let current_fuel_level = store.get_fuel().unwrap_or(0); let consumed_fuel_for_call = store .data_mut() @@ -530,7 +657,8 @@ async fn call_exported_function( } record_invocation_consumption(consumed_fuel_for_call); - Ok((result.map(|_| results), consumed_fuel_for_call)) + + Ok(consumed_fuel_for_call) } #[derive(Clone, Debug)] @@ -613,3 +741,26 @@ impl InvokeResult { } } } + +enum FindFunctionResult { + ExportedFunction(Func), + ResourceDrop, + IncomingHttpHandlerBridge, +} + +fn wasi_http_scheme_from_request( + req: &hyper::Request, +) -> Result { + use http::uri::*; + use wasmtime_wasi_http::bindings::http::types::Scheme as WasiScheme; + + let raw_scheme = req.uri().scheme().ok_or(GolemError::invalid_request( + "Could not extract scheme from uri".to_string(), + ))?; + + match raw_scheme { + scheme if *scheme == Scheme::HTTP => Ok(WasiScheme::Http), + scheme if *scheme == Scheme::HTTPS => Ok(WasiScheme::Https), + scheme => Ok(WasiScheme::Other(scheme.to_string())), + } +} diff --git a/golem-worker-executor-base/src/lib.rs b/golem-worker-executor-base/src/lib.rs index c81bcca2a1..d1d7683415 100644 --- a/golem-worker-executor-base/src/lib.rs +++ b/golem-worker-executor-base/src/lib.rs @@ -22,6 +22,7 @@ pub mod model; pub mod preview2; pub mod services; pub mod storage; +pub mod virtual_export_compat; pub mod wasi_host; pub mod worker; pub mod workerctx; diff --git a/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs b/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs new file mode 100644 index 0000000000..197f3f31d4 --- /dev/null +++ b/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs @@ -0,0 +1,142 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::convert::Infallible; + +use crate::error::GolemError; +use bytes::Bytes; +use golem_common::virtual_exports::http_incoming_handler::*; +use golem_wasm_rpc::Value; +use http::{HeaderName, HeaderValue}; +use http_body_util::combinators::BoxBody; +use http_body_util::BodyExt; +use wasmtime_wasi_http::bindings::http::types::ErrorCode; + +pub fn input_to_hyper_request( + inputs: &[Value], +) -> Result>, GolemError> { + let request = IncomingHttpRequest::from_function_input(inputs).map_err(|e| { + GolemError::invalid_request(format!("Failed contructing incoming request: {e}")) + })?; + + let mut builder = hyper::Request::builder() + .uri(request.uri) + .method(request.method); + + for (name, value) in request.headers.0 { + let converted = http::HeaderValue::from_bytes(&value) + .map_err(|e| GolemError::invalid_request(format!("Invalid header value: {e}")))?; + + builder = builder.header(name, converted); + } + + let body = if let Some(b) = request.body { + tracing::debug!("adding request body to wasi:http/incoming-request"); + + let body = http_body_util::Full::new(b.content.0); + + let converted_trailers = if let Some(trailers) = b.trailers { + let mut converted_trailers = http::HeaderMap::new(); + for (name, value) in trailers.0.into_iter() { + let header_name = HeaderName::from_bytes(name.as_bytes()).map_err(|e| { + GolemError::invalid_request(format!("Failed to convert header name {e}")) + })?; + let header_value = HeaderValue::from_bytes(&value).map_err(|e| { + GolemError::invalid_request(format!("Failed to convert header value {e}")) + })?; + + converted_trailers.insert(header_name, header_value); + } + Some(Ok(converted_trailers)) + } else { + None + }; + + let with_trailers = body.with_trailers(async { converted_trailers }); + BoxBody::new(with_trailers.map_err(hyper_error_from_infallible)) + } else { + BoxBody::new(http_body_util::Empty::new().map_err(hyper_error_from_infallible)) + }; + + builder + .body(body) + .map_err(|e| GolemError::invalid_request(format!("Failed to attach body {e}"))) +} + +pub async fn http_response_to_output( + response: http::Response>, +) -> Result { + use http_body_util::BodyExt; + + tracing::debug!("Converting wasi:http/incoming-handler response to golem compatible value"); + + let status = response.status().as_u16(); + + let converted_headers = { + let mut acc: Vec<(String, Bytes)> = Vec::new(); + for (name, value) in response.headers().into_iter() { + acc.push((name.to_string(), Bytes::copy_from_slice(value.as_bytes()))); + } + HttpFields(acc) + }; + + let collected = response.into_body().collect().await.map_err(|e| { + GolemError::runtime(format!("Failed collection body of http response: {e}")) + })?; + + let trailers = collected.trailers().cloned(); + let bytes = collected.to_bytes(); + + let converted_body = if !bytes.is_empty() || trailers.is_some() { + let converted_trailers = if let Some(hm) = trailers { + let mut result = Vec::new(); + let mut previous = None; + for (name, value) in hm.into_iter() { + let current = match name { + None => previous.clone().unwrap(), + Some(next) => { + previous = Some(next.clone()); + next + } + }; + result.push(( + current.to_string(), + Bytes::copy_from_slice(value.as_bytes()), + )) + } + Some(HttpFields(result)) + } else { + None + }; + + Some(HttpBodyAndTrailers { + content: HttpBodyContent(bytes), + trailers: converted_trailers, + }) + } else { + None + }; + + let response = HttpResponse { + status, + headers: converted_headers, + body: converted_body, + }; + + Ok(response.to_value()) +} + +fn hyper_error_from_infallible(_infallible: Infallible) -> hyper::Error { + unreachable!() +} diff --git a/golem-worker-executor-base/src/virtual_export_compat/mod.rs b/golem-worker-executor-base/src/virtual_export_compat/mod.rs new file mode 100644 index 0000000000..a3d76a162c --- /dev/null +++ b/golem-worker-executor-base/src/virtual_export_compat/mod.rs @@ -0,0 +1,15 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod http_incoming_handler; diff --git a/golem-worker-executor-base/tests/wasi.rs b/golem-worker-executor-base/tests/wasi.rs index c7de8dc350..976e169dfb 100644 --- a/golem-worker-executor-base/tests/wasi.rs +++ b/golem-worker-executor-base/tests/wasi.rs @@ -1849,3 +1849,316 @@ async fn ip_address_resolve( check!(result1.len() > 0); check!(result2.len() > 0); } + +#[test] +#[tracing::instrument] +async fn wasi_incoming_request_handler( + last_unique_id: &LastUniqueId, + deps: &WorkerExecutorTestDependencies, + _tracing: &Tracing, +) { + let context = TestContext::new(last_unique_id); + let executor = start(deps, &context).await.unwrap(); + + let component_id = executor + .store_component("wasi-http-incoming-request-handler") + .await; + let worker_id = executor + .start_worker(&component_id, "wasi-http-incoming-request-handler-1") + .await; + + let args: Value = Value::Record(vec![ + Value::String("http://localhost:8000".to_string()), + Value::Variant { + case_idx: 0, + case_value: None, + }, + Value::List(vec![]), + Value::Option(None), + ]); + + let result = executor + .invoke_and_await( + &worker_id, + "golem:http/incoming-handler.{handle}", + vec![args], + ) + .await + .unwrap(); + + drop(executor); + + check!(result.len() == 1); + check!( + result[0] + == Value::Record(vec![ + Value::U16(200), + Value::List(vec![]), + Value::Option(None) + ]) + ); +} + +#[test] +#[tracing::instrument] +async fn wasi_incoming_request_handler_echo( + last_unique_id: &LastUniqueId, + deps: &WorkerExecutorTestDependencies, + _tracing: &Tracing, +) { + let context = TestContext::new(last_unique_id); + let executor = start(deps, &context).await.unwrap(); + + let component_id = executor + .store_component("wasi-http-incoming-request-handler-echo") + .await; + + let worker_id = executor + .start_worker(&component_id, "wasi-http-incoming-request-handler-echo-1") + .await; + + let args: Value = Value::Record(vec![ + Value::String("http://localhost:8000/foo?bar=baz".to_string()), + Value::Variant { + case_idx: 2, + case_value: None, + }, + Value::List(vec![Value::Tuple(vec![ + Value::String("test-header".to_string()), + Value::List( + "foobar" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect(), + ), + ])]), + Value::Option(Some(Box::new(Value::Record(vec![ + Value::List( + "test-body" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect(), + ), + Value::Option(Some(Box::new(Value::List(vec![Value::Tuple(vec![ + Value::String("test-trailer".to_string()), + Value::List( + "barfoo" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect(), + ), + ])])))), + ])))), + ]); + + let result = executor + .invoke_and_await( + &worker_id, + "golem:http/incoming-handler.{handle}", + vec![args], + ) + .await + .unwrap(); + + drop(executor); + + check!(result.len() == 1); + check!( + result[0] + == Value::Record(vec![ + Value::U16(200), + Value::List(vec![ + Value::Tuple(vec![ + Value::String("echo-test-header".to_string()), + Value::List( + "foobar" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect() + ) + ]), + Value::Tuple(vec![ + Value::String("x-location".to_string()), + Value::List( + "http://localhost:8000/foo?bar=baz" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect() + ) + ]), + Value::Tuple(vec![ + Value::String("x-method".to_string()), + Value::List( + "POST" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect() + ) + ]) + ]), + Value::Option(Some(Box::new(Value::Record(vec![ + Value::List( + "test-body" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect() + ), + Value::Option(Some(Box::new(Value::List(vec![Value::Tuple(vec![ + Value::String("echo-test-trailer".to_string()), + Value::List( + "barfoo" + .to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect() + ) + ])]),))) + ])))) + ]) + ); +} + +#[test] +#[tracing::instrument] +async fn wasi_incoming_request_handler_state( + last_unique_id: &LastUniqueId, + deps: &WorkerExecutorTestDependencies, + _tracing: &Tracing, +) { + let context = TestContext::new(last_unique_id); + let executor = start(deps, &context).await.unwrap(); + + let component_id = executor + .store_component("wasi-http-incoming-request-handler-state") + .await; + + let worker_id = executor + .start_worker(&component_id, "wasi-http-incoming-request-handler-state-1") + .await; + + let args_put: Value = Value::Record(vec![ + Value::String("http://localhost:8000".to_string()), + Value::Variant { + case_idx: 3, + case_value: None, + }, + Value::List(vec![]), + Value::Option(Some(Box::new(Value::Record(vec![ + Value::List( + "1".to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect(), + ), + Value::Option(None), + ])))), + ]); + + let args_get: Value = Value::Record(vec![ + Value::String("http://localhost:8000".to_string()), + Value::Variant { + case_idx: 0, + case_value: None, + }, + Value::List(vec![]), + Value::Option(None), + ]); + + let result1 = executor + .invoke_and_await( + &worker_id, + "golem:http/incoming-handler.{handle}", + vec![args_put], + ) + .await + .unwrap(); + + let result2 = executor + .invoke_and_await( + &worker_id, + "golem:http/incoming-handler.{handle}", + vec![args_get.clone()], + ) + .await + .unwrap(); + + drop(executor); + + check!(result1.len() == 1); + check!( + result1[0] + == Value::Record(vec![ + Value::U16(200), + Value::List(vec![]), + Value::Option(None) + ]) + ); + + check!(result2.len() == 1); + check!( + result2[0] + == Value::Record(vec![ + Value::U16(200), + Value::List(vec![]), + Value::Option(Some(Box::new(Value::Record(vec![ + Value::List( + "1".to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect() + ), + Value::Option(None) + ])))) + ]) + ); + + // restart executor and check whether we are restoring the state + let executor = start(deps, &context).await.unwrap(); + + let result3 = executor + .invoke_and_await( + &worker_id, + "golem:http/incoming-handler.{handle}", + vec![args_get.clone()], + ) + .await + .unwrap(); + + drop(executor); + + check!(result3.len() == 1); + check!( + result3[0] + == Value::Record(vec![ + Value::U16(200), + Value::List(vec![]), + Value::Option(Some(Box::new(Value::Record(vec![ + Value::List( + "1".to_string() + .into_bytes() + .into_iter() + .map(Value::U8) + .collect() + ), + Value::Option(None) + ])))) + ]) + ); +} diff --git a/test-components/wasi-http-incoming-request-handler-echo.wasm b/test-components/wasi-http-incoming-request-handler-echo.wasm new file mode 100644 index 0000000000000000000000000000000000000000..b36965f135490ad64ac82328432acbc2455f2b0f GIT binary patch literal 103873 zcmdqK3xHi$UGKlw-sd%Q&P-0)v`w3|-RCs4sbtzHkko*f9qA($5TSVaU-jRn$+VeA zXEKk3R)I`u!HR%Is}!kNpxjoZ+KVVvxf-!Rl>$|JwQ$jkf>0H;*Jtmw+WYzb*4q2* zbLLE%V!i)I(`4_x_Imu*@BRC&wbzOEEnPPjxv2iFZcn8WH4e?s&hEQiLVU{XzNO`f`9qV7`gMw<1LWsEHFxa<;2m(I?qJPL zGljf)v$21EZh3NUd8rY#D$xabAAKYDI(hBl)bixSzPSSv*UTPXI_Snm&v4NxIj;N! zmIAht+674x#r^n+N|cM@{t4EL2I! zT{lVJV51T>ebJG9vxh0GxP@eVYL2I=0~1R(%q{P`KBANP#jB?d9GINre(JjG4lj#! z4Cx0!%j9B?^jalqPtEP0zs_T9;qc_rGH@)6Cf80bQ(v{Y9GYL^DSK@poM39daa9%xs;D!X;tY4g5I>fM(6QbU}MX@8LJX|~P=i^^9 zp_wH&^Mh_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7?FxPVuMCN)IwLl?4X0C5_Tx=a}~_T5iSZ zhOMle1&$5ntxDrOR~+OU4<(({LDr_IQH<=RxO67~#bx7n)S;z<4$W|mY~1Q4Eq#cy za%)9Cn^CxPI4%`M`>=fh8g9bh-K9BNdM_eE}q?x+m}k?xKn{o$3amY80+|&YsIoC)~N|Zj4&0AvB7O6aV=g6m#96IO%ni{=__*fwqT% zb}gkoA+Kd6_fpAuN?T`7v#>?h?!H>P5x7S3-gLZRvk<_z9V>gm%(9!6FhPn0sH>~uwKO%>%}x$VMO zM7upev*X)SZ^4Y=QnS^)?8Fevp9Fwwo8Hfa--?q#ZB_euJeOyZ$qDv7PC;kiHkWZ& WnB6$s?ZMGjo;C_2{#>#O;{OM2e_*r# literal 0 HcmV?d00001 diff --git a/test-components/wasi-http-incoming-request-handler-echo/Cargo.lock b/test-components/wasi-http-incoming-request-handler-echo/Cargo.lock new file mode 100644 index 0000000000..d68f982507 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/Cargo.lock @@ -0,0 +1,25 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" + +[[package]] +name = "wasi-http-incoming-request-handler-echo" +version = "0.1.0" +dependencies = [ + "wit-bindgen-rt", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc801b991c56492f87ab3086e786468f75c285a4d73017ab0ebc2fa1aed5d82c" +dependencies = [ + "bitflags", +] diff --git a/test-components/wasi-http-incoming-request-handler-echo/Cargo.toml b/test-components/wasi-http-incoming-request-handler-echo/Cargo.toml new file mode 100644 index 0000000000..c21935b55d --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "wasi-http-incoming-request-handler-echo" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +path = "src/lib.rs" +crate-type = ["cdylib"] + +[dependencies] +wit-bindgen-rt = { version = "0.37.0", features = ["bitflags"] } + +[package.metadata.component] +package = "golem:handler" +proxy = true + +[package.metadata.component.target.dependencies] +"wasi:cli" = { path = "wit/deps/cli" } +"wasi:clocks" = { path = "wit/deps/clocks" } +"wasi:filesystem" = { path = "wit/deps/filesystem" } +"wasi:http" = { path = "wit/deps/http" } +"wasi:io" = { path = "wit/deps/io" } +"wasi:random" = { path = "wit/deps/random" } +"wasi:sockets" = { path = "wit/deps/sockets" } diff --git a/test-components/wasi-http-incoming-request-handler-echo/src/bindings.rs b/test-components/wasi-http-incoming-request-handler-echo/src/bindings.rs new file mode 100644 index 0000000000..b9a1d24912 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/src/bindings.rs @@ -0,0 +1,7502 @@ +#[allow(dead_code)] +pub mod wasi { + #[allow(dead_code)] + pub mod clocks { + #[allow(dead_code, clippy::all)] + pub mod monotonic_clock { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Pollable = super::super::super::wasi::io::poll::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. + pub type Instant = u64; + /// A duration of time, in nanoseconds. + pub type Duration = u64; + #[allow(unused_unsafe, clippy::all)] + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + pub fn now() -> Instant { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "now"] + fn wit_import() -> i64; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i64 { + unreachable!() + } + let ret = wit_import(); + ret as u64 + } + } + #[allow(unused_unsafe, clippy::all)] + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + pub fn resolution() -> Duration { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "resolution"] + fn wit_import() -> i64; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i64 { + unreachable!() + } + let ret = wit_import(); + ret as u64 + } + } + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + pub fn subscribe_instant(when: Instant) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "subscribe-instant"] + fn wit_import(_: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i64) -> i32 { + unreachable!() + } + let ret = wit_import(_rt::as_i64(when)); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + pub fn subscribe_duration(when: Duration) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "subscribe-duration"] + fn wit_import(_: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i64) -> i32 { + unreachable!() + } + let ret = wit_import(_rt::as_i64(when)); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + } + #[allow(dead_code)] + pub mod http { + #[allow(dead_code, clippy::all)] + pub mod types { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Duration = super::super::super::wasi::clocks::monotonic_clock::Duration; + pub type InputStream = super::super::super::wasi::io::streams::InputStream; + pub type OutputStream = super::super::super::wasi::io::streams::OutputStream; + pub type IoError = super::super::super::wasi::io::error::Error; + pub type Pollable = super::super::super::wasi::io::poll::Pollable; + /// This type corresponds to HTTP standard Methods. + #[derive(Clone)] + pub enum Method { + Get, + Head, + Post, + Put, + Delete, + Connect, + Options, + Trace, + Patch, + Other(_rt::String), + } + impl ::core::fmt::Debug for Method { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + Method::Get => f.debug_tuple("Method::Get").finish(), + Method::Head => f.debug_tuple("Method::Head").finish(), + Method::Post => f.debug_tuple("Method::Post").finish(), + Method::Put => f.debug_tuple("Method::Put").finish(), + Method::Delete => f.debug_tuple("Method::Delete").finish(), + Method::Connect => f.debug_tuple("Method::Connect").finish(), + Method::Options => f.debug_tuple("Method::Options").finish(), + Method::Trace => f.debug_tuple("Method::Trace").finish(), + Method::Patch => f.debug_tuple("Method::Patch").finish(), + Method::Other(e) => { + f.debug_tuple("Method::Other").field(e).finish() + } + } + } + } + /// This type corresponds to HTTP standard Related Schemes. + #[derive(Clone)] + pub enum Scheme { + Http, + Https, + Other(_rt::String), + } + impl ::core::fmt::Debug for Scheme { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + Scheme::Http => f.debug_tuple("Scheme::Http").finish(), + Scheme::Https => f.debug_tuple("Scheme::Https").finish(), + Scheme::Other(e) => { + f.debug_tuple("Scheme::Other").field(e).finish() + } + } + } + } + /// Defines the case payload type for `DNS-error` above: + #[derive(Clone)] + pub struct DnsErrorPayload { + pub rcode: Option<_rt::String>, + pub info_code: Option, + } + impl ::core::fmt::Debug for DnsErrorPayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("DnsErrorPayload") + .field("rcode", &self.rcode) + .field("info-code", &self.info_code) + .finish() + } + } + /// Defines the case payload type for `TLS-alert-received` above: + #[derive(Clone)] + pub struct TlsAlertReceivedPayload { + pub alert_id: Option, + pub alert_message: Option<_rt::String>, + } + impl ::core::fmt::Debug for TlsAlertReceivedPayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("TlsAlertReceivedPayload") + .field("alert-id", &self.alert_id) + .field("alert-message", &self.alert_message) + .finish() + } + } + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + #[derive(Clone)] + pub struct FieldSizePayload { + pub field_name: Option<_rt::String>, + pub field_size: Option, + } + impl ::core::fmt::Debug for FieldSizePayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("FieldSizePayload") + .field("field-name", &self.field_name) + .field("field-size", &self.field_size) + .finish() + } + } + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + #[derive(Clone)] + pub enum ErrorCode { + DnsTimeout, + DnsError(DnsErrorPayload), + DestinationNotFound, + DestinationUnavailable, + DestinationIpProhibited, + DestinationIpUnroutable, + ConnectionRefused, + ConnectionTerminated, + ConnectionTimeout, + ConnectionReadTimeout, + ConnectionWriteTimeout, + ConnectionLimitReached, + TlsProtocolError, + TlsCertificateError, + TlsAlertReceived(TlsAlertReceivedPayload), + HttpRequestDenied, + HttpRequestLengthRequired, + HttpRequestBodySize(Option), + HttpRequestMethodInvalid, + HttpRequestUriInvalid, + HttpRequestUriTooLong, + HttpRequestHeaderSectionSize(Option), + HttpRequestHeaderSize(Option), + HttpRequestTrailerSectionSize(Option), + HttpRequestTrailerSize(FieldSizePayload), + HttpResponseIncomplete, + HttpResponseHeaderSectionSize(Option), + HttpResponseHeaderSize(FieldSizePayload), + HttpResponseBodySize(Option), + HttpResponseTrailerSectionSize(Option), + HttpResponseTrailerSize(FieldSizePayload), + HttpResponseTransferCoding(Option<_rt::String>), + HttpResponseContentCoding(Option<_rt::String>), + HttpResponseTimeout, + HttpUpgradeFailed, + HttpProtocolError, + LoopDetected, + ConfigurationError, + /// 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. + InternalError(Option<_rt::String>), + } + impl ::core::fmt::Debug for ErrorCode { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + ErrorCode::DnsTimeout => { + f.debug_tuple("ErrorCode::DnsTimeout").finish() + } + ErrorCode::DnsError(e) => { + f.debug_tuple("ErrorCode::DnsError").field(e).finish() + } + ErrorCode::DestinationNotFound => { + f.debug_tuple("ErrorCode::DestinationNotFound").finish() + } + ErrorCode::DestinationUnavailable => { + f.debug_tuple("ErrorCode::DestinationUnavailable").finish() + } + ErrorCode::DestinationIpProhibited => { + f.debug_tuple("ErrorCode::DestinationIpProhibited").finish() + } + ErrorCode::DestinationIpUnroutable => { + f.debug_tuple("ErrorCode::DestinationIpUnroutable").finish() + } + ErrorCode::ConnectionRefused => { + f.debug_tuple("ErrorCode::ConnectionRefused").finish() + } + ErrorCode::ConnectionTerminated => { + f.debug_tuple("ErrorCode::ConnectionTerminated").finish() + } + ErrorCode::ConnectionTimeout => { + f.debug_tuple("ErrorCode::ConnectionTimeout").finish() + } + ErrorCode::ConnectionReadTimeout => { + f.debug_tuple("ErrorCode::ConnectionReadTimeout").finish() + } + ErrorCode::ConnectionWriteTimeout => { + f.debug_tuple("ErrorCode::ConnectionWriteTimeout").finish() + } + ErrorCode::ConnectionLimitReached => { + f.debug_tuple("ErrorCode::ConnectionLimitReached").finish() + } + ErrorCode::TlsProtocolError => { + f.debug_tuple("ErrorCode::TlsProtocolError").finish() + } + ErrorCode::TlsCertificateError => { + f.debug_tuple("ErrorCode::TlsCertificateError").finish() + } + ErrorCode::TlsAlertReceived(e) => { + f.debug_tuple("ErrorCode::TlsAlertReceived") + .field(e) + .finish() + } + ErrorCode::HttpRequestDenied => { + f.debug_tuple("ErrorCode::HttpRequestDenied").finish() + } + ErrorCode::HttpRequestLengthRequired => { + f.debug_tuple("ErrorCode::HttpRequestLengthRequired") + .finish() + } + ErrorCode::HttpRequestBodySize(e) => { + f.debug_tuple("ErrorCode::HttpRequestBodySize") + .field(e) + .finish() + } + ErrorCode::HttpRequestMethodInvalid => { + f.debug_tuple("ErrorCode::HttpRequestMethodInvalid").finish() + } + ErrorCode::HttpRequestUriInvalid => { + f.debug_tuple("ErrorCode::HttpRequestUriInvalid").finish() + } + ErrorCode::HttpRequestUriTooLong => { + f.debug_tuple("ErrorCode::HttpRequestUriTooLong").finish() + } + ErrorCode::HttpRequestHeaderSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestHeaderSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestHeaderSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestHeaderSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestTrailerSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestTrailerSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestTrailerSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestTrailerSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseIncomplete => { + f.debug_tuple("ErrorCode::HttpResponseIncomplete").finish() + } + ErrorCode::HttpResponseHeaderSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseHeaderSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseHeaderSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseHeaderSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseBodySize(e) => { + f.debug_tuple("ErrorCode::HttpResponseBodySize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTrailerSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseTrailerSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTrailerSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseTrailerSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTransferCoding(e) => { + f.debug_tuple("ErrorCode::HttpResponseTransferCoding") + .field(e) + .finish() + } + ErrorCode::HttpResponseContentCoding(e) => { + f.debug_tuple("ErrorCode::HttpResponseContentCoding") + .field(e) + .finish() + } + ErrorCode::HttpResponseTimeout => { + f.debug_tuple("ErrorCode::HttpResponseTimeout").finish() + } + ErrorCode::HttpUpgradeFailed => { + f.debug_tuple("ErrorCode::HttpUpgradeFailed").finish() + } + ErrorCode::HttpProtocolError => { + f.debug_tuple("ErrorCode::HttpProtocolError").finish() + } + ErrorCode::LoopDetected => { + f.debug_tuple("ErrorCode::LoopDetected").finish() + } + ErrorCode::ConfigurationError => { + f.debug_tuple("ErrorCode::ConfigurationError").finish() + } + ErrorCode::InternalError(e) => { + f.debug_tuple("ErrorCode::InternalError").field(e).finish() + } + } + } + } + impl ::core::fmt::Display for ErrorCode { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for ErrorCode {} + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + #[derive(Clone, Copy)] + pub enum HeaderError { + /// This error indicates that a `field-name` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + InvalidSyntax, + /// This error indicates that a forbidden `field-name` was used when trying + /// to set a header in a `fields`. + Forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + Immutable, + } + impl ::core::fmt::Debug for HeaderError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + HeaderError::InvalidSyntax => { + f.debug_tuple("HeaderError::InvalidSyntax").finish() + } + HeaderError::Forbidden => { + f.debug_tuple("HeaderError::Forbidden").finish() + } + HeaderError::Immutable => { + f.debug_tuple("HeaderError::Immutable").finish() + } + } + } + } + impl ::core::fmt::Display for HeaderError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for HeaderError {} + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + pub type FieldKey = _rt::String; + /// Field names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + pub type FieldName = FieldKey; + /// 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. + pub type FieldValue = _rt::Vec; + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct Fields { + handle: _rt::Resource, + } + impl Fields { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Fields { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]fields"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Headers is an alias for Fields. + pub type Headers = Fields; + /// Trailers is an alias for Fields. + pub type Trailers = Fields; + /// Represents an incoming HTTP Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingRequest { + handle: _rt::Resource, + } + impl IncomingRequest { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingRequest { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-request"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingRequest { + handle: _rt::Resource, + } + impl OutgoingRequest { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingRequest { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-request"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct RequestOptions { + handle: _rt::Resource, + } + impl RequestOptions { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for RequestOptions { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]request-options"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct ResponseOutparam { + handle: _rt::Resource, + } + impl ResponseOutparam { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for ResponseOutparam { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]response-outparam"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// This type corresponds to the HTTP standard Status Code. + pub type StatusCode = u16; + /// Represents an incoming HTTP Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingResponse { + handle: _rt::Resource, + } + impl IncomingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingBody { + handle: _rt::Resource, + } + impl IncomingBody { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingBody { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-body"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + #[derive(Debug)] + #[repr(transparent)] + pub struct FutureTrailers { + handle: _rt::Resource, + } + impl FutureTrailers { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for FutureTrailers { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]future-trailers"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingResponse { + handle: _rt::Resource, + } + impl OutgoingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingBody { + handle: _rt::Resource, + } + impl OutgoingBody { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingBody { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-body"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct FutureIncomingResponse { + handle: _rt::Resource, + } + impl FutureIncomingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for FutureIncomingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]future-incoming-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn http_error_code(err: &IoError) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 40]); + let mut ret_area = RetArea([::core::mem::MaybeUninit::uninit(); 40]); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "http-error-code"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((err).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + let v64 = match l2 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e64 = { + let l3 = i32::from(*ptr0.add(16).cast::()); + let l7 = i32::from(*ptr0.add(28).cast::()); + DnsErrorPayload { + rcode: match l3 { + 0 => None, + 1 => { + let e = { + let l4 = *ptr0.add(20).cast::<*mut u8>(); + let l5 = *ptr0.add(24).cast::(); + let len6 = l5; + let bytes6 = _rt::Vec::from_raw_parts( + l4.cast(), + len6, + len6, + ); + _rt::string_lift(bytes6) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l7 { + 0 => None, + 1 => { + let e = { + let l8 = i32::from(*ptr0.add(30).cast::()); + l8 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e64) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e64 = { + let l9 = i32::from(*ptr0.add(16).cast::()); + let l11 = i32::from(*ptr0.add(20).cast::()); + TlsAlertReceivedPayload { + alert_id: match l9 { + 0 => None, + 1 => { + let e = { + let l10 = i32::from(*ptr0.add(17).cast::()); + l10 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l11 { + 0 => None, + 1 => { + let e = { + let l12 = *ptr0.add(24).cast::<*mut u8>(); + let l13 = *ptr0.add(28).cast::(); + let len14 = l13; + let bytes14 = _rt::Vec::from_raw_parts( + l12.cast(), + len14, + len14, + ); + _rt::string_lift(bytes14) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e64) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e64 = { + let l15 = i32::from(*ptr0.add(16).cast::()); + match l15 { + 0 => None, + 1 => { + let e = { + let l16 = *ptr0.add(24).cast::(); + l16 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e64) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e64 = { + let l17 = i32::from(*ptr0.add(16).cast::()); + match l17 { + 0 => None, + 1 => { + let e = { + let l18 = *ptr0.add(20).cast::(); + l18 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e64) + } + 22 => { + let e64 = { + let l19 = i32::from(*ptr0.add(16).cast::()); + match l19 { + 0 => None, + 1 => { + let e = { + let l20 = i32::from(*ptr0.add(20).cast::()); + let l24 = i32::from(*ptr0.add(32).cast::()); + FieldSizePayload { + field_name: match l20 { + 0 => None, + 1 => { + let e = { + let l21 = *ptr0.add(24).cast::<*mut u8>(); + let l22 = *ptr0.add(28).cast::(); + let len23 = l22; + let bytes23 = _rt::Vec::from_raw_parts( + l21.cast(), + len23, + len23, + ); + _rt::string_lift(bytes23) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l24 { + 0 => None, + 1 => { + let e = { + let l25 = *ptr0.add(36).cast::(); + l25 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e64) + } + 23 => { + let e64 = { + let l26 = i32::from(*ptr0.add(16).cast::()); + match l26 { + 0 => None, + 1 => { + let e = { + let l27 = *ptr0.add(20).cast::(); + l27 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e64) + } + 24 => { + let e64 = { + let l28 = i32::from(*ptr0.add(16).cast::()); + let l32 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l28 { + 0 => None, + 1 => { + let e = { + let l29 = *ptr0.add(20).cast::<*mut u8>(); + let l30 = *ptr0.add(24).cast::(); + let len31 = l30; + let bytes31 = _rt::Vec::from_raw_parts( + l29.cast(), + len31, + len31, + ); + _rt::string_lift(bytes31) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l32 { + 0 => None, + 1 => { + let e = { + let l33 = *ptr0.add(32).cast::(); + l33 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e64) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e64 = { + let l34 = i32::from(*ptr0.add(16).cast::()); + match l34 { + 0 => None, + 1 => { + let e = { + let l35 = *ptr0.add(20).cast::(); + l35 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e64) + } + 27 => { + let e64 = { + let l36 = i32::from(*ptr0.add(16).cast::()); + let l40 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l36 { + 0 => None, + 1 => { + let e = { + let l37 = *ptr0.add(20).cast::<*mut u8>(); + let l38 = *ptr0.add(24).cast::(); + let len39 = l38; + let bytes39 = _rt::Vec::from_raw_parts( + l37.cast(), + len39, + len39, + ); + _rt::string_lift(bytes39) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l40 { + 0 => None, + 1 => { + let e = { + let l41 = *ptr0.add(32).cast::(); + l41 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e64) + } + 28 => { + let e64 = { + let l42 = i32::from(*ptr0.add(16).cast::()); + match l42 { + 0 => None, + 1 => { + let e = { + let l43 = *ptr0.add(24).cast::(); + l43 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e64) + } + 29 => { + let e64 = { + let l44 = i32::from(*ptr0.add(16).cast::()); + match l44 { + 0 => None, + 1 => { + let e = { + let l45 = *ptr0.add(20).cast::(); + l45 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e64) + } + 30 => { + let e64 = { + let l46 = i32::from(*ptr0.add(16).cast::()); + let l50 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l46 { + 0 => None, + 1 => { + let e = { + let l47 = *ptr0.add(20).cast::<*mut u8>(); + let l48 = *ptr0.add(24).cast::(); + let len49 = l48; + let bytes49 = _rt::Vec::from_raw_parts( + l47.cast(), + len49, + len49, + ); + _rt::string_lift(bytes49) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l50 { + 0 => None, + 1 => { + let e = { + let l51 = *ptr0.add(32).cast::(); + l51 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e64) + } + 31 => { + let e64 = { + let l52 = i32::from(*ptr0.add(16).cast::()); + match l52 { + 0 => None, + 1 => { + let e = { + let l53 = *ptr0.add(20).cast::<*mut u8>(); + let l54 = *ptr0.add(24).cast::(); + let len55 = l54; + let bytes55 = _rt::Vec::from_raw_parts( + l53.cast(), + len55, + len55, + ); + _rt::string_lift(bytes55) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e64) + } + 32 => { + let e64 = { + let l56 = i32::from(*ptr0.add(16).cast::()); + match l56 { + 0 => None, + 1 => { + let e = { + let l57 = *ptr0.add(20).cast::<*mut u8>(); + let l58 = *ptr0.add(24).cast::(); + let len59 = l58; + let bytes59 = _rt::Vec::from_raw_parts( + l57.cast(), + len59, + len59, + ); + _rt::string_lift(bytes59) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e64) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e64 = { + let l60 = i32::from(*ptr0.add(16).cast::()); + match l60 { + 0 => None, + 1 => { + let e = { + let l61 = *ptr0.add(20).cast::<*mut u8>(); + let l62 = *ptr0.add(24).cast::(); + let len63 = l62; + let bytes63 = _rt::Vec::from_raw_parts( + l61.cast(), + len63, + len63, + ); + _rt::string_lift(bytes63) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e64) + } + }; + v64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + pub fn new() -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]fields"] + fn wit_import() -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i32 { + unreachable!() + } + let ret = wit_import(); + Fields::from_handle(ret as u32) + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + pub fn from_list( + entries: &[(FieldName, FieldValue)], + ) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let vec3 = entries; + let len3 = vec3.len(); + let layout3 = _rt::alloc::Layout::from_size_align_unchecked( + vec3.len() * 16, + 4, + ); + let result3 = if layout3.size() != 0 { + let ptr = _rt::alloc::alloc(layout3).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout3); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec3.into_iter().enumerate() { + let base = result3.add(i * 16); + { + let (t0_0, t0_1) = e; + let vec1 = t0_0; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + *base.add(4).cast::() = len1; + *base.add(0).cast::<*mut u8>() = ptr1.cast_mut(); + let vec2 = t0_1; + let ptr2 = vec2.as_ptr().cast::(); + let len2 = vec2.len(); + *base.add(12).cast::() = len2; + *base.add(8).cast::<*mut u8>() = ptr2.cast_mut(); + } + } + let ptr4 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]fields.from-list"] + fn wit_import(_: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import(result3, len3, ptr4); + let l5 = i32::from(*ptr4.add(0).cast::()); + if layout3.size() != 0 { + _rt::alloc::dealloc(result3.cast(), layout3); + } + match l5 { + 0 => { + let e = { + let l6 = *ptr4.add(4).cast::(); + Fields::from_handle(l6 as u32) + }; + Ok(e) + } + 1 => { + let e = { + let l7 = i32::from(*ptr4.add(4).cast::()); + let v8 = match l7 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v8 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + pub fn get(&self, name: &FieldName) -> _rt::Vec { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.get"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = *ptr1.add(0).cast::<*mut u8>(); + let l3 = *ptr1.add(4).cast::(); + let base7 = l2; + let len7 = l3; + let mut result7 = _rt::Vec::with_capacity(len7); + for i in 0..len7 { + let base = base7.add(i * 8); + let e7 = { + let l4 = *base.add(0).cast::<*mut u8>(); + let l5 = *base.add(4).cast::(); + let len6 = l5; + _rt::Vec::from_raw_parts(l4.cast(), len6, len6) + }; + result7.push(e7); + } + _rt::cabi_dealloc(base7, len7 * 8, 4); + result7 + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + pub fn has(&self, name: &FieldName) -> bool { + unsafe { + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.has"] + fn wit_import(_: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + ); + _rt::bool_lift(ret as u8) + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + pub fn set( + &self, + name: &FieldName, + value: &[FieldValue], + ) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let vec2 = value; + let len2 = vec2.len(); + let layout2 = _rt::alloc::Layout::from_size_align_unchecked( + vec2.len() * 8, + 4, + ); + let result2 = if layout2.size() != 0 { + let ptr = _rt::alloc::alloc(layout2).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout2); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec2.into_iter().enumerate() { + let base = result2.add(i * 8); + { + let vec1 = e; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + *base.add(4).cast::() = len1; + *base.add(0).cast::<*mut u8>() = ptr1.cast_mut(); + } + } + let ptr3 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.set"] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ) { + unreachable!() + } + wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + result2, + len2, + ptr3, + ); + let l4 = i32::from(*ptr3.add(0).cast::()); + if layout2.size() != 0 { + _rt::alloc::dealloc(result2.cast(), layout2); + } + match l4 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr3.add(1).cast::()); + let v6 = match l5 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v6 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + pub fn delete(&self, name: &FieldName) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.delete"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(1).cast::()); + let v4 = match l3 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + pub fn append( + &self, + name: &FieldName, + value: &FieldValue, + ) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let vec1 = value; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + let ptr2 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.append"] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ) { + unreachable!() + } + wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + ptr1.cast_mut(), + len1, + ptr2, + ); + let l3 = i32::from(*ptr2.add(0).cast::()); + match l3 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l4 = i32::from(*ptr2.add(1).cast::()); + let v5 = match l4 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + pub fn entries(&self) -> _rt::Vec<(FieldName, FieldValue)> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.entries"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = *ptr0.add(0).cast::<*mut u8>(); + let l2 = *ptr0.add(4).cast::(); + let base9 = l1; + let len9 = l2; + let mut result9 = _rt::Vec::with_capacity(len9); + for i in 0..len9 { + let base = base9.add(i * 16); + let e9 = { + let l3 = *base.add(0).cast::<*mut u8>(); + let l4 = *base.add(4).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + let l6 = *base.add(8).cast::<*mut u8>(); + let l7 = *base.add(12).cast::(); + let len8 = l7; + ( + _rt::string_lift(bytes5), + _rt::Vec::from_raw_parts(l6.cast(), len8, len8), + ) + }; + result9.push(e9); + } + _rt::cabi_dealloc(base9, len9 * 16, 4); + result9 + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + pub fn clone(&self) -> Fields { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.clone"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the method of the incoming request. + pub fn method(&self) -> Method { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.method"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + let v5 = match l1 { + 0 => Method::Get, + 1 => Method::Head, + 2 => Method::Post, + 3 => Method::Put, + 4 => Method::Delete, + 5 => Method::Connect, + 6 => Method::Options, + 7 => Method::Trace, + 8 => Method::Patch, + n => { + debug_assert_eq!(n, 9, "invalid enum discriminant"); + let e5 = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Method::Other(e5) + } + }; + v5 + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the path with query parameters from the request, as a string. + pub fn path_with_query(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.path-with-query"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the protocol scheme from the request. + pub fn scheme(&self) -> Option { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.scheme"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v6 = match l2 { + 0 => Scheme::Http, + 1 => Scheme::Https, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + let e6 = { + let l3 = *ptr0.add(8).cast::<*mut u8>(); + let l4 = *ptr0.add(12).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + _rt::string_lift(bytes5) + }; + Scheme::Other(e6) + } + }; + v6 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the authority of the Request's target URI, if present. + pub fn authority(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.authority"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + pub fn consume(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.consume"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + IncomingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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`. + pub fn new(headers: Headers) -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]outgoing-request"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&headers).take_handle() as i32); + OutgoingRequest::from_handle(ret as u32) + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn body(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.body"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + OutgoingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the Method for the Request. + pub fn method(&self) -> Method { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.method"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + let v5 = match l1 { + 0 => Method::Get, + 1 => Method::Head, + 2 => Method::Post, + 3 => Method::Put, + 4 => Method::Delete, + 5 => Method::Connect, + 6 => Method::Options, + 7 => Method::Trace, + 8 => Method::Patch, + n => { + debug_assert_eq!(n, 9, "invalid enum discriminant"); + let e5 = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Method::Other(e5) + } + }; + v5 + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + pub fn set_method(&self, method: &Method) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match method { + Method::Get => (0i32, ::core::ptr::null_mut(), 0usize), + Method::Head => (1i32, ::core::ptr::null_mut(), 0usize), + Method::Post => (2i32, ::core::ptr::null_mut(), 0usize), + Method::Put => (3i32, ::core::ptr::null_mut(), 0usize), + Method::Delete => (4i32, ::core::ptr::null_mut(), 0usize), + Method::Connect => (5i32, ::core::ptr::null_mut(), 0usize), + Method::Options => (6i32, ::core::ptr::null_mut(), 0usize), + Method::Trace => (7i32, ::core::ptr::null_mut(), 0usize), + Method::Patch => (8i32, ::core::ptr::null_mut(), 0usize), + Method::Other(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (9i32, ptr0.cast_mut(), len0) + } + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-method"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + pub fn path_with_query(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.path-with-query"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_path_with_query( + &self, + path_with_query: Option<&str>, + ) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match path_with_query { + Some(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (1i32, ptr0.cast_mut(), len0) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-path-with-query"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + pub fn scheme(&self) -> Option { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.scheme"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v6 = match l2 { + 0 => Scheme::Http, + 1 => Scheme::Https, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + let e6 = { + let l3 = *ptr0.add(8).cast::<*mut u8>(); + let l4 = *ptr0.add(12).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + _rt::string_lift(bytes5) + }; + Scheme::Other(e6) + } + }; + v6 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_scheme(&self, scheme: Option<&Scheme>) -> Result<(), ()> { + unsafe { + let (result2_0, result2_1, result2_2, result2_3) = match scheme { + Some(e) => { + let (result1_0, result1_1, result1_2) = match e { + Scheme::Http => (0i32, ::core::ptr::null_mut(), 0usize), + Scheme::Https => (1i32, ::core::ptr::null_mut(), 0usize), + Scheme::Other(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (2i32, ptr0.cast_mut(), len0) + } + }; + (1i32, result1_0, result1_1, result1_2) + } + None => (0i32, 0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-scheme"] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: *mut u8, + _: usize, + ) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: *mut u8, + _: usize, + ) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result2_0, + result2_1, + result2_2, + result2_3, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. + pub fn authority(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.authority"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Set the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid URI authority. + pub fn set_authority(&self, authority: Option<&str>) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match authority { + Some(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (1i32, ptr0.cast_mut(), len0) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-authority"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Construct a default `request-options` value. + pub fn new() -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]request-options"] + fn wit_import() -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i32 { + unreachable!() + } + let ret = wit_import(); + RequestOptions::from_handle(ret as u32) + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for the initial connect to the HTTP Server. + pub fn connect_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.connect-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + pub fn set_connect_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-connect-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for receiving the first byte of the Response body. + pub fn first_byte_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.first-byte-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + pub fn set_first_byte_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-first-byte-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + pub fn between_bytes_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.between-bytes-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_between_bytes_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-between-bytes-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl ResponseOutparam { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set( + param: ResponseOutparam, + response: Result, + ) { + unsafe { + let ( + result38_0, + result38_1, + result38_2, + result38_3, + result38_4, + result38_5, + result38_6, + result38_7, + ) = match &response { + Ok(e) => { + ( + 0i32, + (e).take_handle() as i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + Err(e) => { + let ( + result37_0, + result37_1, + result37_2, + result37_3, + result37_4, + result37_5, + result37_6, + ) = match e { + ErrorCode::DnsTimeout => { + ( + 0i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DnsError(e) => { + let DnsErrorPayload { + rcode: rcode0, + info_code: info_code0, + } = e; + let (result2_0, result2_1, result2_2) = match rcode0 { + Some(e) => { + let vec1 = e; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + (1i32, ptr1.cast_mut(), len1) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result3_0, result3_1) = match info_code0 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 1i32, + result2_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result2_1); + t + }, + result2_2 as *mut u8, + result3_0 as *mut u8, + result3_1 as usize, + 0i32, + ) + } + ErrorCode::DestinationNotFound => { + ( + 2i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationUnavailable => { + ( + 3i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationIpProhibited => { + ( + 4i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationIpUnroutable => { + ( + 5i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionRefused => { + ( + 6i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionTerminated => { + ( + 7i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionTimeout => { + ( + 8i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionReadTimeout => { + ( + 9i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionWriteTimeout => { + ( + 10i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionLimitReached => { + ( + 11i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsProtocolError => { + ( + 12i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsCertificateError => { + ( + 13i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsAlertReceived(e) => { + let TlsAlertReceivedPayload { + alert_id: alert_id4, + alert_message: alert_message4, + } = e; + let (result5_0, result5_1) = match alert_id4 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + let (result7_0, result7_1, result7_2) = match alert_message4 { + Some(e) => { + let vec6 = e; + let ptr6 = vec6.as_ptr().cast::(); + let len6 = vec6.len(); + (1i32, ptr6.cast_mut(), len6) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 14i32, + result5_0, + ::core::mem::MaybeUninit::new(i64::from(result5_1) as u64), + result7_0 as *mut u8, + result7_1, + result7_2, + 0i32, + ) + } + ErrorCode::HttpRequestDenied => { + ( + 15i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestLengthRequired => { + ( + 16i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestBodySize(e) => { + let (result8_0, result8_1) = match e { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + ( + 17i32, + result8_0, + ::core::mem::MaybeUninit::new(result8_1 as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestMethodInvalid => { + ( + 18i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestUriInvalid => { + ( + 19i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestUriTooLong => { + ( + 20i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestHeaderSectionSize(e) => { + let (result9_0, result9_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 21i32, + result9_0, + ::core::mem::MaybeUninit::new(i64::from(result9_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestHeaderSize(e) => { + let ( + result14_0, + result14_1, + result14_2, + result14_3, + result14_4, + result14_5, + ) = match e { + Some(e) => { + let FieldSizePayload { + field_name: field_name10, + field_size: field_size10, + } = e; + let (result12_0, result12_1, result12_2) = match field_name10 { + Some(e) => { + let vec11 = e; + let ptr11 = vec11.as_ptr().cast::(); + let len11 = vec11.len(); + (1i32, ptr11.cast_mut(), len11) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result13_0, result13_1) = match field_size10 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 1i32, + result12_0, + result12_1, + result12_2, + result13_0, + result13_1, + ) + } + None => { + (0i32, 0i32, ::core::ptr::null_mut(), 0usize, 0i32, 0i32) + } + }; + ( + 22i32, + result14_0, + ::core::mem::MaybeUninit::new(i64::from(result14_1) as u64), + result14_2, + result14_3 as *mut u8, + result14_4 as usize, + result14_5, + ) + } + ErrorCode::HttpRequestTrailerSectionSize(e) => { + let (result15_0, result15_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 23i32, + result15_0, + ::core::mem::MaybeUninit::new(i64::from(result15_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestTrailerSize(e) => { + let FieldSizePayload { + field_name: field_name16, + field_size: field_size16, + } = e; + let (result18_0, result18_1, result18_2) = match field_name16 { + Some(e) => { + let vec17 = e; + let ptr17 = vec17.as_ptr().cast::(); + let len17 = vec17.len(); + (1i32, ptr17.cast_mut(), len17) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result19_0, result19_1) = match field_size16 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 24i32, + result18_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result18_1); + t + }, + result18_2 as *mut u8, + result19_0 as *mut u8, + result19_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseIncomplete => { + ( + 25i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseHeaderSectionSize(e) => { + let (result20_0, result20_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 26i32, + result20_0, + ::core::mem::MaybeUninit::new(i64::from(result20_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseHeaderSize(e) => { + let FieldSizePayload { + field_name: field_name21, + field_size: field_size21, + } = e; + let (result23_0, result23_1, result23_2) = match field_name21 { + Some(e) => { + let vec22 = e; + let ptr22 = vec22.as_ptr().cast::(); + let len22 = vec22.len(); + (1i32, ptr22.cast_mut(), len22) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result24_0, result24_1) = match field_size21 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 27i32, + result23_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result23_1); + t + }, + result23_2 as *mut u8, + result24_0 as *mut u8, + result24_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseBodySize(e) => { + let (result25_0, result25_1) = match e { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + ( + 28i32, + result25_0, + ::core::mem::MaybeUninit::new(result25_1 as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTrailerSectionSize(e) => { + let (result26_0, result26_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 29i32, + result26_0, + ::core::mem::MaybeUninit::new(i64::from(result26_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTrailerSize(e) => { + let FieldSizePayload { + field_name: field_name27, + field_size: field_size27, + } = e; + let (result29_0, result29_1, result29_2) = match field_name27 { + Some(e) => { + let vec28 = e; + let ptr28 = vec28.as_ptr().cast::(); + let len28 = vec28.len(); + (1i32, ptr28.cast_mut(), len28) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result30_0, result30_1) = match field_size27 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 30i32, + result29_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result29_1); + t + }, + result29_2 as *mut u8, + result30_0 as *mut u8, + result30_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseTransferCoding(e) => { + let (result32_0, result32_1, result32_2) = match e { + Some(e) => { + let vec31 = e; + let ptr31 = vec31.as_ptr().cast::(); + let len31 = vec31.len(); + (1i32, ptr31.cast_mut(), len31) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 31i32, + result32_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result32_1); + t + }, + result32_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseContentCoding(e) => { + let (result34_0, result34_1, result34_2) = match e { + Some(e) => { + let vec33 = e; + let ptr33 = vec33.as_ptr().cast::(); + let len33 = vec33.len(); + (1i32, ptr33.cast_mut(), len33) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 32i32, + result34_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result34_1); + t + }, + result34_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTimeout => { + ( + 33i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpUpgradeFailed => { + ( + 34i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpProtocolError => { + ( + 35i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::LoopDetected => { + ( + 36i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConfigurationError => { + ( + 37i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::InternalError(e) => { + let (result36_0, result36_1, result36_2) = match e { + Some(e) => { + let vec35 = e; + let ptr35 = vec35.as_ptr().cast::(); + let len35 = vec35.len(); + (1i32, ptr35.cast_mut(), len35) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 38i32, + result36_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result36_1); + t + }, + result36_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + }; + ( + 1i32, + result37_0, + result37_1, + result37_2, + result37_3, + result37_4, + result37_5, + result37_6, + ) + } + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]response-outparam.set"] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: i32, + _: ::core::mem::MaybeUninit, + _: *mut u8, + _: *mut u8, + _: usize, + _: i32, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: i32, + _: ::core::mem::MaybeUninit, + _: *mut u8, + _: *mut u8, + _: usize, + _: i32, + ) { + unreachable!() + } + wit_import( + (¶m).take_handle() as i32, + result38_0, + result38_1, + result38_2, + result38_3, + result38_4, + result38_5, + result38_6, + result38_7, + ); + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the status code from the incoming response. + pub fn status(&self) -> StatusCode { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.status"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + ret as u16 + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + pub fn consume(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.consume"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + IncomingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn stream(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-body.stream"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + super::super::super::wasi::io::streams::InputStream::from_handle( + l2 as u32, + ) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingBody { + #[allow(unused_unsafe, clippy::all)] + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + pub fn finish(this: IncomingBody) -> FutureTrailers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]incoming-body.finish"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&this).take_handle() as i32); + FutureTrailers::from_handle(ret as u32) + } + } + } + impl FutureTrailers { + #[allow(unused_unsafe, clippy::all)] + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-trailers.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl FutureTrailers { + #[allow(unused_unsafe, clippy::all)] + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + pub fn get( + &self, + ) -> Option, ErrorCode>, ()>> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 56]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 56], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-trailers.get"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + match l2 { + 0 => { + let e = { + let l3 = i32::from(*ptr0.add(16).cast::()); + match l3 { + 0 => { + let e = { + let l4 = i32::from(*ptr0.add(24).cast::()); + match l4 { + 0 => None, + 1 => { + let e = { + let l5 = *ptr0.add(28).cast::(); + Fields::from_handle(l5 as u32) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = { + let l6 = i32::from(*ptr0.add(24).cast::()); + let v68 = match l6 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e68 = { + let l7 = i32::from(*ptr0.add(32).cast::()); + let l11 = i32::from(*ptr0.add(44).cast::()); + DnsErrorPayload { + rcode: match l7 { + 0 => None, + 1 => { + let e = { + let l8 = *ptr0.add(36).cast::<*mut u8>(); + let l9 = *ptr0.add(40).cast::(); + let len10 = l9; + let bytes10 = _rt::Vec::from_raw_parts( + l8.cast(), + len10, + len10, + ); + _rt::string_lift(bytes10) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l11 { + 0 => None, + 1 => { + let e = { + let l12 = i32::from(*ptr0.add(46).cast::()); + l12 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e68) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e68 = { + let l13 = i32::from(*ptr0.add(32).cast::()); + let l15 = i32::from(*ptr0.add(36).cast::()); + TlsAlertReceivedPayload { + alert_id: match l13 { + 0 => None, + 1 => { + let e = { + let l14 = i32::from(*ptr0.add(33).cast::()); + l14 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l15 { + 0 => None, + 1 => { + let e = { + let l16 = *ptr0.add(40).cast::<*mut u8>(); + let l17 = *ptr0.add(44).cast::(); + let len18 = l17; + let bytes18 = _rt::Vec::from_raw_parts( + l16.cast(), + len18, + len18, + ); + _rt::string_lift(bytes18) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e68) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e68 = { + let l19 = i32::from(*ptr0.add(32).cast::()); + match l19 { + 0 => None, + 1 => { + let e = { + let l20 = *ptr0.add(40).cast::(); + l20 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e68) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e68 = { + let l21 = i32::from(*ptr0.add(32).cast::()); + match l21 { + 0 => None, + 1 => { + let e = { + let l22 = *ptr0.add(36).cast::(); + l22 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e68) + } + 22 => { + let e68 = { + let l23 = i32::from(*ptr0.add(32).cast::()); + match l23 { + 0 => None, + 1 => { + let e = { + let l24 = i32::from(*ptr0.add(36).cast::()); + let l28 = i32::from(*ptr0.add(48).cast::()); + FieldSizePayload { + field_name: match l24 { + 0 => None, + 1 => { + let e = { + let l25 = *ptr0.add(40).cast::<*mut u8>(); + let l26 = *ptr0.add(44).cast::(); + let len27 = l26; + let bytes27 = _rt::Vec::from_raw_parts( + l25.cast(), + len27, + len27, + ); + _rt::string_lift(bytes27) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l28 { + 0 => None, + 1 => { + let e = { + let l29 = *ptr0.add(52).cast::(); + l29 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e68) + } + 23 => { + let e68 = { + let l30 = i32::from(*ptr0.add(32).cast::()); + match l30 { + 0 => None, + 1 => { + let e = { + let l31 = *ptr0.add(36).cast::(); + l31 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e68) + } + 24 => { + let e68 = { + let l32 = i32::from(*ptr0.add(32).cast::()); + let l36 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l32 { + 0 => None, + 1 => { + let e = { + let l33 = *ptr0.add(36).cast::<*mut u8>(); + let l34 = *ptr0.add(40).cast::(); + let len35 = l34; + let bytes35 = _rt::Vec::from_raw_parts( + l33.cast(), + len35, + len35, + ); + _rt::string_lift(bytes35) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l36 { + 0 => None, + 1 => { + let e = { + let l37 = *ptr0.add(48).cast::(); + l37 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e68) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e68 = { + let l38 = i32::from(*ptr0.add(32).cast::()); + match l38 { + 0 => None, + 1 => { + let e = { + let l39 = *ptr0.add(36).cast::(); + l39 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e68) + } + 27 => { + let e68 = { + let l40 = i32::from(*ptr0.add(32).cast::()); + let l44 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l40 { + 0 => None, + 1 => { + let e = { + let l41 = *ptr0.add(36).cast::<*mut u8>(); + let l42 = *ptr0.add(40).cast::(); + let len43 = l42; + let bytes43 = _rt::Vec::from_raw_parts( + l41.cast(), + len43, + len43, + ); + _rt::string_lift(bytes43) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l44 { + 0 => None, + 1 => { + let e = { + let l45 = *ptr0.add(48).cast::(); + l45 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e68) + } + 28 => { + let e68 = { + let l46 = i32::from(*ptr0.add(32).cast::()); + match l46 { + 0 => None, + 1 => { + let e = { + let l47 = *ptr0.add(40).cast::(); + l47 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e68) + } + 29 => { + let e68 = { + let l48 = i32::from(*ptr0.add(32).cast::()); + match l48 { + 0 => None, + 1 => { + let e = { + let l49 = *ptr0.add(36).cast::(); + l49 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e68) + } + 30 => { + let e68 = { + let l50 = i32::from(*ptr0.add(32).cast::()); + let l54 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l50 { + 0 => None, + 1 => { + let e = { + let l51 = *ptr0.add(36).cast::<*mut u8>(); + let l52 = *ptr0.add(40).cast::(); + let len53 = l52; + let bytes53 = _rt::Vec::from_raw_parts( + l51.cast(), + len53, + len53, + ); + _rt::string_lift(bytes53) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l54 { + 0 => None, + 1 => { + let e = { + let l55 = *ptr0.add(48).cast::(); + l55 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e68) + } + 31 => { + let e68 = { + let l56 = i32::from(*ptr0.add(32).cast::()); + match l56 { + 0 => None, + 1 => { + let e = { + let l57 = *ptr0.add(36).cast::<*mut u8>(); + let l58 = *ptr0.add(40).cast::(); + let len59 = l58; + let bytes59 = _rt::Vec::from_raw_parts( + l57.cast(), + len59, + len59, + ); + _rt::string_lift(bytes59) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e68) + } + 32 => { + let e68 = { + let l60 = i32::from(*ptr0.add(32).cast::()); + match l60 { + 0 => None, + 1 => { + let e = { + let l61 = *ptr0.add(36).cast::<*mut u8>(); + let l62 = *ptr0.add(40).cast::(); + let len63 = l62; + let bytes63 = _rt::Vec::from_raw_parts( + l61.cast(), + len63, + len63, + ); + _rt::string_lift(bytes63) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e68) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e68 = { + let l64 = i32::from(*ptr0.add(32).cast::()); + match l64 { + 0 => None, + 1 => { + let e = { + let l65 = *ptr0.add(36).cast::<*mut u8>(); + let l66 = *ptr0.add(40).cast::(); + let len67 = l66; + let bytes67 = _rt::Vec::from_raw_parts( + l65.cast(), + len67, + len67, + ); + _rt::string_lift(bytes67) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e68) + } + }; + v68 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn new(headers: Headers) -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]outgoing-response"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&headers).take_handle() as i32); + OutgoingResponse::from_handle(ret as u32) + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Get the HTTP Status Code for the Response. + pub fn status_code(&self) -> StatusCode { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.status-code"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + ret as u16 + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + pub fn set_status_code( + &self, + status_code: StatusCode, + ) -> Result<(), ()> { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.set-status-code"] + fn wit_import(_: i32, _: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + _rt::as_i32(status_code), + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn body(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.body"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + OutgoingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-body.write"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + super::super::super::wasi::io::streams::OutputStream::from_handle( + l2 as u32, + ) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn finish( + this: OutgoingBody, + trailers: Option, + ) -> Result<(), ErrorCode> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 40]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 40], + ); + let (result0_0, result0_1) = match &trailers { + Some(e) => (1i32, (e).take_handle() as i32), + None => (0i32, 0i32), + }; + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]outgoing-body.finish"] + fn wit_import(_: i32, _: i32, _: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i32, _: *mut u8) { + unreachable!() + } + wit_import( + (&this).take_handle() as i32, + result0_0, + result0_1, + ptr1, + ); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(8).cast::()); + let v65 = match l3 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e65 = { + let l4 = i32::from(*ptr1.add(16).cast::()); + let l8 = i32::from(*ptr1.add(28).cast::()); + DnsErrorPayload { + rcode: match l4 { + 0 => None, + 1 => { + let e = { + let l5 = *ptr1.add(20).cast::<*mut u8>(); + let l6 = *ptr1.add(24).cast::(); + let len7 = l6; + let bytes7 = _rt::Vec::from_raw_parts( + l5.cast(), + len7, + len7, + ); + _rt::string_lift(bytes7) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l8 { + 0 => None, + 1 => { + let e = { + let l9 = i32::from(*ptr1.add(30).cast::()); + l9 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e65) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e65 = { + let l10 = i32::from(*ptr1.add(16).cast::()); + let l12 = i32::from(*ptr1.add(20).cast::()); + TlsAlertReceivedPayload { + alert_id: match l10 { + 0 => None, + 1 => { + let e = { + let l11 = i32::from(*ptr1.add(17).cast::()); + l11 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l12 { + 0 => None, + 1 => { + let e = { + let l13 = *ptr1.add(24).cast::<*mut u8>(); + let l14 = *ptr1.add(28).cast::(); + let len15 = l14; + let bytes15 = _rt::Vec::from_raw_parts( + l13.cast(), + len15, + len15, + ); + _rt::string_lift(bytes15) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e65) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e65 = { + let l16 = i32::from(*ptr1.add(16).cast::()); + match l16 { + 0 => None, + 1 => { + let e = { + let l17 = *ptr1.add(24).cast::(); + l17 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e65) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e65 = { + let l18 = i32::from(*ptr1.add(16).cast::()); + match l18 { + 0 => None, + 1 => { + let e = { + let l19 = *ptr1.add(20).cast::(); + l19 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e65) + } + 22 => { + let e65 = { + let l20 = i32::from(*ptr1.add(16).cast::()); + match l20 { + 0 => None, + 1 => { + let e = { + let l21 = i32::from(*ptr1.add(20).cast::()); + let l25 = i32::from(*ptr1.add(32).cast::()); + FieldSizePayload { + field_name: match l21 { + 0 => None, + 1 => { + let e = { + let l22 = *ptr1.add(24).cast::<*mut u8>(); + let l23 = *ptr1.add(28).cast::(); + let len24 = l23; + let bytes24 = _rt::Vec::from_raw_parts( + l22.cast(), + len24, + len24, + ); + _rt::string_lift(bytes24) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l25 { + 0 => None, + 1 => { + let e = { + let l26 = *ptr1.add(36).cast::(); + l26 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e65) + } + 23 => { + let e65 = { + let l27 = i32::from(*ptr1.add(16).cast::()); + match l27 { + 0 => None, + 1 => { + let e = { + let l28 = *ptr1.add(20).cast::(); + l28 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e65) + } + 24 => { + let e65 = { + let l29 = i32::from(*ptr1.add(16).cast::()); + let l33 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l29 { + 0 => None, + 1 => { + let e = { + let l30 = *ptr1.add(20).cast::<*mut u8>(); + let l31 = *ptr1.add(24).cast::(); + let len32 = l31; + let bytes32 = _rt::Vec::from_raw_parts( + l30.cast(), + len32, + len32, + ); + _rt::string_lift(bytes32) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l33 { + 0 => None, + 1 => { + let e = { + let l34 = *ptr1.add(32).cast::(); + l34 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e65) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e65 = { + let l35 = i32::from(*ptr1.add(16).cast::()); + match l35 { + 0 => None, + 1 => { + let e = { + let l36 = *ptr1.add(20).cast::(); + l36 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e65) + } + 27 => { + let e65 = { + let l37 = i32::from(*ptr1.add(16).cast::()); + let l41 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l37 { + 0 => None, + 1 => { + let e = { + let l38 = *ptr1.add(20).cast::<*mut u8>(); + let l39 = *ptr1.add(24).cast::(); + let len40 = l39; + let bytes40 = _rt::Vec::from_raw_parts( + l38.cast(), + len40, + len40, + ); + _rt::string_lift(bytes40) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l41 { + 0 => None, + 1 => { + let e = { + let l42 = *ptr1.add(32).cast::(); + l42 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e65) + } + 28 => { + let e65 = { + let l43 = i32::from(*ptr1.add(16).cast::()); + match l43 { + 0 => None, + 1 => { + let e = { + let l44 = *ptr1.add(24).cast::(); + l44 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e65) + } + 29 => { + let e65 = { + let l45 = i32::from(*ptr1.add(16).cast::()); + match l45 { + 0 => None, + 1 => { + let e = { + let l46 = *ptr1.add(20).cast::(); + l46 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e65) + } + 30 => { + let e65 = { + let l47 = i32::from(*ptr1.add(16).cast::()); + let l51 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l47 { + 0 => None, + 1 => { + let e = { + let l48 = *ptr1.add(20).cast::<*mut u8>(); + let l49 = *ptr1.add(24).cast::(); + let len50 = l49; + let bytes50 = _rt::Vec::from_raw_parts( + l48.cast(), + len50, + len50, + ); + _rt::string_lift(bytes50) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l51 { + 0 => None, + 1 => { + let e = { + let l52 = *ptr1.add(32).cast::(); + l52 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e65) + } + 31 => { + let e65 = { + let l53 = i32::from(*ptr1.add(16).cast::()); + match l53 { + 0 => None, + 1 => { + let e = { + let l54 = *ptr1.add(20).cast::<*mut u8>(); + let l55 = *ptr1.add(24).cast::(); + let len56 = l55; + let bytes56 = _rt::Vec::from_raw_parts( + l54.cast(), + len56, + len56, + ); + _rt::string_lift(bytes56) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e65) + } + 32 => { + let e65 = { + let l57 = i32::from(*ptr1.add(16).cast::()); + match l57 { + 0 => None, + 1 => { + let e = { + let l58 = *ptr1.add(20).cast::<*mut u8>(); + let l59 = *ptr1.add(24).cast::(); + let len60 = l59; + let bytes60 = _rt::Vec::from_raw_parts( + l58.cast(), + len60, + len60, + ); + _rt::string_lift(bytes60) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e65) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e65 = { + let l61 = i32::from(*ptr1.add(16).cast::()); + match l61 { + 0 => None, + 1 => { + let e = { + let l62 = *ptr1.add(20).cast::<*mut u8>(); + let l63 = *ptr1.add(24).cast::(); + let len64 = l63; + let bytes64 = _rt::Vec::from_raw_parts( + l62.cast(), + len64, + len64, + ); + _rt::string_lift(bytes64) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e65) + } + }; + v65 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl FutureIncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-incoming-response.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl FutureIncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + pub fn get( + &self, + ) -> Option, ()>> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 56]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 56], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-incoming-response.get"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + match l2 { + 0 => { + let e = { + let l3 = i32::from(*ptr0.add(16).cast::()); + match l3 { + 0 => { + let e = { + let l4 = *ptr0.add(24).cast::(); + IncomingResponse::from_handle(l4 as u32) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(24).cast::()); + let v67 = match l5 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e67 = { + let l6 = i32::from(*ptr0.add(32).cast::()); + let l10 = i32::from(*ptr0.add(44).cast::()); + DnsErrorPayload { + rcode: match l6 { + 0 => None, + 1 => { + let e = { + let l7 = *ptr0.add(36).cast::<*mut u8>(); + let l8 = *ptr0.add(40).cast::(); + let len9 = l8; + let bytes9 = _rt::Vec::from_raw_parts( + l7.cast(), + len9, + len9, + ); + _rt::string_lift(bytes9) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l10 { + 0 => None, + 1 => { + let e = { + let l11 = i32::from(*ptr0.add(46).cast::()); + l11 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e67) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e67 = { + let l12 = i32::from(*ptr0.add(32).cast::()); + let l14 = i32::from(*ptr0.add(36).cast::()); + TlsAlertReceivedPayload { + alert_id: match l12 { + 0 => None, + 1 => { + let e = { + let l13 = i32::from(*ptr0.add(33).cast::()); + l13 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l14 { + 0 => None, + 1 => { + let e = { + let l15 = *ptr0.add(40).cast::<*mut u8>(); + let l16 = *ptr0.add(44).cast::(); + let len17 = l16; + let bytes17 = _rt::Vec::from_raw_parts( + l15.cast(), + len17, + len17, + ); + _rt::string_lift(bytes17) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e67) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e67 = { + let l18 = i32::from(*ptr0.add(32).cast::()); + match l18 { + 0 => None, + 1 => { + let e = { + let l19 = *ptr0.add(40).cast::(); + l19 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e67) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e67 = { + let l20 = i32::from(*ptr0.add(32).cast::()); + match l20 { + 0 => None, + 1 => { + let e = { + let l21 = *ptr0.add(36).cast::(); + l21 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e67) + } + 22 => { + let e67 = { + let l22 = i32::from(*ptr0.add(32).cast::()); + match l22 { + 0 => None, + 1 => { + let e = { + let l23 = i32::from(*ptr0.add(36).cast::()); + let l27 = i32::from(*ptr0.add(48).cast::()); + FieldSizePayload { + field_name: match l23 { + 0 => None, + 1 => { + let e = { + let l24 = *ptr0.add(40).cast::<*mut u8>(); + let l25 = *ptr0.add(44).cast::(); + let len26 = l25; + let bytes26 = _rt::Vec::from_raw_parts( + l24.cast(), + len26, + len26, + ); + _rt::string_lift(bytes26) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l27 { + 0 => None, + 1 => { + let e = { + let l28 = *ptr0.add(52).cast::(); + l28 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e67) + } + 23 => { + let e67 = { + let l29 = i32::from(*ptr0.add(32).cast::()); + match l29 { + 0 => None, + 1 => { + let e = { + let l30 = *ptr0.add(36).cast::(); + l30 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e67) + } + 24 => { + let e67 = { + let l31 = i32::from(*ptr0.add(32).cast::()); + let l35 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l31 { + 0 => None, + 1 => { + let e = { + let l32 = *ptr0.add(36).cast::<*mut u8>(); + let l33 = *ptr0.add(40).cast::(); + let len34 = l33; + let bytes34 = _rt::Vec::from_raw_parts( + l32.cast(), + len34, + len34, + ); + _rt::string_lift(bytes34) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l35 { + 0 => None, + 1 => { + let e = { + let l36 = *ptr0.add(48).cast::(); + l36 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e67) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e67 = { + let l37 = i32::from(*ptr0.add(32).cast::()); + match l37 { + 0 => None, + 1 => { + let e = { + let l38 = *ptr0.add(36).cast::(); + l38 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e67) + } + 27 => { + let e67 = { + let l39 = i32::from(*ptr0.add(32).cast::()); + let l43 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l39 { + 0 => None, + 1 => { + let e = { + let l40 = *ptr0.add(36).cast::<*mut u8>(); + let l41 = *ptr0.add(40).cast::(); + let len42 = l41; + let bytes42 = _rt::Vec::from_raw_parts( + l40.cast(), + len42, + len42, + ); + _rt::string_lift(bytes42) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l43 { + 0 => None, + 1 => { + let e = { + let l44 = *ptr0.add(48).cast::(); + l44 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e67) + } + 28 => { + let e67 = { + let l45 = i32::from(*ptr0.add(32).cast::()); + match l45 { + 0 => None, + 1 => { + let e = { + let l46 = *ptr0.add(40).cast::(); + l46 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e67) + } + 29 => { + let e67 = { + let l47 = i32::from(*ptr0.add(32).cast::()); + match l47 { + 0 => None, + 1 => { + let e = { + let l48 = *ptr0.add(36).cast::(); + l48 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e67) + } + 30 => { + let e67 = { + let l49 = i32::from(*ptr0.add(32).cast::()); + let l53 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l49 { + 0 => None, + 1 => { + let e = { + let l50 = *ptr0.add(36).cast::<*mut u8>(); + let l51 = *ptr0.add(40).cast::(); + let len52 = l51; + let bytes52 = _rt::Vec::from_raw_parts( + l50.cast(), + len52, + len52, + ); + _rt::string_lift(bytes52) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l53 { + 0 => None, + 1 => { + let e = { + let l54 = *ptr0.add(48).cast::(); + l54 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e67) + } + 31 => { + let e67 = { + let l55 = i32::from(*ptr0.add(32).cast::()); + match l55 { + 0 => None, + 1 => { + let e = { + let l56 = *ptr0.add(36).cast::<*mut u8>(); + let l57 = *ptr0.add(40).cast::(); + let len58 = l57; + let bytes58 = _rt::Vec::from_raw_parts( + l56.cast(), + len58, + len58, + ); + _rt::string_lift(bytes58) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e67) + } + 32 => { + let e67 = { + let l59 = i32::from(*ptr0.add(32).cast::()); + match l59 { + 0 => None, + 1 => { + let e = { + let l60 = *ptr0.add(36).cast::<*mut u8>(); + let l61 = *ptr0.add(40).cast::(); + let len62 = l61; + let bytes62 = _rt::Vec::from_raw_parts( + l60.cast(), + len62, + len62, + ); + _rt::string_lift(bytes62) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e67) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e67 = { + let l63 = i32::from(*ptr0.add(32).cast::()); + match l63 { + 0 => None, + 1 => { + let e = { + let l64 = *ptr0.add(36).cast::<*mut u8>(); + let l65 = *ptr0.add(40).cast::(); + let len66 = l65; + let bytes66 = _rt::Vec::from_raw_parts( + l64.cast(), + len66, + len66, + ); + _rt::string_lift(bytes66) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e67) + } + }; + v67 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + } + } + #[allow(dead_code)] + pub mod io { + #[allow(dead_code, clippy::all)] + pub mod poll { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + /// `pollable` represents a single I/O event which may be ready, or not. + #[derive(Debug)] + #[repr(transparent)] + pub struct Pollable { + handle: _rt::Resource, + } + impl Pollable { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Pollable { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]pollable"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl Pollable { + #[allow(unused_unsafe, clippy::all)] + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + pub fn ready(&self) -> bool { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[method]pollable.ready"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + _rt::bool_lift(ret as u8) + } + } + } + impl Pollable { + #[allow(unused_unsafe, clippy::all)] + /// `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. + pub fn block(&self) { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[method]pollable.block"] + fn wit_import(_: i32); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) { + unreachable!() + } + wit_import((self).handle() as i32); + } + } + } + #[allow(unused_unsafe, clippy::all)] + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being ready for I/O. + pub fn poll(in_: &[&Pollable]) -> _rt::Vec { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea([::core::mem::MaybeUninit::uninit(); 8]); + let vec0 = in_; + let len0 = vec0.len(); + let layout0 = _rt::alloc::Layout::from_size_align_unchecked( + vec0.len() * 4, + 4, + ); + let result0 = if layout0.size() != 0 { + let ptr = _rt::alloc::alloc(layout0).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout0); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec0.into_iter().enumerate() { + let base = result0.add(i * 4); + { + *base.add(0).cast::() = (e).handle() as i32; + } + } + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "poll"] + fn wit_import(_: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import(result0, len0, ptr1); + let l2 = *ptr1.add(0).cast::<*mut u8>(); + let l3 = *ptr1.add(4).cast::(); + let len4 = l3; + if layout0.size() != 0 { + _rt::alloc::dealloc(result0.cast(), layout0); + } + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + } + } + } + #[allow(dead_code, clippy::all)] + pub mod error { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + #[derive(Debug)] + #[repr(transparent)] + pub struct Error { + handle: _rt::Resource, + } + impl Error { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Error { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/error@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]error"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl Error { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn to_debug_string(&self) -> _rt::String { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/error@0.2.3")] + extern "C" { + #[link_name = "[method]error.to-debug-string"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = *ptr0.add(0).cast::<*mut u8>(); + let l2 = *ptr0.add(4).cast::(); + let len3 = l2; + let bytes3 = _rt::Vec::from_raw_parts(l1.cast(), len3, len3); + _rt::string_lift(bytes3) + } + } + } + } + #[allow(dead_code, clippy::all)] + pub mod streams { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Error = super::super::super::wasi::io::error::Error; + pub type Pollable = super::super::super::wasi::io::poll::Pollable; + /// An error for input-stream and output-stream operations. + pub enum StreamError { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + LastOperationFailed(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, + } + impl ::core::fmt::Debug for StreamError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + StreamError::LastOperationFailed(e) => { + f.debug_tuple("StreamError::LastOperationFailed") + .field(e) + .finish() + } + StreamError::Closed => { + f.debug_tuple("StreamError::Closed").finish() + } + } + } + } + impl ::core::fmt::Display for StreamError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for StreamError {} + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct InputStream { + handle: _rt::Resource, + } + impl InputStream { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for InputStream { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]input-stream"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutputStream { + handle: _rt::Resource, + } + impl OutputStream { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutputStream { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]output-stream"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn read(&self, len: u64) -> Result<_rt::Vec, StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.read"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(4).cast::()); + let v7 = match l5 { + 0 => { + let e7 = { + let l6 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l6 as u32, + ) + }; + StreamError::LastOperationFailed(e7) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v7 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + pub fn blocking_read( + &self, + len: u64, + ) -> Result<_rt::Vec, StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.blocking-read"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(4).cast::()); + let v7 = match l5 { + 0 => { + let e7 = { + let l6 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l6 as u32, + ) + }; + StreamError::LastOperationFailed(e7) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v7 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn skip(&self, len: u64) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.skip"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + pub fn blocking_skip(&self, len: u64) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.blocking-skip"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn check_write(&self) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.check-write"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write(&self, contents: &[u8]) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let vec0 = contents; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.write"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(4).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr1.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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 + /// ``` + pub fn blocking_write_and_flush( + &self, + contents: &[u8], + ) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let vec0 = contents; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-write-and-flush"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(4).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr1.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn flush(&self) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.flush"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + pub fn blocking_flush(&self) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-flush"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write_zeroes(&self, len: u64) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.write-zeroes"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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 + /// ``` + pub fn blocking_write_zeroes_and_flush( + &self, + len: u64, + ) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-write-zeroes-and-flush"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + pub fn splice( + &self, + src: &InputStream, + len: u64, + ) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.splice"] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import( + (self).handle() as i32, + (src).handle() as i32, + _rt::as_i64(&len), + ptr0, + ); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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`. + pub fn blocking_splice( + &self, + src: &InputStream, + len: u64, + ) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-splice"] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import( + (self).handle() as i32, + (src).handle() as i32, + _rt::as_i64(&len), + ptr0, + ); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + } + } +} +#[allow(dead_code)] +pub mod exports { + #[allow(dead_code)] + pub mod wasi { + #[allow(dead_code)] + pub mod http { + #[allow(dead_code, clippy::all)] + pub mod incoming_handler { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::super::__link_custom_section_describing_imports; + use super::super::super::super::_rt; + pub type IncomingRequest = super::super::super::super::wasi::http::types::IncomingRequest; + pub type ResponseOutparam = super::super::super::super::wasi::http::types::ResponseOutparam; + #[doc(hidden)] + #[allow(non_snake_case)] + pub unsafe fn _export_handle_cabi(arg0: i32, arg1: i32) { + #[cfg(target_arch = "wasm32")] _rt::run_ctors_once(); + T::handle( + super::super::super::super::wasi::http::types::IncomingRequest::from_handle( + arg0 as u32, + ), + super::super::super::super::wasi::http::types::ResponseOutparam::from_handle( + arg1 as u32, + ), + ); + } + pub trait Guest { + /// 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. + fn handle(request: IncomingRequest, response_out: ResponseOutparam); + } + #[doc(hidden)] + macro_rules! __export_wasi_http_incoming_handler_0_2_3_cabi { + ($ty:ident with_types_in $($path_to_types:tt)*) => { + const _ : () = { #[export_name = + "wasi:http/incoming-handler@0.2.3#handle"] unsafe extern "C" fn + export_handle(arg0 : i32, arg1 : i32,) { $($path_to_types)*:: + _export_handle_cabi::<$ty > (arg0, arg1) } }; + }; + } + #[doc(hidden)] + pub(crate) use __export_wasi_http_incoming_handler_0_2_3_cabi; + } + } + } +} +mod _rt { + use core::fmt; + use core::marker; + use core::sync::atomic::{AtomicU32, Ordering::Relaxed}; + /// A type which represents a component model resource, either imported or + /// exported into this component. + /// + /// This is a low-level wrapper which handles the lifetime of the resource + /// (namely this has a destructor). The `T` provided defines the component model + /// intrinsics that this wrapper uses. + /// + /// One of the chief purposes of this type is to provide `Deref` implementations + /// to access the underlying data when it is owned. + /// + /// This type is primarily used in generated code for exported and imported + /// resources. + #[repr(transparent)] + pub struct Resource { + handle: AtomicU32, + _marker: marker::PhantomData, + } + /// A trait which all wasm resources implement, namely providing the ability to + /// drop a resource. + /// + /// This generally is implemented by generated code, not user-facing code. + #[allow(clippy::missing_safety_doc)] + pub unsafe trait WasmResource { + /// Invokes the `[resource-drop]...` intrinsic. + unsafe fn drop(handle: u32); + } + impl Resource { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + debug_assert!(handle != u32::MAX); + Self { + handle: AtomicU32::new(handle), + _marker: marker::PhantomData, + } + } + /// Takes ownership of the handle owned by `resource`. + /// + /// Note that this ideally would be `into_handle` taking `Resource` by + /// ownership. The code generator does not enable that in all situations, + /// unfortunately, so this is provided instead. + /// + /// Also note that `take_handle` is in theory only ever called on values + /// owned by a generated function. For example a generated function might + /// take `Resource` as an argument but then call `take_handle` on a + /// reference to that argument. In that sense the dynamic nature of + /// `take_handle` should only be exposed internally to generated code, not + /// to user code. + #[doc(hidden)] + pub fn take_handle(resource: &Resource) -> u32 { + resource.handle.swap(u32::MAX, Relaxed) + } + #[doc(hidden)] + pub fn handle(resource: &Resource) -> u32 { + resource.handle.load(Relaxed) + } + } + impl fmt::Debug for Resource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Resource").field("handle", &self.handle).finish() + } + } + impl Drop for Resource { + fn drop(&mut self) { + unsafe { + match self.handle.load(Relaxed) { + u32::MAX => {} + other => T::drop(other), + } + } + } + } + pub unsafe fn bool_lift(val: u8) -> bool { + if cfg!(debug_assertions) { + match val { + 0 => false, + 1 => true, + _ => panic!("invalid bool discriminant"), + } + } else { + val != 0 + } + } + pub use alloc_crate::vec::Vec; + pub use alloc_crate::alloc; + pub fn as_i64(t: T) -> i64 { + t.as_i64() + } + pub trait AsI64 { + fn as_i64(self) -> i64; + } + impl<'a, T: Copy + AsI64> AsI64 for &'a T { + fn as_i64(self) -> i64 { + (*self).as_i64() + } + } + impl AsI64 for i64 { + #[inline] + fn as_i64(self) -> i64 { + self as i64 + } + } + impl AsI64 for u64 { + #[inline] + fn as_i64(self) -> i64 { + self as i64 + } + } + pub use alloc_crate::string::String; + pub unsafe fn string_lift(bytes: Vec) -> String { + if cfg!(debug_assertions) { + String::from_utf8(bytes).unwrap() + } else { + String::from_utf8_unchecked(bytes) + } + } + pub unsafe fn invalid_enum_discriminant() -> T { + if cfg!(debug_assertions) { + panic!("invalid enum discriminant") + } else { + core::hint::unreachable_unchecked() + } + } + pub unsafe fn cabi_dealloc(ptr: *mut u8, size: usize, align: usize) { + if size == 0 { + return; + } + let layout = alloc::Layout::from_size_align_unchecked(size, align); + alloc::dealloc(ptr, layout); + } + pub fn as_i32(t: T) -> i32 { + t.as_i32() + } + pub trait AsI32 { + fn as_i32(self) -> i32; + } + impl<'a, T: Copy + AsI32> AsI32 for &'a T { + fn as_i32(self) -> i32 { + (*self).as_i32() + } + } + impl AsI32 for i32 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u32 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for i16 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u16 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for i8 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u8 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for char { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for usize { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + #[cfg(target_arch = "wasm32")] + pub fn run_ctors_once() { + wit_bindgen_rt::run_ctors_once(); + } + extern crate alloc as alloc_crate; +} +/// Generates `#[no_mangle]` functions to export the specified type as the +/// root implementation of all generated traits. +/// +/// For more information see the documentation of `wit_bindgen::generate!`. +/// +/// ```rust +/// # macro_rules! export{ ($($t:tt)*) => (); } +/// # trait Guest {} +/// struct MyType; +/// +/// impl Guest for MyType { +/// // ... +/// } +/// +/// export!(MyType); +/// ``` +#[allow(unused_macros)] +#[doc(hidden)] +macro_rules! __export_api_impl { + ($ty:ident) => { + self::export!($ty with_types_in self); + }; + ($ty:ident with_types_in $($path_to_types_root:tt)*) => { + $($path_to_types_root)*:: + exports::wasi::http::incoming_handler::__export_wasi_http_incoming_handler_0_2_3_cabi!($ty + with_types_in $($path_to_types_root)*:: exports::wasi::http::incoming_handler); + }; +} +#[doc(inline)] +pub(crate) use __export_api_impl as export; +#[cfg(target_arch = "wasm32")] +#[link_section = "component-type:wit-bindgen:0.35.0:golem:handler:api:encoded world"] +#[doc(hidden)] +pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; 6330] = *b"\ +\0asm\x0d\0\x01\0\0\x19\x16wit-component-encoding\x04\0\x07\xc00\x01A\x02\x01A\x13\ +\x01B\x0a\x04\0\x08pollable\x03\x01\x01h\0\x01@\x01\x04self\x01\0\x7f\x04\0\x16[\ +method]pollable.ready\x01\x02\x01@\x01\x04self\x01\x01\0\x04\0\x16[method]pollab\ +le.block\x01\x03\x01p\x01\x01py\x01@\x01\x02in\x04\0\x05\x04\0\x04poll\x01\x06\x03\ +\0\x12wasi:io/poll@0.2.3\x05\0\x02\x03\0\0\x08pollable\x01B\x0f\x02\x03\x02\x01\x01\ +\x04\0\x08pollable\x03\0\0\x01w\x04\0\x07instant\x03\0\x02\x01w\x04\0\x08duratio\ +n\x03\0\x04\x01@\0\0\x03\x04\0\x03now\x01\x06\x01@\0\0\x05\x04\0\x0aresolution\x01\ +\x07\x01i\x01\x01@\x01\x04when\x03\0\x08\x04\0\x11subscribe-instant\x01\x09\x01@\ +\x01\x04when\x05\0\x08\x04\0\x12subscribe-duration\x01\x0a\x03\0!wasi:clocks/mon\ +otonic-clock@0.2.3\x05\x02\x01B\x04\x04\0\x05error\x03\x01\x01h\0\x01@\x01\x04se\ +lf\x01\0s\x04\0\x1d[method]error.to-debug-string\x01\x02\x03\0\x13wasi:io/error@\ +0.2.3\x05\x03\x02\x03\0\x02\x05error\x01B(\x02\x03\x02\x01\x04\x04\0\x05error\x03\ +\0\0\x02\x03\x02\x01\x01\x04\0\x08pollable\x03\0\x02\x01i\x01\x01q\x02\x15last-o\ +peration-failed\x01\x04\0\x06closed\0\0\x04\0\x0cstream-error\x03\0\x05\x04\0\x0c\ +input-stream\x03\x01\x04\0\x0doutput-stream\x03\x01\x01h\x07\x01p}\x01j\x01\x0a\x01\ +\x06\x01@\x02\x04self\x09\x03lenw\0\x0b\x04\0\x19[method]input-stream.read\x01\x0c\ +\x04\0\"[method]input-stream.blocking-read\x01\x0c\x01j\x01w\x01\x06\x01@\x02\x04\ +self\x09\x03lenw\0\x0d\x04\0\x19[method]input-stream.skip\x01\x0e\x04\0\"[method\ +]input-stream.blocking-skip\x01\x0e\x01i\x03\x01@\x01\x04self\x09\0\x0f\x04\0\x1e\ +[method]input-stream.subscribe\x01\x10\x01h\x08\x01@\x01\x04self\x11\0\x0d\x04\0\ +![method]output-stream.check-write\x01\x12\x01j\0\x01\x06\x01@\x02\x04self\x11\x08\ +contents\x0a\0\x13\x04\0\x1b[method]output-stream.write\x01\x14\x04\0.[method]ou\ +tput-stream.blocking-write-and-flush\x01\x14\x01@\x01\x04self\x11\0\x13\x04\0\x1b\ +[method]output-stream.flush\x01\x15\x04\0$[method]output-stream.blocking-flush\x01\ +\x15\x01@\x01\x04self\x11\0\x0f\x04\0\x1f[method]output-stream.subscribe\x01\x16\ +\x01@\x02\x04self\x11\x03lenw\0\x13\x04\0\"[method]output-stream.write-zeroes\x01\ +\x17\x04\05[method]output-stream.blocking-write-zeroes-and-flush\x01\x17\x01@\x03\ +\x04self\x11\x03src\x09\x03lenw\0\x0d\x04\0\x1c[method]output-stream.splice\x01\x18\ +\x04\0%[method]output-stream.blocking-splice\x01\x18\x03\0\x15wasi:io/streams@0.\ +2.3\x05\x05\x02\x03\0\x01\x08duration\x02\x03\0\x03\x0cinput-stream\x02\x03\0\x03\ +\x0doutput-stream\x01B\xc1\x01\x02\x03\x02\x01\x06\x04\0\x08duration\x03\0\0\x02\ +\x03\x02\x01\x07\x04\0\x0cinput-stream\x03\0\x02\x02\x03\x02\x01\x08\x04\0\x0dou\ +tput-stream\x03\0\x04\x02\x03\x02\x01\x04\x04\0\x08io-error\x03\0\x06\x02\x03\x02\ +\x01\x01\x04\0\x08pollable\x03\0\x08\x01q\x0a\x03get\0\0\x04head\0\0\x04post\0\0\ +\x03put\0\0\x06delete\0\0\x07connect\0\0\x07options\0\0\x05trace\0\0\x05patch\0\0\ +\x05other\x01s\0\x04\0\x06method\x03\0\x0a\x01q\x03\x04HTTP\0\0\x05HTTPS\0\0\x05\ +other\x01s\0\x04\0\x06scheme\x03\0\x0c\x01ks\x01k{\x01r\x02\x05rcode\x0e\x09info\ +-code\x0f\x04\0\x11DNS-error-payload\x03\0\x10\x01k}\x01r\x02\x08alert-id\x12\x0d\ +alert-message\x0e\x04\0\x1aTLS-alert-received-payload\x03\0\x13\x01ky\x01r\x02\x0a\ +field-name\x0e\x0afield-size\x15\x04\0\x12field-size-payload\x03\0\x16\x01kw\x01\ +k\x17\x01q'\x0bDNS-timeout\0\0\x09DNS-error\x01\x11\0\x15destination-not-found\0\ +\0\x17destination-unavailable\0\0\x19destination-IP-prohibited\0\0\x19destinatio\ +n-IP-unroutable\0\0\x12connection-refused\0\0\x15connection-terminated\0\0\x12co\ +nnection-timeout\0\0\x17connection-read-timeout\0\0\x18connection-write-timeout\0\ +\0\x18connection-limit-reached\0\0\x12TLS-protocol-error\0\0\x15TLS-certificate-\ +error\0\0\x12TLS-alert-received\x01\x14\0\x13HTTP-request-denied\0\0\x1cHTTP-req\ +uest-length-required\0\0\x16HTTP-request-body-size\x01\x18\0\x1bHTTP-request-met\ +hod-invalid\0\0\x18HTTP-request-URI-invalid\0\0\x19HTTP-request-URI-too-long\0\0\ +\x20HTTP-request-header-section-size\x01\x15\0\x18HTTP-request-header-size\x01\x19\ +\0!HTTP-request-trailer-section-size\x01\x15\0\x19HTTP-request-trailer-size\x01\x17\ +\0\x18HTTP-response-incomplete\0\0!HTTP-response-header-section-size\x01\x15\0\x19\ +HTTP-response-header-size\x01\x17\0\x17HTTP-response-body-size\x01\x18\0\"HTTP-r\ +esponse-trailer-section-size\x01\x15\0\x1aHTTP-response-trailer-size\x01\x17\0\x1d\ +HTTP-response-transfer-coding\x01\x0e\0\x1cHTTP-response-content-coding\x01\x0e\0\ +\x15HTTP-response-timeout\0\0\x13HTTP-upgrade-failed\0\0\x13HTTP-protocol-error\0\ +\0\x0dloop-detected\0\0\x13configuration-error\0\0\x0einternal-error\x01\x0e\0\x04\ +\0\x0aerror-code\x03\0\x1a\x01q\x03\x0einvalid-syntax\0\0\x09forbidden\0\0\x09im\ +mutable\0\0\x04\0\x0cheader-error\x03\0\x1c\x01s\x04\0\x09field-key\x03\0\x1e\x04\ +\0\x0afield-name\x03\0\x1f\x01p}\x04\0\x0bfield-value\x03\0!\x04\0\x06fields\x03\ +\x01\x04\0\x07headers\x03\0#\x04\0\x08trailers\x03\0#\x04\0\x10incoming-request\x03\ +\x01\x04\0\x10outgoing-request\x03\x01\x04\0\x0frequest-options\x03\x01\x04\0\x11\ +response-outparam\x03\x01\x01{\x04\0\x0bstatus-code\x03\0*\x04\0\x11incoming-res\ +ponse\x03\x01\x04\0\x0dincoming-body\x03\x01\x04\0\x0ffuture-trailers\x03\x01\x04\ +\0\x11outgoing-response\x03\x01\x04\0\x0doutgoing-body\x03\x01\x04\0\x18future-i\ +ncoming-response\x03\x01\x01i#\x01@\0\02\x04\0\x13[constructor]fields\x013\x01o\x02\ +\x20\"\x01p4\x01j\x012\x01\x1d\x01@\x01\x07entries5\06\x04\0\x18[static]fields.f\ +rom-list\x017\x01h#\x01p\"\x01@\x02\x04self8\x04name\x20\09\x04\0\x12[method]fie\ +lds.get\x01:\x01@\x02\x04self8\x04name\x20\0\x7f\x04\0\x12[method]fields.has\x01\ +;\x01j\0\x01\x1d\x01@\x03\x04self8\x04name\x20\x05value9\0<\x04\0\x12[method]fie\ +lds.set\x01=\x01@\x02\x04self8\x04name\x20\0<\x04\0\x15[method]fields.delete\x01\ +>\x01@\x03\x04self8\x04name\x20\x05value\"\0<\x04\0\x15[method]fields.append\x01\ +?\x01@\x01\x04self8\05\x04\0\x16[method]fields.entries\x01@\x01@\x01\x04self8\02\ +\x04\0\x14[method]fields.clone\x01A\x01h&\x01@\x01\x04self\xc2\0\0\x0b\x04\0\x1f\ +[method]incoming-request.method\x01C\x01@\x01\x04self\xc2\0\0\x0e\x04\0([method]\ +incoming-request.path-with-query\x01D\x01k\x0d\x01@\x01\x04self\xc2\0\0\xc5\0\x04\ +\0\x1f[method]incoming-request.scheme\x01F\x04\0\"[method]incoming-request.autho\ +rity\x01D\x01i$\x01@\x01\x04self\xc2\0\0\xc7\0\x04\0\x20[method]incoming-request\ +.headers\x01H\x01i-\x01j\x01\xc9\0\0\x01@\x01\x04self\xc2\0\0\xca\0\x04\0\x20[me\ +thod]incoming-request.consume\x01K\x01i'\x01@\x01\x07headers\xc7\0\0\xcc\0\x04\0\ +\x1d[constructor]outgoing-request\x01M\x01h'\x01i0\x01j\x01\xcf\0\0\x01@\x01\x04\ +self\xce\0\0\xd0\0\x04\0\x1d[method]outgoing-request.body\x01Q\x01@\x01\x04self\xce\ +\0\0\x0b\x04\0\x1f[method]outgoing-request.method\x01R\x01j\0\0\x01@\x02\x04self\ +\xce\0\x06method\x0b\0\xd3\0\x04\0#[method]outgoing-request.set-method\x01T\x01@\ +\x01\x04self\xce\0\0\x0e\x04\0([method]outgoing-request.path-with-query\x01U\x01\ +@\x02\x04self\xce\0\x0fpath-with-query\x0e\0\xd3\0\x04\0,[method]outgoing-reques\ +t.set-path-with-query\x01V\x01@\x01\x04self\xce\0\0\xc5\0\x04\0\x1f[method]outgo\ +ing-request.scheme\x01W\x01@\x02\x04self\xce\0\x06scheme\xc5\0\0\xd3\0\x04\0#[me\ +thod]outgoing-request.set-scheme\x01X\x04\0\"[method]outgoing-request.authority\x01\ +U\x01@\x02\x04self\xce\0\x09authority\x0e\0\xd3\0\x04\0&[method]outgoing-request\ +.set-authority\x01Y\x01@\x01\x04self\xce\0\0\xc7\0\x04\0\x20[method]outgoing-req\ +uest.headers\x01Z\x01i(\x01@\0\0\xdb\0\x04\0\x1c[constructor]request-options\x01\ +\\\x01h(\x01k\x01\x01@\x01\x04self\xdd\0\0\xde\0\x04\0'[method]request-options.c\ +onnect-timeout\x01_\x01@\x02\x04self\xdd\0\x08duration\xde\0\0\xd3\0\x04\0+[meth\ +od]request-options.set-connect-timeout\x01`\x04\0*[method]request-options.first-\ +byte-timeout\x01_\x04\0.[method]request-options.set-first-byte-timeout\x01`\x04\0\ +-[method]request-options.between-bytes-timeout\x01_\x04\01[method]request-option\ +s.set-between-bytes-timeout\x01`\x01i)\x01i/\x01j\x01\xe2\0\x01\x1b\x01@\x02\x05\ +param\xe1\0\x08response\xe3\0\x01\0\x04\0\x1d[static]response-outparam.set\x01d\x01\ +h,\x01@\x01\x04self\xe5\0\0+\x04\0\x20[method]incoming-response.status\x01f\x01@\ +\x01\x04self\xe5\0\0\xc7\0\x04\0![method]incoming-response.headers\x01g\x01@\x01\ +\x04self\xe5\0\0\xca\0\x04\0![method]incoming-response.consume\x01h\x01h-\x01i\x03\ +\x01j\x01\xea\0\0\x01@\x01\x04self\xe9\0\0\xeb\0\x04\0\x1c[method]incoming-body.\ +stream\x01l\x01i.\x01@\x01\x04this\xc9\0\0\xed\0\x04\0\x1c[static]incoming-body.\ +finish\x01n\x01h.\x01i\x09\x01@\x01\x04self\xef\0\0\xf0\0\x04\0![method]future-t\ +railers.subscribe\x01q\x01i%\x01k\xf2\0\x01j\x01\xf3\0\x01\x1b\x01j\x01\xf4\0\0\x01\ +k\xf5\0\x01@\x01\x04self\xef\0\0\xf6\0\x04\0\x1b[method]future-trailers.get\x01w\ +\x01@\x01\x07headers\xc7\0\0\xe2\0\x04\0\x1e[constructor]outgoing-response\x01x\x01\ +h/\x01@\x01\x04self\xf9\0\0+\x04\0%[method]outgoing-response.status-code\x01z\x01\ +@\x02\x04self\xf9\0\x0bstatus-code+\0\xd3\0\x04\0)[method]outgoing-response.set-\ +status-code\x01{\x01@\x01\x04self\xf9\0\0\xc7\0\x04\0![method]outgoing-response.\ +headers\x01|\x01@\x01\x04self\xf9\0\0\xd0\0\x04\0\x1e[method]outgoing-response.b\ +ody\x01}\x01h0\x01i\x05\x01j\x01\xff\0\0\x01@\x01\x04self\xfe\0\0\x80\x01\x04\0\x1b\ +[method]outgoing-body.write\x01\x81\x01\x01j\0\x01\x1b\x01@\x02\x04this\xcf\0\x08\ +trailers\xf3\0\0\x82\x01\x04\0\x1c[static]outgoing-body.finish\x01\x83\x01\x01h1\ +\x01@\x01\x04self\x84\x01\0\xf0\0\x04\0*[method]future-incoming-response.subscri\ +be\x01\x85\x01\x01i,\x01j\x01\x86\x01\x01\x1b\x01j\x01\x87\x01\0\x01k\x88\x01\x01\ +@\x01\x04self\x84\x01\0\x89\x01\x04\0$[method]future-incoming-response.get\x01\x8a\ +\x01\x01h\x07\x01k\x1b\x01@\x01\x03err\x8b\x01\0\x8c\x01\x04\0\x0fhttp-error-cod\ +e\x01\x8d\x01\x03\0\x15wasi:http/types@0.2.3\x05\x09\x02\x03\0\x04\x10incoming-r\ +equest\x02\x03\0\x04\x11response-outparam\x01B\x08\x02\x03\x02\x01\x0a\x04\0\x10\ +incoming-request\x03\0\0\x02\x03\x02\x01\x0b\x04\0\x11response-outparam\x03\0\x02\ +\x01i\x01\x01i\x03\x01@\x02\x07request\x04\x0cresponse-out\x05\x01\0\x04\0\x06ha\ +ndle\x01\x06\x04\0\x20wasi:http/incoming-handler@0.2.3\x05\x0c\x04\0\x11golem:ha\ +ndler/api\x04\0\x0b\x09\x01\0\x03api\x03\0\0\0G\x09producers\x01\x0cprocessed-by\ +\x02\x0dwit-component\x070.220.0\x10wit-bindgen-rust\x060.35.0"; +#[inline(never)] +#[doc(hidden)] +pub fn __link_custom_section_describing_imports() { + wit_bindgen_rt::maybe_link_cabi_realloc(); +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/src/lib.rs b/test-components/wasi-http-incoming-request-handler-echo/src/lib.rs new file mode 100644 index 0000000000..002b024c5d --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/src/lib.rs @@ -0,0 +1,95 @@ +mod bindings; + +pub use bindings::wasi::http::types::{ + Fields, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam, +}; + +use self::bindings::wasi::http::types::{IncomingBody, Method, Scheme}; + +struct Component; + +impl bindings::exports::wasi::http::incoming_handler::Guest for Component { + fn handle(request: IncomingRequest, outparam: ResponseOutparam) { + let hdrs = Fields::new(); + + for (header_name, header_value) in request.headers().entries() { + hdrs.append(&format!("echo-{header_name}"), &header_value).unwrap(); + } + + { + let scheme_string = match request.scheme().unwrap() { + Scheme::Http => "http".to_string(), + Scheme::Https => "https".to_string(), + Scheme::Other(inner) => inner + }; + + let location_string = format!("{}://{}{}", scheme_string, request.authority().unwrap(), request.path_with_query().unwrap()); + hdrs.append(&"x-location".to_string(), &location_string.into_bytes()).unwrap(); + } + + { + let method_string = match request.method() { + Method::Get => "GET".to_string(), + Method::Connect => "Connect".to_string(), + Method::Post => "POST".to_string(), + Method::Put => "PUT".to_string(), + Method::Delete => "DELETE".to_string(), + Method::Head => "HEAD".to_string(), + Method::Options => "OPTIONS".to_string(), + Method::Patch => "PATCH".to_string(), + Method::Trace => "TRACE".to_string(), + Method::Other(inner) => inner + }; + hdrs.append(&"x-method".to_string(), &method_string.into_bytes()).unwrap(); + } + + + let incoming_body: IncomingBody = request.consume().unwrap(); + + let mut incoming_body_data: Vec = Vec::new(); + { + let incoming_body_stream = incoming_body.stream().unwrap(); + loop { + let item = match incoming_body_stream.blocking_read(1024) { + Ok(x) => x, + Err(_) => break, + }; + if item.is_empty() { + break; + } + for i in item.into_iter() { + incoming_body_data.push(i); + } + } + } + + let mut outgoing_trailers = None; + { + let future_trailers = IncomingBody::finish(incoming_body); + future_trailers.subscribe().block(); + let trailers = future_trailers.get().unwrap().unwrap().unwrap(); + if let Some(trailers) = trailers { + let actual_outgoing_trailers = Fields::new(); + for (trailer_name, trailer_value) in trailers.entries() { + actual_outgoing_trailers.append(&format!("echo-{trailer_name}"), &trailer_value).unwrap(); + } + outgoing_trailers = Some(actual_outgoing_trailers); + } + } + + let resp = OutgoingResponse::new(hdrs); + let body = resp.body().unwrap(); + + ResponseOutparam::set(outparam, Ok(resp)); + + { + let out = body.write().unwrap(); + out.blocking_write_and_flush(&incoming_body_data).unwrap(); + drop(out); + } + + OutgoingBody::finish(body, outgoing_trailers).unwrap(); + } +} + +bindings::export!(Component with_types_in bindings); diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps.lock b/test-components/wasi-http-incoming-request-handler-echo/wit/deps.lock new file mode 100644 index 0000000000..b97967bf09 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps.lock @@ -0,0 +1,29 @@ +[cli] +sha256 = "4dadd13d55aaf626833d1f4b9c34a17b0f04e993babd09552b785cda3b95ea76" +sha512 = "898dcc4e8c15d18acc6b88dbe232336fa4d19019430a910dbc9e7aeaace3077a164af3be9f002de6e7e65ef693df340801ac0c7e421e9a746bf1b6d698a90835" + +[clocks] +sha256 = "93a701968a7dd3c5d69031bc0601681c468972fdf7e28a93bb6150a67d6ebe8b" +sha512 = "98fca567c7a01887b0fb38981f1772169b6ea8de475b546508f8b86738d84e44ba95cae81def40ac34e8809f5f60e85224077ab8cb6d6d5d6296acc1df73c159" + +[filesystem] +sha256 = "69d42fb10a04a33545b17e055f13db9b1e10e82ba0ed5bdb52334e40dc07c679" +sha512 = "612effbac6f4804fe0c29dae20b78bbba59e52cb754c15402f5fe229c3153a221e0fbdff1d9d00ceaa3fe049c6a95523a5b99f772f1c16d972eade2c88326a30" + +[http] +url = "https://github.com/WebAssembly/wasi-http/archive/v0.2.3.tar.gz" +sha256 = "72d3a00dbf39eed40a134e8b1dee85834961153f9d205ee4dd56657270c084ce" +sha512 = "636150c464c0eb3d60bd212fc5d4012638c8cd4f89b583b87a38154ef99de828aac4296ac13c5cface10ee61e164fcfc43a5c104f916229dfdf49c0d11047677" +deps = ["cli", "clocks", "filesystem", "io", "random", "sockets"] + +[io] +sha256 = "1cccbfe4122686ea57a25cd368e8cdfc408cbcad089f47fb6685b6f92e96f050" +sha512 = "7a95f964c13da52611141acd89bc8876226497f128e99dd176a4270c5b5efbd8cc847b5fbd1a91258d028c646db99e0424d72590cf1caf20f9f3a3343fad5017" + +[random] +sha256 = "dd0c91e7125172eb8fd4568e15ad9fc7305643015e6ece4396c3cc5e8c2bf79a" +sha512 = "d1ca2e7b0616a94a3b39d1b9450bb3fb595b01fd94a8626ad75433038dde40988ecb41ab93a374d569ab72163af3b30038d7bfc3499b9c07193181f4f1d9292a" + +[sockets] +sha256 = "2bc0f65a8046207ee3330ad7d63f6fafeafd4cc0ea4084f081bd5e4f7b177e74" +sha512 = "3e5490e41547dffa78d52631825d93da8d60f4af0246cbaf97e1ecb879285953a86d5f1f390b10c32f91dd7eaec6f43e625a26b1c92c32a0c86fde428aedaaab" diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps.toml b/test-components/wasi-http-incoming-request-handler-echo/wit/deps.toml new file mode 100644 index 0000000000..64ca58191a --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps.toml @@ -0,0 +1 @@ +http = "https://github.com/WebAssembly/wasi-http/archive/v0.2.3.tar.gz" diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/command.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/command.wit new file mode 100644 index 0000000000..3a81766d64 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.2.3; + +@since(version = 0.2.0) +world command { + @since(version = 0.2.0) + include imports; + + @since(version = 0.2.0) + export run; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/environment.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/environment.wit new file mode 100644 index 0000000000..2f449bd7c1 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/environment.wit @@ -0,0 +1,22 @@ +@since(version = 0.2.0) +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + @since(version = 0.2.0) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.2.0) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.2.0) + initial-cwd: func() -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/exit.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/exit.wit new file mode 100644 index 0000000000..427935c8d0 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.2.0) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.2.0) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/imports.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/imports.wit new file mode 100644 index 0000000000..8b4e3975ec --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/imports.wit @@ -0,0 +1,36 @@ +package wasi:cli@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + include wasi:clocks/imports@0.2.3; + @since(version = 0.2.0) + include wasi:filesystem/imports@0.2.3; + @since(version = 0.2.0) + include wasi:sockets/imports@0.2.3; + @since(version = 0.2.0) + include wasi:random/imports@0.2.3; + @since(version = 0.2.0) + include wasi:io/imports@0.2.3; + + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import stdin; + @since(version = 0.2.0) + import stdout; + @since(version = 0.2.0) + import stderr; + @since(version = 0.2.0) + import terminal-input; + @since(version = 0.2.0) + import terminal-output; + @since(version = 0.2.0) + import terminal-stdin; + @since(version = 0.2.0) + import terminal-stdout; + @since(version = 0.2.0) + import terminal-stderr; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/run.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/run.wit new file mode 100644 index 0000000000..655346efb6 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.2.0) +interface run { + /// Run the program. + @since(version = 0.2.0) + run: func() -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/stdio.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/stdio.wit new file mode 100644 index 0000000000..1b54f5318a --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/stdio.wit @@ -0,0 +1,26 @@ +@since(version = 0.2.0) +interface stdin { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream}; + + @since(version = 0.2.0) + get-stdin: func() -> input-stream; +} + +@since(version = 0.2.0) +interface stdout { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{output-stream}; + + @since(version = 0.2.0) + get-stdout: func() -> output-stream; +} + +@since(version = 0.2.0) +interface stderr { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{output-stream}; + + @since(version = 0.2.0) + get-stderr: func() -> output-stream; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/terminal.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/terminal.wit new file mode 100644 index 0000000000..d305498c64 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/cli/terminal.wit @@ -0,0 +1,62 @@ +/// Terminal input. +/// +/// In the future, this may include functions for disabling echoing, +/// disabling input buffering so that keyboard events are sent through +/// immediately, querying supported features, and so on. +@since(version = 0.2.0) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.2.0) + resource terminal-input; +} + +/// Terminal output. +/// +/// In the future, this may include functions for querying the terminal +/// size, being notified of terminal size changes, querying supported +/// features, and so on. +@since(version = 0.2.0) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.2.0) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdin { + @since(version = 0.2.0) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdout { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stderr { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stderr: func() -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/monotonic-clock.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 0000000000..c676fb84d8 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,50 @@ +package wasi:clocks@0.2.3; +/// WASI Monotonic Clock is a clock API intended to let users measure elapsed +/// time. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A monotonic clock is a clock which has an unspecified initial value, and +/// successive reads of the clock will produce non-decreasing values. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/timezone.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/timezone.wit new file mode 100644 index 0000000000..b43e93b233 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.3; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/wall-clock.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/wall-clock.wit new file mode 100644 index 0000000000..e00ce08933 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.3; +/// WASI Wall Clock is a clock API intended to let users query the current +/// time. The name "wall" makes an analogy to a "clock on the wall", which +/// is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A wall clock is a clock which measures the date and time according to +/// some external reference. +/// +/// External references may be reset, so this clock is not necessarily +/// monotonic, making it unsuitable for measuring elapsed time. +/// +/// It is intended for reporting the current date and time for humans. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/world.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/world.wit new file mode 100644 index 0000000000..05f04f797d --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/preopens.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/preopens.wit new file mode 100644 index 0000000000..cea97495b5 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.2.3; + +@since(version = 0.2.0) +interface preopens { + @since(version = 0.2.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.2.0) + get-directories: func() -> list>; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/types.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/types.wit new file mode 100644 index 0000000000..d229a21f48 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/types.wit @@ -0,0 +1,672 @@ +package wasi:filesystem@0.2.3; +/// WASI filesystem is a filesystem API primarily intended to let users run WASI +/// programs that access their files on their existing filesystems, without +/// significant overhead. +/// +/// It is intended to be roughly portable between Unix-family platforms and +/// Windows, though it does not hide many of the major differences. +/// +/// Paths are passed as interface-type `string`s, meaning they must consist of +/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +/// paths which are not accessible by this API. +/// +/// The directory separator in WASI is always the forward-slash (`/`). +/// +/// All paths in WASI are relative paths, and are interpreted relative to a +/// `descriptor` referring to a base directory. If a `path` argument to any WASI +/// function starts with `/`, or if any step of resolving a `path`, including +/// `..` and symbolic link steps, reaches a directory outside of the base +/// directory, or reaches a symlink to an absolute or rooted path in the +/// underlying filesystem, the function fails with `error-code::not-permitted`. +/// +/// For more information about WASI path resolution and sandboxing, see +/// [WASI filesystem path resolution]. +/// +/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream, error}; + @since(version = 0.2.0) + use wasi:clocks/wall-clock@0.2.3.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.2.0) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.2.0) + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + @since(version = 0.2.0) + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrity + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.2.0) + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.2.0) + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + @since(version = 0.2.0) + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + @since(version = 0.2.0) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.2.0) + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device, + } + + /// File or memory access pattern advisory information. + @since(version = 0.2.0) + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse, + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + @since(version = 0.2.0) + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + @since(version = 0.2.0) + resource descriptor { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + @since(version = 0.2.0) + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + @since(version = 0.2.0) + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in POSIX. + @since(version = 0.2.0) + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.2.0) + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + @since(version = 0.2.0) + sync-data: func() -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + @since(version = 0.2.0) + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + @since(version = 0.2.0) + get-type: func() -> result; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + @since(version = 0.2.0) + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + @since(version = 0.2.0) + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.2.0) + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + @since(version = 0.2.0) + read-directory: func() -> result; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + @since(version = 0.2.0) + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.2.0) + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + @since(version = 0.2.0) + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + @since(version = 0.2.0) + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + @since(version = 0.2.0) + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.2.0) + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + @since(version = 0.2.0) + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + @since(version = 0.2.0) + readlink-at: func( + /// The relative path of the symbolic link from which to read. + path: string, + ) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + @since(version = 0.2.0) + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.2.0) + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + @since(version = 0.2.0) + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + @since(version = 0.2.0) + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + @since(version = 0.2.0) + is-same-object: func(other: borrow) -> bool; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encouraged to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + @since(version = 0.2.0) + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + @since(version = 0.2.0) + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + @since(version = 0.2.0) + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + @since(version = 0.2.0) + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + @since(version = 0.2.0) + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/world.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/world.wit new file mode 100644 index 0000000000..29405bc2cc --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/handler.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/handler.wit new file mode 100644 index 0000000000..6a6c62966f --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/handler.wit @@ -0,0 +1,49 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +@since(version = 0.2.0) +interface incoming-handler { + @since(version = 0.2.0) + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + @since(version = 0.2.0) + handle: func( + request: incoming-request, + response-out: response-outparam + ); +} + +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +@since(version = 0.2.0) +interface outgoing-handler { + @since(version = 0.2.0) + use types.{ + outgoing-request, request-options, future-incoming-response, error-code + }; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + @since(version = 0.2.0) + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/proxy.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/proxy.wit new file mode 100644 index 0000000000..de3bbe8ae0 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/proxy.wit @@ -0,0 +1,50 @@ +package wasi:http@0.2.3; + +/// The `wasi:http/imports` world imports all the APIs for HTTP proxies. +/// It is intended to be `include`d in other worlds. +@since(version = 0.2.0) +world imports { + /// HTTP proxies have access to time and randomness. + @since(version = 0.2.0) + import wasi:clocks/monotonic-clock@0.2.3; + @since(version = 0.2.0) + import wasi:clocks/wall-clock@0.2.3; + @since(version = 0.2.0) + import wasi:random/random@0.2.3; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + @since(version = 0.2.0) + import wasi:cli/stdout@0.2.3; + @since(version = 0.2.0) + import wasi:cli/stderr@0.2.3; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + @since(version = 0.2.0) + import wasi:cli/stdin@0.2.3; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + @since(version = 0.2.0) + import outgoing-handler; +} + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +@since(version = 0.2.0) +world proxy { + @since(version = 0.2.0) + include imports; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + @since(version = 0.2.0) + export incoming-handler; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/types.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/types.wit new file mode 100644 index 0000000000..2498f180ad --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/http/types.wit @@ -0,0 +1,673 @@ +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.3.{duration}; + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/error@0.2.3.{error as io-error}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + + /// This type corresponds to HTTP standard Methods. + @since(version = 0.2.0) + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + @since(version = 0.2.0) + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + @since(version = 0.2.0) + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option) + } + + /// Defines the case payload type for `DNS-error` above: + @since(version = 0.2.0) + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + @since(version = 0.2.0) + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + @since(version = 0.2.0) + record field-size-payload { + field-name: option, + field-size: option + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + @since(version = 0.2.0) + http-error-code: func(err: borrow) -> option; + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + @since(version = 0.2.0) + variant header-error { + /// This error indicates that a `field-name` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + + /// This error indicates that a forbidden `field-name` was used when trying + /// to set a header in a `fields`. + forbidden, + + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + @since(version = 0.2.1) + type field-name = field-key; + + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + @since(version = 0.2.0) + @deprecated(version = 0.2.2) + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + @since(version = 0.2.0) + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + @since(version = 0.2.0) + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + @since(version = 0.2.0) + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + @since(version = 0.2.0) + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + @since(version = 0.2.0) + get: func(name: field-name) -> list; + + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + @since(version = 0.2.0) + has: func(name: field-name) -> bool; + + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + @since(version = 0.2.0) + set: func(name: field-name, value: list) -> result<_, header-error>; + + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + @since(version = 0.2.0) + delete: func(name: field-name) -> result<_, header-error>; + + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + @since(version = 0.2.0) + append: func(name: field-name, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + @since(version = 0.2.0) + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + @since(version = 0.2.0) + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + @since(version = 0.2.0) + type headers = fields; + + /// Trailers is an alias for Fields. + @since(version = 0.2.0) + type trailers = fields; + + /// Represents an incoming HTTP Request. + @since(version = 0.2.0) + resource incoming-request { + + /// Returns the method of the incoming request. + @since(version = 0.2.0) + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + @since(version = 0.2.0) + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + @since(version = 0.2.0) + scheme: func() -> option; + + /// Returns the authority of the Request's target URI, if present. + @since(version = 0.2.0) + authority: func() -> option; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + @since(version = 0.2.0) + resource outgoing-request { + + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + @since(version = 0.2.0) + constructor( + headers: headers + ); + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + @since(version = 0.2.0) + body: func() -> result; + + /// Get the Method for the Request. + @since(version = 0.2.0) + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + @since(version = 0.2.0) + set-method: func(method: method) -> result; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + @since(version = 0.2.0) + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + @since(version = 0.2.0) + set-path-with-query: func(path-with-query: option) -> result; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + @since(version = 0.2.0) + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + @since(version = 0.2.0) + set-scheme: func(scheme: option) -> result; + + /// Get the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. + @since(version = 0.2.0) + authority: func() -> option; + /// Set the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid URI authority. + @since(version = 0.2.0) + set-authority: func(authority: option) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + @since(version = 0.2.0) + resource request-options { + /// Construct a default `request-options` value. + @since(version = 0.2.0) + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + @since(version = 0.2.0) + connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + @since(version = 0.2.0) + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + @since(version = 0.2.0) + between-bytes-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + @since(version = 0.2.0) + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + @since(version = 0.2.0) + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + @since(version = 0.2.0) + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + @since(version = 0.2.0) + type status-code = u16; + + /// Represents an incoming HTTP Response. + @since(version = 0.2.0) + resource incoming-response { + + /// Returns the status code from the incoming response. + @since(version = 0.2.0) + status: func() -> status-code; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + @since(version = 0.2.0) + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + @since(version = 0.2.0) + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + @since(version = 0.2.0) + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + @since(version = 0.2.0) + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + @since(version = 0.2.0) + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + @since(version = 0.2.0) + resource outgoing-response { + + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + @since(version = 0.2.0) + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + @since(version = 0.2.0) + status-code: func() -> status-code; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + @since(version = 0.2.0) + set-status-code: func(status-code: status-code) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + @since(version = 0.2.0) + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + @since(version = 0.2.0) + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + @since(version = 0.2.0) + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + @since(version = 0.2.0) + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + @since(version = 0.2.0) + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + @since(version = 0.2.0) + get: func() -> option>>; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/error.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/error.wit new file mode 100644 index 0000000000..97c6068779 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.3; + +@since(version = 0.2.0) +interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + resource error { + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/poll.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/poll.wit new file mode 100644 index 0000000000..9bcbe8e036 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.3; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + @since(version = 0.2.0) + block: func(); + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/streams.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/streams.wit new file mode 100644 index 0000000000..0de0846293 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/streams.wit @@ -0,0 +1,290 @@ +package wasi:io@0.2.3; + +/// WASI I/O is an I/O abstraction API which is currently focused on providing +/// stream types. +/// +/// In the future, the component model is expected to add built-in stream types; +/// when it does, they are expected to subsume this API. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + @since(version = 0.2.0) + resource input-stream { + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + @since(version = 0.2.0) + check-write: func() -> result; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/world.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/world.wit new file mode 100644 index 0000000000..f1d2102dca --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure-seed.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure-seed.wit new file mode 100644 index 0000000000..67d024d5bf --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.2.3; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + @since(version = 0.2.0) + insecure-seed: func() -> tuple; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure.wit new file mode 100644 index 0000000000..a07dfab327 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.3; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + @since(version = 0.2.0) + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + @since(version = 0.2.0) + get-insecure-random-u64: func() -> u64; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/random.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/random.wit new file mode 100644 index 0000000000..91957e6330 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.2.3; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + @since(version = 0.2.0) + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + @since(version = 0.2.0) + get-random-u64: func() -> u64; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/world.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/world.wit new file mode 100644 index 0000000000..0c1218f36e --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import random; + + @since(version = 0.2.0) + import insecure; + + @since(version = 0.2.0) + import insecure-seed; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/instance-network.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/instance-network.wit new file mode 100644 index 0000000000..5f6e6c1cc9 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/instance-network.wit @@ -0,0 +1,11 @@ + +/// This interface provides a value-export of the default network handle.. +@since(version = 0.2.0) +interface instance-network { + @since(version = 0.2.0) + use network.{network}; + + /// Get a handle to the default network. + @since(version = 0.2.0) + instance-network: func() -> network; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/ip-name-lookup.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 0000000000..c1d8a47c16 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,56 @@ +@since(version = 0.2.0) +interface ip-name-lookup { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-address}; + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + resolve-addresses: func(network: borrow, name: string) -> result; + + @since(version = 0.2.0) + resource resolve-address-stream { + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + @since(version = 0.2.0) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/network.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/network.wit new file mode 100644 index 0000000000..f3f60a3709 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/network.wit @@ -0,0 +1,169 @@ +@since(version = 0.2.0) +interface network { + @unstable(feature = network-error-code) + use wasi:io/error@0.2.3.{error}; + + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + @since(version = 0.2.0) + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + @since(version = 0.2.0) + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + + /// The operation timed out before it could finish completely. + timeout, + + /// This operation is incompatible with another asynchronous operation that is already in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + + /// A bind operation failed because the provided address is not an address that the `network` can bind to. + address-not-bindable, + + /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. + address-in-use, + + /// The remote address is not reachable + remote-unreachable, + + + /// The TCP connection was forcefully rejected + connection-refused, + + /// The TCP connection was reset. + connection-reset, + + /// A TCP connection was aborted. + connection-aborted, + + + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + + + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + permanent-resolver-failure, + } + + /// Attempts to extract a network-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// network-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are network-related errors. + @unstable(feature = network-error-code) + network-error-code: func(err: borrow) -> option; + + @since(version = 0.2.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.2.0) + type ipv4-address = tuple; + @since(version = 0.2.0) + type ipv6-address = tuple; + + @since(version = 0.2.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.2.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.2.0) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.2.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp-create-socket.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 0000000000..eedbd30768 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface tcp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp.wit new file mode 100644 index 0000000000..b4cd87fcef --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/tcp.wit @@ -0,0 +1,387 @@ +@since(version = 0.2.0) +interface tcp { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.3.{duration}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + @since(version = 0.2.0) + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + + /// Similar to `SHUT_WR` in POSIX. + send, + + /// Similar to `SHUT_RDWR` in POSIX. + both, + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + @since(version = 0.2.0) + resource tcp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connected` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-connect: func() -> result, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-listen: func() -> result<_, error-code>; + @since(version = 0.2.0) + finish-listen: func() -> result<_, error-code>; + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + accept: func() -> result, error-code>; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.2.0) + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` state. + @since(version = 0.2.0) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + @since(version = 0.2.0) + keep-alive-enabled: func() -> result; + @since(version = 0.2.0) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-idle-time: func() -> result; + @since(version = 0.2.0) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-interval: func() -> result; + @since(version = 0.2.0) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-count: func() -> result; + @since(version = 0.2.0) + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + @since(version = 0.2.0) + hop-limit: func() -> result; + @since(version = 0.2.0) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for more information. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent; shutting down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp-create-socket.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 0000000000..e8eeacbfef --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface udp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp.wit new file mode 100644 index 0000000000..01901ca27f --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/udp.wit @@ -0,0 +1,288 @@ +@since(version = 0.2.0) +interface udp { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + @since(version = 0.2.0) + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + @since(version = 0.2.0) + record outgoing-datagram { + /// The payload. + data: list, + + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + @since(version = 0.2.0) + resource udp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, but + /// only the most recently returned pair of streams will be operational. Implementations may trap if + /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + %stream: func(remote-address: option) -> result, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + @since(version = 0.2.0) + unicast-hop-limit: func() -> result; + @since(version = 0.2.0) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + resource incoming-datagram-stream { + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + resource outgoing-datagram-stream { + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without blocking and + /// returns how many messages were actually sent (or queued for sending). This function never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list and sequentially + /// sending each individual datagram until either the end of the list has been reached or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/world.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/world.wit new file mode 100644 index 0000000000..2f0ad0d7c9 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/deps/sockets/world.wit @@ -0,0 +1,19 @@ +package wasi:sockets@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import tcp; + @since(version = 0.2.0) + import tcp-create-socket; + @since(version = 0.2.0) + import ip-name-lookup; +} diff --git a/test-components/wasi-http-incoming-request-handler-echo/wit/world.wit b/test-components/wasi-http-incoming-request-handler-echo/wit/world.wit new file mode 100644 index 0000000000..85633a60d5 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/wit/world.wit @@ -0,0 +1,6 @@ +package golem:handler; + +world api { + import wasi:http/types@0.2.3; + export wasi:http/incoming-handler@0.2.3; +} diff --git a/test-components/wasi-http-incoming-request-handler-state.wasm b/test-components/wasi-http-incoming-request-handler-state.wasm new file mode 100644 index 0000000000000000000000000000000000000000..c79518733aa5a440e50b1e7200607014fdd29d96 GIT binary patch literal 115473 zcmeFa4V+z9UGKf$&dba`XR_0#ZQ7)CpVLrM+i9afS_5i!v~RZZqWF3IT*Wpd(`IHu zl9^1?qRqV{U>mP?W6`}?o8 z_u1#nnIuJg?!BMSlQ!9Vuf1OW>;L}$ueH|+b{>3nHwc4PH{1~>L1SidasOf*POcAw zQ*YXNaCY15{)??_`<9Eo<)Y^|g63ox2fkkGwkX_@B|&F)-+>#KrVlPH&g^`397b^z z4*Ckha5f4TqSN;7Jh(Ky|G>=R&ZXJ?`=+noIlFgeH=Q+i?cINHW_J+Kk?UgGK@lWL z(A|IIQoZkRPY@n>T{suE!$!D0N)FEKy}lLio!NI&Fp&iPAAI%9(w_ahUs(s}qF3$R zziWPW-wo4%w>z8+_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=E2g5?Dt_OV5zFszRq17WT~}$s}W9W!ZdUU~-LAS+PmN5_oq0 z`SPBKuacm+5)$7CqgKbe8G9;$N67KJrOEec6R>K?h(J+Y4Ni38xJ==iV{I-@1r zpguQ{4LeF7#)7Xw2QG@;@izj&h4@@`FF1M+ zu0BQwuIczbyZ@FQtJhX^pCbwi@zJC0-XF)L+%}&XMw;6U)9=BmTx~^RBG^*PXVm`- Ddz+Rr literal 0 HcmV?d00001 diff --git a/test-components/wasi-http-incoming-request-handler-state/Cargo.lock b/test-components/wasi-http-incoming-request-handler-state/Cargo.lock new file mode 100644 index 0000000000..5cba176dcc --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/Cargo.lock @@ -0,0 +1,25 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" + +[[package]] +name = "wasi-http-incoming-request-handler-state" +version = "0.1.0" +dependencies = [ + "wit-bindgen-rt", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc801b991c56492f87ab3086e786468f75c285a4d73017ab0ebc2fa1aed5d82c" +dependencies = [ + "bitflags", +] diff --git a/test-components/wasi-http-incoming-request-handler-state/Cargo.toml b/test-components/wasi-http-incoming-request-handler-state/Cargo.toml new file mode 100644 index 0000000000..3222a5c2c8 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "wasi-http-incoming-request-handler-state" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +path = "src/lib.rs" +crate-type = ["cdylib"] + +[dependencies] +wit-bindgen-rt = { version = "0.37.0", features = ["bitflags"] } + +[package.metadata.component] +package = "golem:handler" +proxy = true + +[package.metadata.component.target.dependencies] +"wasi:cli" = { path = "wit/deps/cli" } +"wasi:clocks" = { path = "wit/deps/clocks" } +"wasi:filesystem" = { path = "wit/deps/filesystem" } +"wasi:http" = { path = "wit/deps/http" } +"wasi:io" = { path = "wit/deps/io" } +"wasi:random" = { path = "wit/deps/random" } +"wasi:sockets" = { path = "wit/deps/sockets" } diff --git a/test-components/wasi-http-incoming-request-handler-state/src/bindings.rs b/test-components/wasi-http-incoming-request-handler-state/src/bindings.rs new file mode 100644 index 0000000000..b9a1d24912 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/src/bindings.rs @@ -0,0 +1,7502 @@ +#[allow(dead_code)] +pub mod wasi { + #[allow(dead_code)] + pub mod clocks { + #[allow(dead_code, clippy::all)] + pub mod monotonic_clock { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Pollable = super::super::super::wasi::io::poll::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. + pub type Instant = u64; + /// A duration of time, in nanoseconds. + pub type Duration = u64; + #[allow(unused_unsafe, clippy::all)] + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + pub fn now() -> Instant { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "now"] + fn wit_import() -> i64; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i64 { + unreachable!() + } + let ret = wit_import(); + ret as u64 + } + } + #[allow(unused_unsafe, clippy::all)] + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + pub fn resolution() -> Duration { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "resolution"] + fn wit_import() -> i64; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i64 { + unreachable!() + } + let ret = wit_import(); + ret as u64 + } + } + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + pub fn subscribe_instant(when: Instant) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "subscribe-instant"] + fn wit_import(_: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i64) -> i32 { + unreachable!() + } + let ret = wit_import(_rt::as_i64(when)); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + pub fn subscribe_duration(when: Duration) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "subscribe-duration"] + fn wit_import(_: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i64) -> i32 { + unreachable!() + } + let ret = wit_import(_rt::as_i64(when)); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + } + #[allow(dead_code)] + pub mod http { + #[allow(dead_code, clippy::all)] + pub mod types { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Duration = super::super::super::wasi::clocks::monotonic_clock::Duration; + pub type InputStream = super::super::super::wasi::io::streams::InputStream; + pub type OutputStream = super::super::super::wasi::io::streams::OutputStream; + pub type IoError = super::super::super::wasi::io::error::Error; + pub type Pollable = super::super::super::wasi::io::poll::Pollable; + /// This type corresponds to HTTP standard Methods. + #[derive(Clone)] + pub enum Method { + Get, + Head, + Post, + Put, + Delete, + Connect, + Options, + Trace, + Patch, + Other(_rt::String), + } + impl ::core::fmt::Debug for Method { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + Method::Get => f.debug_tuple("Method::Get").finish(), + Method::Head => f.debug_tuple("Method::Head").finish(), + Method::Post => f.debug_tuple("Method::Post").finish(), + Method::Put => f.debug_tuple("Method::Put").finish(), + Method::Delete => f.debug_tuple("Method::Delete").finish(), + Method::Connect => f.debug_tuple("Method::Connect").finish(), + Method::Options => f.debug_tuple("Method::Options").finish(), + Method::Trace => f.debug_tuple("Method::Trace").finish(), + Method::Patch => f.debug_tuple("Method::Patch").finish(), + Method::Other(e) => { + f.debug_tuple("Method::Other").field(e).finish() + } + } + } + } + /// This type corresponds to HTTP standard Related Schemes. + #[derive(Clone)] + pub enum Scheme { + Http, + Https, + Other(_rt::String), + } + impl ::core::fmt::Debug for Scheme { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + Scheme::Http => f.debug_tuple("Scheme::Http").finish(), + Scheme::Https => f.debug_tuple("Scheme::Https").finish(), + Scheme::Other(e) => { + f.debug_tuple("Scheme::Other").field(e).finish() + } + } + } + } + /// Defines the case payload type for `DNS-error` above: + #[derive(Clone)] + pub struct DnsErrorPayload { + pub rcode: Option<_rt::String>, + pub info_code: Option, + } + impl ::core::fmt::Debug for DnsErrorPayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("DnsErrorPayload") + .field("rcode", &self.rcode) + .field("info-code", &self.info_code) + .finish() + } + } + /// Defines the case payload type for `TLS-alert-received` above: + #[derive(Clone)] + pub struct TlsAlertReceivedPayload { + pub alert_id: Option, + pub alert_message: Option<_rt::String>, + } + impl ::core::fmt::Debug for TlsAlertReceivedPayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("TlsAlertReceivedPayload") + .field("alert-id", &self.alert_id) + .field("alert-message", &self.alert_message) + .finish() + } + } + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + #[derive(Clone)] + pub struct FieldSizePayload { + pub field_name: Option<_rt::String>, + pub field_size: Option, + } + impl ::core::fmt::Debug for FieldSizePayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("FieldSizePayload") + .field("field-name", &self.field_name) + .field("field-size", &self.field_size) + .finish() + } + } + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + #[derive(Clone)] + pub enum ErrorCode { + DnsTimeout, + DnsError(DnsErrorPayload), + DestinationNotFound, + DestinationUnavailable, + DestinationIpProhibited, + DestinationIpUnroutable, + ConnectionRefused, + ConnectionTerminated, + ConnectionTimeout, + ConnectionReadTimeout, + ConnectionWriteTimeout, + ConnectionLimitReached, + TlsProtocolError, + TlsCertificateError, + TlsAlertReceived(TlsAlertReceivedPayload), + HttpRequestDenied, + HttpRequestLengthRequired, + HttpRequestBodySize(Option), + HttpRequestMethodInvalid, + HttpRequestUriInvalid, + HttpRequestUriTooLong, + HttpRequestHeaderSectionSize(Option), + HttpRequestHeaderSize(Option), + HttpRequestTrailerSectionSize(Option), + HttpRequestTrailerSize(FieldSizePayload), + HttpResponseIncomplete, + HttpResponseHeaderSectionSize(Option), + HttpResponseHeaderSize(FieldSizePayload), + HttpResponseBodySize(Option), + HttpResponseTrailerSectionSize(Option), + HttpResponseTrailerSize(FieldSizePayload), + HttpResponseTransferCoding(Option<_rt::String>), + HttpResponseContentCoding(Option<_rt::String>), + HttpResponseTimeout, + HttpUpgradeFailed, + HttpProtocolError, + LoopDetected, + ConfigurationError, + /// 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. + InternalError(Option<_rt::String>), + } + impl ::core::fmt::Debug for ErrorCode { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + ErrorCode::DnsTimeout => { + f.debug_tuple("ErrorCode::DnsTimeout").finish() + } + ErrorCode::DnsError(e) => { + f.debug_tuple("ErrorCode::DnsError").field(e).finish() + } + ErrorCode::DestinationNotFound => { + f.debug_tuple("ErrorCode::DestinationNotFound").finish() + } + ErrorCode::DestinationUnavailable => { + f.debug_tuple("ErrorCode::DestinationUnavailable").finish() + } + ErrorCode::DestinationIpProhibited => { + f.debug_tuple("ErrorCode::DestinationIpProhibited").finish() + } + ErrorCode::DestinationIpUnroutable => { + f.debug_tuple("ErrorCode::DestinationIpUnroutable").finish() + } + ErrorCode::ConnectionRefused => { + f.debug_tuple("ErrorCode::ConnectionRefused").finish() + } + ErrorCode::ConnectionTerminated => { + f.debug_tuple("ErrorCode::ConnectionTerminated").finish() + } + ErrorCode::ConnectionTimeout => { + f.debug_tuple("ErrorCode::ConnectionTimeout").finish() + } + ErrorCode::ConnectionReadTimeout => { + f.debug_tuple("ErrorCode::ConnectionReadTimeout").finish() + } + ErrorCode::ConnectionWriteTimeout => { + f.debug_tuple("ErrorCode::ConnectionWriteTimeout").finish() + } + ErrorCode::ConnectionLimitReached => { + f.debug_tuple("ErrorCode::ConnectionLimitReached").finish() + } + ErrorCode::TlsProtocolError => { + f.debug_tuple("ErrorCode::TlsProtocolError").finish() + } + ErrorCode::TlsCertificateError => { + f.debug_tuple("ErrorCode::TlsCertificateError").finish() + } + ErrorCode::TlsAlertReceived(e) => { + f.debug_tuple("ErrorCode::TlsAlertReceived") + .field(e) + .finish() + } + ErrorCode::HttpRequestDenied => { + f.debug_tuple("ErrorCode::HttpRequestDenied").finish() + } + ErrorCode::HttpRequestLengthRequired => { + f.debug_tuple("ErrorCode::HttpRequestLengthRequired") + .finish() + } + ErrorCode::HttpRequestBodySize(e) => { + f.debug_tuple("ErrorCode::HttpRequestBodySize") + .field(e) + .finish() + } + ErrorCode::HttpRequestMethodInvalid => { + f.debug_tuple("ErrorCode::HttpRequestMethodInvalid").finish() + } + ErrorCode::HttpRequestUriInvalid => { + f.debug_tuple("ErrorCode::HttpRequestUriInvalid").finish() + } + ErrorCode::HttpRequestUriTooLong => { + f.debug_tuple("ErrorCode::HttpRequestUriTooLong").finish() + } + ErrorCode::HttpRequestHeaderSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestHeaderSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestHeaderSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestHeaderSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestTrailerSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestTrailerSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestTrailerSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestTrailerSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseIncomplete => { + f.debug_tuple("ErrorCode::HttpResponseIncomplete").finish() + } + ErrorCode::HttpResponseHeaderSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseHeaderSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseHeaderSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseHeaderSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseBodySize(e) => { + f.debug_tuple("ErrorCode::HttpResponseBodySize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTrailerSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseTrailerSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTrailerSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseTrailerSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTransferCoding(e) => { + f.debug_tuple("ErrorCode::HttpResponseTransferCoding") + .field(e) + .finish() + } + ErrorCode::HttpResponseContentCoding(e) => { + f.debug_tuple("ErrorCode::HttpResponseContentCoding") + .field(e) + .finish() + } + ErrorCode::HttpResponseTimeout => { + f.debug_tuple("ErrorCode::HttpResponseTimeout").finish() + } + ErrorCode::HttpUpgradeFailed => { + f.debug_tuple("ErrorCode::HttpUpgradeFailed").finish() + } + ErrorCode::HttpProtocolError => { + f.debug_tuple("ErrorCode::HttpProtocolError").finish() + } + ErrorCode::LoopDetected => { + f.debug_tuple("ErrorCode::LoopDetected").finish() + } + ErrorCode::ConfigurationError => { + f.debug_tuple("ErrorCode::ConfigurationError").finish() + } + ErrorCode::InternalError(e) => { + f.debug_tuple("ErrorCode::InternalError").field(e).finish() + } + } + } + } + impl ::core::fmt::Display for ErrorCode { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for ErrorCode {} + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + #[derive(Clone, Copy)] + pub enum HeaderError { + /// This error indicates that a `field-name` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + InvalidSyntax, + /// This error indicates that a forbidden `field-name` was used when trying + /// to set a header in a `fields`. + Forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + Immutable, + } + impl ::core::fmt::Debug for HeaderError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + HeaderError::InvalidSyntax => { + f.debug_tuple("HeaderError::InvalidSyntax").finish() + } + HeaderError::Forbidden => { + f.debug_tuple("HeaderError::Forbidden").finish() + } + HeaderError::Immutable => { + f.debug_tuple("HeaderError::Immutable").finish() + } + } + } + } + impl ::core::fmt::Display for HeaderError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for HeaderError {} + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + pub type FieldKey = _rt::String; + /// Field names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + pub type FieldName = FieldKey; + /// 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. + pub type FieldValue = _rt::Vec; + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct Fields { + handle: _rt::Resource, + } + impl Fields { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Fields { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]fields"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Headers is an alias for Fields. + pub type Headers = Fields; + /// Trailers is an alias for Fields. + pub type Trailers = Fields; + /// Represents an incoming HTTP Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingRequest { + handle: _rt::Resource, + } + impl IncomingRequest { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingRequest { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-request"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingRequest { + handle: _rt::Resource, + } + impl OutgoingRequest { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingRequest { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-request"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct RequestOptions { + handle: _rt::Resource, + } + impl RequestOptions { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for RequestOptions { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]request-options"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct ResponseOutparam { + handle: _rt::Resource, + } + impl ResponseOutparam { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for ResponseOutparam { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]response-outparam"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// This type corresponds to the HTTP standard Status Code. + pub type StatusCode = u16; + /// Represents an incoming HTTP Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingResponse { + handle: _rt::Resource, + } + impl IncomingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingBody { + handle: _rt::Resource, + } + impl IncomingBody { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingBody { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-body"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + #[derive(Debug)] + #[repr(transparent)] + pub struct FutureTrailers { + handle: _rt::Resource, + } + impl FutureTrailers { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for FutureTrailers { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]future-trailers"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingResponse { + handle: _rt::Resource, + } + impl OutgoingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingBody { + handle: _rt::Resource, + } + impl OutgoingBody { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingBody { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-body"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct FutureIncomingResponse { + handle: _rt::Resource, + } + impl FutureIncomingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for FutureIncomingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]future-incoming-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn http_error_code(err: &IoError) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 40]); + let mut ret_area = RetArea([::core::mem::MaybeUninit::uninit(); 40]); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "http-error-code"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((err).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + let v64 = match l2 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e64 = { + let l3 = i32::from(*ptr0.add(16).cast::()); + let l7 = i32::from(*ptr0.add(28).cast::()); + DnsErrorPayload { + rcode: match l3 { + 0 => None, + 1 => { + let e = { + let l4 = *ptr0.add(20).cast::<*mut u8>(); + let l5 = *ptr0.add(24).cast::(); + let len6 = l5; + let bytes6 = _rt::Vec::from_raw_parts( + l4.cast(), + len6, + len6, + ); + _rt::string_lift(bytes6) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l7 { + 0 => None, + 1 => { + let e = { + let l8 = i32::from(*ptr0.add(30).cast::()); + l8 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e64) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e64 = { + let l9 = i32::from(*ptr0.add(16).cast::()); + let l11 = i32::from(*ptr0.add(20).cast::()); + TlsAlertReceivedPayload { + alert_id: match l9 { + 0 => None, + 1 => { + let e = { + let l10 = i32::from(*ptr0.add(17).cast::()); + l10 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l11 { + 0 => None, + 1 => { + let e = { + let l12 = *ptr0.add(24).cast::<*mut u8>(); + let l13 = *ptr0.add(28).cast::(); + let len14 = l13; + let bytes14 = _rt::Vec::from_raw_parts( + l12.cast(), + len14, + len14, + ); + _rt::string_lift(bytes14) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e64) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e64 = { + let l15 = i32::from(*ptr0.add(16).cast::()); + match l15 { + 0 => None, + 1 => { + let e = { + let l16 = *ptr0.add(24).cast::(); + l16 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e64) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e64 = { + let l17 = i32::from(*ptr0.add(16).cast::()); + match l17 { + 0 => None, + 1 => { + let e = { + let l18 = *ptr0.add(20).cast::(); + l18 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e64) + } + 22 => { + let e64 = { + let l19 = i32::from(*ptr0.add(16).cast::()); + match l19 { + 0 => None, + 1 => { + let e = { + let l20 = i32::from(*ptr0.add(20).cast::()); + let l24 = i32::from(*ptr0.add(32).cast::()); + FieldSizePayload { + field_name: match l20 { + 0 => None, + 1 => { + let e = { + let l21 = *ptr0.add(24).cast::<*mut u8>(); + let l22 = *ptr0.add(28).cast::(); + let len23 = l22; + let bytes23 = _rt::Vec::from_raw_parts( + l21.cast(), + len23, + len23, + ); + _rt::string_lift(bytes23) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l24 { + 0 => None, + 1 => { + let e = { + let l25 = *ptr0.add(36).cast::(); + l25 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e64) + } + 23 => { + let e64 = { + let l26 = i32::from(*ptr0.add(16).cast::()); + match l26 { + 0 => None, + 1 => { + let e = { + let l27 = *ptr0.add(20).cast::(); + l27 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e64) + } + 24 => { + let e64 = { + let l28 = i32::from(*ptr0.add(16).cast::()); + let l32 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l28 { + 0 => None, + 1 => { + let e = { + let l29 = *ptr0.add(20).cast::<*mut u8>(); + let l30 = *ptr0.add(24).cast::(); + let len31 = l30; + let bytes31 = _rt::Vec::from_raw_parts( + l29.cast(), + len31, + len31, + ); + _rt::string_lift(bytes31) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l32 { + 0 => None, + 1 => { + let e = { + let l33 = *ptr0.add(32).cast::(); + l33 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e64) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e64 = { + let l34 = i32::from(*ptr0.add(16).cast::()); + match l34 { + 0 => None, + 1 => { + let e = { + let l35 = *ptr0.add(20).cast::(); + l35 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e64) + } + 27 => { + let e64 = { + let l36 = i32::from(*ptr0.add(16).cast::()); + let l40 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l36 { + 0 => None, + 1 => { + let e = { + let l37 = *ptr0.add(20).cast::<*mut u8>(); + let l38 = *ptr0.add(24).cast::(); + let len39 = l38; + let bytes39 = _rt::Vec::from_raw_parts( + l37.cast(), + len39, + len39, + ); + _rt::string_lift(bytes39) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l40 { + 0 => None, + 1 => { + let e = { + let l41 = *ptr0.add(32).cast::(); + l41 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e64) + } + 28 => { + let e64 = { + let l42 = i32::from(*ptr0.add(16).cast::()); + match l42 { + 0 => None, + 1 => { + let e = { + let l43 = *ptr0.add(24).cast::(); + l43 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e64) + } + 29 => { + let e64 = { + let l44 = i32::from(*ptr0.add(16).cast::()); + match l44 { + 0 => None, + 1 => { + let e = { + let l45 = *ptr0.add(20).cast::(); + l45 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e64) + } + 30 => { + let e64 = { + let l46 = i32::from(*ptr0.add(16).cast::()); + let l50 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l46 { + 0 => None, + 1 => { + let e = { + let l47 = *ptr0.add(20).cast::<*mut u8>(); + let l48 = *ptr0.add(24).cast::(); + let len49 = l48; + let bytes49 = _rt::Vec::from_raw_parts( + l47.cast(), + len49, + len49, + ); + _rt::string_lift(bytes49) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l50 { + 0 => None, + 1 => { + let e = { + let l51 = *ptr0.add(32).cast::(); + l51 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e64) + } + 31 => { + let e64 = { + let l52 = i32::from(*ptr0.add(16).cast::()); + match l52 { + 0 => None, + 1 => { + let e = { + let l53 = *ptr0.add(20).cast::<*mut u8>(); + let l54 = *ptr0.add(24).cast::(); + let len55 = l54; + let bytes55 = _rt::Vec::from_raw_parts( + l53.cast(), + len55, + len55, + ); + _rt::string_lift(bytes55) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e64) + } + 32 => { + let e64 = { + let l56 = i32::from(*ptr0.add(16).cast::()); + match l56 { + 0 => None, + 1 => { + let e = { + let l57 = *ptr0.add(20).cast::<*mut u8>(); + let l58 = *ptr0.add(24).cast::(); + let len59 = l58; + let bytes59 = _rt::Vec::from_raw_parts( + l57.cast(), + len59, + len59, + ); + _rt::string_lift(bytes59) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e64) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e64 = { + let l60 = i32::from(*ptr0.add(16).cast::()); + match l60 { + 0 => None, + 1 => { + let e = { + let l61 = *ptr0.add(20).cast::<*mut u8>(); + let l62 = *ptr0.add(24).cast::(); + let len63 = l62; + let bytes63 = _rt::Vec::from_raw_parts( + l61.cast(), + len63, + len63, + ); + _rt::string_lift(bytes63) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e64) + } + }; + v64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + pub fn new() -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]fields"] + fn wit_import() -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i32 { + unreachable!() + } + let ret = wit_import(); + Fields::from_handle(ret as u32) + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + pub fn from_list( + entries: &[(FieldName, FieldValue)], + ) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let vec3 = entries; + let len3 = vec3.len(); + let layout3 = _rt::alloc::Layout::from_size_align_unchecked( + vec3.len() * 16, + 4, + ); + let result3 = if layout3.size() != 0 { + let ptr = _rt::alloc::alloc(layout3).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout3); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec3.into_iter().enumerate() { + let base = result3.add(i * 16); + { + let (t0_0, t0_1) = e; + let vec1 = t0_0; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + *base.add(4).cast::() = len1; + *base.add(0).cast::<*mut u8>() = ptr1.cast_mut(); + let vec2 = t0_1; + let ptr2 = vec2.as_ptr().cast::(); + let len2 = vec2.len(); + *base.add(12).cast::() = len2; + *base.add(8).cast::<*mut u8>() = ptr2.cast_mut(); + } + } + let ptr4 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]fields.from-list"] + fn wit_import(_: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import(result3, len3, ptr4); + let l5 = i32::from(*ptr4.add(0).cast::()); + if layout3.size() != 0 { + _rt::alloc::dealloc(result3.cast(), layout3); + } + match l5 { + 0 => { + let e = { + let l6 = *ptr4.add(4).cast::(); + Fields::from_handle(l6 as u32) + }; + Ok(e) + } + 1 => { + let e = { + let l7 = i32::from(*ptr4.add(4).cast::()); + let v8 = match l7 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v8 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + pub fn get(&self, name: &FieldName) -> _rt::Vec { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.get"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = *ptr1.add(0).cast::<*mut u8>(); + let l3 = *ptr1.add(4).cast::(); + let base7 = l2; + let len7 = l3; + let mut result7 = _rt::Vec::with_capacity(len7); + for i in 0..len7 { + let base = base7.add(i * 8); + let e7 = { + let l4 = *base.add(0).cast::<*mut u8>(); + let l5 = *base.add(4).cast::(); + let len6 = l5; + _rt::Vec::from_raw_parts(l4.cast(), len6, len6) + }; + result7.push(e7); + } + _rt::cabi_dealloc(base7, len7 * 8, 4); + result7 + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + pub fn has(&self, name: &FieldName) -> bool { + unsafe { + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.has"] + fn wit_import(_: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + ); + _rt::bool_lift(ret as u8) + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + pub fn set( + &self, + name: &FieldName, + value: &[FieldValue], + ) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let vec2 = value; + let len2 = vec2.len(); + let layout2 = _rt::alloc::Layout::from_size_align_unchecked( + vec2.len() * 8, + 4, + ); + let result2 = if layout2.size() != 0 { + let ptr = _rt::alloc::alloc(layout2).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout2); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec2.into_iter().enumerate() { + let base = result2.add(i * 8); + { + let vec1 = e; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + *base.add(4).cast::() = len1; + *base.add(0).cast::<*mut u8>() = ptr1.cast_mut(); + } + } + let ptr3 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.set"] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ) { + unreachable!() + } + wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + result2, + len2, + ptr3, + ); + let l4 = i32::from(*ptr3.add(0).cast::()); + if layout2.size() != 0 { + _rt::alloc::dealloc(result2.cast(), layout2); + } + match l4 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr3.add(1).cast::()); + let v6 = match l5 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v6 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + pub fn delete(&self, name: &FieldName) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.delete"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(1).cast::()); + let v4 = match l3 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + pub fn append( + &self, + name: &FieldName, + value: &FieldValue, + ) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let vec1 = value; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + let ptr2 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.append"] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ) { + unreachable!() + } + wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + ptr1.cast_mut(), + len1, + ptr2, + ); + let l3 = i32::from(*ptr2.add(0).cast::()); + match l3 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l4 = i32::from(*ptr2.add(1).cast::()); + let v5 = match l4 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + pub fn entries(&self) -> _rt::Vec<(FieldName, FieldValue)> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.entries"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = *ptr0.add(0).cast::<*mut u8>(); + let l2 = *ptr0.add(4).cast::(); + let base9 = l1; + let len9 = l2; + let mut result9 = _rt::Vec::with_capacity(len9); + for i in 0..len9 { + let base = base9.add(i * 16); + let e9 = { + let l3 = *base.add(0).cast::<*mut u8>(); + let l4 = *base.add(4).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + let l6 = *base.add(8).cast::<*mut u8>(); + let l7 = *base.add(12).cast::(); + let len8 = l7; + ( + _rt::string_lift(bytes5), + _rt::Vec::from_raw_parts(l6.cast(), len8, len8), + ) + }; + result9.push(e9); + } + _rt::cabi_dealloc(base9, len9 * 16, 4); + result9 + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + pub fn clone(&self) -> Fields { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.clone"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the method of the incoming request. + pub fn method(&self) -> Method { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.method"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + let v5 = match l1 { + 0 => Method::Get, + 1 => Method::Head, + 2 => Method::Post, + 3 => Method::Put, + 4 => Method::Delete, + 5 => Method::Connect, + 6 => Method::Options, + 7 => Method::Trace, + 8 => Method::Patch, + n => { + debug_assert_eq!(n, 9, "invalid enum discriminant"); + let e5 = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Method::Other(e5) + } + }; + v5 + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the path with query parameters from the request, as a string. + pub fn path_with_query(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.path-with-query"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the protocol scheme from the request. + pub fn scheme(&self) -> Option { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.scheme"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v6 = match l2 { + 0 => Scheme::Http, + 1 => Scheme::Https, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + let e6 = { + let l3 = *ptr0.add(8).cast::<*mut u8>(); + let l4 = *ptr0.add(12).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + _rt::string_lift(bytes5) + }; + Scheme::Other(e6) + } + }; + v6 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the authority of the Request's target URI, if present. + pub fn authority(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.authority"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + pub fn consume(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.consume"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + IncomingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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`. + pub fn new(headers: Headers) -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]outgoing-request"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&headers).take_handle() as i32); + OutgoingRequest::from_handle(ret as u32) + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn body(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.body"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + OutgoingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the Method for the Request. + pub fn method(&self) -> Method { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.method"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + let v5 = match l1 { + 0 => Method::Get, + 1 => Method::Head, + 2 => Method::Post, + 3 => Method::Put, + 4 => Method::Delete, + 5 => Method::Connect, + 6 => Method::Options, + 7 => Method::Trace, + 8 => Method::Patch, + n => { + debug_assert_eq!(n, 9, "invalid enum discriminant"); + let e5 = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Method::Other(e5) + } + }; + v5 + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + pub fn set_method(&self, method: &Method) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match method { + Method::Get => (0i32, ::core::ptr::null_mut(), 0usize), + Method::Head => (1i32, ::core::ptr::null_mut(), 0usize), + Method::Post => (2i32, ::core::ptr::null_mut(), 0usize), + Method::Put => (3i32, ::core::ptr::null_mut(), 0usize), + Method::Delete => (4i32, ::core::ptr::null_mut(), 0usize), + Method::Connect => (5i32, ::core::ptr::null_mut(), 0usize), + Method::Options => (6i32, ::core::ptr::null_mut(), 0usize), + Method::Trace => (7i32, ::core::ptr::null_mut(), 0usize), + Method::Patch => (8i32, ::core::ptr::null_mut(), 0usize), + Method::Other(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (9i32, ptr0.cast_mut(), len0) + } + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-method"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + pub fn path_with_query(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.path-with-query"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_path_with_query( + &self, + path_with_query: Option<&str>, + ) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match path_with_query { + Some(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (1i32, ptr0.cast_mut(), len0) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-path-with-query"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + pub fn scheme(&self) -> Option { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.scheme"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v6 = match l2 { + 0 => Scheme::Http, + 1 => Scheme::Https, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + let e6 = { + let l3 = *ptr0.add(8).cast::<*mut u8>(); + let l4 = *ptr0.add(12).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + _rt::string_lift(bytes5) + }; + Scheme::Other(e6) + } + }; + v6 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_scheme(&self, scheme: Option<&Scheme>) -> Result<(), ()> { + unsafe { + let (result2_0, result2_1, result2_2, result2_3) = match scheme { + Some(e) => { + let (result1_0, result1_1, result1_2) = match e { + Scheme::Http => (0i32, ::core::ptr::null_mut(), 0usize), + Scheme::Https => (1i32, ::core::ptr::null_mut(), 0usize), + Scheme::Other(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (2i32, ptr0.cast_mut(), len0) + } + }; + (1i32, result1_0, result1_1, result1_2) + } + None => (0i32, 0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-scheme"] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: *mut u8, + _: usize, + ) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: *mut u8, + _: usize, + ) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result2_0, + result2_1, + result2_2, + result2_3, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. + pub fn authority(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.authority"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Set the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid URI authority. + pub fn set_authority(&self, authority: Option<&str>) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match authority { + Some(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (1i32, ptr0.cast_mut(), len0) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-authority"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Construct a default `request-options` value. + pub fn new() -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]request-options"] + fn wit_import() -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i32 { + unreachable!() + } + let ret = wit_import(); + RequestOptions::from_handle(ret as u32) + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for the initial connect to the HTTP Server. + pub fn connect_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.connect-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + pub fn set_connect_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-connect-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for receiving the first byte of the Response body. + pub fn first_byte_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.first-byte-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + pub fn set_first_byte_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-first-byte-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + pub fn between_bytes_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.between-bytes-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_between_bytes_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-between-bytes-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl ResponseOutparam { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set( + param: ResponseOutparam, + response: Result, + ) { + unsafe { + let ( + result38_0, + result38_1, + result38_2, + result38_3, + result38_4, + result38_5, + result38_6, + result38_7, + ) = match &response { + Ok(e) => { + ( + 0i32, + (e).take_handle() as i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + Err(e) => { + let ( + result37_0, + result37_1, + result37_2, + result37_3, + result37_4, + result37_5, + result37_6, + ) = match e { + ErrorCode::DnsTimeout => { + ( + 0i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DnsError(e) => { + let DnsErrorPayload { + rcode: rcode0, + info_code: info_code0, + } = e; + let (result2_0, result2_1, result2_2) = match rcode0 { + Some(e) => { + let vec1 = e; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + (1i32, ptr1.cast_mut(), len1) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result3_0, result3_1) = match info_code0 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 1i32, + result2_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result2_1); + t + }, + result2_2 as *mut u8, + result3_0 as *mut u8, + result3_1 as usize, + 0i32, + ) + } + ErrorCode::DestinationNotFound => { + ( + 2i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationUnavailable => { + ( + 3i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationIpProhibited => { + ( + 4i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationIpUnroutable => { + ( + 5i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionRefused => { + ( + 6i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionTerminated => { + ( + 7i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionTimeout => { + ( + 8i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionReadTimeout => { + ( + 9i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionWriteTimeout => { + ( + 10i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionLimitReached => { + ( + 11i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsProtocolError => { + ( + 12i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsCertificateError => { + ( + 13i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsAlertReceived(e) => { + let TlsAlertReceivedPayload { + alert_id: alert_id4, + alert_message: alert_message4, + } = e; + let (result5_0, result5_1) = match alert_id4 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + let (result7_0, result7_1, result7_2) = match alert_message4 { + Some(e) => { + let vec6 = e; + let ptr6 = vec6.as_ptr().cast::(); + let len6 = vec6.len(); + (1i32, ptr6.cast_mut(), len6) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 14i32, + result5_0, + ::core::mem::MaybeUninit::new(i64::from(result5_1) as u64), + result7_0 as *mut u8, + result7_1, + result7_2, + 0i32, + ) + } + ErrorCode::HttpRequestDenied => { + ( + 15i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestLengthRequired => { + ( + 16i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestBodySize(e) => { + let (result8_0, result8_1) = match e { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + ( + 17i32, + result8_0, + ::core::mem::MaybeUninit::new(result8_1 as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestMethodInvalid => { + ( + 18i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestUriInvalid => { + ( + 19i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestUriTooLong => { + ( + 20i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestHeaderSectionSize(e) => { + let (result9_0, result9_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 21i32, + result9_0, + ::core::mem::MaybeUninit::new(i64::from(result9_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestHeaderSize(e) => { + let ( + result14_0, + result14_1, + result14_2, + result14_3, + result14_4, + result14_5, + ) = match e { + Some(e) => { + let FieldSizePayload { + field_name: field_name10, + field_size: field_size10, + } = e; + let (result12_0, result12_1, result12_2) = match field_name10 { + Some(e) => { + let vec11 = e; + let ptr11 = vec11.as_ptr().cast::(); + let len11 = vec11.len(); + (1i32, ptr11.cast_mut(), len11) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result13_0, result13_1) = match field_size10 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 1i32, + result12_0, + result12_1, + result12_2, + result13_0, + result13_1, + ) + } + None => { + (0i32, 0i32, ::core::ptr::null_mut(), 0usize, 0i32, 0i32) + } + }; + ( + 22i32, + result14_0, + ::core::mem::MaybeUninit::new(i64::from(result14_1) as u64), + result14_2, + result14_3 as *mut u8, + result14_4 as usize, + result14_5, + ) + } + ErrorCode::HttpRequestTrailerSectionSize(e) => { + let (result15_0, result15_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 23i32, + result15_0, + ::core::mem::MaybeUninit::new(i64::from(result15_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestTrailerSize(e) => { + let FieldSizePayload { + field_name: field_name16, + field_size: field_size16, + } = e; + let (result18_0, result18_1, result18_2) = match field_name16 { + Some(e) => { + let vec17 = e; + let ptr17 = vec17.as_ptr().cast::(); + let len17 = vec17.len(); + (1i32, ptr17.cast_mut(), len17) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result19_0, result19_1) = match field_size16 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 24i32, + result18_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result18_1); + t + }, + result18_2 as *mut u8, + result19_0 as *mut u8, + result19_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseIncomplete => { + ( + 25i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseHeaderSectionSize(e) => { + let (result20_0, result20_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 26i32, + result20_0, + ::core::mem::MaybeUninit::new(i64::from(result20_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseHeaderSize(e) => { + let FieldSizePayload { + field_name: field_name21, + field_size: field_size21, + } = e; + let (result23_0, result23_1, result23_2) = match field_name21 { + Some(e) => { + let vec22 = e; + let ptr22 = vec22.as_ptr().cast::(); + let len22 = vec22.len(); + (1i32, ptr22.cast_mut(), len22) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result24_0, result24_1) = match field_size21 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 27i32, + result23_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result23_1); + t + }, + result23_2 as *mut u8, + result24_0 as *mut u8, + result24_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseBodySize(e) => { + let (result25_0, result25_1) = match e { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + ( + 28i32, + result25_0, + ::core::mem::MaybeUninit::new(result25_1 as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTrailerSectionSize(e) => { + let (result26_0, result26_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 29i32, + result26_0, + ::core::mem::MaybeUninit::new(i64::from(result26_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTrailerSize(e) => { + let FieldSizePayload { + field_name: field_name27, + field_size: field_size27, + } = e; + let (result29_0, result29_1, result29_2) = match field_name27 { + Some(e) => { + let vec28 = e; + let ptr28 = vec28.as_ptr().cast::(); + let len28 = vec28.len(); + (1i32, ptr28.cast_mut(), len28) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result30_0, result30_1) = match field_size27 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 30i32, + result29_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result29_1); + t + }, + result29_2 as *mut u8, + result30_0 as *mut u8, + result30_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseTransferCoding(e) => { + let (result32_0, result32_1, result32_2) = match e { + Some(e) => { + let vec31 = e; + let ptr31 = vec31.as_ptr().cast::(); + let len31 = vec31.len(); + (1i32, ptr31.cast_mut(), len31) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 31i32, + result32_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result32_1); + t + }, + result32_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseContentCoding(e) => { + let (result34_0, result34_1, result34_2) = match e { + Some(e) => { + let vec33 = e; + let ptr33 = vec33.as_ptr().cast::(); + let len33 = vec33.len(); + (1i32, ptr33.cast_mut(), len33) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 32i32, + result34_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result34_1); + t + }, + result34_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTimeout => { + ( + 33i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpUpgradeFailed => { + ( + 34i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpProtocolError => { + ( + 35i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::LoopDetected => { + ( + 36i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConfigurationError => { + ( + 37i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::InternalError(e) => { + let (result36_0, result36_1, result36_2) = match e { + Some(e) => { + let vec35 = e; + let ptr35 = vec35.as_ptr().cast::(); + let len35 = vec35.len(); + (1i32, ptr35.cast_mut(), len35) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 38i32, + result36_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result36_1); + t + }, + result36_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + }; + ( + 1i32, + result37_0, + result37_1, + result37_2, + result37_3, + result37_4, + result37_5, + result37_6, + ) + } + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]response-outparam.set"] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: i32, + _: ::core::mem::MaybeUninit, + _: *mut u8, + _: *mut u8, + _: usize, + _: i32, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: i32, + _: ::core::mem::MaybeUninit, + _: *mut u8, + _: *mut u8, + _: usize, + _: i32, + ) { + unreachable!() + } + wit_import( + (¶m).take_handle() as i32, + result38_0, + result38_1, + result38_2, + result38_3, + result38_4, + result38_5, + result38_6, + result38_7, + ); + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the status code from the incoming response. + pub fn status(&self) -> StatusCode { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.status"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + ret as u16 + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + pub fn consume(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.consume"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + IncomingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn stream(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-body.stream"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + super::super::super::wasi::io::streams::InputStream::from_handle( + l2 as u32, + ) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingBody { + #[allow(unused_unsafe, clippy::all)] + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + pub fn finish(this: IncomingBody) -> FutureTrailers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]incoming-body.finish"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&this).take_handle() as i32); + FutureTrailers::from_handle(ret as u32) + } + } + } + impl FutureTrailers { + #[allow(unused_unsafe, clippy::all)] + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-trailers.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl FutureTrailers { + #[allow(unused_unsafe, clippy::all)] + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + pub fn get( + &self, + ) -> Option, ErrorCode>, ()>> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 56]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 56], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-trailers.get"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + match l2 { + 0 => { + let e = { + let l3 = i32::from(*ptr0.add(16).cast::()); + match l3 { + 0 => { + let e = { + let l4 = i32::from(*ptr0.add(24).cast::()); + match l4 { + 0 => None, + 1 => { + let e = { + let l5 = *ptr0.add(28).cast::(); + Fields::from_handle(l5 as u32) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = { + let l6 = i32::from(*ptr0.add(24).cast::()); + let v68 = match l6 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e68 = { + let l7 = i32::from(*ptr0.add(32).cast::()); + let l11 = i32::from(*ptr0.add(44).cast::()); + DnsErrorPayload { + rcode: match l7 { + 0 => None, + 1 => { + let e = { + let l8 = *ptr0.add(36).cast::<*mut u8>(); + let l9 = *ptr0.add(40).cast::(); + let len10 = l9; + let bytes10 = _rt::Vec::from_raw_parts( + l8.cast(), + len10, + len10, + ); + _rt::string_lift(bytes10) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l11 { + 0 => None, + 1 => { + let e = { + let l12 = i32::from(*ptr0.add(46).cast::()); + l12 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e68) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e68 = { + let l13 = i32::from(*ptr0.add(32).cast::()); + let l15 = i32::from(*ptr0.add(36).cast::()); + TlsAlertReceivedPayload { + alert_id: match l13 { + 0 => None, + 1 => { + let e = { + let l14 = i32::from(*ptr0.add(33).cast::()); + l14 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l15 { + 0 => None, + 1 => { + let e = { + let l16 = *ptr0.add(40).cast::<*mut u8>(); + let l17 = *ptr0.add(44).cast::(); + let len18 = l17; + let bytes18 = _rt::Vec::from_raw_parts( + l16.cast(), + len18, + len18, + ); + _rt::string_lift(bytes18) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e68) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e68 = { + let l19 = i32::from(*ptr0.add(32).cast::()); + match l19 { + 0 => None, + 1 => { + let e = { + let l20 = *ptr0.add(40).cast::(); + l20 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e68) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e68 = { + let l21 = i32::from(*ptr0.add(32).cast::()); + match l21 { + 0 => None, + 1 => { + let e = { + let l22 = *ptr0.add(36).cast::(); + l22 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e68) + } + 22 => { + let e68 = { + let l23 = i32::from(*ptr0.add(32).cast::()); + match l23 { + 0 => None, + 1 => { + let e = { + let l24 = i32::from(*ptr0.add(36).cast::()); + let l28 = i32::from(*ptr0.add(48).cast::()); + FieldSizePayload { + field_name: match l24 { + 0 => None, + 1 => { + let e = { + let l25 = *ptr0.add(40).cast::<*mut u8>(); + let l26 = *ptr0.add(44).cast::(); + let len27 = l26; + let bytes27 = _rt::Vec::from_raw_parts( + l25.cast(), + len27, + len27, + ); + _rt::string_lift(bytes27) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l28 { + 0 => None, + 1 => { + let e = { + let l29 = *ptr0.add(52).cast::(); + l29 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e68) + } + 23 => { + let e68 = { + let l30 = i32::from(*ptr0.add(32).cast::()); + match l30 { + 0 => None, + 1 => { + let e = { + let l31 = *ptr0.add(36).cast::(); + l31 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e68) + } + 24 => { + let e68 = { + let l32 = i32::from(*ptr0.add(32).cast::()); + let l36 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l32 { + 0 => None, + 1 => { + let e = { + let l33 = *ptr0.add(36).cast::<*mut u8>(); + let l34 = *ptr0.add(40).cast::(); + let len35 = l34; + let bytes35 = _rt::Vec::from_raw_parts( + l33.cast(), + len35, + len35, + ); + _rt::string_lift(bytes35) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l36 { + 0 => None, + 1 => { + let e = { + let l37 = *ptr0.add(48).cast::(); + l37 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e68) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e68 = { + let l38 = i32::from(*ptr0.add(32).cast::()); + match l38 { + 0 => None, + 1 => { + let e = { + let l39 = *ptr0.add(36).cast::(); + l39 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e68) + } + 27 => { + let e68 = { + let l40 = i32::from(*ptr0.add(32).cast::()); + let l44 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l40 { + 0 => None, + 1 => { + let e = { + let l41 = *ptr0.add(36).cast::<*mut u8>(); + let l42 = *ptr0.add(40).cast::(); + let len43 = l42; + let bytes43 = _rt::Vec::from_raw_parts( + l41.cast(), + len43, + len43, + ); + _rt::string_lift(bytes43) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l44 { + 0 => None, + 1 => { + let e = { + let l45 = *ptr0.add(48).cast::(); + l45 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e68) + } + 28 => { + let e68 = { + let l46 = i32::from(*ptr0.add(32).cast::()); + match l46 { + 0 => None, + 1 => { + let e = { + let l47 = *ptr0.add(40).cast::(); + l47 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e68) + } + 29 => { + let e68 = { + let l48 = i32::from(*ptr0.add(32).cast::()); + match l48 { + 0 => None, + 1 => { + let e = { + let l49 = *ptr0.add(36).cast::(); + l49 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e68) + } + 30 => { + let e68 = { + let l50 = i32::from(*ptr0.add(32).cast::()); + let l54 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l50 { + 0 => None, + 1 => { + let e = { + let l51 = *ptr0.add(36).cast::<*mut u8>(); + let l52 = *ptr0.add(40).cast::(); + let len53 = l52; + let bytes53 = _rt::Vec::from_raw_parts( + l51.cast(), + len53, + len53, + ); + _rt::string_lift(bytes53) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l54 { + 0 => None, + 1 => { + let e = { + let l55 = *ptr0.add(48).cast::(); + l55 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e68) + } + 31 => { + let e68 = { + let l56 = i32::from(*ptr0.add(32).cast::()); + match l56 { + 0 => None, + 1 => { + let e = { + let l57 = *ptr0.add(36).cast::<*mut u8>(); + let l58 = *ptr0.add(40).cast::(); + let len59 = l58; + let bytes59 = _rt::Vec::from_raw_parts( + l57.cast(), + len59, + len59, + ); + _rt::string_lift(bytes59) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e68) + } + 32 => { + let e68 = { + let l60 = i32::from(*ptr0.add(32).cast::()); + match l60 { + 0 => None, + 1 => { + let e = { + let l61 = *ptr0.add(36).cast::<*mut u8>(); + let l62 = *ptr0.add(40).cast::(); + let len63 = l62; + let bytes63 = _rt::Vec::from_raw_parts( + l61.cast(), + len63, + len63, + ); + _rt::string_lift(bytes63) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e68) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e68 = { + let l64 = i32::from(*ptr0.add(32).cast::()); + match l64 { + 0 => None, + 1 => { + let e = { + let l65 = *ptr0.add(36).cast::<*mut u8>(); + let l66 = *ptr0.add(40).cast::(); + let len67 = l66; + let bytes67 = _rt::Vec::from_raw_parts( + l65.cast(), + len67, + len67, + ); + _rt::string_lift(bytes67) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e68) + } + }; + v68 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn new(headers: Headers) -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]outgoing-response"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&headers).take_handle() as i32); + OutgoingResponse::from_handle(ret as u32) + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Get the HTTP Status Code for the Response. + pub fn status_code(&self) -> StatusCode { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.status-code"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + ret as u16 + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + pub fn set_status_code( + &self, + status_code: StatusCode, + ) -> Result<(), ()> { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.set-status-code"] + fn wit_import(_: i32, _: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + _rt::as_i32(status_code), + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn body(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.body"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + OutgoingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-body.write"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + super::super::super::wasi::io::streams::OutputStream::from_handle( + l2 as u32, + ) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn finish( + this: OutgoingBody, + trailers: Option, + ) -> Result<(), ErrorCode> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 40]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 40], + ); + let (result0_0, result0_1) = match &trailers { + Some(e) => (1i32, (e).take_handle() as i32), + None => (0i32, 0i32), + }; + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]outgoing-body.finish"] + fn wit_import(_: i32, _: i32, _: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i32, _: *mut u8) { + unreachable!() + } + wit_import( + (&this).take_handle() as i32, + result0_0, + result0_1, + ptr1, + ); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(8).cast::()); + let v65 = match l3 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e65 = { + let l4 = i32::from(*ptr1.add(16).cast::()); + let l8 = i32::from(*ptr1.add(28).cast::()); + DnsErrorPayload { + rcode: match l4 { + 0 => None, + 1 => { + let e = { + let l5 = *ptr1.add(20).cast::<*mut u8>(); + let l6 = *ptr1.add(24).cast::(); + let len7 = l6; + let bytes7 = _rt::Vec::from_raw_parts( + l5.cast(), + len7, + len7, + ); + _rt::string_lift(bytes7) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l8 { + 0 => None, + 1 => { + let e = { + let l9 = i32::from(*ptr1.add(30).cast::()); + l9 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e65) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e65 = { + let l10 = i32::from(*ptr1.add(16).cast::()); + let l12 = i32::from(*ptr1.add(20).cast::()); + TlsAlertReceivedPayload { + alert_id: match l10 { + 0 => None, + 1 => { + let e = { + let l11 = i32::from(*ptr1.add(17).cast::()); + l11 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l12 { + 0 => None, + 1 => { + let e = { + let l13 = *ptr1.add(24).cast::<*mut u8>(); + let l14 = *ptr1.add(28).cast::(); + let len15 = l14; + let bytes15 = _rt::Vec::from_raw_parts( + l13.cast(), + len15, + len15, + ); + _rt::string_lift(bytes15) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e65) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e65 = { + let l16 = i32::from(*ptr1.add(16).cast::()); + match l16 { + 0 => None, + 1 => { + let e = { + let l17 = *ptr1.add(24).cast::(); + l17 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e65) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e65 = { + let l18 = i32::from(*ptr1.add(16).cast::()); + match l18 { + 0 => None, + 1 => { + let e = { + let l19 = *ptr1.add(20).cast::(); + l19 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e65) + } + 22 => { + let e65 = { + let l20 = i32::from(*ptr1.add(16).cast::()); + match l20 { + 0 => None, + 1 => { + let e = { + let l21 = i32::from(*ptr1.add(20).cast::()); + let l25 = i32::from(*ptr1.add(32).cast::()); + FieldSizePayload { + field_name: match l21 { + 0 => None, + 1 => { + let e = { + let l22 = *ptr1.add(24).cast::<*mut u8>(); + let l23 = *ptr1.add(28).cast::(); + let len24 = l23; + let bytes24 = _rt::Vec::from_raw_parts( + l22.cast(), + len24, + len24, + ); + _rt::string_lift(bytes24) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l25 { + 0 => None, + 1 => { + let e = { + let l26 = *ptr1.add(36).cast::(); + l26 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e65) + } + 23 => { + let e65 = { + let l27 = i32::from(*ptr1.add(16).cast::()); + match l27 { + 0 => None, + 1 => { + let e = { + let l28 = *ptr1.add(20).cast::(); + l28 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e65) + } + 24 => { + let e65 = { + let l29 = i32::from(*ptr1.add(16).cast::()); + let l33 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l29 { + 0 => None, + 1 => { + let e = { + let l30 = *ptr1.add(20).cast::<*mut u8>(); + let l31 = *ptr1.add(24).cast::(); + let len32 = l31; + let bytes32 = _rt::Vec::from_raw_parts( + l30.cast(), + len32, + len32, + ); + _rt::string_lift(bytes32) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l33 { + 0 => None, + 1 => { + let e = { + let l34 = *ptr1.add(32).cast::(); + l34 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e65) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e65 = { + let l35 = i32::from(*ptr1.add(16).cast::()); + match l35 { + 0 => None, + 1 => { + let e = { + let l36 = *ptr1.add(20).cast::(); + l36 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e65) + } + 27 => { + let e65 = { + let l37 = i32::from(*ptr1.add(16).cast::()); + let l41 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l37 { + 0 => None, + 1 => { + let e = { + let l38 = *ptr1.add(20).cast::<*mut u8>(); + let l39 = *ptr1.add(24).cast::(); + let len40 = l39; + let bytes40 = _rt::Vec::from_raw_parts( + l38.cast(), + len40, + len40, + ); + _rt::string_lift(bytes40) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l41 { + 0 => None, + 1 => { + let e = { + let l42 = *ptr1.add(32).cast::(); + l42 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e65) + } + 28 => { + let e65 = { + let l43 = i32::from(*ptr1.add(16).cast::()); + match l43 { + 0 => None, + 1 => { + let e = { + let l44 = *ptr1.add(24).cast::(); + l44 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e65) + } + 29 => { + let e65 = { + let l45 = i32::from(*ptr1.add(16).cast::()); + match l45 { + 0 => None, + 1 => { + let e = { + let l46 = *ptr1.add(20).cast::(); + l46 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e65) + } + 30 => { + let e65 = { + let l47 = i32::from(*ptr1.add(16).cast::()); + let l51 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l47 { + 0 => None, + 1 => { + let e = { + let l48 = *ptr1.add(20).cast::<*mut u8>(); + let l49 = *ptr1.add(24).cast::(); + let len50 = l49; + let bytes50 = _rt::Vec::from_raw_parts( + l48.cast(), + len50, + len50, + ); + _rt::string_lift(bytes50) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l51 { + 0 => None, + 1 => { + let e = { + let l52 = *ptr1.add(32).cast::(); + l52 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e65) + } + 31 => { + let e65 = { + let l53 = i32::from(*ptr1.add(16).cast::()); + match l53 { + 0 => None, + 1 => { + let e = { + let l54 = *ptr1.add(20).cast::<*mut u8>(); + let l55 = *ptr1.add(24).cast::(); + let len56 = l55; + let bytes56 = _rt::Vec::from_raw_parts( + l54.cast(), + len56, + len56, + ); + _rt::string_lift(bytes56) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e65) + } + 32 => { + let e65 = { + let l57 = i32::from(*ptr1.add(16).cast::()); + match l57 { + 0 => None, + 1 => { + let e = { + let l58 = *ptr1.add(20).cast::<*mut u8>(); + let l59 = *ptr1.add(24).cast::(); + let len60 = l59; + let bytes60 = _rt::Vec::from_raw_parts( + l58.cast(), + len60, + len60, + ); + _rt::string_lift(bytes60) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e65) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e65 = { + let l61 = i32::from(*ptr1.add(16).cast::()); + match l61 { + 0 => None, + 1 => { + let e = { + let l62 = *ptr1.add(20).cast::<*mut u8>(); + let l63 = *ptr1.add(24).cast::(); + let len64 = l63; + let bytes64 = _rt::Vec::from_raw_parts( + l62.cast(), + len64, + len64, + ); + _rt::string_lift(bytes64) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e65) + } + }; + v65 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl FutureIncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-incoming-response.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl FutureIncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + pub fn get( + &self, + ) -> Option, ()>> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 56]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 56], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-incoming-response.get"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + match l2 { + 0 => { + let e = { + let l3 = i32::from(*ptr0.add(16).cast::()); + match l3 { + 0 => { + let e = { + let l4 = *ptr0.add(24).cast::(); + IncomingResponse::from_handle(l4 as u32) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(24).cast::()); + let v67 = match l5 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e67 = { + let l6 = i32::from(*ptr0.add(32).cast::()); + let l10 = i32::from(*ptr0.add(44).cast::()); + DnsErrorPayload { + rcode: match l6 { + 0 => None, + 1 => { + let e = { + let l7 = *ptr0.add(36).cast::<*mut u8>(); + let l8 = *ptr0.add(40).cast::(); + let len9 = l8; + let bytes9 = _rt::Vec::from_raw_parts( + l7.cast(), + len9, + len9, + ); + _rt::string_lift(bytes9) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l10 { + 0 => None, + 1 => { + let e = { + let l11 = i32::from(*ptr0.add(46).cast::()); + l11 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e67) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e67 = { + let l12 = i32::from(*ptr0.add(32).cast::()); + let l14 = i32::from(*ptr0.add(36).cast::()); + TlsAlertReceivedPayload { + alert_id: match l12 { + 0 => None, + 1 => { + let e = { + let l13 = i32::from(*ptr0.add(33).cast::()); + l13 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l14 { + 0 => None, + 1 => { + let e = { + let l15 = *ptr0.add(40).cast::<*mut u8>(); + let l16 = *ptr0.add(44).cast::(); + let len17 = l16; + let bytes17 = _rt::Vec::from_raw_parts( + l15.cast(), + len17, + len17, + ); + _rt::string_lift(bytes17) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e67) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e67 = { + let l18 = i32::from(*ptr0.add(32).cast::()); + match l18 { + 0 => None, + 1 => { + let e = { + let l19 = *ptr0.add(40).cast::(); + l19 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e67) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e67 = { + let l20 = i32::from(*ptr0.add(32).cast::()); + match l20 { + 0 => None, + 1 => { + let e = { + let l21 = *ptr0.add(36).cast::(); + l21 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e67) + } + 22 => { + let e67 = { + let l22 = i32::from(*ptr0.add(32).cast::()); + match l22 { + 0 => None, + 1 => { + let e = { + let l23 = i32::from(*ptr0.add(36).cast::()); + let l27 = i32::from(*ptr0.add(48).cast::()); + FieldSizePayload { + field_name: match l23 { + 0 => None, + 1 => { + let e = { + let l24 = *ptr0.add(40).cast::<*mut u8>(); + let l25 = *ptr0.add(44).cast::(); + let len26 = l25; + let bytes26 = _rt::Vec::from_raw_parts( + l24.cast(), + len26, + len26, + ); + _rt::string_lift(bytes26) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l27 { + 0 => None, + 1 => { + let e = { + let l28 = *ptr0.add(52).cast::(); + l28 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e67) + } + 23 => { + let e67 = { + let l29 = i32::from(*ptr0.add(32).cast::()); + match l29 { + 0 => None, + 1 => { + let e = { + let l30 = *ptr0.add(36).cast::(); + l30 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e67) + } + 24 => { + let e67 = { + let l31 = i32::from(*ptr0.add(32).cast::()); + let l35 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l31 { + 0 => None, + 1 => { + let e = { + let l32 = *ptr0.add(36).cast::<*mut u8>(); + let l33 = *ptr0.add(40).cast::(); + let len34 = l33; + let bytes34 = _rt::Vec::from_raw_parts( + l32.cast(), + len34, + len34, + ); + _rt::string_lift(bytes34) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l35 { + 0 => None, + 1 => { + let e = { + let l36 = *ptr0.add(48).cast::(); + l36 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e67) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e67 = { + let l37 = i32::from(*ptr0.add(32).cast::()); + match l37 { + 0 => None, + 1 => { + let e = { + let l38 = *ptr0.add(36).cast::(); + l38 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e67) + } + 27 => { + let e67 = { + let l39 = i32::from(*ptr0.add(32).cast::()); + let l43 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l39 { + 0 => None, + 1 => { + let e = { + let l40 = *ptr0.add(36).cast::<*mut u8>(); + let l41 = *ptr0.add(40).cast::(); + let len42 = l41; + let bytes42 = _rt::Vec::from_raw_parts( + l40.cast(), + len42, + len42, + ); + _rt::string_lift(bytes42) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l43 { + 0 => None, + 1 => { + let e = { + let l44 = *ptr0.add(48).cast::(); + l44 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e67) + } + 28 => { + let e67 = { + let l45 = i32::from(*ptr0.add(32).cast::()); + match l45 { + 0 => None, + 1 => { + let e = { + let l46 = *ptr0.add(40).cast::(); + l46 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e67) + } + 29 => { + let e67 = { + let l47 = i32::from(*ptr0.add(32).cast::()); + match l47 { + 0 => None, + 1 => { + let e = { + let l48 = *ptr0.add(36).cast::(); + l48 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e67) + } + 30 => { + let e67 = { + let l49 = i32::from(*ptr0.add(32).cast::()); + let l53 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l49 { + 0 => None, + 1 => { + let e = { + let l50 = *ptr0.add(36).cast::<*mut u8>(); + let l51 = *ptr0.add(40).cast::(); + let len52 = l51; + let bytes52 = _rt::Vec::from_raw_parts( + l50.cast(), + len52, + len52, + ); + _rt::string_lift(bytes52) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l53 { + 0 => None, + 1 => { + let e = { + let l54 = *ptr0.add(48).cast::(); + l54 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e67) + } + 31 => { + let e67 = { + let l55 = i32::from(*ptr0.add(32).cast::()); + match l55 { + 0 => None, + 1 => { + let e = { + let l56 = *ptr0.add(36).cast::<*mut u8>(); + let l57 = *ptr0.add(40).cast::(); + let len58 = l57; + let bytes58 = _rt::Vec::from_raw_parts( + l56.cast(), + len58, + len58, + ); + _rt::string_lift(bytes58) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e67) + } + 32 => { + let e67 = { + let l59 = i32::from(*ptr0.add(32).cast::()); + match l59 { + 0 => None, + 1 => { + let e = { + let l60 = *ptr0.add(36).cast::<*mut u8>(); + let l61 = *ptr0.add(40).cast::(); + let len62 = l61; + let bytes62 = _rt::Vec::from_raw_parts( + l60.cast(), + len62, + len62, + ); + _rt::string_lift(bytes62) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e67) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e67 = { + let l63 = i32::from(*ptr0.add(32).cast::()); + match l63 { + 0 => None, + 1 => { + let e = { + let l64 = *ptr0.add(36).cast::<*mut u8>(); + let l65 = *ptr0.add(40).cast::(); + let len66 = l65; + let bytes66 = _rt::Vec::from_raw_parts( + l64.cast(), + len66, + len66, + ); + _rt::string_lift(bytes66) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e67) + } + }; + v67 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + } + } + #[allow(dead_code)] + pub mod io { + #[allow(dead_code, clippy::all)] + pub mod poll { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + /// `pollable` represents a single I/O event which may be ready, or not. + #[derive(Debug)] + #[repr(transparent)] + pub struct Pollable { + handle: _rt::Resource, + } + impl Pollable { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Pollable { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]pollable"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl Pollable { + #[allow(unused_unsafe, clippy::all)] + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + pub fn ready(&self) -> bool { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[method]pollable.ready"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + _rt::bool_lift(ret as u8) + } + } + } + impl Pollable { + #[allow(unused_unsafe, clippy::all)] + /// `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. + pub fn block(&self) { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[method]pollable.block"] + fn wit_import(_: i32); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) { + unreachable!() + } + wit_import((self).handle() as i32); + } + } + } + #[allow(unused_unsafe, clippy::all)] + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being ready for I/O. + pub fn poll(in_: &[&Pollable]) -> _rt::Vec { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea([::core::mem::MaybeUninit::uninit(); 8]); + let vec0 = in_; + let len0 = vec0.len(); + let layout0 = _rt::alloc::Layout::from_size_align_unchecked( + vec0.len() * 4, + 4, + ); + let result0 = if layout0.size() != 0 { + let ptr = _rt::alloc::alloc(layout0).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout0); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec0.into_iter().enumerate() { + let base = result0.add(i * 4); + { + *base.add(0).cast::() = (e).handle() as i32; + } + } + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "poll"] + fn wit_import(_: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import(result0, len0, ptr1); + let l2 = *ptr1.add(0).cast::<*mut u8>(); + let l3 = *ptr1.add(4).cast::(); + let len4 = l3; + if layout0.size() != 0 { + _rt::alloc::dealloc(result0.cast(), layout0); + } + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + } + } + } + #[allow(dead_code, clippy::all)] + pub mod error { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + #[derive(Debug)] + #[repr(transparent)] + pub struct Error { + handle: _rt::Resource, + } + impl Error { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Error { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/error@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]error"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl Error { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn to_debug_string(&self) -> _rt::String { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/error@0.2.3")] + extern "C" { + #[link_name = "[method]error.to-debug-string"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = *ptr0.add(0).cast::<*mut u8>(); + let l2 = *ptr0.add(4).cast::(); + let len3 = l2; + let bytes3 = _rt::Vec::from_raw_parts(l1.cast(), len3, len3); + _rt::string_lift(bytes3) + } + } + } + } + #[allow(dead_code, clippy::all)] + pub mod streams { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Error = super::super::super::wasi::io::error::Error; + pub type Pollable = super::super::super::wasi::io::poll::Pollable; + /// An error for input-stream and output-stream operations. + pub enum StreamError { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + LastOperationFailed(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, + } + impl ::core::fmt::Debug for StreamError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + StreamError::LastOperationFailed(e) => { + f.debug_tuple("StreamError::LastOperationFailed") + .field(e) + .finish() + } + StreamError::Closed => { + f.debug_tuple("StreamError::Closed").finish() + } + } + } + } + impl ::core::fmt::Display for StreamError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for StreamError {} + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct InputStream { + handle: _rt::Resource, + } + impl InputStream { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for InputStream { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]input-stream"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutputStream { + handle: _rt::Resource, + } + impl OutputStream { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutputStream { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]output-stream"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn read(&self, len: u64) -> Result<_rt::Vec, StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.read"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(4).cast::()); + let v7 = match l5 { + 0 => { + let e7 = { + let l6 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l6 as u32, + ) + }; + StreamError::LastOperationFailed(e7) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v7 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + pub fn blocking_read( + &self, + len: u64, + ) -> Result<_rt::Vec, StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.blocking-read"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(4).cast::()); + let v7 = match l5 { + 0 => { + let e7 = { + let l6 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l6 as u32, + ) + }; + StreamError::LastOperationFailed(e7) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v7 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn skip(&self, len: u64) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.skip"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + pub fn blocking_skip(&self, len: u64) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.blocking-skip"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn check_write(&self) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.check-write"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write(&self, contents: &[u8]) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let vec0 = contents; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.write"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(4).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr1.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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 + /// ``` + pub fn blocking_write_and_flush( + &self, + contents: &[u8], + ) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let vec0 = contents; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-write-and-flush"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(4).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr1.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn flush(&self) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.flush"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + pub fn blocking_flush(&self) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-flush"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write_zeroes(&self, len: u64) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.write-zeroes"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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 + /// ``` + pub fn blocking_write_zeroes_and_flush( + &self, + len: u64, + ) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-write-zeroes-and-flush"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + pub fn splice( + &self, + src: &InputStream, + len: u64, + ) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.splice"] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import( + (self).handle() as i32, + (src).handle() as i32, + _rt::as_i64(&len), + ptr0, + ); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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`. + pub fn blocking_splice( + &self, + src: &InputStream, + len: u64, + ) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-splice"] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import( + (self).handle() as i32, + (src).handle() as i32, + _rt::as_i64(&len), + ptr0, + ); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + } + } +} +#[allow(dead_code)] +pub mod exports { + #[allow(dead_code)] + pub mod wasi { + #[allow(dead_code)] + pub mod http { + #[allow(dead_code, clippy::all)] + pub mod incoming_handler { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::super::__link_custom_section_describing_imports; + use super::super::super::super::_rt; + pub type IncomingRequest = super::super::super::super::wasi::http::types::IncomingRequest; + pub type ResponseOutparam = super::super::super::super::wasi::http::types::ResponseOutparam; + #[doc(hidden)] + #[allow(non_snake_case)] + pub unsafe fn _export_handle_cabi(arg0: i32, arg1: i32) { + #[cfg(target_arch = "wasm32")] _rt::run_ctors_once(); + T::handle( + super::super::super::super::wasi::http::types::IncomingRequest::from_handle( + arg0 as u32, + ), + super::super::super::super::wasi::http::types::ResponseOutparam::from_handle( + arg1 as u32, + ), + ); + } + pub trait Guest { + /// 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. + fn handle(request: IncomingRequest, response_out: ResponseOutparam); + } + #[doc(hidden)] + macro_rules! __export_wasi_http_incoming_handler_0_2_3_cabi { + ($ty:ident with_types_in $($path_to_types:tt)*) => { + const _ : () = { #[export_name = + "wasi:http/incoming-handler@0.2.3#handle"] unsafe extern "C" fn + export_handle(arg0 : i32, arg1 : i32,) { $($path_to_types)*:: + _export_handle_cabi::<$ty > (arg0, arg1) } }; + }; + } + #[doc(hidden)] + pub(crate) use __export_wasi_http_incoming_handler_0_2_3_cabi; + } + } + } +} +mod _rt { + use core::fmt; + use core::marker; + use core::sync::atomic::{AtomicU32, Ordering::Relaxed}; + /// A type which represents a component model resource, either imported or + /// exported into this component. + /// + /// This is a low-level wrapper which handles the lifetime of the resource + /// (namely this has a destructor). The `T` provided defines the component model + /// intrinsics that this wrapper uses. + /// + /// One of the chief purposes of this type is to provide `Deref` implementations + /// to access the underlying data when it is owned. + /// + /// This type is primarily used in generated code for exported and imported + /// resources. + #[repr(transparent)] + pub struct Resource { + handle: AtomicU32, + _marker: marker::PhantomData, + } + /// A trait which all wasm resources implement, namely providing the ability to + /// drop a resource. + /// + /// This generally is implemented by generated code, not user-facing code. + #[allow(clippy::missing_safety_doc)] + pub unsafe trait WasmResource { + /// Invokes the `[resource-drop]...` intrinsic. + unsafe fn drop(handle: u32); + } + impl Resource { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + debug_assert!(handle != u32::MAX); + Self { + handle: AtomicU32::new(handle), + _marker: marker::PhantomData, + } + } + /// Takes ownership of the handle owned by `resource`. + /// + /// Note that this ideally would be `into_handle` taking `Resource` by + /// ownership. The code generator does not enable that in all situations, + /// unfortunately, so this is provided instead. + /// + /// Also note that `take_handle` is in theory only ever called on values + /// owned by a generated function. For example a generated function might + /// take `Resource` as an argument but then call `take_handle` on a + /// reference to that argument. In that sense the dynamic nature of + /// `take_handle` should only be exposed internally to generated code, not + /// to user code. + #[doc(hidden)] + pub fn take_handle(resource: &Resource) -> u32 { + resource.handle.swap(u32::MAX, Relaxed) + } + #[doc(hidden)] + pub fn handle(resource: &Resource) -> u32 { + resource.handle.load(Relaxed) + } + } + impl fmt::Debug for Resource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Resource").field("handle", &self.handle).finish() + } + } + impl Drop for Resource { + fn drop(&mut self) { + unsafe { + match self.handle.load(Relaxed) { + u32::MAX => {} + other => T::drop(other), + } + } + } + } + pub unsafe fn bool_lift(val: u8) -> bool { + if cfg!(debug_assertions) { + match val { + 0 => false, + 1 => true, + _ => panic!("invalid bool discriminant"), + } + } else { + val != 0 + } + } + pub use alloc_crate::vec::Vec; + pub use alloc_crate::alloc; + pub fn as_i64(t: T) -> i64 { + t.as_i64() + } + pub trait AsI64 { + fn as_i64(self) -> i64; + } + impl<'a, T: Copy + AsI64> AsI64 for &'a T { + fn as_i64(self) -> i64 { + (*self).as_i64() + } + } + impl AsI64 for i64 { + #[inline] + fn as_i64(self) -> i64 { + self as i64 + } + } + impl AsI64 for u64 { + #[inline] + fn as_i64(self) -> i64 { + self as i64 + } + } + pub use alloc_crate::string::String; + pub unsafe fn string_lift(bytes: Vec) -> String { + if cfg!(debug_assertions) { + String::from_utf8(bytes).unwrap() + } else { + String::from_utf8_unchecked(bytes) + } + } + pub unsafe fn invalid_enum_discriminant() -> T { + if cfg!(debug_assertions) { + panic!("invalid enum discriminant") + } else { + core::hint::unreachable_unchecked() + } + } + pub unsafe fn cabi_dealloc(ptr: *mut u8, size: usize, align: usize) { + if size == 0 { + return; + } + let layout = alloc::Layout::from_size_align_unchecked(size, align); + alloc::dealloc(ptr, layout); + } + pub fn as_i32(t: T) -> i32 { + t.as_i32() + } + pub trait AsI32 { + fn as_i32(self) -> i32; + } + impl<'a, T: Copy + AsI32> AsI32 for &'a T { + fn as_i32(self) -> i32 { + (*self).as_i32() + } + } + impl AsI32 for i32 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u32 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for i16 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u16 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for i8 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u8 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for char { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for usize { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + #[cfg(target_arch = "wasm32")] + pub fn run_ctors_once() { + wit_bindgen_rt::run_ctors_once(); + } + extern crate alloc as alloc_crate; +} +/// Generates `#[no_mangle]` functions to export the specified type as the +/// root implementation of all generated traits. +/// +/// For more information see the documentation of `wit_bindgen::generate!`. +/// +/// ```rust +/// # macro_rules! export{ ($($t:tt)*) => (); } +/// # trait Guest {} +/// struct MyType; +/// +/// impl Guest for MyType { +/// // ... +/// } +/// +/// export!(MyType); +/// ``` +#[allow(unused_macros)] +#[doc(hidden)] +macro_rules! __export_api_impl { + ($ty:ident) => { + self::export!($ty with_types_in self); + }; + ($ty:ident with_types_in $($path_to_types_root:tt)*) => { + $($path_to_types_root)*:: + exports::wasi::http::incoming_handler::__export_wasi_http_incoming_handler_0_2_3_cabi!($ty + with_types_in $($path_to_types_root)*:: exports::wasi::http::incoming_handler); + }; +} +#[doc(inline)] +pub(crate) use __export_api_impl as export; +#[cfg(target_arch = "wasm32")] +#[link_section = "component-type:wit-bindgen:0.35.0:golem:handler:api:encoded world"] +#[doc(hidden)] +pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; 6330] = *b"\ +\0asm\x0d\0\x01\0\0\x19\x16wit-component-encoding\x04\0\x07\xc00\x01A\x02\x01A\x13\ +\x01B\x0a\x04\0\x08pollable\x03\x01\x01h\0\x01@\x01\x04self\x01\0\x7f\x04\0\x16[\ +method]pollable.ready\x01\x02\x01@\x01\x04self\x01\x01\0\x04\0\x16[method]pollab\ +le.block\x01\x03\x01p\x01\x01py\x01@\x01\x02in\x04\0\x05\x04\0\x04poll\x01\x06\x03\ +\0\x12wasi:io/poll@0.2.3\x05\0\x02\x03\0\0\x08pollable\x01B\x0f\x02\x03\x02\x01\x01\ +\x04\0\x08pollable\x03\0\0\x01w\x04\0\x07instant\x03\0\x02\x01w\x04\0\x08duratio\ +n\x03\0\x04\x01@\0\0\x03\x04\0\x03now\x01\x06\x01@\0\0\x05\x04\0\x0aresolution\x01\ +\x07\x01i\x01\x01@\x01\x04when\x03\0\x08\x04\0\x11subscribe-instant\x01\x09\x01@\ +\x01\x04when\x05\0\x08\x04\0\x12subscribe-duration\x01\x0a\x03\0!wasi:clocks/mon\ +otonic-clock@0.2.3\x05\x02\x01B\x04\x04\0\x05error\x03\x01\x01h\0\x01@\x01\x04se\ +lf\x01\0s\x04\0\x1d[method]error.to-debug-string\x01\x02\x03\0\x13wasi:io/error@\ +0.2.3\x05\x03\x02\x03\0\x02\x05error\x01B(\x02\x03\x02\x01\x04\x04\0\x05error\x03\ +\0\0\x02\x03\x02\x01\x01\x04\0\x08pollable\x03\0\x02\x01i\x01\x01q\x02\x15last-o\ +peration-failed\x01\x04\0\x06closed\0\0\x04\0\x0cstream-error\x03\0\x05\x04\0\x0c\ +input-stream\x03\x01\x04\0\x0doutput-stream\x03\x01\x01h\x07\x01p}\x01j\x01\x0a\x01\ +\x06\x01@\x02\x04self\x09\x03lenw\0\x0b\x04\0\x19[method]input-stream.read\x01\x0c\ +\x04\0\"[method]input-stream.blocking-read\x01\x0c\x01j\x01w\x01\x06\x01@\x02\x04\ +self\x09\x03lenw\0\x0d\x04\0\x19[method]input-stream.skip\x01\x0e\x04\0\"[method\ +]input-stream.blocking-skip\x01\x0e\x01i\x03\x01@\x01\x04self\x09\0\x0f\x04\0\x1e\ +[method]input-stream.subscribe\x01\x10\x01h\x08\x01@\x01\x04self\x11\0\x0d\x04\0\ +![method]output-stream.check-write\x01\x12\x01j\0\x01\x06\x01@\x02\x04self\x11\x08\ +contents\x0a\0\x13\x04\0\x1b[method]output-stream.write\x01\x14\x04\0.[method]ou\ +tput-stream.blocking-write-and-flush\x01\x14\x01@\x01\x04self\x11\0\x13\x04\0\x1b\ +[method]output-stream.flush\x01\x15\x04\0$[method]output-stream.blocking-flush\x01\ +\x15\x01@\x01\x04self\x11\0\x0f\x04\0\x1f[method]output-stream.subscribe\x01\x16\ +\x01@\x02\x04self\x11\x03lenw\0\x13\x04\0\"[method]output-stream.write-zeroes\x01\ +\x17\x04\05[method]output-stream.blocking-write-zeroes-and-flush\x01\x17\x01@\x03\ +\x04self\x11\x03src\x09\x03lenw\0\x0d\x04\0\x1c[method]output-stream.splice\x01\x18\ +\x04\0%[method]output-stream.blocking-splice\x01\x18\x03\0\x15wasi:io/streams@0.\ +2.3\x05\x05\x02\x03\0\x01\x08duration\x02\x03\0\x03\x0cinput-stream\x02\x03\0\x03\ +\x0doutput-stream\x01B\xc1\x01\x02\x03\x02\x01\x06\x04\0\x08duration\x03\0\0\x02\ +\x03\x02\x01\x07\x04\0\x0cinput-stream\x03\0\x02\x02\x03\x02\x01\x08\x04\0\x0dou\ +tput-stream\x03\0\x04\x02\x03\x02\x01\x04\x04\0\x08io-error\x03\0\x06\x02\x03\x02\ +\x01\x01\x04\0\x08pollable\x03\0\x08\x01q\x0a\x03get\0\0\x04head\0\0\x04post\0\0\ +\x03put\0\0\x06delete\0\0\x07connect\0\0\x07options\0\0\x05trace\0\0\x05patch\0\0\ +\x05other\x01s\0\x04\0\x06method\x03\0\x0a\x01q\x03\x04HTTP\0\0\x05HTTPS\0\0\x05\ +other\x01s\0\x04\0\x06scheme\x03\0\x0c\x01ks\x01k{\x01r\x02\x05rcode\x0e\x09info\ +-code\x0f\x04\0\x11DNS-error-payload\x03\0\x10\x01k}\x01r\x02\x08alert-id\x12\x0d\ +alert-message\x0e\x04\0\x1aTLS-alert-received-payload\x03\0\x13\x01ky\x01r\x02\x0a\ +field-name\x0e\x0afield-size\x15\x04\0\x12field-size-payload\x03\0\x16\x01kw\x01\ +k\x17\x01q'\x0bDNS-timeout\0\0\x09DNS-error\x01\x11\0\x15destination-not-found\0\ +\0\x17destination-unavailable\0\0\x19destination-IP-prohibited\0\0\x19destinatio\ +n-IP-unroutable\0\0\x12connection-refused\0\0\x15connection-terminated\0\0\x12co\ +nnection-timeout\0\0\x17connection-read-timeout\0\0\x18connection-write-timeout\0\ +\0\x18connection-limit-reached\0\0\x12TLS-protocol-error\0\0\x15TLS-certificate-\ +error\0\0\x12TLS-alert-received\x01\x14\0\x13HTTP-request-denied\0\0\x1cHTTP-req\ +uest-length-required\0\0\x16HTTP-request-body-size\x01\x18\0\x1bHTTP-request-met\ +hod-invalid\0\0\x18HTTP-request-URI-invalid\0\0\x19HTTP-request-URI-too-long\0\0\ +\x20HTTP-request-header-section-size\x01\x15\0\x18HTTP-request-header-size\x01\x19\ +\0!HTTP-request-trailer-section-size\x01\x15\0\x19HTTP-request-trailer-size\x01\x17\ +\0\x18HTTP-response-incomplete\0\0!HTTP-response-header-section-size\x01\x15\0\x19\ +HTTP-response-header-size\x01\x17\0\x17HTTP-response-body-size\x01\x18\0\"HTTP-r\ +esponse-trailer-section-size\x01\x15\0\x1aHTTP-response-trailer-size\x01\x17\0\x1d\ +HTTP-response-transfer-coding\x01\x0e\0\x1cHTTP-response-content-coding\x01\x0e\0\ +\x15HTTP-response-timeout\0\0\x13HTTP-upgrade-failed\0\0\x13HTTP-protocol-error\0\ +\0\x0dloop-detected\0\0\x13configuration-error\0\0\x0einternal-error\x01\x0e\0\x04\ +\0\x0aerror-code\x03\0\x1a\x01q\x03\x0einvalid-syntax\0\0\x09forbidden\0\0\x09im\ +mutable\0\0\x04\0\x0cheader-error\x03\0\x1c\x01s\x04\0\x09field-key\x03\0\x1e\x04\ +\0\x0afield-name\x03\0\x1f\x01p}\x04\0\x0bfield-value\x03\0!\x04\0\x06fields\x03\ +\x01\x04\0\x07headers\x03\0#\x04\0\x08trailers\x03\0#\x04\0\x10incoming-request\x03\ +\x01\x04\0\x10outgoing-request\x03\x01\x04\0\x0frequest-options\x03\x01\x04\0\x11\ +response-outparam\x03\x01\x01{\x04\0\x0bstatus-code\x03\0*\x04\0\x11incoming-res\ +ponse\x03\x01\x04\0\x0dincoming-body\x03\x01\x04\0\x0ffuture-trailers\x03\x01\x04\ +\0\x11outgoing-response\x03\x01\x04\0\x0doutgoing-body\x03\x01\x04\0\x18future-i\ +ncoming-response\x03\x01\x01i#\x01@\0\02\x04\0\x13[constructor]fields\x013\x01o\x02\ +\x20\"\x01p4\x01j\x012\x01\x1d\x01@\x01\x07entries5\06\x04\0\x18[static]fields.f\ +rom-list\x017\x01h#\x01p\"\x01@\x02\x04self8\x04name\x20\09\x04\0\x12[method]fie\ +lds.get\x01:\x01@\x02\x04self8\x04name\x20\0\x7f\x04\0\x12[method]fields.has\x01\ +;\x01j\0\x01\x1d\x01@\x03\x04self8\x04name\x20\x05value9\0<\x04\0\x12[method]fie\ +lds.set\x01=\x01@\x02\x04self8\x04name\x20\0<\x04\0\x15[method]fields.delete\x01\ +>\x01@\x03\x04self8\x04name\x20\x05value\"\0<\x04\0\x15[method]fields.append\x01\ +?\x01@\x01\x04self8\05\x04\0\x16[method]fields.entries\x01@\x01@\x01\x04self8\02\ +\x04\0\x14[method]fields.clone\x01A\x01h&\x01@\x01\x04self\xc2\0\0\x0b\x04\0\x1f\ +[method]incoming-request.method\x01C\x01@\x01\x04self\xc2\0\0\x0e\x04\0([method]\ +incoming-request.path-with-query\x01D\x01k\x0d\x01@\x01\x04self\xc2\0\0\xc5\0\x04\ +\0\x1f[method]incoming-request.scheme\x01F\x04\0\"[method]incoming-request.autho\ +rity\x01D\x01i$\x01@\x01\x04self\xc2\0\0\xc7\0\x04\0\x20[method]incoming-request\ +.headers\x01H\x01i-\x01j\x01\xc9\0\0\x01@\x01\x04self\xc2\0\0\xca\0\x04\0\x20[me\ +thod]incoming-request.consume\x01K\x01i'\x01@\x01\x07headers\xc7\0\0\xcc\0\x04\0\ +\x1d[constructor]outgoing-request\x01M\x01h'\x01i0\x01j\x01\xcf\0\0\x01@\x01\x04\ +self\xce\0\0\xd0\0\x04\0\x1d[method]outgoing-request.body\x01Q\x01@\x01\x04self\xce\ +\0\0\x0b\x04\0\x1f[method]outgoing-request.method\x01R\x01j\0\0\x01@\x02\x04self\ +\xce\0\x06method\x0b\0\xd3\0\x04\0#[method]outgoing-request.set-method\x01T\x01@\ +\x01\x04self\xce\0\0\x0e\x04\0([method]outgoing-request.path-with-query\x01U\x01\ +@\x02\x04self\xce\0\x0fpath-with-query\x0e\0\xd3\0\x04\0,[method]outgoing-reques\ +t.set-path-with-query\x01V\x01@\x01\x04self\xce\0\0\xc5\0\x04\0\x1f[method]outgo\ +ing-request.scheme\x01W\x01@\x02\x04self\xce\0\x06scheme\xc5\0\0\xd3\0\x04\0#[me\ +thod]outgoing-request.set-scheme\x01X\x04\0\"[method]outgoing-request.authority\x01\ +U\x01@\x02\x04self\xce\0\x09authority\x0e\0\xd3\0\x04\0&[method]outgoing-request\ +.set-authority\x01Y\x01@\x01\x04self\xce\0\0\xc7\0\x04\0\x20[method]outgoing-req\ +uest.headers\x01Z\x01i(\x01@\0\0\xdb\0\x04\0\x1c[constructor]request-options\x01\ +\\\x01h(\x01k\x01\x01@\x01\x04self\xdd\0\0\xde\0\x04\0'[method]request-options.c\ +onnect-timeout\x01_\x01@\x02\x04self\xdd\0\x08duration\xde\0\0\xd3\0\x04\0+[meth\ +od]request-options.set-connect-timeout\x01`\x04\0*[method]request-options.first-\ +byte-timeout\x01_\x04\0.[method]request-options.set-first-byte-timeout\x01`\x04\0\ +-[method]request-options.between-bytes-timeout\x01_\x04\01[method]request-option\ +s.set-between-bytes-timeout\x01`\x01i)\x01i/\x01j\x01\xe2\0\x01\x1b\x01@\x02\x05\ +param\xe1\0\x08response\xe3\0\x01\0\x04\0\x1d[static]response-outparam.set\x01d\x01\ +h,\x01@\x01\x04self\xe5\0\0+\x04\0\x20[method]incoming-response.status\x01f\x01@\ +\x01\x04self\xe5\0\0\xc7\0\x04\0![method]incoming-response.headers\x01g\x01@\x01\ +\x04self\xe5\0\0\xca\0\x04\0![method]incoming-response.consume\x01h\x01h-\x01i\x03\ +\x01j\x01\xea\0\0\x01@\x01\x04self\xe9\0\0\xeb\0\x04\0\x1c[method]incoming-body.\ +stream\x01l\x01i.\x01@\x01\x04this\xc9\0\0\xed\0\x04\0\x1c[static]incoming-body.\ +finish\x01n\x01h.\x01i\x09\x01@\x01\x04self\xef\0\0\xf0\0\x04\0![method]future-t\ +railers.subscribe\x01q\x01i%\x01k\xf2\0\x01j\x01\xf3\0\x01\x1b\x01j\x01\xf4\0\0\x01\ +k\xf5\0\x01@\x01\x04self\xef\0\0\xf6\0\x04\0\x1b[method]future-trailers.get\x01w\ +\x01@\x01\x07headers\xc7\0\0\xe2\0\x04\0\x1e[constructor]outgoing-response\x01x\x01\ +h/\x01@\x01\x04self\xf9\0\0+\x04\0%[method]outgoing-response.status-code\x01z\x01\ +@\x02\x04self\xf9\0\x0bstatus-code+\0\xd3\0\x04\0)[method]outgoing-response.set-\ +status-code\x01{\x01@\x01\x04self\xf9\0\0\xc7\0\x04\0![method]outgoing-response.\ +headers\x01|\x01@\x01\x04self\xf9\0\0\xd0\0\x04\0\x1e[method]outgoing-response.b\ +ody\x01}\x01h0\x01i\x05\x01j\x01\xff\0\0\x01@\x01\x04self\xfe\0\0\x80\x01\x04\0\x1b\ +[method]outgoing-body.write\x01\x81\x01\x01j\0\x01\x1b\x01@\x02\x04this\xcf\0\x08\ +trailers\xf3\0\0\x82\x01\x04\0\x1c[static]outgoing-body.finish\x01\x83\x01\x01h1\ +\x01@\x01\x04self\x84\x01\0\xf0\0\x04\0*[method]future-incoming-response.subscri\ +be\x01\x85\x01\x01i,\x01j\x01\x86\x01\x01\x1b\x01j\x01\x87\x01\0\x01k\x88\x01\x01\ +@\x01\x04self\x84\x01\0\x89\x01\x04\0$[method]future-incoming-response.get\x01\x8a\ +\x01\x01h\x07\x01k\x1b\x01@\x01\x03err\x8b\x01\0\x8c\x01\x04\0\x0fhttp-error-cod\ +e\x01\x8d\x01\x03\0\x15wasi:http/types@0.2.3\x05\x09\x02\x03\0\x04\x10incoming-r\ +equest\x02\x03\0\x04\x11response-outparam\x01B\x08\x02\x03\x02\x01\x0a\x04\0\x10\ +incoming-request\x03\0\0\x02\x03\x02\x01\x0b\x04\0\x11response-outparam\x03\0\x02\ +\x01i\x01\x01i\x03\x01@\x02\x07request\x04\x0cresponse-out\x05\x01\0\x04\0\x06ha\ +ndle\x01\x06\x04\0\x20wasi:http/incoming-handler@0.2.3\x05\x0c\x04\0\x11golem:ha\ +ndler/api\x04\0\x0b\x09\x01\0\x03api\x03\0\0\0G\x09producers\x01\x0cprocessed-by\ +\x02\x0dwit-component\x070.220.0\x10wit-bindgen-rust\x060.35.0"; +#[inline(never)] +#[doc(hidden)] +pub fn __link_custom_section_describing_imports() { + wit_bindgen_rt::maybe_link_cabi_realloc(); +} diff --git a/test-components/wasi-http-incoming-request-handler-state/src/lib.rs b/test-components/wasi-http-incoming-request-handler-state/src/lib.rs new file mode 100644 index 0000000000..6c06a26c9c --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/src/lib.rs @@ -0,0 +1,73 @@ +mod bindings; + +use std::sync::{LazyLock, Mutex}; + +pub use bindings::wasi::http::types::{ + Fields, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam, +}; +use self::bindings::wasi::http::types::{IncomingBody, Method}; + +struct State { + last: u64, +} + +static STATE: LazyLock> = LazyLock::new(|| Mutex::new(State { last: 0 })); + +struct Component; + +impl bindings::exports::wasi::http::incoming_handler::Guest for Component { + fn handle(request: IncomingRequest, outparam: ResponseOutparam) { + match request.method() { + Method::Get => { + let current = STATE.lock().unwrap().last; + + let headers = Fields::new(); + let resp = OutgoingResponse::new(headers); + resp.set_status_code(200).unwrap(); + let body = resp.body().unwrap(); + { + let out = body.write().unwrap(); + out.blocking_write_and_flush(¤t.to_string().into_bytes()).unwrap(); + drop(out); + } + + OutgoingBody::finish(body, None).unwrap(); + ResponseOutparam::set(outparam, Ok(resp)); + }, + Method::Put => { + let mut incoming_body_data: Vec = Vec::new(); + { + let incoming_body: IncomingBody = request.consume().unwrap(); + let incoming_body_stream = incoming_body.stream().unwrap(); + loop { + let item = match incoming_body_stream.blocking_read(1024) { + Ok(x) => x, + Err(_) => break, + }; + if item.is_empty() { + break; + } + for i in item.into_iter() { + incoming_body_data.push(i); + } + } + drop(incoming_body_stream); + IncomingBody::finish(incoming_body); + } + let body_string = String::from_utf8(incoming_body_data).unwrap(); + println!("{}", body_string); + let body_number: u64 = body_string.trim().parse().unwrap(); + + STATE.lock().unwrap().last = body_number; + + let headers = Fields::new(); + let resp = OutgoingResponse::new(headers); + resp.set_status_code(200).unwrap(); + ResponseOutparam::set(outparam, Ok(resp)); + }, + _ => panic!("unsupported method") + } + } +} + +bindings::export!(Component with_types_in bindings); diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps.lock b/test-components/wasi-http-incoming-request-handler-state/wit/deps.lock new file mode 100644 index 0000000000..b97967bf09 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps.lock @@ -0,0 +1,29 @@ +[cli] +sha256 = "4dadd13d55aaf626833d1f4b9c34a17b0f04e993babd09552b785cda3b95ea76" +sha512 = "898dcc4e8c15d18acc6b88dbe232336fa4d19019430a910dbc9e7aeaace3077a164af3be9f002de6e7e65ef693df340801ac0c7e421e9a746bf1b6d698a90835" + +[clocks] +sha256 = "93a701968a7dd3c5d69031bc0601681c468972fdf7e28a93bb6150a67d6ebe8b" +sha512 = "98fca567c7a01887b0fb38981f1772169b6ea8de475b546508f8b86738d84e44ba95cae81def40ac34e8809f5f60e85224077ab8cb6d6d5d6296acc1df73c159" + +[filesystem] +sha256 = "69d42fb10a04a33545b17e055f13db9b1e10e82ba0ed5bdb52334e40dc07c679" +sha512 = "612effbac6f4804fe0c29dae20b78bbba59e52cb754c15402f5fe229c3153a221e0fbdff1d9d00ceaa3fe049c6a95523a5b99f772f1c16d972eade2c88326a30" + +[http] +url = "https://github.com/WebAssembly/wasi-http/archive/v0.2.3.tar.gz" +sha256 = "72d3a00dbf39eed40a134e8b1dee85834961153f9d205ee4dd56657270c084ce" +sha512 = "636150c464c0eb3d60bd212fc5d4012638c8cd4f89b583b87a38154ef99de828aac4296ac13c5cface10ee61e164fcfc43a5c104f916229dfdf49c0d11047677" +deps = ["cli", "clocks", "filesystem", "io", "random", "sockets"] + +[io] +sha256 = "1cccbfe4122686ea57a25cd368e8cdfc408cbcad089f47fb6685b6f92e96f050" +sha512 = "7a95f964c13da52611141acd89bc8876226497f128e99dd176a4270c5b5efbd8cc847b5fbd1a91258d028c646db99e0424d72590cf1caf20f9f3a3343fad5017" + +[random] +sha256 = "dd0c91e7125172eb8fd4568e15ad9fc7305643015e6ece4396c3cc5e8c2bf79a" +sha512 = "d1ca2e7b0616a94a3b39d1b9450bb3fb595b01fd94a8626ad75433038dde40988ecb41ab93a374d569ab72163af3b30038d7bfc3499b9c07193181f4f1d9292a" + +[sockets] +sha256 = "2bc0f65a8046207ee3330ad7d63f6fafeafd4cc0ea4084f081bd5e4f7b177e74" +sha512 = "3e5490e41547dffa78d52631825d93da8d60f4af0246cbaf97e1ecb879285953a86d5f1f390b10c32f91dd7eaec6f43e625a26b1c92c32a0c86fde428aedaaab" diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps.toml b/test-components/wasi-http-incoming-request-handler-state/wit/deps.toml new file mode 100644 index 0000000000..64ca58191a --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps.toml @@ -0,0 +1 @@ +http = "https://github.com/WebAssembly/wasi-http/archive/v0.2.3.tar.gz" diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/command.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/command.wit new file mode 100644 index 0000000000..3a81766d64 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.2.3; + +@since(version = 0.2.0) +world command { + @since(version = 0.2.0) + include imports; + + @since(version = 0.2.0) + export run; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/environment.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/environment.wit new file mode 100644 index 0000000000..2f449bd7c1 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/environment.wit @@ -0,0 +1,22 @@ +@since(version = 0.2.0) +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + @since(version = 0.2.0) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.2.0) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.2.0) + initial-cwd: func() -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/exit.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/exit.wit new file mode 100644 index 0000000000..427935c8d0 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.2.0) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.2.0) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/imports.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/imports.wit new file mode 100644 index 0000000000..8b4e3975ec --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/imports.wit @@ -0,0 +1,36 @@ +package wasi:cli@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + include wasi:clocks/imports@0.2.3; + @since(version = 0.2.0) + include wasi:filesystem/imports@0.2.3; + @since(version = 0.2.0) + include wasi:sockets/imports@0.2.3; + @since(version = 0.2.0) + include wasi:random/imports@0.2.3; + @since(version = 0.2.0) + include wasi:io/imports@0.2.3; + + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import stdin; + @since(version = 0.2.0) + import stdout; + @since(version = 0.2.0) + import stderr; + @since(version = 0.2.0) + import terminal-input; + @since(version = 0.2.0) + import terminal-output; + @since(version = 0.2.0) + import terminal-stdin; + @since(version = 0.2.0) + import terminal-stdout; + @since(version = 0.2.0) + import terminal-stderr; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/run.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/run.wit new file mode 100644 index 0000000000..655346efb6 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.2.0) +interface run { + /// Run the program. + @since(version = 0.2.0) + run: func() -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/stdio.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/stdio.wit new file mode 100644 index 0000000000..1b54f5318a --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/stdio.wit @@ -0,0 +1,26 @@ +@since(version = 0.2.0) +interface stdin { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream}; + + @since(version = 0.2.0) + get-stdin: func() -> input-stream; +} + +@since(version = 0.2.0) +interface stdout { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{output-stream}; + + @since(version = 0.2.0) + get-stdout: func() -> output-stream; +} + +@since(version = 0.2.0) +interface stderr { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{output-stream}; + + @since(version = 0.2.0) + get-stderr: func() -> output-stream; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/terminal.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/terminal.wit new file mode 100644 index 0000000000..d305498c64 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/cli/terminal.wit @@ -0,0 +1,62 @@ +/// Terminal input. +/// +/// In the future, this may include functions for disabling echoing, +/// disabling input buffering so that keyboard events are sent through +/// immediately, querying supported features, and so on. +@since(version = 0.2.0) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.2.0) + resource terminal-input; +} + +/// Terminal output. +/// +/// In the future, this may include functions for querying the terminal +/// size, being notified of terminal size changes, querying supported +/// features, and so on. +@since(version = 0.2.0) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.2.0) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdin { + @since(version = 0.2.0) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdout { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stderr { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stderr: func() -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/monotonic-clock.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 0000000000..c676fb84d8 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,50 @@ +package wasi:clocks@0.2.3; +/// WASI Monotonic Clock is a clock API intended to let users measure elapsed +/// time. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A monotonic clock is a clock which has an unspecified initial value, and +/// successive reads of the clock will produce non-decreasing values. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/timezone.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/timezone.wit new file mode 100644 index 0000000000..b43e93b233 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.3; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/wall-clock.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/wall-clock.wit new file mode 100644 index 0000000000..e00ce08933 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.3; +/// WASI Wall Clock is a clock API intended to let users query the current +/// time. The name "wall" makes an analogy to a "clock on the wall", which +/// is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A wall clock is a clock which measures the date and time according to +/// some external reference. +/// +/// External references may be reset, so this clock is not necessarily +/// monotonic, making it unsuitable for measuring elapsed time. +/// +/// It is intended for reporting the current date and time for humans. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/world.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/world.wit new file mode 100644 index 0000000000..05f04f797d --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/preopens.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/preopens.wit new file mode 100644 index 0000000000..cea97495b5 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.2.3; + +@since(version = 0.2.0) +interface preopens { + @since(version = 0.2.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.2.0) + get-directories: func() -> list>; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/types.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/types.wit new file mode 100644 index 0000000000..d229a21f48 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/types.wit @@ -0,0 +1,672 @@ +package wasi:filesystem@0.2.3; +/// WASI filesystem is a filesystem API primarily intended to let users run WASI +/// programs that access their files on their existing filesystems, without +/// significant overhead. +/// +/// It is intended to be roughly portable between Unix-family platforms and +/// Windows, though it does not hide many of the major differences. +/// +/// Paths are passed as interface-type `string`s, meaning they must consist of +/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +/// paths which are not accessible by this API. +/// +/// The directory separator in WASI is always the forward-slash (`/`). +/// +/// All paths in WASI are relative paths, and are interpreted relative to a +/// `descriptor` referring to a base directory. If a `path` argument to any WASI +/// function starts with `/`, or if any step of resolving a `path`, including +/// `..` and symbolic link steps, reaches a directory outside of the base +/// directory, or reaches a symlink to an absolute or rooted path in the +/// underlying filesystem, the function fails with `error-code::not-permitted`. +/// +/// For more information about WASI path resolution and sandboxing, see +/// [WASI filesystem path resolution]. +/// +/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream, error}; + @since(version = 0.2.0) + use wasi:clocks/wall-clock@0.2.3.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.2.0) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.2.0) + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + @since(version = 0.2.0) + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrity + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.2.0) + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.2.0) + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + @since(version = 0.2.0) + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + @since(version = 0.2.0) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.2.0) + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device, + } + + /// File or memory access pattern advisory information. + @since(version = 0.2.0) + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse, + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + @since(version = 0.2.0) + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + @since(version = 0.2.0) + resource descriptor { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + @since(version = 0.2.0) + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + @since(version = 0.2.0) + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in POSIX. + @since(version = 0.2.0) + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.2.0) + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + @since(version = 0.2.0) + sync-data: func() -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + @since(version = 0.2.0) + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + @since(version = 0.2.0) + get-type: func() -> result; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + @since(version = 0.2.0) + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + @since(version = 0.2.0) + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.2.0) + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + @since(version = 0.2.0) + read-directory: func() -> result; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + @since(version = 0.2.0) + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.2.0) + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + @since(version = 0.2.0) + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + @since(version = 0.2.0) + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + @since(version = 0.2.0) + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.2.0) + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + @since(version = 0.2.0) + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + @since(version = 0.2.0) + readlink-at: func( + /// The relative path of the symbolic link from which to read. + path: string, + ) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + @since(version = 0.2.0) + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.2.0) + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + @since(version = 0.2.0) + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + @since(version = 0.2.0) + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + @since(version = 0.2.0) + is-same-object: func(other: borrow) -> bool; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encouraged to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + @since(version = 0.2.0) + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + @since(version = 0.2.0) + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + @since(version = 0.2.0) + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + @since(version = 0.2.0) + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + @since(version = 0.2.0) + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/world.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/world.wit new file mode 100644 index 0000000000..29405bc2cc --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/handler.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/handler.wit new file mode 100644 index 0000000000..6a6c62966f --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/handler.wit @@ -0,0 +1,49 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +@since(version = 0.2.0) +interface incoming-handler { + @since(version = 0.2.0) + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + @since(version = 0.2.0) + handle: func( + request: incoming-request, + response-out: response-outparam + ); +} + +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +@since(version = 0.2.0) +interface outgoing-handler { + @since(version = 0.2.0) + use types.{ + outgoing-request, request-options, future-incoming-response, error-code + }; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + @since(version = 0.2.0) + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/proxy.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/proxy.wit new file mode 100644 index 0000000000..de3bbe8ae0 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/proxy.wit @@ -0,0 +1,50 @@ +package wasi:http@0.2.3; + +/// The `wasi:http/imports` world imports all the APIs for HTTP proxies. +/// It is intended to be `include`d in other worlds. +@since(version = 0.2.0) +world imports { + /// HTTP proxies have access to time and randomness. + @since(version = 0.2.0) + import wasi:clocks/monotonic-clock@0.2.3; + @since(version = 0.2.0) + import wasi:clocks/wall-clock@0.2.3; + @since(version = 0.2.0) + import wasi:random/random@0.2.3; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + @since(version = 0.2.0) + import wasi:cli/stdout@0.2.3; + @since(version = 0.2.0) + import wasi:cli/stderr@0.2.3; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + @since(version = 0.2.0) + import wasi:cli/stdin@0.2.3; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + @since(version = 0.2.0) + import outgoing-handler; +} + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +@since(version = 0.2.0) +world proxy { + @since(version = 0.2.0) + include imports; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + @since(version = 0.2.0) + export incoming-handler; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/types.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/types.wit new file mode 100644 index 0000000000..2498f180ad --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/http/types.wit @@ -0,0 +1,673 @@ +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.3.{duration}; + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/error@0.2.3.{error as io-error}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + + /// This type corresponds to HTTP standard Methods. + @since(version = 0.2.0) + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + @since(version = 0.2.0) + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + @since(version = 0.2.0) + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option) + } + + /// Defines the case payload type for `DNS-error` above: + @since(version = 0.2.0) + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + @since(version = 0.2.0) + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + @since(version = 0.2.0) + record field-size-payload { + field-name: option, + field-size: option + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + @since(version = 0.2.0) + http-error-code: func(err: borrow) -> option; + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + @since(version = 0.2.0) + variant header-error { + /// This error indicates that a `field-name` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + + /// This error indicates that a forbidden `field-name` was used when trying + /// to set a header in a `fields`. + forbidden, + + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + @since(version = 0.2.1) + type field-name = field-key; + + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + @since(version = 0.2.0) + @deprecated(version = 0.2.2) + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + @since(version = 0.2.0) + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + @since(version = 0.2.0) + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + @since(version = 0.2.0) + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + @since(version = 0.2.0) + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + @since(version = 0.2.0) + get: func(name: field-name) -> list; + + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + @since(version = 0.2.0) + has: func(name: field-name) -> bool; + + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + @since(version = 0.2.0) + set: func(name: field-name, value: list) -> result<_, header-error>; + + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + @since(version = 0.2.0) + delete: func(name: field-name) -> result<_, header-error>; + + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + @since(version = 0.2.0) + append: func(name: field-name, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + @since(version = 0.2.0) + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + @since(version = 0.2.0) + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + @since(version = 0.2.0) + type headers = fields; + + /// Trailers is an alias for Fields. + @since(version = 0.2.0) + type trailers = fields; + + /// Represents an incoming HTTP Request. + @since(version = 0.2.0) + resource incoming-request { + + /// Returns the method of the incoming request. + @since(version = 0.2.0) + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + @since(version = 0.2.0) + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + @since(version = 0.2.0) + scheme: func() -> option; + + /// Returns the authority of the Request's target URI, if present. + @since(version = 0.2.0) + authority: func() -> option; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + @since(version = 0.2.0) + resource outgoing-request { + + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + @since(version = 0.2.0) + constructor( + headers: headers + ); + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + @since(version = 0.2.0) + body: func() -> result; + + /// Get the Method for the Request. + @since(version = 0.2.0) + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + @since(version = 0.2.0) + set-method: func(method: method) -> result; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + @since(version = 0.2.0) + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + @since(version = 0.2.0) + set-path-with-query: func(path-with-query: option) -> result; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + @since(version = 0.2.0) + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + @since(version = 0.2.0) + set-scheme: func(scheme: option) -> result; + + /// Get the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. + @since(version = 0.2.0) + authority: func() -> option; + /// Set the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid URI authority. + @since(version = 0.2.0) + set-authority: func(authority: option) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + @since(version = 0.2.0) + resource request-options { + /// Construct a default `request-options` value. + @since(version = 0.2.0) + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + @since(version = 0.2.0) + connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + @since(version = 0.2.0) + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + @since(version = 0.2.0) + between-bytes-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + @since(version = 0.2.0) + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + @since(version = 0.2.0) + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + @since(version = 0.2.0) + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + @since(version = 0.2.0) + type status-code = u16; + + /// Represents an incoming HTTP Response. + @since(version = 0.2.0) + resource incoming-response { + + /// Returns the status code from the incoming response. + @since(version = 0.2.0) + status: func() -> status-code; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + @since(version = 0.2.0) + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + @since(version = 0.2.0) + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + @since(version = 0.2.0) + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + @since(version = 0.2.0) + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + @since(version = 0.2.0) + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + @since(version = 0.2.0) + resource outgoing-response { + + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + @since(version = 0.2.0) + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + @since(version = 0.2.0) + status-code: func() -> status-code; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + @since(version = 0.2.0) + set-status-code: func(status-code: status-code) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + @since(version = 0.2.0) + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + @since(version = 0.2.0) + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + @since(version = 0.2.0) + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + @since(version = 0.2.0) + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + @since(version = 0.2.0) + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + @since(version = 0.2.0) + get: func() -> option>>; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/error.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/error.wit new file mode 100644 index 0000000000..97c6068779 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.3; + +@since(version = 0.2.0) +interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + resource error { + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/poll.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/poll.wit new file mode 100644 index 0000000000..9bcbe8e036 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.3; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + @since(version = 0.2.0) + block: func(); + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/streams.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/streams.wit new file mode 100644 index 0000000000..0de0846293 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/streams.wit @@ -0,0 +1,290 @@ +package wasi:io@0.2.3; + +/// WASI I/O is an I/O abstraction API which is currently focused on providing +/// stream types. +/// +/// In the future, the component model is expected to add built-in stream types; +/// when it does, they are expected to subsume this API. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + @since(version = 0.2.0) + resource input-stream { + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + @since(version = 0.2.0) + check-write: func() -> result; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/world.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/world.wit new file mode 100644 index 0000000000..f1d2102dca --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure-seed.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure-seed.wit new file mode 100644 index 0000000000..67d024d5bf --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.2.3; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + @since(version = 0.2.0) + insecure-seed: func() -> tuple; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure.wit new file mode 100644 index 0000000000..a07dfab327 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.3; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + @since(version = 0.2.0) + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + @since(version = 0.2.0) + get-insecure-random-u64: func() -> u64; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/random.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/random.wit new file mode 100644 index 0000000000..91957e6330 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.2.3; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + @since(version = 0.2.0) + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + @since(version = 0.2.0) + get-random-u64: func() -> u64; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/world.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/world.wit new file mode 100644 index 0000000000..0c1218f36e --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import random; + + @since(version = 0.2.0) + import insecure; + + @since(version = 0.2.0) + import insecure-seed; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/instance-network.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/instance-network.wit new file mode 100644 index 0000000000..5f6e6c1cc9 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/instance-network.wit @@ -0,0 +1,11 @@ + +/// This interface provides a value-export of the default network handle.. +@since(version = 0.2.0) +interface instance-network { + @since(version = 0.2.0) + use network.{network}; + + /// Get a handle to the default network. + @since(version = 0.2.0) + instance-network: func() -> network; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/ip-name-lookup.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 0000000000..c1d8a47c16 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,56 @@ +@since(version = 0.2.0) +interface ip-name-lookup { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-address}; + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + resolve-addresses: func(network: borrow, name: string) -> result; + + @since(version = 0.2.0) + resource resolve-address-stream { + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + @since(version = 0.2.0) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/network.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/network.wit new file mode 100644 index 0000000000..f3f60a3709 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/network.wit @@ -0,0 +1,169 @@ +@since(version = 0.2.0) +interface network { + @unstable(feature = network-error-code) + use wasi:io/error@0.2.3.{error}; + + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + @since(version = 0.2.0) + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + @since(version = 0.2.0) + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + + /// The operation timed out before it could finish completely. + timeout, + + /// This operation is incompatible with another asynchronous operation that is already in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + + /// A bind operation failed because the provided address is not an address that the `network` can bind to. + address-not-bindable, + + /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. + address-in-use, + + /// The remote address is not reachable + remote-unreachable, + + + /// The TCP connection was forcefully rejected + connection-refused, + + /// The TCP connection was reset. + connection-reset, + + /// A TCP connection was aborted. + connection-aborted, + + + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + + + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + permanent-resolver-failure, + } + + /// Attempts to extract a network-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// network-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are network-related errors. + @unstable(feature = network-error-code) + network-error-code: func(err: borrow) -> option; + + @since(version = 0.2.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.2.0) + type ipv4-address = tuple; + @since(version = 0.2.0) + type ipv6-address = tuple; + + @since(version = 0.2.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.2.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.2.0) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.2.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp-create-socket.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 0000000000..eedbd30768 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface tcp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp.wit new file mode 100644 index 0000000000..b4cd87fcef --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/tcp.wit @@ -0,0 +1,387 @@ +@since(version = 0.2.0) +interface tcp { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.3.{duration}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + @since(version = 0.2.0) + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + + /// Similar to `SHUT_WR` in POSIX. + send, + + /// Similar to `SHUT_RDWR` in POSIX. + both, + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + @since(version = 0.2.0) + resource tcp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connected` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-connect: func() -> result, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-listen: func() -> result<_, error-code>; + @since(version = 0.2.0) + finish-listen: func() -> result<_, error-code>; + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + accept: func() -> result, error-code>; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.2.0) + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` state. + @since(version = 0.2.0) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + @since(version = 0.2.0) + keep-alive-enabled: func() -> result; + @since(version = 0.2.0) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-idle-time: func() -> result; + @since(version = 0.2.0) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-interval: func() -> result; + @since(version = 0.2.0) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-count: func() -> result; + @since(version = 0.2.0) + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + @since(version = 0.2.0) + hop-limit: func() -> result; + @since(version = 0.2.0) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for more information. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent; shutting down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp-create-socket.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 0000000000..e8eeacbfef --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface udp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp.wit new file mode 100644 index 0000000000..01901ca27f --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/udp.wit @@ -0,0 +1,288 @@ +@since(version = 0.2.0) +interface udp { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + @since(version = 0.2.0) + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + @since(version = 0.2.0) + record outgoing-datagram { + /// The payload. + data: list, + + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + @since(version = 0.2.0) + resource udp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, but + /// only the most recently returned pair of streams will be operational. Implementations may trap if + /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + %stream: func(remote-address: option) -> result, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + @since(version = 0.2.0) + unicast-hop-limit: func() -> result; + @since(version = 0.2.0) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + resource incoming-datagram-stream { + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + resource outgoing-datagram-stream { + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without blocking and + /// returns how many messages were actually sent (or queued for sending). This function never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list and sequentially + /// sending each individual datagram until either the end of the list has been reached or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/world.wit b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/world.wit new file mode 100644 index 0000000000..2f0ad0d7c9 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/deps/sockets/world.wit @@ -0,0 +1,19 @@ +package wasi:sockets@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import tcp; + @since(version = 0.2.0) + import tcp-create-socket; + @since(version = 0.2.0) + import ip-name-lookup; +} diff --git a/test-components/wasi-http-incoming-request-handler-state/wit/world.wit b/test-components/wasi-http-incoming-request-handler-state/wit/world.wit new file mode 100644 index 0000000000..85633a60d5 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-state/wit/world.wit @@ -0,0 +1,6 @@ +package golem:handler; + +world api { + import wasi:http/types@0.2.3; + export wasi:http/incoming-handler@0.2.3; +} diff --git a/test-components/wasi-http-incoming-request-handler.wasm b/test-components/wasi-http-incoming-request-handler.wasm new file mode 100644 index 0000000000000000000000000000000000000000..cfd8b2acac142b6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ABY_-WT94fb4|db|XD->OLcT@1z2{uh*|(aMwj~ z2jN~X93S(zel*Nvvi^oYHa32I+%I^ZU-W#xWNq zj-Gp;44fNv-L<>jsI9Y0=ll-^W8QP*2XUl++v57}gpP&8Eks+MdyS~H)OjsYYdeuR zhXJvZbn`Hf|6S&eS=If{*jyT24Ng2}v5`P+IRAu74#K>dXFO*4L5Mi}(%r+{8z!H7 zauIL;xBMr|Pr>}SCk8SO^29+iE5$oBb{NjgjI5p+>xpY9JCf{OLyJh~A?dswF{@V1 z1jga9adm~@2Cwq{;IUWP4*$=}t|g~o7>Ld|@uvxt)cpwr6$``ywS1QBSaA^$QdV4q zLvRL8$g@*qCvj4`j5D#v&oj>x%{VzWpH`_U6qF%>=Jm@-KyMDMH1iY5{xpV`UQm+w zW*BCX{4kR9SFopD_a5uDzL+P(;s8~T&evy<5Q=YVJD9pJx*ZHT z+WH)u{|LABox=Ew_lz!^(8p)dcU_*rJg?&Wv9>;j=n8Z@z#c#j5K-JPZAQC-C_8xa z08iF}M?&E>fZzA>f#SIR31n8~R#0!pz}VEEKUBu&FKb1zmH#a2sK;YGF>}r9y^^a;c%}*v8PDKo@Z}(L;VaD9Vpy* IdcJ@B1?9dy3jhEB literal 0 HcmV?d00001 diff --git a/test-components/wasi-http-incoming-request-handler/Cargo.lock b/test-components/wasi-http-incoming-request-handler/Cargo.lock new file mode 100644 index 0000000000..1ef2185fc6 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/Cargo.lock @@ -0,0 +1,25 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" + +[[package]] +name = "handler" +version = "0.1.0" +dependencies = [ + "wit-bindgen-rt", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc801b991c56492f87ab3086e786468f75c285a4d73017ab0ebc2fa1aed5d82c" +dependencies = [ + "bitflags", +] diff --git a/test-components/wasi-http-incoming-request-handler/Cargo.toml b/test-components/wasi-http-incoming-request-handler/Cargo.toml new file mode 100644 index 0000000000..e694da15c2 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "wasi-http-incoming-request-handler" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +path = "src/lib.rs" +crate-type = ["cdylib"] + +[dependencies] +wit-bindgen-rt = { version = "0.37.0", features = ["bitflags"] } + +[package.metadata.component] +package = "golem:handler" +proxy = true + +[package.metadata.component.target.dependencies] +"wasi:cli" = { path = "wit/deps/cli" } +"wasi:clocks" = { path = "wit/deps/clocks" } +"wasi:filesystem" = { path = "wit/deps/filesystem" } +"wasi:http" = { path = "wit/deps/http" } +"wasi:io" = { path = "wit/deps/io" } +"wasi:random" = { path = "wit/deps/random" } +"wasi:sockets" = { path = "wit/deps/sockets" } diff --git a/test-components/wasi-http-incoming-request-handler/src/bindings.rs b/test-components/wasi-http-incoming-request-handler/src/bindings.rs new file mode 100644 index 0000000000..b9a1d24912 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/src/bindings.rs @@ -0,0 +1,7502 @@ +#[allow(dead_code)] +pub mod wasi { + #[allow(dead_code)] + pub mod clocks { + #[allow(dead_code, clippy::all)] + pub mod monotonic_clock { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Pollable = super::super::super::wasi::io::poll::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. + pub type Instant = u64; + /// A duration of time, in nanoseconds. + pub type Duration = u64; + #[allow(unused_unsafe, clippy::all)] + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + pub fn now() -> Instant { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "now"] + fn wit_import() -> i64; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i64 { + unreachable!() + } + let ret = wit_import(); + ret as u64 + } + } + #[allow(unused_unsafe, clippy::all)] + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + pub fn resolution() -> Duration { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "resolution"] + fn wit_import() -> i64; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i64 { + unreachable!() + } + let ret = wit_import(); + ret as u64 + } + } + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + pub fn subscribe_instant(when: Instant) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "subscribe-instant"] + fn wit_import(_: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i64) -> i32 { + unreachable!() + } + let ret = wit_import(_rt::as_i64(when)); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + pub fn subscribe_duration(when: Duration) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:clocks/monotonic-clock@0.2.3")] + extern "C" { + #[link_name = "subscribe-duration"] + fn wit_import(_: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i64) -> i32 { + unreachable!() + } + let ret = wit_import(_rt::as_i64(when)); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + } + #[allow(dead_code)] + pub mod http { + #[allow(dead_code, clippy::all)] + pub mod types { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Duration = super::super::super::wasi::clocks::monotonic_clock::Duration; + pub type InputStream = super::super::super::wasi::io::streams::InputStream; + pub type OutputStream = super::super::super::wasi::io::streams::OutputStream; + pub type IoError = super::super::super::wasi::io::error::Error; + pub type Pollable = super::super::super::wasi::io::poll::Pollable; + /// This type corresponds to HTTP standard Methods. + #[derive(Clone)] + pub enum Method { + Get, + Head, + Post, + Put, + Delete, + Connect, + Options, + Trace, + Patch, + Other(_rt::String), + } + impl ::core::fmt::Debug for Method { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + Method::Get => f.debug_tuple("Method::Get").finish(), + Method::Head => f.debug_tuple("Method::Head").finish(), + Method::Post => f.debug_tuple("Method::Post").finish(), + Method::Put => f.debug_tuple("Method::Put").finish(), + Method::Delete => f.debug_tuple("Method::Delete").finish(), + Method::Connect => f.debug_tuple("Method::Connect").finish(), + Method::Options => f.debug_tuple("Method::Options").finish(), + Method::Trace => f.debug_tuple("Method::Trace").finish(), + Method::Patch => f.debug_tuple("Method::Patch").finish(), + Method::Other(e) => { + f.debug_tuple("Method::Other").field(e).finish() + } + } + } + } + /// This type corresponds to HTTP standard Related Schemes. + #[derive(Clone)] + pub enum Scheme { + Http, + Https, + Other(_rt::String), + } + impl ::core::fmt::Debug for Scheme { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + Scheme::Http => f.debug_tuple("Scheme::Http").finish(), + Scheme::Https => f.debug_tuple("Scheme::Https").finish(), + Scheme::Other(e) => { + f.debug_tuple("Scheme::Other").field(e).finish() + } + } + } + } + /// Defines the case payload type for `DNS-error` above: + #[derive(Clone)] + pub struct DnsErrorPayload { + pub rcode: Option<_rt::String>, + pub info_code: Option, + } + impl ::core::fmt::Debug for DnsErrorPayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("DnsErrorPayload") + .field("rcode", &self.rcode) + .field("info-code", &self.info_code) + .finish() + } + } + /// Defines the case payload type for `TLS-alert-received` above: + #[derive(Clone)] + pub struct TlsAlertReceivedPayload { + pub alert_id: Option, + pub alert_message: Option<_rt::String>, + } + impl ::core::fmt::Debug for TlsAlertReceivedPayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("TlsAlertReceivedPayload") + .field("alert-id", &self.alert_id) + .field("alert-message", &self.alert_message) + .finish() + } + } + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + #[derive(Clone)] + pub struct FieldSizePayload { + pub field_name: Option<_rt::String>, + pub field_size: Option, + } + impl ::core::fmt::Debug for FieldSizePayload { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + f.debug_struct("FieldSizePayload") + .field("field-name", &self.field_name) + .field("field-size", &self.field_size) + .finish() + } + } + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + #[derive(Clone)] + pub enum ErrorCode { + DnsTimeout, + DnsError(DnsErrorPayload), + DestinationNotFound, + DestinationUnavailable, + DestinationIpProhibited, + DestinationIpUnroutable, + ConnectionRefused, + ConnectionTerminated, + ConnectionTimeout, + ConnectionReadTimeout, + ConnectionWriteTimeout, + ConnectionLimitReached, + TlsProtocolError, + TlsCertificateError, + TlsAlertReceived(TlsAlertReceivedPayload), + HttpRequestDenied, + HttpRequestLengthRequired, + HttpRequestBodySize(Option), + HttpRequestMethodInvalid, + HttpRequestUriInvalid, + HttpRequestUriTooLong, + HttpRequestHeaderSectionSize(Option), + HttpRequestHeaderSize(Option), + HttpRequestTrailerSectionSize(Option), + HttpRequestTrailerSize(FieldSizePayload), + HttpResponseIncomplete, + HttpResponseHeaderSectionSize(Option), + HttpResponseHeaderSize(FieldSizePayload), + HttpResponseBodySize(Option), + HttpResponseTrailerSectionSize(Option), + HttpResponseTrailerSize(FieldSizePayload), + HttpResponseTransferCoding(Option<_rt::String>), + HttpResponseContentCoding(Option<_rt::String>), + HttpResponseTimeout, + HttpUpgradeFailed, + HttpProtocolError, + LoopDetected, + ConfigurationError, + /// 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. + InternalError(Option<_rt::String>), + } + impl ::core::fmt::Debug for ErrorCode { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + ErrorCode::DnsTimeout => { + f.debug_tuple("ErrorCode::DnsTimeout").finish() + } + ErrorCode::DnsError(e) => { + f.debug_tuple("ErrorCode::DnsError").field(e).finish() + } + ErrorCode::DestinationNotFound => { + f.debug_tuple("ErrorCode::DestinationNotFound").finish() + } + ErrorCode::DestinationUnavailable => { + f.debug_tuple("ErrorCode::DestinationUnavailable").finish() + } + ErrorCode::DestinationIpProhibited => { + f.debug_tuple("ErrorCode::DestinationIpProhibited").finish() + } + ErrorCode::DestinationIpUnroutable => { + f.debug_tuple("ErrorCode::DestinationIpUnroutable").finish() + } + ErrorCode::ConnectionRefused => { + f.debug_tuple("ErrorCode::ConnectionRefused").finish() + } + ErrorCode::ConnectionTerminated => { + f.debug_tuple("ErrorCode::ConnectionTerminated").finish() + } + ErrorCode::ConnectionTimeout => { + f.debug_tuple("ErrorCode::ConnectionTimeout").finish() + } + ErrorCode::ConnectionReadTimeout => { + f.debug_tuple("ErrorCode::ConnectionReadTimeout").finish() + } + ErrorCode::ConnectionWriteTimeout => { + f.debug_tuple("ErrorCode::ConnectionWriteTimeout").finish() + } + ErrorCode::ConnectionLimitReached => { + f.debug_tuple("ErrorCode::ConnectionLimitReached").finish() + } + ErrorCode::TlsProtocolError => { + f.debug_tuple("ErrorCode::TlsProtocolError").finish() + } + ErrorCode::TlsCertificateError => { + f.debug_tuple("ErrorCode::TlsCertificateError").finish() + } + ErrorCode::TlsAlertReceived(e) => { + f.debug_tuple("ErrorCode::TlsAlertReceived") + .field(e) + .finish() + } + ErrorCode::HttpRequestDenied => { + f.debug_tuple("ErrorCode::HttpRequestDenied").finish() + } + ErrorCode::HttpRequestLengthRequired => { + f.debug_tuple("ErrorCode::HttpRequestLengthRequired") + .finish() + } + ErrorCode::HttpRequestBodySize(e) => { + f.debug_tuple("ErrorCode::HttpRequestBodySize") + .field(e) + .finish() + } + ErrorCode::HttpRequestMethodInvalid => { + f.debug_tuple("ErrorCode::HttpRequestMethodInvalid").finish() + } + ErrorCode::HttpRequestUriInvalid => { + f.debug_tuple("ErrorCode::HttpRequestUriInvalid").finish() + } + ErrorCode::HttpRequestUriTooLong => { + f.debug_tuple("ErrorCode::HttpRequestUriTooLong").finish() + } + ErrorCode::HttpRequestHeaderSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestHeaderSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestHeaderSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestHeaderSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestTrailerSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestTrailerSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpRequestTrailerSize(e) => { + f.debug_tuple("ErrorCode::HttpRequestTrailerSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseIncomplete => { + f.debug_tuple("ErrorCode::HttpResponseIncomplete").finish() + } + ErrorCode::HttpResponseHeaderSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseHeaderSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseHeaderSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseHeaderSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseBodySize(e) => { + f.debug_tuple("ErrorCode::HttpResponseBodySize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTrailerSectionSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseTrailerSectionSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTrailerSize(e) => { + f.debug_tuple("ErrorCode::HttpResponseTrailerSize") + .field(e) + .finish() + } + ErrorCode::HttpResponseTransferCoding(e) => { + f.debug_tuple("ErrorCode::HttpResponseTransferCoding") + .field(e) + .finish() + } + ErrorCode::HttpResponseContentCoding(e) => { + f.debug_tuple("ErrorCode::HttpResponseContentCoding") + .field(e) + .finish() + } + ErrorCode::HttpResponseTimeout => { + f.debug_tuple("ErrorCode::HttpResponseTimeout").finish() + } + ErrorCode::HttpUpgradeFailed => { + f.debug_tuple("ErrorCode::HttpUpgradeFailed").finish() + } + ErrorCode::HttpProtocolError => { + f.debug_tuple("ErrorCode::HttpProtocolError").finish() + } + ErrorCode::LoopDetected => { + f.debug_tuple("ErrorCode::LoopDetected").finish() + } + ErrorCode::ConfigurationError => { + f.debug_tuple("ErrorCode::ConfigurationError").finish() + } + ErrorCode::InternalError(e) => { + f.debug_tuple("ErrorCode::InternalError").field(e).finish() + } + } + } + } + impl ::core::fmt::Display for ErrorCode { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for ErrorCode {} + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + #[derive(Clone, Copy)] + pub enum HeaderError { + /// This error indicates that a `field-name` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + InvalidSyntax, + /// This error indicates that a forbidden `field-name` was used when trying + /// to set a header in a `fields`. + Forbidden, + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + Immutable, + } + impl ::core::fmt::Debug for HeaderError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + HeaderError::InvalidSyntax => { + f.debug_tuple("HeaderError::InvalidSyntax").finish() + } + HeaderError::Forbidden => { + f.debug_tuple("HeaderError::Forbidden").finish() + } + HeaderError::Immutable => { + f.debug_tuple("HeaderError::Immutable").finish() + } + } + } + } + impl ::core::fmt::Display for HeaderError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for HeaderError {} + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + pub type FieldKey = _rt::String; + /// Field names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + pub type FieldName = FieldKey; + /// 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. + pub type FieldValue = _rt::Vec; + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct Fields { + handle: _rt::Resource, + } + impl Fields { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Fields { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]fields"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Headers is an alias for Fields. + pub type Headers = Fields; + /// Trailers is an alias for Fields. + pub type Trailers = Fields; + /// Represents an incoming HTTP Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingRequest { + handle: _rt::Resource, + } + impl IncomingRequest { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingRequest { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-request"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingRequest { + handle: _rt::Resource, + } + impl OutgoingRequest { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingRequest { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-request"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct RequestOptions { + handle: _rt::Resource, + } + impl RequestOptions { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for RequestOptions { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]request-options"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct ResponseOutparam { + handle: _rt::Resource, + } + impl ResponseOutparam { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for ResponseOutparam { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]response-outparam"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// This type corresponds to the HTTP standard Status Code. + pub type StatusCode = u16; + /// Represents an incoming HTTP Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingResponse { + handle: _rt::Resource, + } + impl IncomingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// 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. + #[derive(Debug)] + #[repr(transparent)] + pub struct IncomingBody { + handle: _rt::Resource, + } + impl IncomingBody { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for IncomingBody { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]incoming-body"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + #[derive(Debug)] + #[repr(transparent)] + pub struct FutureTrailers { + handle: _rt::Resource, + } + impl FutureTrailers { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for FutureTrailers { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]future-trailers"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingResponse { + handle: _rt::Resource, + } + impl OutgoingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutgoingBody { + handle: _rt::Resource, + } + impl OutgoingBody { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutgoingBody { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]outgoing-body"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + #[derive(Debug)] + #[repr(transparent)] + pub struct FutureIncomingResponse { + handle: _rt::Resource, + } + impl FutureIncomingResponse { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for FutureIncomingResponse { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]future-incoming-response"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn http_error_code(err: &IoError) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 40]); + let mut ret_area = RetArea([::core::mem::MaybeUninit::uninit(); 40]); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "http-error-code"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((err).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + let v64 = match l2 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e64 = { + let l3 = i32::from(*ptr0.add(16).cast::()); + let l7 = i32::from(*ptr0.add(28).cast::()); + DnsErrorPayload { + rcode: match l3 { + 0 => None, + 1 => { + let e = { + let l4 = *ptr0.add(20).cast::<*mut u8>(); + let l5 = *ptr0.add(24).cast::(); + let len6 = l5; + let bytes6 = _rt::Vec::from_raw_parts( + l4.cast(), + len6, + len6, + ); + _rt::string_lift(bytes6) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l7 { + 0 => None, + 1 => { + let e = { + let l8 = i32::from(*ptr0.add(30).cast::()); + l8 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e64) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e64 = { + let l9 = i32::from(*ptr0.add(16).cast::()); + let l11 = i32::from(*ptr0.add(20).cast::()); + TlsAlertReceivedPayload { + alert_id: match l9 { + 0 => None, + 1 => { + let e = { + let l10 = i32::from(*ptr0.add(17).cast::()); + l10 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l11 { + 0 => None, + 1 => { + let e = { + let l12 = *ptr0.add(24).cast::<*mut u8>(); + let l13 = *ptr0.add(28).cast::(); + let len14 = l13; + let bytes14 = _rt::Vec::from_raw_parts( + l12.cast(), + len14, + len14, + ); + _rt::string_lift(bytes14) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e64) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e64 = { + let l15 = i32::from(*ptr0.add(16).cast::()); + match l15 { + 0 => None, + 1 => { + let e = { + let l16 = *ptr0.add(24).cast::(); + l16 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e64) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e64 = { + let l17 = i32::from(*ptr0.add(16).cast::()); + match l17 { + 0 => None, + 1 => { + let e = { + let l18 = *ptr0.add(20).cast::(); + l18 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e64) + } + 22 => { + let e64 = { + let l19 = i32::from(*ptr0.add(16).cast::()); + match l19 { + 0 => None, + 1 => { + let e = { + let l20 = i32::from(*ptr0.add(20).cast::()); + let l24 = i32::from(*ptr0.add(32).cast::()); + FieldSizePayload { + field_name: match l20 { + 0 => None, + 1 => { + let e = { + let l21 = *ptr0.add(24).cast::<*mut u8>(); + let l22 = *ptr0.add(28).cast::(); + let len23 = l22; + let bytes23 = _rt::Vec::from_raw_parts( + l21.cast(), + len23, + len23, + ); + _rt::string_lift(bytes23) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l24 { + 0 => None, + 1 => { + let e = { + let l25 = *ptr0.add(36).cast::(); + l25 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e64) + } + 23 => { + let e64 = { + let l26 = i32::from(*ptr0.add(16).cast::()); + match l26 { + 0 => None, + 1 => { + let e = { + let l27 = *ptr0.add(20).cast::(); + l27 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e64) + } + 24 => { + let e64 = { + let l28 = i32::from(*ptr0.add(16).cast::()); + let l32 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l28 { + 0 => None, + 1 => { + let e = { + let l29 = *ptr0.add(20).cast::<*mut u8>(); + let l30 = *ptr0.add(24).cast::(); + let len31 = l30; + let bytes31 = _rt::Vec::from_raw_parts( + l29.cast(), + len31, + len31, + ); + _rt::string_lift(bytes31) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l32 { + 0 => None, + 1 => { + let e = { + let l33 = *ptr0.add(32).cast::(); + l33 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e64) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e64 = { + let l34 = i32::from(*ptr0.add(16).cast::()); + match l34 { + 0 => None, + 1 => { + let e = { + let l35 = *ptr0.add(20).cast::(); + l35 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e64) + } + 27 => { + let e64 = { + let l36 = i32::from(*ptr0.add(16).cast::()); + let l40 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l36 { + 0 => None, + 1 => { + let e = { + let l37 = *ptr0.add(20).cast::<*mut u8>(); + let l38 = *ptr0.add(24).cast::(); + let len39 = l38; + let bytes39 = _rt::Vec::from_raw_parts( + l37.cast(), + len39, + len39, + ); + _rt::string_lift(bytes39) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l40 { + 0 => None, + 1 => { + let e = { + let l41 = *ptr0.add(32).cast::(); + l41 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e64) + } + 28 => { + let e64 = { + let l42 = i32::from(*ptr0.add(16).cast::()); + match l42 { + 0 => None, + 1 => { + let e = { + let l43 = *ptr0.add(24).cast::(); + l43 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e64) + } + 29 => { + let e64 = { + let l44 = i32::from(*ptr0.add(16).cast::()); + match l44 { + 0 => None, + 1 => { + let e = { + let l45 = *ptr0.add(20).cast::(); + l45 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e64) + } + 30 => { + let e64 = { + let l46 = i32::from(*ptr0.add(16).cast::()); + let l50 = i32::from(*ptr0.add(28).cast::()); + FieldSizePayload { + field_name: match l46 { + 0 => None, + 1 => { + let e = { + let l47 = *ptr0.add(20).cast::<*mut u8>(); + let l48 = *ptr0.add(24).cast::(); + let len49 = l48; + let bytes49 = _rt::Vec::from_raw_parts( + l47.cast(), + len49, + len49, + ); + _rt::string_lift(bytes49) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l50 { + 0 => None, + 1 => { + let e = { + let l51 = *ptr0.add(32).cast::(); + l51 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e64) + } + 31 => { + let e64 = { + let l52 = i32::from(*ptr0.add(16).cast::()); + match l52 { + 0 => None, + 1 => { + let e = { + let l53 = *ptr0.add(20).cast::<*mut u8>(); + let l54 = *ptr0.add(24).cast::(); + let len55 = l54; + let bytes55 = _rt::Vec::from_raw_parts( + l53.cast(), + len55, + len55, + ); + _rt::string_lift(bytes55) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e64) + } + 32 => { + let e64 = { + let l56 = i32::from(*ptr0.add(16).cast::()); + match l56 { + 0 => None, + 1 => { + let e = { + let l57 = *ptr0.add(20).cast::<*mut u8>(); + let l58 = *ptr0.add(24).cast::(); + let len59 = l58; + let bytes59 = _rt::Vec::from_raw_parts( + l57.cast(), + len59, + len59, + ); + _rt::string_lift(bytes59) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e64) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e64 = { + let l60 = i32::from(*ptr0.add(16).cast::()); + match l60 { + 0 => None, + 1 => { + let e = { + let l61 = *ptr0.add(20).cast::<*mut u8>(); + let l62 = *ptr0.add(24).cast::(); + let len63 = l62; + let bytes63 = _rt::Vec::from_raw_parts( + l61.cast(), + len63, + len63, + ); + _rt::string_lift(bytes63) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e64) + } + }; + v64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + pub fn new() -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]fields"] + fn wit_import() -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i32 { + unreachable!() + } + let ret = wit_import(); + Fields::from_handle(ret as u32) + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + pub fn from_list( + entries: &[(FieldName, FieldValue)], + ) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let vec3 = entries; + let len3 = vec3.len(); + let layout3 = _rt::alloc::Layout::from_size_align_unchecked( + vec3.len() * 16, + 4, + ); + let result3 = if layout3.size() != 0 { + let ptr = _rt::alloc::alloc(layout3).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout3); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec3.into_iter().enumerate() { + let base = result3.add(i * 16); + { + let (t0_0, t0_1) = e; + let vec1 = t0_0; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + *base.add(4).cast::() = len1; + *base.add(0).cast::<*mut u8>() = ptr1.cast_mut(); + let vec2 = t0_1; + let ptr2 = vec2.as_ptr().cast::(); + let len2 = vec2.len(); + *base.add(12).cast::() = len2; + *base.add(8).cast::<*mut u8>() = ptr2.cast_mut(); + } + } + let ptr4 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]fields.from-list"] + fn wit_import(_: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import(result3, len3, ptr4); + let l5 = i32::from(*ptr4.add(0).cast::()); + if layout3.size() != 0 { + _rt::alloc::dealloc(result3.cast(), layout3); + } + match l5 { + 0 => { + let e = { + let l6 = *ptr4.add(4).cast::(); + Fields::from_handle(l6 as u32) + }; + Ok(e) + } + 1 => { + let e = { + let l7 = i32::from(*ptr4.add(4).cast::()); + let v8 = match l7 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v8 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + pub fn get(&self, name: &FieldName) -> _rt::Vec { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.get"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = *ptr1.add(0).cast::<*mut u8>(); + let l3 = *ptr1.add(4).cast::(); + let base7 = l2; + let len7 = l3; + let mut result7 = _rt::Vec::with_capacity(len7); + for i in 0..len7 { + let base = base7.add(i * 8); + let e7 = { + let l4 = *base.add(0).cast::<*mut u8>(); + let l5 = *base.add(4).cast::(); + let len6 = l5; + _rt::Vec::from_raw_parts(l4.cast(), len6, len6) + }; + result7.push(e7); + } + _rt::cabi_dealloc(base7, len7 * 8, 4); + result7 + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + pub fn has(&self, name: &FieldName) -> bool { + unsafe { + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.has"] + fn wit_import(_: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + ); + _rt::bool_lift(ret as u8) + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + pub fn set( + &self, + name: &FieldName, + value: &[FieldValue], + ) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let vec2 = value; + let len2 = vec2.len(); + let layout2 = _rt::alloc::Layout::from_size_align_unchecked( + vec2.len() * 8, + 4, + ); + let result2 = if layout2.size() != 0 { + let ptr = _rt::alloc::alloc(layout2).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout2); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec2.into_iter().enumerate() { + let base = result2.add(i * 8); + { + let vec1 = e; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + *base.add(4).cast::() = len1; + *base.add(0).cast::<*mut u8>() = ptr1.cast_mut(); + } + } + let ptr3 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.set"] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ) { + unreachable!() + } + wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + result2, + len2, + ptr3, + ); + let l4 = i32::from(*ptr3.add(0).cast::()); + if layout2.size() != 0 { + _rt::alloc::dealloc(result2.cast(), layout2); + } + match l4 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr3.add(1).cast::()); + let v6 = match l5 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v6 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + pub fn delete(&self, name: &FieldName) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.delete"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(1).cast::()); + let v4 = match l3 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + pub fn append( + &self, + name: &FieldName, + value: &FieldValue, + ) -> Result<(), HeaderError> { + unsafe { + #[repr(align(1))] + struct RetArea([::core::mem::MaybeUninit; 2]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 2], + ); + let vec0 = name; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let vec1 = value; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + let ptr2 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.append"] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: *mut u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut u8, + ) { + unreachable!() + } + wit_import( + (self).handle() as i32, + ptr0.cast_mut(), + len0, + ptr1.cast_mut(), + len1, + ptr2, + ); + let l3 = i32::from(*ptr2.add(0).cast::()); + match l3 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l4 = i32::from(*ptr2.add(1).cast::()); + let v5 = match l4 { + 0 => HeaderError::InvalidSyntax, + 1 => HeaderError::Forbidden, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + HeaderError::Immutable + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + pub fn entries(&self) -> _rt::Vec<(FieldName, FieldValue)> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.entries"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = *ptr0.add(0).cast::<*mut u8>(); + let l2 = *ptr0.add(4).cast::(); + let base9 = l1; + let len9 = l2; + let mut result9 = _rt::Vec::with_capacity(len9); + for i in 0..len9 { + let base = base9.add(i * 16); + let e9 = { + let l3 = *base.add(0).cast::<*mut u8>(); + let l4 = *base.add(4).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + let l6 = *base.add(8).cast::<*mut u8>(); + let l7 = *base.add(12).cast::(); + let len8 = l7; + ( + _rt::string_lift(bytes5), + _rt::Vec::from_raw_parts(l6.cast(), len8, len8), + ) + }; + result9.push(e9); + } + _rt::cabi_dealloc(base9, len9 * 16, 4); + result9 + } + } + } + impl Fields { + #[allow(unused_unsafe, clippy::all)] + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + pub fn clone(&self) -> Fields { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]fields.clone"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the method of the incoming request. + pub fn method(&self) -> Method { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.method"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + let v5 = match l1 { + 0 => Method::Get, + 1 => Method::Head, + 2 => Method::Post, + 3 => Method::Put, + 4 => Method::Delete, + 5 => Method::Connect, + 6 => Method::Options, + 7 => Method::Trace, + 8 => Method::Patch, + n => { + debug_assert_eq!(n, 9, "invalid enum discriminant"); + let e5 = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Method::Other(e5) + } + }; + v5 + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the path with query parameters from the request, as a string. + pub fn path_with_query(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.path-with-query"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the protocol scheme from the request. + pub fn scheme(&self) -> Option { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.scheme"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v6 = match l2 { + 0 => Scheme::Http, + 1 => Scheme::Https, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + let e6 = { + let l3 = *ptr0.add(8).cast::<*mut u8>(); + let l4 = *ptr0.add(12).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + _rt::string_lift(bytes5) + }; + Scheme::Other(e6) + } + }; + v6 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Returns the authority of the Request's target URI, if present. + pub fn authority(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.authority"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + pub fn consume(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-request.consume"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + IncomingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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`. + pub fn new(headers: Headers) -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]outgoing-request"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&headers).take_handle() as i32); + OutgoingRequest::from_handle(ret as u32) + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn body(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.body"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + OutgoingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the Method for the Request. + pub fn method(&self) -> Method { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.method"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + let v5 = match l1 { + 0 => Method::Get, + 1 => Method::Head, + 2 => Method::Post, + 3 => Method::Put, + 4 => Method::Delete, + 5 => Method::Connect, + 6 => Method::Options, + 7 => Method::Trace, + 8 => Method::Patch, + n => { + debug_assert_eq!(n, 9, "invalid enum discriminant"); + let e5 = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Method::Other(e5) + } + }; + v5 + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + pub fn set_method(&self, method: &Method) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match method { + Method::Get => (0i32, ::core::ptr::null_mut(), 0usize), + Method::Head => (1i32, ::core::ptr::null_mut(), 0usize), + Method::Post => (2i32, ::core::ptr::null_mut(), 0usize), + Method::Put => (3i32, ::core::ptr::null_mut(), 0usize), + Method::Delete => (4i32, ::core::ptr::null_mut(), 0usize), + Method::Connect => (5i32, ::core::ptr::null_mut(), 0usize), + Method::Options => (6i32, ::core::ptr::null_mut(), 0usize), + Method::Trace => (7i32, ::core::ptr::null_mut(), 0usize), + Method::Patch => (8i32, ::core::ptr::null_mut(), 0usize), + Method::Other(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (9i32, ptr0.cast_mut(), len0) + } + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-method"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + pub fn path_with_query(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.path-with-query"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_path_with_query( + &self, + path_with_query: Option<&str>, + ) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match path_with_query { + Some(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (1i32, ptr0.cast_mut(), len0) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-path-with-query"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + pub fn scheme(&self) -> Option { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.scheme"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v6 = match l2 { + 0 => Scheme::Http, + 1 => Scheme::Https, + n => { + debug_assert_eq!(n, 2, "invalid enum discriminant"); + let e6 = { + let l3 = *ptr0.add(8).cast::<*mut u8>(); + let l4 = *ptr0.add(12).cast::(); + let len5 = l4; + let bytes5 = _rt::Vec::from_raw_parts( + l3.cast(), + len5, + len5, + ); + _rt::string_lift(bytes5) + }; + Scheme::Other(e6) + } + }; + v6 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_scheme(&self, scheme: Option<&Scheme>) -> Result<(), ()> { + unsafe { + let (result2_0, result2_1, result2_2, result2_3) = match scheme { + Some(e) => { + let (result1_0, result1_1, result1_2) = match e { + Scheme::Http => (0i32, ::core::ptr::null_mut(), 0usize), + Scheme::Https => (1i32, ::core::ptr::null_mut(), 0usize), + Scheme::Other(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (2i32, ptr0.cast_mut(), len0) + } + }; + (1i32, result1_0, result1_1, result1_2) + } + None => (0i32, 0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-scheme"] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: *mut u8, + _: usize, + ) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: *mut u8, + _: usize, + ) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result2_0, + result2_1, + result2_2, + result2_3, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. + pub fn authority(&self) -> Option<_rt::String> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.authority"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + let bytes4 = _rt::Vec::from_raw_parts( + l2.cast(), + len4, + len4, + ); + _rt::string_lift(bytes4) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Set the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid URI authority. + pub fn set_authority(&self, authority: Option<&str>) -> Result<(), ()> { + unsafe { + let (result1_0, result1_1, result1_2) = match authority { + Some(e) => { + let vec0 = e; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + (1i32, ptr0.cast_mut(), len0) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.set-authority"] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: *mut u8, _: usize) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result1_0, + result1_1, + result1_2, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingRequest { + #[allow(unused_unsafe, clippy::all)] + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-request.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Construct a default `request-options` value. + pub fn new() -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]request-options"] + fn wit_import() -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import() -> i32 { + unreachable!() + } + let ret = wit_import(); + RequestOptions::from_handle(ret as u32) + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for the initial connect to the HTTP Server. + pub fn connect_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.connect-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + pub fn set_connect_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-connect-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for receiving the first byte of the Response body. + pub fn first_byte_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.first-byte-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + pub fn set_first_byte_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-first-byte-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + pub fn between_bytes_timeout(&self) -> Option { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.between-bytes-timeout"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl RequestOptions { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set_between_bytes_timeout( + &self, + duration: Option, + ) -> Result<(), ()> { + unsafe { + let (result0_0, result0_1) = match duration { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]request-options.set-between-bytes-timeout"] + fn wit_import(_: i32, _: i32, _: i64) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + result0_0, + result0_1, + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl ResponseOutparam { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn set( + param: ResponseOutparam, + response: Result, + ) { + unsafe { + let ( + result38_0, + result38_1, + result38_2, + result38_3, + result38_4, + result38_5, + result38_6, + result38_7, + ) = match &response { + Ok(e) => { + ( + 0i32, + (e).take_handle() as i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + Err(e) => { + let ( + result37_0, + result37_1, + result37_2, + result37_3, + result37_4, + result37_5, + result37_6, + ) = match e { + ErrorCode::DnsTimeout => { + ( + 0i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DnsError(e) => { + let DnsErrorPayload { + rcode: rcode0, + info_code: info_code0, + } = e; + let (result2_0, result2_1, result2_2) = match rcode0 { + Some(e) => { + let vec1 = e; + let ptr1 = vec1.as_ptr().cast::(); + let len1 = vec1.len(); + (1i32, ptr1.cast_mut(), len1) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result3_0, result3_1) = match info_code0 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 1i32, + result2_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result2_1); + t + }, + result2_2 as *mut u8, + result3_0 as *mut u8, + result3_1 as usize, + 0i32, + ) + } + ErrorCode::DestinationNotFound => { + ( + 2i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationUnavailable => { + ( + 3i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationIpProhibited => { + ( + 4i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::DestinationIpUnroutable => { + ( + 5i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionRefused => { + ( + 6i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionTerminated => { + ( + 7i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionTimeout => { + ( + 8i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionReadTimeout => { + ( + 9i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionWriteTimeout => { + ( + 10i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConnectionLimitReached => { + ( + 11i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsProtocolError => { + ( + 12i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsCertificateError => { + ( + 13i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::TlsAlertReceived(e) => { + let TlsAlertReceivedPayload { + alert_id: alert_id4, + alert_message: alert_message4, + } = e; + let (result5_0, result5_1) = match alert_id4 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + let (result7_0, result7_1, result7_2) = match alert_message4 { + Some(e) => { + let vec6 = e; + let ptr6 = vec6.as_ptr().cast::(); + let len6 = vec6.len(); + (1i32, ptr6.cast_mut(), len6) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 14i32, + result5_0, + ::core::mem::MaybeUninit::new(i64::from(result5_1) as u64), + result7_0 as *mut u8, + result7_1, + result7_2, + 0i32, + ) + } + ErrorCode::HttpRequestDenied => { + ( + 15i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestLengthRequired => { + ( + 16i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestBodySize(e) => { + let (result8_0, result8_1) = match e { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + ( + 17i32, + result8_0, + ::core::mem::MaybeUninit::new(result8_1 as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestMethodInvalid => { + ( + 18i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestUriInvalid => { + ( + 19i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestUriTooLong => { + ( + 20i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestHeaderSectionSize(e) => { + let (result9_0, result9_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 21i32, + result9_0, + ::core::mem::MaybeUninit::new(i64::from(result9_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestHeaderSize(e) => { + let ( + result14_0, + result14_1, + result14_2, + result14_3, + result14_4, + result14_5, + ) = match e { + Some(e) => { + let FieldSizePayload { + field_name: field_name10, + field_size: field_size10, + } = e; + let (result12_0, result12_1, result12_2) = match field_name10 { + Some(e) => { + let vec11 = e; + let ptr11 = vec11.as_ptr().cast::(); + let len11 = vec11.len(); + (1i32, ptr11.cast_mut(), len11) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result13_0, result13_1) = match field_size10 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 1i32, + result12_0, + result12_1, + result12_2, + result13_0, + result13_1, + ) + } + None => { + (0i32, 0i32, ::core::ptr::null_mut(), 0usize, 0i32, 0i32) + } + }; + ( + 22i32, + result14_0, + ::core::mem::MaybeUninit::new(i64::from(result14_1) as u64), + result14_2, + result14_3 as *mut u8, + result14_4 as usize, + result14_5, + ) + } + ErrorCode::HttpRequestTrailerSectionSize(e) => { + let (result15_0, result15_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 23i32, + result15_0, + ::core::mem::MaybeUninit::new(i64::from(result15_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpRequestTrailerSize(e) => { + let FieldSizePayload { + field_name: field_name16, + field_size: field_size16, + } = e; + let (result18_0, result18_1, result18_2) = match field_name16 { + Some(e) => { + let vec17 = e; + let ptr17 = vec17.as_ptr().cast::(); + let len17 = vec17.len(); + (1i32, ptr17.cast_mut(), len17) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result19_0, result19_1) = match field_size16 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 24i32, + result18_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result18_1); + t + }, + result18_2 as *mut u8, + result19_0 as *mut u8, + result19_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseIncomplete => { + ( + 25i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseHeaderSectionSize(e) => { + let (result20_0, result20_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 26i32, + result20_0, + ::core::mem::MaybeUninit::new(i64::from(result20_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseHeaderSize(e) => { + let FieldSizePayload { + field_name: field_name21, + field_size: field_size21, + } = e; + let (result23_0, result23_1, result23_2) = match field_name21 { + Some(e) => { + let vec22 = e; + let ptr22 = vec22.as_ptr().cast::(); + let len22 = vec22.len(); + (1i32, ptr22.cast_mut(), len22) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result24_0, result24_1) = match field_size21 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 27i32, + result23_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result23_1); + t + }, + result23_2 as *mut u8, + result24_0 as *mut u8, + result24_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseBodySize(e) => { + let (result25_0, result25_1) = match e { + Some(e) => (1i32, _rt::as_i64(e)), + None => (0i32, 0i64), + }; + ( + 28i32, + result25_0, + ::core::mem::MaybeUninit::new(result25_1 as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTrailerSectionSize(e) => { + let (result26_0, result26_1) = match e { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 29i32, + result26_0, + ::core::mem::MaybeUninit::new(i64::from(result26_1) as u64), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTrailerSize(e) => { + let FieldSizePayload { + field_name: field_name27, + field_size: field_size27, + } = e; + let (result29_0, result29_1, result29_2) = match field_name27 { + Some(e) => { + let vec28 = e; + let ptr28 = vec28.as_ptr().cast::(); + let len28 = vec28.len(); + (1i32, ptr28.cast_mut(), len28) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + let (result30_0, result30_1) = match field_size27 { + Some(e) => (1i32, _rt::as_i32(e)), + None => (0i32, 0i32), + }; + ( + 30i32, + result29_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result29_1); + t + }, + result29_2 as *mut u8, + result30_0 as *mut u8, + result30_1 as usize, + 0i32, + ) + } + ErrorCode::HttpResponseTransferCoding(e) => { + let (result32_0, result32_1, result32_2) = match e { + Some(e) => { + let vec31 = e; + let ptr31 = vec31.as_ptr().cast::(); + let len31 = vec31.len(); + (1i32, ptr31.cast_mut(), len31) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 31i32, + result32_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result32_1); + t + }, + result32_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseContentCoding(e) => { + let (result34_0, result34_1, result34_2) = match e { + Some(e) => { + let vec33 = e; + let ptr33 = vec33.as_ptr().cast::(); + let len33 = vec33.len(); + (1i32, ptr33.cast_mut(), len33) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 32i32, + result34_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result34_1); + t + }, + result34_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpResponseTimeout => { + ( + 33i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpUpgradeFailed => { + ( + 34i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::HttpProtocolError => { + ( + 35i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::LoopDetected => { + ( + 36i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::ConfigurationError => { + ( + 37i32, + 0i32, + ::core::mem::MaybeUninit::::zeroed(), + ::core::ptr::null_mut(), + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + ErrorCode::InternalError(e) => { + let (result36_0, result36_1, result36_2) = match e { + Some(e) => { + let vec35 = e; + let ptr35 = vec35.as_ptr().cast::(); + let len35 = vec35.len(); + (1i32, ptr35.cast_mut(), len35) + } + None => (0i32, ::core::ptr::null_mut(), 0usize), + }; + ( + 38i32, + result36_0, + { + let mut t = ::core::mem::MaybeUninit::::uninit(); + t.as_mut_ptr().cast::<*mut u8>().write(result36_1); + t + }, + result36_2 as *mut u8, + ::core::ptr::null_mut(), + 0usize, + 0i32, + ) + } + }; + ( + 1i32, + result37_0, + result37_1, + result37_2, + result37_3, + result37_4, + result37_5, + result37_6, + ) + } + }; + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]response-outparam.set"] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: i32, + _: ::core::mem::MaybeUninit, + _: *mut u8, + _: *mut u8, + _: usize, + _: i32, + ); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import( + _: i32, + _: i32, + _: i32, + _: i32, + _: ::core::mem::MaybeUninit, + _: *mut u8, + _: *mut u8, + _: usize, + _: i32, + ) { + unreachable!() + } + wit_import( + (¶m).take_handle() as i32, + result38_0, + result38_1, + result38_2, + result38_3, + result38_4, + result38_5, + result38_6, + result38_7, + ); + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the status code from the incoming response. + pub fn status(&self) -> StatusCode { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.status"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + ret as u16 + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl IncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + pub fn consume(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-response.consume"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + IncomingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn stream(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]incoming-body.stream"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + super::super::super::wasi::io::streams::InputStream::from_handle( + l2 as u32, + ) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl IncomingBody { + #[allow(unused_unsafe, clippy::all)] + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + pub fn finish(this: IncomingBody) -> FutureTrailers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]incoming-body.finish"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&this).take_handle() as i32); + FutureTrailers::from_handle(ret as u32) + } + } + } + impl FutureTrailers { + #[allow(unused_unsafe, clippy::all)] + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-trailers.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl FutureTrailers { + #[allow(unused_unsafe, clippy::all)] + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + pub fn get( + &self, + ) -> Option, ErrorCode>, ()>> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 56]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 56], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-trailers.get"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + match l2 { + 0 => { + let e = { + let l3 = i32::from(*ptr0.add(16).cast::()); + match l3 { + 0 => { + let e = { + let l4 = i32::from(*ptr0.add(24).cast::()); + match l4 { + 0 => None, + 1 => { + let e = { + let l5 = *ptr0.add(28).cast::(); + Fields::from_handle(l5 as u32) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = { + let l6 = i32::from(*ptr0.add(24).cast::()); + let v68 = match l6 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e68 = { + let l7 = i32::from(*ptr0.add(32).cast::()); + let l11 = i32::from(*ptr0.add(44).cast::()); + DnsErrorPayload { + rcode: match l7 { + 0 => None, + 1 => { + let e = { + let l8 = *ptr0.add(36).cast::<*mut u8>(); + let l9 = *ptr0.add(40).cast::(); + let len10 = l9; + let bytes10 = _rt::Vec::from_raw_parts( + l8.cast(), + len10, + len10, + ); + _rt::string_lift(bytes10) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l11 { + 0 => None, + 1 => { + let e = { + let l12 = i32::from(*ptr0.add(46).cast::()); + l12 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e68) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e68 = { + let l13 = i32::from(*ptr0.add(32).cast::()); + let l15 = i32::from(*ptr0.add(36).cast::()); + TlsAlertReceivedPayload { + alert_id: match l13 { + 0 => None, + 1 => { + let e = { + let l14 = i32::from(*ptr0.add(33).cast::()); + l14 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l15 { + 0 => None, + 1 => { + let e = { + let l16 = *ptr0.add(40).cast::<*mut u8>(); + let l17 = *ptr0.add(44).cast::(); + let len18 = l17; + let bytes18 = _rt::Vec::from_raw_parts( + l16.cast(), + len18, + len18, + ); + _rt::string_lift(bytes18) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e68) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e68 = { + let l19 = i32::from(*ptr0.add(32).cast::()); + match l19 { + 0 => None, + 1 => { + let e = { + let l20 = *ptr0.add(40).cast::(); + l20 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e68) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e68 = { + let l21 = i32::from(*ptr0.add(32).cast::()); + match l21 { + 0 => None, + 1 => { + let e = { + let l22 = *ptr0.add(36).cast::(); + l22 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e68) + } + 22 => { + let e68 = { + let l23 = i32::from(*ptr0.add(32).cast::()); + match l23 { + 0 => None, + 1 => { + let e = { + let l24 = i32::from(*ptr0.add(36).cast::()); + let l28 = i32::from(*ptr0.add(48).cast::()); + FieldSizePayload { + field_name: match l24 { + 0 => None, + 1 => { + let e = { + let l25 = *ptr0.add(40).cast::<*mut u8>(); + let l26 = *ptr0.add(44).cast::(); + let len27 = l26; + let bytes27 = _rt::Vec::from_raw_parts( + l25.cast(), + len27, + len27, + ); + _rt::string_lift(bytes27) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l28 { + 0 => None, + 1 => { + let e = { + let l29 = *ptr0.add(52).cast::(); + l29 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e68) + } + 23 => { + let e68 = { + let l30 = i32::from(*ptr0.add(32).cast::()); + match l30 { + 0 => None, + 1 => { + let e = { + let l31 = *ptr0.add(36).cast::(); + l31 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e68) + } + 24 => { + let e68 = { + let l32 = i32::from(*ptr0.add(32).cast::()); + let l36 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l32 { + 0 => None, + 1 => { + let e = { + let l33 = *ptr0.add(36).cast::<*mut u8>(); + let l34 = *ptr0.add(40).cast::(); + let len35 = l34; + let bytes35 = _rt::Vec::from_raw_parts( + l33.cast(), + len35, + len35, + ); + _rt::string_lift(bytes35) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l36 { + 0 => None, + 1 => { + let e = { + let l37 = *ptr0.add(48).cast::(); + l37 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e68) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e68 = { + let l38 = i32::from(*ptr0.add(32).cast::()); + match l38 { + 0 => None, + 1 => { + let e = { + let l39 = *ptr0.add(36).cast::(); + l39 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e68) + } + 27 => { + let e68 = { + let l40 = i32::from(*ptr0.add(32).cast::()); + let l44 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l40 { + 0 => None, + 1 => { + let e = { + let l41 = *ptr0.add(36).cast::<*mut u8>(); + let l42 = *ptr0.add(40).cast::(); + let len43 = l42; + let bytes43 = _rt::Vec::from_raw_parts( + l41.cast(), + len43, + len43, + ); + _rt::string_lift(bytes43) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l44 { + 0 => None, + 1 => { + let e = { + let l45 = *ptr0.add(48).cast::(); + l45 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e68) + } + 28 => { + let e68 = { + let l46 = i32::from(*ptr0.add(32).cast::()); + match l46 { + 0 => None, + 1 => { + let e = { + let l47 = *ptr0.add(40).cast::(); + l47 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e68) + } + 29 => { + let e68 = { + let l48 = i32::from(*ptr0.add(32).cast::()); + match l48 { + 0 => None, + 1 => { + let e = { + let l49 = *ptr0.add(36).cast::(); + l49 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e68) + } + 30 => { + let e68 = { + let l50 = i32::from(*ptr0.add(32).cast::()); + let l54 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l50 { + 0 => None, + 1 => { + let e = { + let l51 = *ptr0.add(36).cast::<*mut u8>(); + let l52 = *ptr0.add(40).cast::(); + let len53 = l52; + let bytes53 = _rt::Vec::from_raw_parts( + l51.cast(), + len53, + len53, + ); + _rt::string_lift(bytes53) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l54 { + 0 => None, + 1 => { + let e = { + let l55 = *ptr0.add(48).cast::(); + l55 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e68) + } + 31 => { + let e68 = { + let l56 = i32::from(*ptr0.add(32).cast::()); + match l56 { + 0 => None, + 1 => { + let e = { + let l57 = *ptr0.add(36).cast::<*mut u8>(); + let l58 = *ptr0.add(40).cast::(); + let len59 = l58; + let bytes59 = _rt::Vec::from_raw_parts( + l57.cast(), + len59, + len59, + ); + _rt::string_lift(bytes59) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e68) + } + 32 => { + let e68 = { + let l60 = i32::from(*ptr0.add(32).cast::()); + match l60 { + 0 => None, + 1 => { + let e = { + let l61 = *ptr0.add(36).cast::<*mut u8>(); + let l62 = *ptr0.add(40).cast::(); + let len63 = l62; + let bytes63 = _rt::Vec::from_raw_parts( + l61.cast(), + len63, + len63, + ); + _rt::string_lift(bytes63) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e68) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e68 = { + let l64 = i32::from(*ptr0.add(32).cast::()); + match l64 { + 0 => None, + 1 => { + let e = { + let l65 = *ptr0.add(36).cast::<*mut u8>(); + let l66 = *ptr0.add(40).cast::(); + let len67 = l66; + let bytes67 = _rt::Vec::from_raw_parts( + l65.cast(), + len67, + len67, + ); + _rt::string_lift(bytes67) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e68) + } + }; + v68 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn new(headers: Headers) -> Self { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[constructor]outgoing-response"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((&headers).take_handle() as i32); + OutgoingResponse::from_handle(ret as u32) + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Get the HTTP Status Code for the Response. + pub fn status_code(&self) -> StatusCode { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.status-code"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + ret as u16 + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + pub fn set_status_code( + &self, + status_code: StatusCode, + ) -> Result<(), ()> { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.set-status-code"] + fn wit_import(_: i32, _: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32) -> i32 { + unreachable!() + } + let ret = wit_import( + (self).handle() as i32, + _rt::as_i32(status_code), + ); + match ret { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + pub fn headers(&self) -> Headers { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.headers"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + Fields::from_handle(ret as u32) + } + } + } + impl OutgoingResponse { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn body(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-response.body"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + OutgoingBody::from_handle(l2 as u32) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write(&self) -> Result { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]outgoing-body.write"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::(); + super::super::super::wasi::io::streams::OutputStream::from_handle( + l2 as u32, + ) + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutgoingBody { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn finish( + this: OutgoingBody, + trailers: Option, + ) -> Result<(), ErrorCode> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 40]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 40], + ); + let (result0_0, result0_1) = match &trailers { + Some(e) => (1i32, (e).take_handle() as i32), + None => (0i32, 0i32), + }; + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[static]outgoing-body.finish"] + fn wit_import(_: i32, _: i32, _: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i32, _: *mut u8) { + unreachable!() + } + wit_import( + (&this).take_handle() as i32, + result0_0, + result0_1, + ptr1, + ); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(8).cast::()); + let v65 = match l3 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e65 = { + let l4 = i32::from(*ptr1.add(16).cast::()); + let l8 = i32::from(*ptr1.add(28).cast::()); + DnsErrorPayload { + rcode: match l4 { + 0 => None, + 1 => { + let e = { + let l5 = *ptr1.add(20).cast::<*mut u8>(); + let l6 = *ptr1.add(24).cast::(); + let len7 = l6; + let bytes7 = _rt::Vec::from_raw_parts( + l5.cast(), + len7, + len7, + ); + _rt::string_lift(bytes7) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l8 { + 0 => None, + 1 => { + let e = { + let l9 = i32::from(*ptr1.add(30).cast::()); + l9 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e65) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e65 = { + let l10 = i32::from(*ptr1.add(16).cast::()); + let l12 = i32::from(*ptr1.add(20).cast::()); + TlsAlertReceivedPayload { + alert_id: match l10 { + 0 => None, + 1 => { + let e = { + let l11 = i32::from(*ptr1.add(17).cast::()); + l11 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l12 { + 0 => None, + 1 => { + let e = { + let l13 = *ptr1.add(24).cast::<*mut u8>(); + let l14 = *ptr1.add(28).cast::(); + let len15 = l14; + let bytes15 = _rt::Vec::from_raw_parts( + l13.cast(), + len15, + len15, + ); + _rt::string_lift(bytes15) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e65) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e65 = { + let l16 = i32::from(*ptr1.add(16).cast::()); + match l16 { + 0 => None, + 1 => { + let e = { + let l17 = *ptr1.add(24).cast::(); + l17 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e65) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e65 = { + let l18 = i32::from(*ptr1.add(16).cast::()); + match l18 { + 0 => None, + 1 => { + let e = { + let l19 = *ptr1.add(20).cast::(); + l19 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e65) + } + 22 => { + let e65 = { + let l20 = i32::from(*ptr1.add(16).cast::()); + match l20 { + 0 => None, + 1 => { + let e = { + let l21 = i32::from(*ptr1.add(20).cast::()); + let l25 = i32::from(*ptr1.add(32).cast::()); + FieldSizePayload { + field_name: match l21 { + 0 => None, + 1 => { + let e = { + let l22 = *ptr1.add(24).cast::<*mut u8>(); + let l23 = *ptr1.add(28).cast::(); + let len24 = l23; + let bytes24 = _rt::Vec::from_raw_parts( + l22.cast(), + len24, + len24, + ); + _rt::string_lift(bytes24) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l25 { + 0 => None, + 1 => { + let e = { + let l26 = *ptr1.add(36).cast::(); + l26 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e65) + } + 23 => { + let e65 = { + let l27 = i32::from(*ptr1.add(16).cast::()); + match l27 { + 0 => None, + 1 => { + let e = { + let l28 = *ptr1.add(20).cast::(); + l28 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e65) + } + 24 => { + let e65 = { + let l29 = i32::from(*ptr1.add(16).cast::()); + let l33 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l29 { + 0 => None, + 1 => { + let e = { + let l30 = *ptr1.add(20).cast::<*mut u8>(); + let l31 = *ptr1.add(24).cast::(); + let len32 = l31; + let bytes32 = _rt::Vec::from_raw_parts( + l30.cast(), + len32, + len32, + ); + _rt::string_lift(bytes32) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l33 { + 0 => None, + 1 => { + let e = { + let l34 = *ptr1.add(32).cast::(); + l34 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e65) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e65 = { + let l35 = i32::from(*ptr1.add(16).cast::()); + match l35 { + 0 => None, + 1 => { + let e = { + let l36 = *ptr1.add(20).cast::(); + l36 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e65) + } + 27 => { + let e65 = { + let l37 = i32::from(*ptr1.add(16).cast::()); + let l41 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l37 { + 0 => None, + 1 => { + let e = { + let l38 = *ptr1.add(20).cast::<*mut u8>(); + let l39 = *ptr1.add(24).cast::(); + let len40 = l39; + let bytes40 = _rt::Vec::from_raw_parts( + l38.cast(), + len40, + len40, + ); + _rt::string_lift(bytes40) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l41 { + 0 => None, + 1 => { + let e = { + let l42 = *ptr1.add(32).cast::(); + l42 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e65) + } + 28 => { + let e65 = { + let l43 = i32::from(*ptr1.add(16).cast::()); + match l43 { + 0 => None, + 1 => { + let e = { + let l44 = *ptr1.add(24).cast::(); + l44 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e65) + } + 29 => { + let e65 = { + let l45 = i32::from(*ptr1.add(16).cast::()); + match l45 { + 0 => None, + 1 => { + let e = { + let l46 = *ptr1.add(20).cast::(); + l46 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e65) + } + 30 => { + let e65 = { + let l47 = i32::from(*ptr1.add(16).cast::()); + let l51 = i32::from(*ptr1.add(28).cast::()); + FieldSizePayload { + field_name: match l47 { + 0 => None, + 1 => { + let e = { + let l48 = *ptr1.add(20).cast::<*mut u8>(); + let l49 = *ptr1.add(24).cast::(); + let len50 = l49; + let bytes50 = _rt::Vec::from_raw_parts( + l48.cast(), + len50, + len50, + ); + _rt::string_lift(bytes50) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l51 { + 0 => None, + 1 => { + let e = { + let l52 = *ptr1.add(32).cast::(); + l52 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e65) + } + 31 => { + let e65 = { + let l53 = i32::from(*ptr1.add(16).cast::()); + match l53 { + 0 => None, + 1 => { + let e = { + let l54 = *ptr1.add(20).cast::<*mut u8>(); + let l55 = *ptr1.add(24).cast::(); + let len56 = l55; + let bytes56 = _rt::Vec::from_raw_parts( + l54.cast(), + len56, + len56, + ); + _rt::string_lift(bytes56) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e65) + } + 32 => { + let e65 = { + let l57 = i32::from(*ptr1.add(16).cast::()); + match l57 { + 0 => None, + 1 => { + let e = { + let l58 = *ptr1.add(20).cast::<*mut u8>(); + let l59 = *ptr1.add(24).cast::(); + let len60 = l59; + let bytes60 = _rt::Vec::from_raw_parts( + l58.cast(), + len60, + len60, + ); + _rt::string_lift(bytes60) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e65) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e65 = { + let l61 = i32::from(*ptr1.add(16).cast::()); + match l61 { + 0 => None, + 1 => { + let e = { + let l62 = *ptr1.add(20).cast::<*mut u8>(); + let l63 = *ptr1.add(24).cast::(); + let len64 = l63; + let bytes64 = _rt::Vec::from_raw_parts( + l62.cast(), + len64, + len64, + ); + _rt::string_lift(bytes64) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e65) + } + }; + v65 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl FutureIncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-incoming-response.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl FutureIncomingResponse { + #[allow(unused_unsafe, clippy::all)] + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + pub fn get( + &self, + ) -> Option, ()>> { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 56]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 56], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:http/types@0.2.3")] + extern "C" { + #[link_name = "[method]future-incoming-response.get"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => None, + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(8).cast::()); + match l2 { + 0 => { + let e = { + let l3 = i32::from(*ptr0.add(16).cast::()); + match l3 { + 0 => { + let e = { + let l4 = *ptr0.add(24).cast::(); + IncomingResponse::from_handle(l4 as u32) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(24).cast::()); + let v67 = match l5 { + 0 => ErrorCode::DnsTimeout, + 1 => { + let e67 = { + let l6 = i32::from(*ptr0.add(32).cast::()); + let l10 = i32::from(*ptr0.add(44).cast::()); + DnsErrorPayload { + rcode: match l6 { + 0 => None, + 1 => { + let e = { + let l7 = *ptr0.add(36).cast::<*mut u8>(); + let l8 = *ptr0.add(40).cast::(); + let len9 = l8; + let bytes9 = _rt::Vec::from_raw_parts( + l7.cast(), + len9, + len9, + ); + _rt::string_lift(bytes9) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + info_code: match l10 { + 0 => None, + 1 => { + let e = { + let l11 = i32::from(*ptr0.add(46).cast::()); + l11 as u16 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::DnsError(e67) + } + 2 => ErrorCode::DestinationNotFound, + 3 => ErrorCode::DestinationUnavailable, + 4 => ErrorCode::DestinationIpProhibited, + 5 => ErrorCode::DestinationIpUnroutable, + 6 => ErrorCode::ConnectionRefused, + 7 => ErrorCode::ConnectionTerminated, + 8 => ErrorCode::ConnectionTimeout, + 9 => ErrorCode::ConnectionReadTimeout, + 10 => ErrorCode::ConnectionWriteTimeout, + 11 => ErrorCode::ConnectionLimitReached, + 12 => ErrorCode::TlsProtocolError, + 13 => ErrorCode::TlsCertificateError, + 14 => { + let e67 = { + let l12 = i32::from(*ptr0.add(32).cast::()); + let l14 = i32::from(*ptr0.add(36).cast::()); + TlsAlertReceivedPayload { + alert_id: match l12 { + 0 => None, + 1 => { + let e = { + let l13 = i32::from(*ptr0.add(33).cast::()); + l13 as u8 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + alert_message: match l14 { + 0 => None, + 1 => { + let e = { + let l15 = *ptr0.add(40).cast::<*mut u8>(); + let l16 = *ptr0.add(44).cast::(); + let len17 = l16; + let bytes17 = _rt::Vec::from_raw_parts( + l15.cast(), + len17, + len17, + ); + _rt::string_lift(bytes17) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::TlsAlertReceived(e67) + } + 15 => ErrorCode::HttpRequestDenied, + 16 => ErrorCode::HttpRequestLengthRequired, + 17 => { + let e67 = { + let l18 = i32::from(*ptr0.add(32).cast::()); + match l18 { + 0 => None, + 1 => { + let e = { + let l19 = *ptr0.add(40).cast::(); + l19 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestBodySize(e67) + } + 18 => ErrorCode::HttpRequestMethodInvalid, + 19 => ErrorCode::HttpRequestUriInvalid, + 20 => ErrorCode::HttpRequestUriTooLong, + 21 => { + let e67 = { + let l20 = i32::from(*ptr0.add(32).cast::()); + match l20 { + 0 => None, + 1 => { + let e = { + let l21 = *ptr0.add(36).cast::(); + l21 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSectionSize(e67) + } + 22 => { + let e67 = { + let l22 = i32::from(*ptr0.add(32).cast::()); + match l22 { + 0 => None, + 1 => { + let e = { + let l23 = i32::from(*ptr0.add(36).cast::()); + let l27 = i32::from(*ptr0.add(48).cast::()); + FieldSizePayload { + field_name: match l23 { + 0 => None, + 1 => { + let e = { + let l24 = *ptr0.add(40).cast::<*mut u8>(); + let l25 = *ptr0.add(44).cast::(); + let len26 = l25; + let bytes26 = _rt::Vec::from_raw_parts( + l24.cast(), + len26, + len26, + ); + _rt::string_lift(bytes26) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l27 { + 0 => None, + 1 => { + let e = { + let l28 = *ptr0.add(52).cast::(); + l28 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestHeaderSize(e67) + } + 23 => { + let e67 = { + let l29 = i32::from(*ptr0.add(32).cast::()); + match l29 { + 0 => None, + 1 => { + let e = { + let l30 = *ptr0.add(36).cast::(); + l30 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpRequestTrailerSectionSize(e67) + } + 24 => { + let e67 = { + let l31 = i32::from(*ptr0.add(32).cast::()); + let l35 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l31 { + 0 => None, + 1 => { + let e = { + let l32 = *ptr0.add(36).cast::<*mut u8>(); + let l33 = *ptr0.add(40).cast::(); + let len34 = l33; + let bytes34 = _rt::Vec::from_raw_parts( + l32.cast(), + len34, + len34, + ); + _rt::string_lift(bytes34) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l35 { + 0 => None, + 1 => { + let e = { + let l36 = *ptr0.add(48).cast::(); + l36 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpRequestTrailerSize(e67) + } + 25 => ErrorCode::HttpResponseIncomplete, + 26 => { + let e67 = { + let l37 = i32::from(*ptr0.add(32).cast::()); + match l37 { + 0 => None, + 1 => { + let e = { + let l38 = *ptr0.add(36).cast::(); + l38 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseHeaderSectionSize(e67) + } + 27 => { + let e67 = { + let l39 = i32::from(*ptr0.add(32).cast::()); + let l43 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l39 { + 0 => None, + 1 => { + let e = { + let l40 = *ptr0.add(36).cast::<*mut u8>(); + let l41 = *ptr0.add(40).cast::(); + let len42 = l41; + let bytes42 = _rt::Vec::from_raw_parts( + l40.cast(), + len42, + len42, + ); + _rt::string_lift(bytes42) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l43 { + 0 => None, + 1 => { + let e = { + let l44 = *ptr0.add(48).cast::(); + l44 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseHeaderSize(e67) + } + 28 => { + let e67 = { + let l45 = i32::from(*ptr0.add(32).cast::()); + match l45 { + 0 => None, + 1 => { + let e = { + let l46 = *ptr0.add(40).cast::(); + l46 as u64 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseBodySize(e67) + } + 29 => { + let e67 = { + let l47 = i32::from(*ptr0.add(32).cast::()); + match l47 { + 0 => None, + 1 => { + let e = { + let l48 = *ptr0.add(36).cast::(); + l48 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTrailerSectionSize(e67) + } + 30 => { + let e67 = { + let l49 = i32::from(*ptr0.add(32).cast::()); + let l53 = i32::from(*ptr0.add(44).cast::()); + FieldSizePayload { + field_name: match l49 { + 0 => None, + 1 => { + let e = { + let l50 = *ptr0.add(36).cast::<*mut u8>(); + let l51 = *ptr0.add(40).cast::(); + let len52 = l51; + let bytes52 = _rt::Vec::from_raw_parts( + l50.cast(), + len52, + len52, + ); + _rt::string_lift(bytes52) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + field_size: match l53 { + 0 => None, + 1 => { + let e = { + let l54 = *ptr0.add(48).cast::(); + l54 as u32 + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + }, + } + }; + ErrorCode::HttpResponseTrailerSize(e67) + } + 31 => { + let e67 = { + let l55 = i32::from(*ptr0.add(32).cast::()); + match l55 { + 0 => None, + 1 => { + let e = { + let l56 = *ptr0.add(36).cast::<*mut u8>(); + let l57 = *ptr0.add(40).cast::(); + let len58 = l57; + let bytes58 = _rt::Vec::from_raw_parts( + l56.cast(), + len58, + len58, + ); + _rt::string_lift(bytes58) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseTransferCoding(e67) + } + 32 => { + let e67 = { + let l59 = i32::from(*ptr0.add(32).cast::()); + match l59 { + 0 => None, + 1 => { + let e = { + let l60 = *ptr0.add(36).cast::<*mut u8>(); + let l61 = *ptr0.add(40).cast::(); + let len62 = l61; + let bytes62 = _rt::Vec::from_raw_parts( + l60.cast(), + len62, + len62, + ); + _rt::string_lift(bytes62) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::HttpResponseContentCoding(e67) + } + 33 => ErrorCode::HttpResponseTimeout, + 34 => ErrorCode::HttpUpgradeFailed, + 35 => ErrorCode::HttpProtocolError, + 36 => ErrorCode::LoopDetected, + 37 => ErrorCode::ConfigurationError, + n => { + debug_assert_eq!(n, 38, "invalid enum discriminant"); + let e67 = { + let l63 = i32::from(*ptr0.add(32).cast::()); + match l63 { + 0 => None, + 1 => { + let e = { + let l64 = *ptr0.add(36).cast::<*mut u8>(); + let l65 = *ptr0.add(40).cast::(); + let len66 = l65; + let bytes66 = _rt::Vec::from_raw_parts( + l64.cast(), + len66, + len66, + ); + _rt::string_lift(bytes66) + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + ErrorCode::InternalError(e67) + } + }; + v67 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Ok(e) + } + 1 => { + let e = (); + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + }; + Some(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + } + } + #[allow(dead_code)] + pub mod io { + #[allow(dead_code, clippy::all)] + pub mod poll { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + /// `pollable` represents a single I/O event which may be ready, or not. + #[derive(Debug)] + #[repr(transparent)] + pub struct Pollable { + handle: _rt::Resource, + } + impl Pollable { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Pollable { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]pollable"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl Pollable { + #[allow(unused_unsafe, clippy::all)] + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + pub fn ready(&self) -> bool { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[method]pollable.ready"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + _rt::bool_lift(ret as u8) + } + } + } + impl Pollable { + #[allow(unused_unsafe, clippy::all)] + /// `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. + pub fn block(&self) { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "[method]pollable.block"] + fn wit_import(_: i32); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) { + unreachable!() + } + wit_import((self).handle() as i32); + } + } + } + #[allow(unused_unsafe, clippy::all)] + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being ready for I/O. + pub fn poll(in_: &[&Pollable]) -> _rt::Vec { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea([::core::mem::MaybeUninit::uninit(); 8]); + let vec0 = in_; + let len0 = vec0.len(); + let layout0 = _rt::alloc::Layout::from_size_align_unchecked( + vec0.len() * 4, + 4, + ); + let result0 = if layout0.size() != 0 { + let ptr = _rt::alloc::alloc(layout0).cast::(); + if ptr.is_null() { + _rt::alloc::handle_alloc_error(layout0); + } + ptr + } else { + ::core::ptr::null_mut() + }; + for (i, e) in vec0.into_iter().enumerate() { + let base = result0.add(i * 4); + { + *base.add(0).cast::() = (e).handle() as i32; + } + } + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/poll@0.2.3")] + extern "C" { + #[link_name = "poll"] + fn wit_import(_: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import(result0, len0, ptr1); + let l2 = *ptr1.add(0).cast::<*mut u8>(); + let l3 = *ptr1.add(4).cast::(); + let len4 = l3; + if layout0.size() != 0 { + _rt::alloc::dealloc(result0.cast(), layout0); + } + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + } + } + } + #[allow(dead_code, clippy::all)] + pub mod error { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + #[derive(Debug)] + #[repr(transparent)] + pub struct Error { + handle: _rt::Resource, + } + impl Error { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for Error { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/error@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]error"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl Error { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn to_debug_string(&self) -> _rt::String { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 8]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 8], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/error@0.2.3")] + extern "C" { + #[link_name = "[method]error.to-debug-string"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = *ptr0.add(0).cast::<*mut u8>(); + let l2 = *ptr0.add(4).cast::(); + let len3 = l2; + let bytes3 = _rt::Vec::from_raw_parts(l1.cast(), len3, len3); + _rt::string_lift(bytes3) + } + } + } + } + #[allow(dead_code, clippy::all)] + pub mod streams { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::__link_custom_section_describing_imports; + use super::super::super::_rt; + pub type Error = super::super::super::wasi::io::error::Error; + pub type Pollable = super::super::super::wasi::io::poll::Pollable; + /// An error for input-stream and output-stream operations. + pub enum StreamError { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + LastOperationFailed(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, + } + impl ::core::fmt::Debug for StreamError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + match self { + StreamError::LastOperationFailed(e) => { + f.debug_tuple("StreamError::LastOperationFailed") + .field(e) + .finish() + } + StreamError::Closed => { + f.debug_tuple("StreamError::Closed").finish() + } + } + } + } + impl ::core::fmt::Display for StreamError { + fn fmt( + &self, + f: &mut ::core::fmt::Formatter<'_>, + ) -> ::core::fmt::Result { + write!(f, "{:?}", self) + } + } + impl std::error::Error for StreamError {} + /// 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`. + #[derive(Debug)] + #[repr(transparent)] + pub struct InputStream { + handle: _rt::Resource, + } + impl InputStream { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for InputStream { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]input-stream"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + #[derive(Debug)] + #[repr(transparent)] + pub struct OutputStream { + handle: _rt::Resource, + } + impl OutputStream { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + Self { + handle: _rt::Resource::from_handle(handle), + } + } + #[doc(hidden)] + pub fn take_handle(&self) -> u32 { + _rt::Resource::take_handle(&self.handle) + } + #[doc(hidden)] + pub fn handle(&self) -> u32 { + _rt::Resource::handle(&self.handle) + } + } + unsafe impl _rt::WasmResource for OutputStream { + #[inline] + unsafe fn drop(_handle: u32) { + #[cfg(not(target_arch = "wasm32"))] + unreachable!(); + #[cfg(target_arch = "wasm32")] + { + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[resource-drop]output-stream"] + fn drop(_: u32); + } + drop(_handle); + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn read(&self, len: u64) -> Result<_rt::Vec, StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.read"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(4).cast::()); + let v7 = match l5 { + 0 => { + let e7 = { + let l6 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l6 as u32, + ) + }; + StreamError::LastOperationFailed(e7) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v7 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + pub fn blocking_read( + &self, + len: u64, + ) -> Result<_rt::Vec, StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.blocking-read"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(4).cast::<*mut u8>(); + let l3 = *ptr0.add(8).cast::(); + let len4 = l3; + _rt::Vec::from_raw_parts(l2.cast(), len4, len4) + }; + Ok(e) + } + 1 => { + let e = { + let l5 = i32::from(*ptr0.add(4).cast::()); + let v7 = match l5 { + 0 => { + let e7 = { + let l6 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l6 as u32, + ) + }; + StreamError::LastOperationFailed(e7) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v7 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn skip(&self, len: u64) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.skip"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + pub fn blocking_skip(&self, len: u64) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.blocking-skip"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl InputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]input-stream.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn check_write(&self) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.check-write"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write(&self, contents: &[u8]) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let vec0 = contents; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.write"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(4).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr1.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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 + /// ``` + pub fn blocking_write_and_flush( + &self, + contents: &[u8], + ) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let vec0 = contents; + let ptr0 = vec0.as_ptr().cast::(); + let len0 = vec0.len(); + let ptr1 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-write-and-flush"] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8, _: usize, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0.cast_mut(), len0, ptr1); + let l2 = i32::from(*ptr1.add(0).cast::()); + match l2 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr1.add(4).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr1.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn flush(&self) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.flush"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + pub fn blocking_flush(&self) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-flush"] + fn wit_import(_: i32, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + pub fn subscribe(&self) -> Pollable { + unsafe { + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.subscribe"] + fn wit_import(_: i32) -> i32; + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32) -> i32 { + unreachable!() + } + let ret = wit_import((self).handle() as i32); + super::super::super::wasi::io::poll::Pollable::from_handle( + ret as u32, + ) + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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. + pub fn write_zeroes(&self, len: u64) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.write-zeroes"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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 + /// ``` + pub fn blocking_write_zeroes_and_flush( + &self, + len: u64, + ) -> Result<(), StreamError> { + unsafe { + #[repr(align(4))] + struct RetArea([::core::mem::MaybeUninit; 12]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 12], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-write-zeroes-and-flush"] + fn wit_import(_: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import((self).handle() as i32, _rt::as_i64(&len), ptr0); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = (); + Ok(e) + } + 1 => { + let e = { + let l2 = i32::from(*ptr0.add(4).cast::()); + let v4 = match l2 { + 0 => { + let e4 = { + let l3 = *ptr0.add(8).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l3 as u32, + ) + }; + StreamError::LastOperationFailed(e4) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v4 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + pub fn splice( + &self, + src: &InputStream, + len: u64, + ) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.splice"] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import( + (self).handle() as i32, + (src).handle() as i32, + _rt::as_i64(&len), + ptr0, + ); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + impl OutputStream { + #[allow(unused_unsafe, clippy::all)] + /// 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`. + pub fn blocking_splice( + &self, + src: &InputStream, + len: u64, + ) -> Result { + unsafe { + #[repr(align(8))] + struct RetArea([::core::mem::MaybeUninit; 16]); + let mut ret_area = RetArea( + [::core::mem::MaybeUninit::uninit(); 16], + ); + let ptr0 = ret_area.0.as_mut_ptr().cast::(); + #[cfg(target_arch = "wasm32")] + #[link(wasm_import_module = "wasi:io/streams@0.2.3")] + extern "C" { + #[link_name = "[method]output-stream.blocking-splice"] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8); + } + #[cfg(not(target_arch = "wasm32"))] + fn wit_import(_: i32, _: i32, _: i64, _: *mut u8) { + unreachable!() + } + wit_import( + (self).handle() as i32, + (src).handle() as i32, + _rt::as_i64(&len), + ptr0, + ); + let l1 = i32::from(*ptr0.add(0).cast::()); + match l1 { + 0 => { + let e = { + let l2 = *ptr0.add(8).cast::(); + l2 as u64 + }; + Ok(e) + } + 1 => { + let e = { + let l3 = i32::from(*ptr0.add(8).cast::()); + let v5 = match l3 { + 0 => { + let e5 = { + let l4 = *ptr0.add(12).cast::(); + super::super::super::wasi::io::error::Error::from_handle( + l4 as u32, + ) + }; + StreamError::LastOperationFailed(e5) + } + n => { + debug_assert_eq!(n, 1, "invalid enum discriminant"); + StreamError::Closed + } + }; + v5 + }; + Err(e) + } + _ => _rt::invalid_enum_discriminant(), + } + } + } + } + } + } +} +#[allow(dead_code)] +pub mod exports { + #[allow(dead_code)] + pub mod wasi { + #[allow(dead_code)] + pub mod http { + #[allow(dead_code, clippy::all)] + pub mod incoming_handler { + #[used] + #[doc(hidden)] + static __FORCE_SECTION_REF: fn() = super::super::super::super::__link_custom_section_describing_imports; + use super::super::super::super::_rt; + pub type IncomingRequest = super::super::super::super::wasi::http::types::IncomingRequest; + pub type ResponseOutparam = super::super::super::super::wasi::http::types::ResponseOutparam; + #[doc(hidden)] + #[allow(non_snake_case)] + pub unsafe fn _export_handle_cabi(arg0: i32, arg1: i32) { + #[cfg(target_arch = "wasm32")] _rt::run_ctors_once(); + T::handle( + super::super::super::super::wasi::http::types::IncomingRequest::from_handle( + arg0 as u32, + ), + super::super::super::super::wasi::http::types::ResponseOutparam::from_handle( + arg1 as u32, + ), + ); + } + pub trait Guest { + /// 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. + fn handle(request: IncomingRequest, response_out: ResponseOutparam); + } + #[doc(hidden)] + macro_rules! __export_wasi_http_incoming_handler_0_2_3_cabi { + ($ty:ident with_types_in $($path_to_types:tt)*) => { + const _ : () = { #[export_name = + "wasi:http/incoming-handler@0.2.3#handle"] unsafe extern "C" fn + export_handle(arg0 : i32, arg1 : i32,) { $($path_to_types)*:: + _export_handle_cabi::<$ty > (arg0, arg1) } }; + }; + } + #[doc(hidden)] + pub(crate) use __export_wasi_http_incoming_handler_0_2_3_cabi; + } + } + } +} +mod _rt { + use core::fmt; + use core::marker; + use core::sync::atomic::{AtomicU32, Ordering::Relaxed}; + /// A type which represents a component model resource, either imported or + /// exported into this component. + /// + /// This is a low-level wrapper which handles the lifetime of the resource + /// (namely this has a destructor). The `T` provided defines the component model + /// intrinsics that this wrapper uses. + /// + /// One of the chief purposes of this type is to provide `Deref` implementations + /// to access the underlying data when it is owned. + /// + /// This type is primarily used in generated code for exported and imported + /// resources. + #[repr(transparent)] + pub struct Resource { + handle: AtomicU32, + _marker: marker::PhantomData, + } + /// A trait which all wasm resources implement, namely providing the ability to + /// drop a resource. + /// + /// This generally is implemented by generated code, not user-facing code. + #[allow(clippy::missing_safety_doc)] + pub unsafe trait WasmResource { + /// Invokes the `[resource-drop]...` intrinsic. + unsafe fn drop(handle: u32); + } + impl Resource { + #[doc(hidden)] + pub unsafe fn from_handle(handle: u32) -> Self { + debug_assert!(handle != u32::MAX); + Self { + handle: AtomicU32::new(handle), + _marker: marker::PhantomData, + } + } + /// Takes ownership of the handle owned by `resource`. + /// + /// Note that this ideally would be `into_handle` taking `Resource` by + /// ownership. The code generator does not enable that in all situations, + /// unfortunately, so this is provided instead. + /// + /// Also note that `take_handle` is in theory only ever called on values + /// owned by a generated function. For example a generated function might + /// take `Resource` as an argument but then call `take_handle` on a + /// reference to that argument. In that sense the dynamic nature of + /// `take_handle` should only be exposed internally to generated code, not + /// to user code. + #[doc(hidden)] + pub fn take_handle(resource: &Resource) -> u32 { + resource.handle.swap(u32::MAX, Relaxed) + } + #[doc(hidden)] + pub fn handle(resource: &Resource) -> u32 { + resource.handle.load(Relaxed) + } + } + impl fmt::Debug for Resource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Resource").field("handle", &self.handle).finish() + } + } + impl Drop for Resource { + fn drop(&mut self) { + unsafe { + match self.handle.load(Relaxed) { + u32::MAX => {} + other => T::drop(other), + } + } + } + } + pub unsafe fn bool_lift(val: u8) -> bool { + if cfg!(debug_assertions) { + match val { + 0 => false, + 1 => true, + _ => panic!("invalid bool discriminant"), + } + } else { + val != 0 + } + } + pub use alloc_crate::vec::Vec; + pub use alloc_crate::alloc; + pub fn as_i64(t: T) -> i64 { + t.as_i64() + } + pub trait AsI64 { + fn as_i64(self) -> i64; + } + impl<'a, T: Copy + AsI64> AsI64 for &'a T { + fn as_i64(self) -> i64 { + (*self).as_i64() + } + } + impl AsI64 for i64 { + #[inline] + fn as_i64(self) -> i64 { + self as i64 + } + } + impl AsI64 for u64 { + #[inline] + fn as_i64(self) -> i64 { + self as i64 + } + } + pub use alloc_crate::string::String; + pub unsafe fn string_lift(bytes: Vec) -> String { + if cfg!(debug_assertions) { + String::from_utf8(bytes).unwrap() + } else { + String::from_utf8_unchecked(bytes) + } + } + pub unsafe fn invalid_enum_discriminant() -> T { + if cfg!(debug_assertions) { + panic!("invalid enum discriminant") + } else { + core::hint::unreachable_unchecked() + } + } + pub unsafe fn cabi_dealloc(ptr: *mut u8, size: usize, align: usize) { + if size == 0 { + return; + } + let layout = alloc::Layout::from_size_align_unchecked(size, align); + alloc::dealloc(ptr, layout); + } + pub fn as_i32(t: T) -> i32 { + t.as_i32() + } + pub trait AsI32 { + fn as_i32(self) -> i32; + } + impl<'a, T: Copy + AsI32> AsI32 for &'a T { + fn as_i32(self) -> i32 { + (*self).as_i32() + } + } + impl AsI32 for i32 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u32 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for i16 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u16 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for i8 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for u8 { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for char { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + impl AsI32 for usize { + #[inline] + fn as_i32(self) -> i32 { + self as i32 + } + } + #[cfg(target_arch = "wasm32")] + pub fn run_ctors_once() { + wit_bindgen_rt::run_ctors_once(); + } + extern crate alloc as alloc_crate; +} +/// Generates `#[no_mangle]` functions to export the specified type as the +/// root implementation of all generated traits. +/// +/// For more information see the documentation of `wit_bindgen::generate!`. +/// +/// ```rust +/// # macro_rules! export{ ($($t:tt)*) => (); } +/// # trait Guest {} +/// struct MyType; +/// +/// impl Guest for MyType { +/// // ... +/// } +/// +/// export!(MyType); +/// ``` +#[allow(unused_macros)] +#[doc(hidden)] +macro_rules! __export_api_impl { + ($ty:ident) => { + self::export!($ty with_types_in self); + }; + ($ty:ident with_types_in $($path_to_types_root:tt)*) => { + $($path_to_types_root)*:: + exports::wasi::http::incoming_handler::__export_wasi_http_incoming_handler_0_2_3_cabi!($ty + with_types_in $($path_to_types_root)*:: exports::wasi::http::incoming_handler); + }; +} +#[doc(inline)] +pub(crate) use __export_api_impl as export; +#[cfg(target_arch = "wasm32")] +#[link_section = "component-type:wit-bindgen:0.35.0:golem:handler:api:encoded world"] +#[doc(hidden)] +pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; 6330] = *b"\ +\0asm\x0d\0\x01\0\0\x19\x16wit-component-encoding\x04\0\x07\xc00\x01A\x02\x01A\x13\ +\x01B\x0a\x04\0\x08pollable\x03\x01\x01h\0\x01@\x01\x04self\x01\0\x7f\x04\0\x16[\ +method]pollable.ready\x01\x02\x01@\x01\x04self\x01\x01\0\x04\0\x16[method]pollab\ +le.block\x01\x03\x01p\x01\x01py\x01@\x01\x02in\x04\0\x05\x04\0\x04poll\x01\x06\x03\ +\0\x12wasi:io/poll@0.2.3\x05\0\x02\x03\0\0\x08pollable\x01B\x0f\x02\x03\x02\x01\x01\ +\x04\0\x08pollable\x03\0\0\x01w\x04\0\x07instant\x03\0\x02\x01w\x04\0\x08duratio\ +n\x03\0\x04\x01@\0\0\x03\x04\0\x03now\x01\x06\x01@\0\0\x05\x04\0\x0aresolution\x01\ +\x07\x01i\x01\x01@\x01\x04when\x03\0\x08\x04\0\x11subscribe-instant\x01\x09\x01@\ +\x01\x04when\x05\0\x08\x04\0\x12subscribe-duration\x01\x0a\x03\0!wasi:clocks/mon\ +otonic-clock@0.2.3\x05\x02\x01B\x04\x04\0\x05error\x03\x01\x01h\0\x01@\x01\x04se\ +lf\x01\0s\x04\0\x1d[method]error.to-debug-string\x01\x02\x03\0\x13wasi:io/error@\ +0.2.3\x05\x03\x02\x03\0\x02\x05error\x01B(\x02\x03\x02\x01\x04\x04\0\x05error\x03\ +\0\0\x02\x03\x02\x01\x01\x04\0\x08pollable\x03\0\x02\x01i\x01\x01q\x02\x15last-o\ +peration-failed\x01\x04\0\x06closed\0\0\x04\0\x0cstream-error\x03\0\x05\x04\0\x0c\ +input-stream\x03\x01\x04\0\x0doutput-stream\x03\x01\x01h\x07\x01p}\x01j\x01\x0a\x01\ +\x06\x01@\x02\x04self\x09\x03lenw\0\x0b\x04\0\x19[method]input-stream.read\x01\x0c\ +\x04\0\"[method]input-stream.blocking-read\x01\x0c\x01j\x01w\x01\x06\x01@\x02\x04\ +self\x09\x03lenw\0\x0d\x04\0\x19[method]input-stream.skip\x01\x0e\x04\0\"[method\ +]input-stream.blocking-skip\x01\x0e\x01i\x03\x01@\x01\x04self\x09\0\x0f\x04\0\x1e\ +[method]input-stream.subscribe\x01\x10\x01h\x08\x01@\x01\x04self\x11\0\x0d\x04\0\ +![method]output-stream.check-write\x01\x12\x01j\0\x01\x06\x01@\x02\x04self\x11\x08\ +contents\x0a\0\x13\x04\0\x1b[method]output-stream.write\x01\x14\x04\0.[method]ou\ +tput-stream.blocking-write-and-flush\x01\x14\x01@\x01\x04self\x11\0\x13\x04\0\x1b\ +[method]output-stream.flush\x01\x15\x04\0$[method]output-stream.blocking-flush\x01\ +\x15\x01@\x01\x04self\x11\0\x0f\x04\0\x1f[method]output-stream.subscribe\x01\x16\ +\x01@\x02\x04self\x11\x03lenw\0\x13\x04\0\"[method]output-stream.write-zeroes\x01\ +\x17\x04\05[method]output-stream.blocking-write-zeroes-and-flush\x01\x17\x01@\x03\ +\x04self\x11\x03src\x09\x03lenw\0\x0d\x04\0\x1c[method]output-stream.splice\x01\x18\ +\x04\0%[method]output-stream.blocking-splice\x01\x18\x03\0\x15wasi:io/streams@0.\ +2.3\x05\x05\x02\x03\0\x01\x08duration\x02\x03\0\x03\x0cinput-stream\x02\x03\0\x03\ +\x0doutput-stream\x01B\xc1\x01\x02\x03\x02\x01\x06\x04\0\x08duration\x03\0\0\x02\ +\x03\x02\x01\x07\x04\0\x0cinput-stream\x03\0\x02\x02\x03\x02\x01\x08\x04\0\x0dou\ +tput-stream\x03\0\x04\x02\x03\x02\x01\x04\x04\0\x08io-error\x03\0\x06\x02\x03\x02\ +\x01\x01\x04\0\x08pollable\x03\0\x08\x01q\x0a\x03get\0\0\x04head\0\0\x04post\0\0\ +\x03put\0\0\x06delete\0\0\x07connect\0\0\x07options\0\0\x05trace\0\0\x05patch\0\0\ +\x05other\x01s\0\x04\0\x06method\x03\0\x0a\x01q\x03\x04HTTP\0\0\x05HTTPS\0\0\x05\ +other\x01s\0\x04\0\x06scheme\x03\0\x0c\x01ks\x01k{\x01r\x02\x05rcode\x0e\x09info\ +-code\x0f\x04\0\x11DNS-error-payload\x03\0\x10\x01k}\x01r\x02\x08alert-id\x12\x0d\ +alert-message\x0e\x04\0\x1aTLS-alert-received-payload\x03\0\x13\x01ky\x01r\x02\x0a\ +field-name\x0e\x0afield-size\x15\x04\0\x12field-size-payload\x03\0\x16\x01kw\x01\ +k\x17\x01q'\x0bDNS-timeout\0\0\x09DNS-error\x01\x11\0\x15destination-not-found\0\ +\0\x17destination-unavailable\0\0\x19destination-IP-prohibited\0\0\x19destinatio\ +n-IP-unroutable\0\0\x12connection-refused\0\0\x15connection-terminated\0\0\x12co\ +nnection-timeout\0\0\x17connection-read-timeout\0\0\x18connection-write-timeout\0\ +\0\x18connection-limit-reached\0\0\x12TLS-protocol-error\0\0\x15TLS-certificate-\ +error\0\0\x12TLS-alert-received\x01\x14\0\x13HTTP-request-denied\0\0\x1cHTTP-req\ +uest-length-required\0\0\x16HTTP-request-body-size\x01\x18\0\x1bHTTP-request-met\ +hod-invalid\0\0\x18HTTP-request-URI-invalid\0\0\x19HTTP-request-URI-too-long\0\0\ +\x20HTTP-request-header-section-size\x01\x15\0\x18HTTP-request-header-size\x01\x19\ +\0!HTTP-request-trailer-section-size\x01\x15\0\x19HTTP-request-trailer-size\x01\x17\ +\0\x18HTTP-response-incomplete\0\0!HTTP-response-header-section-size\x01\x15\0\x19\ +HTTP-response-header-size\x01\x17\0\x17HTTP-response-body-size\x01\x18\0\"HTTP-r\ +esponse-trailer-section-size\x01\x15\0\x1aHTTP-response-trailer-size\x01\x17\0\x1d\ +HTTP-response-transfer-coding\x01\x0e\0\x1cHTTP-response-content-coding\x01\x0e\0\ +\x15HTTP-response-timeout\0\0\x13HTTP-upgrade-failed\0\0\x13HTTP-protocol-error\0\ +\0\x0dloop-detected\0\0\x13configuration-error\0\0\x0einternal-error\x01\x0e\0\x04\ +\0\x0aerror-code\x03\0\x1a\x01q\x03\x0einvalid-syntax\0\0\x09forbidden\0\0\x09im\ +mutable\0\0\x04\0\x0cheader-error\x03\0\x1c\x01s\x04\0\x09field-key\x03\0\x1e\x04\ +\0\x0afield-name\x03\0\x1f\x01p}\x04\0\x0bfield-value\x03\0!\x04\0\x06fields\x03\ +\x01\x04\0\x07headers\x03\0#\x04\0\x08trailers\x03\0#\x04\0\x10incoming-request\x03\ +\x01\x04\0\x10outgoing-request\x03\x01\x04\0\x0frequest-options\x03\x01\x04\0\x11\ +response-outparam\x03\x01\x01{\x04\0\x0bstatus-code\x03\0*\x04\0\x11incoming-res\ +ponse\x03\x01\x04\0\x0dincoming-body\x03\x01\x04\0\x0ffuture-trailers\x03\x01\x04\ +\0\x11outgoing-response\x03\x01\x04\0\x0doutgoing-body\x03\x01\x04\0\x18future-i\ +ncoming-response\x03\x01\x01i#\x01@\0\02\x04\0\x13[constructor]fields\x013\x01o\x02\ +\x20\"\x01p4\x01j\x012\x01\x1d\x01@\x01\x07entries5\06\x04\0\x18[static]fields.f\ +rom-list\x017\x01h#\x01p\"\x01@\x02\x04self8\x04name\x20\09\x04\0\x12[method]fie\ +lds.get\x01:\x01@\x02\x04self8\x04name\x20\0\x7f\x04\0\x12[method]fields.has\x01\ +;\x01j\0\x01\x1d\x01@\x03\x04self8\x04name\x20\x05value9\0<\x04\0\x12[method]fie\ +lds.set\x01=\x01@\x02\x04self8\x04name\x20\0<\x04\0\x15[method]fields.delete\x01\ +>\x01@\x03\x04self8\x04name\x20\x05value\"\0<\x04\0\x15[method]fields.append\x01\ +?\x01@\x01\x04self8\05\x04\0\x16[method]fields.entries\x01@\x01@\x01\x04self8\02\ +\x04\0\x14[method]fields.clone\x01A\x01h&\x01@\x01\x04self\xc2\0\0\x0b\x04\0\x1f\ +[method]incoming-request.method\x01C\x01@\x01\x04self\xc2\0\0\x0e\x04\0([method]\ +incoming-request.path-with-query\x01D\x01k\x0d\x01@\x01\x04self\xc2\0\0\xc5\0\x04\ +\0\x1f[method]incoming-request.scheme\x01F\x04\0\"[method]incoming-request.autho\ +rity\x01D\x01i$\x01@\x01\x04self\xc2\0\0\xc7\0\x04\0\x20[method]incoming-request\ +.headers\x01H\x01i-\x01j\x01\xc9\0\0\x01@\x01\x04self\xc2\0\0\xca\0\x04\0\x20[me\ +thod]incoming-request.consume\x01K\x01i'\x01@\x01\x07headers\xc7\0\0\xcc\0\x04\0\ +\x1d[constructor]outgoing-request\x01M\x01h'\x01i0\x01j\x01\xcf\0\0\x01@\x01\x04\ +self\xce\0\0\xd0\0\x04\0\x1d[method]outgoing-request.body\x01Q\x01@\x01\x04self\xce\ +\0\0\x0b\x04\0\x1f[method]outgoing-request.method\x01R\x01j\0\0\x01@\x02\x04self\ +\xce\0\x06method\x0b\0\xd3\0\x04\0#[method]outgoing-request.set-method\x01T\x01@\ +\x01\x04self\xce\0\0\x0e\x04\0([method]outgoing-request.path-with-query\x01U\x01\ +@\x02\x04self\xce\0\x0fpath-with-query\x0e\0\xd3\0\x04\0,[method]outgoing-reques\ +t.set-path-with-query\x01V\x01@\x01\x04self\xce\0\0\xc5\0\x04\0\x1f[method]outgo\ +ing-request.scheme\x01W\x01@\x02\x04self\xce\0\x06scheme\xc5\0\0\xd3\0\x04\0#[me\ +thod]outgoing-request.set-scheme\x01X\x04\0\"[method]outgoing-request.authority\x01\ +U\x01@\x02\x04self\xce\0\x09authority\x0e\0\xd3\0\x04\0&[method]outgoing-request\ +.set-authority\x01Y\x01@\x01\x04self\xce\0\0\xc7\0\x04\0\x20[method]outgoing-req\ +uest.headers\x01Z\x01i(\x01@\0\0\xdb\0\x04\0\x1c[constructor]request-options\x01\ +\\\x01h(\x01k\x01\x01@\x01\x04self\xdd\0\0\xde\0\x04\0'[method]request-options.c\ +onnect-timeout\x01_\x01@\x02\x04self\xdd\0\x08duration\xde\0\0\xd3\0\x04\0+[meth\ +od]request-options.set-connect-timeout\x01`\x04\0*[method]request-options.first-\ +byte-timeout\x01_\x04\0.[method]request-options.set-first-byte-timeout\x01`\x04\0\ +-[method]request-options.between-bytes-timeout\x01_\x04\01[method]request-option\ +s.set-between-bytes-timeout\x01`\x01i)\x01i/\x01j\x01\xe2\0\x01\x1b\x01@\x02\x05\ +param\xe1\0\x08response\xe3\0\x01\0\x04\0\x1d[static]response-outparam.set\x01d\x01\ +h,\x01@\x01\x04self\xe5\0\0+\x04\0\x20[method]incoming-response.status\x01f\x01@\ +\x01\x04self\xe5\0\0\xc7\0\x04\0![method]incoming-response.headers\x01g\x01@\x01\ +\x04self\xe5\0\0\xca\0\x04\0![method]incoming-response.consume\x01h\x01h-\x01i\x03\ +\x01j\x01\xea\0\0\x01@\x01\x04self\xe9\0\0\xeb\0\x04\0\x1c[method]incoming-body.\ +stream\x01l\x01i.\x01@\x01\x04this\xc9\0\0\xed\0\x04\0\x1c[static]incoming-body.\ +finish\x01n\x01h.\x01i\x09\x01@\x01\x04self\xef\0\0\xf0\0\x04\0![method]future-t\ +railers.subscribe\x01q\x01i%\x01k\xf2\0\x01j\x01\xf3\0\x01\x1b\x01j\x01\xf4\0\0\x01\ +k\xf5\0\x01@\x01\x04self\xef\0\0\xf6\0\x04\0\x1b[method]future-trailers.get\x01w\ +\x01@\x01\x07headers\xc7\0\0\xe2\0\x04\0\x1e[constructor]outgoing-response\x01x\x01\ +h/\x01@\x01\x04self\xf9\0\0+\x04\0%[method]outgoing-response.status-code\x01z\x01\ +@\x02\x04self\xf9\0\x0bstatus-code+\0\xd3\0\x04\0)[method]outgoing-response.set-\ +status-code\x01{\x01@\x01\x04self\xf9\0\0\xc7\0\x04\0![method]outgoing-response.\ +headers\x01|\x01@\x01\x04self\xf9\0\0\xd0\0\x04\0\x1e[method]outgoing-response.b\ +ody\x01}\x01h0\x01i\x05\x01j\x01\xff\0\0\x01@\x01\x04self\xfe\0\0\x80\x01\x04\0\x1b\ +[method]outgoing-body.write\x01\x81\x01\x01j\0\x01\x1b\x01@\x02\x04this\xcf\0\x08\ +trailers\xf3\0\0\x82\x01\x04\0\x1c[static]outgoing-body.finish\x01\x83\x01\x01h1\ +\x01@\x01\x04self\x84\x01\0\xf0\0\x04\0*[method]future-incoming-response.subscri\ +be\x01\x85\x01\x01i,\x01j\x01\x86\x01\x01\x1b\x01j\x01\x87\x01\0\x01k\x88\x01\x01\ +@\x01\x04self\x84\x01\0\x89\x01\x04\0$[method]future-incoming-response.get\x01\x8a\ +\x01\x01h\x07\x01k\x1b\x01@\x01\x03err\x8b\x01\0\x8c\x01\x04\0\x0fhttp-error-cod\ +e\x01\x8d\x01\x03\0\x15wasi:http/types@0.2.3\x05\x09\x02\x03\0\x04\x10incoming-r\ +equest\x02\x03\0\x04\x11response-outparam\x01B\x08\x02\x03\x02\x01\x0a\x04\0\x10\ +incoming-request\x03\0\0\x02\x03\x02\x01\x0b\x04\0\x11response-outparam\x03\0\x02\ +\x01i\x01\x01i\x03\x01@\x02\x07request\x04\x0cresponse-out\x05\x01\0\x04\0\x06ha\ +ndle\x01\x06\x04\0\x20wasi:http/incoming-handler@0.2.3\x05\x0c\x04\0\x11golem:ha\ +ndler/api\x04\0\x0b\x09\x01\0\x03api\x03\0\0\0G\x09producers\x01\x0cprocessed-by\ +\x02\x0dwit-component\x070.220.0\x10wit-bindgen-rust\x060.35.0"; +#[inline(never)] +#[doc(hidden)] +pub fn __link_custom_section_describing_imports() { + wit_bindgen_rt::maybe_link_cabi_realloc(); +} diff --git a/test-components/wasi-http-incoming-request-handler/src/lib.rs b/test-components/wasi-http-incoming-request-handler/src/lib.rs new file mode 100644 index 0000000000..261baf5979 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/src/lib.rs @@ -0,0 +1,19 @@ +mod bindings; + +pub use bindings::wasi::http::types::{ + Fields, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam, +}; + +struct Component; + +impl bindings::exports::wasi::http::incoming_handler::Guest for Component { + fn handle(_request: IncomingRequest, outparam: ResponseOutparam) { + let hdrs = Fields::new(); + let resp = OutgoingResponse::new(hdrs); + resp.set_status_code(200).unwrap(); + + ResponseOutparam::set(outparam, Ok(resp)); + } +} + +bindings::export!(Component with_types_in bindings); diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps.lock b/test-components/wasi-http-incoming-request-handler/wit/deps.lock new file mode 100644 index 0000000000..b97967bf09 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps.lock @@ -0,0 +1,29 @@ +[cli] +sha256 = "4dadd13d55aaf626833d1f4b9c34a17b0f04e993babd09552b785cda3b95ea76" +sha512 = "898dcc4e8c15d18acc6b88dbe232336fa4d19019430a910dbc9e7aeaace3077a164af3be9f002de6e7e65ef693df340801ac0c7e421e9a746bf1b6d698a90835" + +[clocks] +sha256 = "93a701968a7dd3c5d69031bc0601681c468972fdf7e28a93bb6150a67d6ebe8b" +sha512 = "98fca567c7a01887b0fb38981f1772169b6ea8de475b546508f8b86738d84e44ba95cae81def40ac34e8809f5f60e85224077ab8cb6d6d5d6296acc1df73c159" + +[filesystem] +sha256 = "69d42fb10a04a33545b17e055f13db9b1e10e82ba0ed5bdb52334e40dc07c679" +sha512 = "612effbac6f4804fe0c29dae20b78bbba59e52cb754c15402f5fe229c3153a221e0fbdff1d9d00ceaa3fe049c6a95523a5b99f772f1c16d972eade2c88326a30" + +[http] +url = "https://github.com/WebAssembly/wasi-http/archive/v0.2.3.tar.gz" +sha256 = "72d3a00dbf39eed40a134e8b1dee85834961153f9d205ee4dd56657270c084ce" +sha512 = "636150c464c0eb3d60bd212fc5d4012638c8cd4f89b583b87a38154ef99de828aac4296ac13c5cface10ee61e164fcfc43a5c104f916229dfdf49c0d11047677" +deps = ["cli", "clocks", "filesystem", "io", "random", "sockets"] + +[io] +sha256 = "1cccbfe4122686ea57a25cd368e8cdfc408cbcad089f47fb6685b6f92e96f050" +sha512 = "7a95f964c13da52611141acd89bc8876226497f128e99dd176a4270c5b5efbd8cc847b5fbd1a91258d028c646db99e0424d72590cf1caf20f9f3a3343fad5017" + +[random] +sha256 = "dd0c91e7125172eb8fd4568e15ad9fc7305643015e6ece4396c3cc5e8c2bf79a" +sha512 = "d1ca2e7b0616a94a3b39d1b9450bb3fb595b01fd94a8626ad75433038dde40988ecb41ab93a374d569ab72163af3b30038d7bfc3499b9c07193181f4f1d9292a" + +[sockets] +sha256 = "2bc0f65a8046207ee3330ad7d63f6fafeafd4cc0ea4084f081bd5e4f7b177e74" +sha512 = "3e5490e41547dffa78d52631825d93da8d60f4af0246cbaf97e1ecb879285953a86d5f1f390b10c32f91dd7eaec6f43e625a26b1c92c32a0c86fde428aedaaab" diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps.toml b/test-components/wasi-http-incoming-request-handler/wit/deps.toml new file mode 100644 index 0000000000..64ca58191a --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps.toml @@ -0,0 +1 @@ +http = "https://github.com/WebAssembly/wasi-http/archive/v0.2.3.tar.gz" diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/cli/command.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/command.wit new file mode 100644 index 0000000000..3a81766d64 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/command.wit @@ -0,0 +1,10 @@ +package wasi:cli@0.2.3; + +@since(version = 0.2.0) +world command { + @since(version = 0.2.0) + include imports; + + @since(version = 0.2.0) + export run; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/cli/environment.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/environment.wit new file mode 100644 index 0000000000..2f449bd7c1 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/environment.wit @@ -0,0 +1,22 @@ +@since(version = 0.2.0) +interface environment { + /// Get the POSIX-style environment variables. + /// + /// Each environment variable is provided as a pair of string variable names + /// and string value. + /// + /// Morally, these are a value import, but until value imports are available + /// in the component model, this import function should return the same + /// values each time it is called. + @since(version = 0.2.0) + get-environment: func() -> list>; + + /// Get the POSIX-style arguments to the program. + @since(version = 0.2.0) + get-arguments: func() -> list; + + /// Return a path that programs should use as their initial current working + /// directory, interpreting `.` as shorthand for this. + @since(version = 0.2.0) + initial-cwd: func() -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/cli/exit.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/exit.wit new file mode 100644 index 0000000000..427935c8d0 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/exit.wit @@ -0,0 +1,17 @@ +@since(version = 0.2.0) +interface exit { + /// Exit the current instance and any linked instances. + @since(version = 0.2.0) + exit: func(status: result); + + /// Exit the current instance and any linked instances, reporting the + /// specified status code to the host. + /// + /// The meaning of the code depends on the context, with 0 usually meaning + /// "success", and other values indicating various types of failure. + /// + /// This function does not return; the effect is analogous to a trap, but + /// without the connotation that something bad has happened. + @unstable(feature = cli-exit-with-code) + exit-with-code: func(status-code: u8); +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/cli/imports.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/imports.wit new file mode 100644 index 0000000000..8b4e3975ec --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/imports.wit @@ -0,0 +1,36 @@ +package wasi:cli@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + include wasi:clocks/imports@0.2.3; + @since(version = 0.2.0) + include wasi:filesystem/imports@0.2.3; + @since(version = 0.2.0) + include wasi:sockets/imports@0.2.3; + @since(version = 0.2.0) + include wasi:random/imports@0.2.3; + @since(version = 0.2.0) + include wasi:io/imports@0.2.3; + + @since(version = 0.2.0) + import environment; + @since(version = 0.2.0) + import exit; + @since(version = 0.2.0) + import stdin; + @since(version = 0.2.0) + import stdout; + @since(version = 0.2.0) + import stderr; + @since(version = 0.2.0) + import terminal-input; + @since(version = 0.2.0) + import terminal-output; + @since(version = 0.2.0) + import terminal-stdin; + @since(version = 0.2.0) + import terminal-stdout; + @since(version = 0.2.0) + import terminal-stderr; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/cli/run.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/run.wit new file mode 100644 index 0000000000..655346efb6 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/run.wit @@ -0,0 +1,6 @@ +@since(version = 0.2.0) +interface run { + /// Run the program. + @since(version = 0.2.0) + run: func() -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/cli/stdio.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/stdio.wit new file mode 100644 index 0000000000..1b54f5318a --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/stdio.wit @@ -0,0 +1,26 @@ +@since(version = 0.2.0) +interface stdin { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream}; + + @since(version = 0.2.0) + get-stdin: func() -> input-stream; +} + +@since(version = 0.2.0) +interface stdout { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{output-stream}; + + @since(version = 0.2.0) + get-stdout: func() -> output-stream; +} + +@since(version = 0.2.0) +interface stderr { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{output-stream}; + + @since(version = 0.2.0) + get-stderr: func() -> output-stream; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/cli/terminal.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/terminal.wit new file mode 100644 index 0000000000..d305498c64 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/cli/terminal.wit @@ -0,0 +1,62 @@ +/// Terminal input. +/// +/// In the future, this may include functions for disabling echoing, +/// disabling input buffering so that keyboard events are sent through +/// immediately, querying supported features, and so on. +@since(version = 0.2.0) +interface terminal-input { + /// The input side of a terminal. + @since(version = 0.2.0) + resource terminal-input; +} + +/// Terminal output. +/// +/// In the future, this may include functions for querying the terminal +/// size, being notified of terminal size changes, querying supported +/// features, and so on. +@since(version = 0.2.0) +interface terminal-output { + /// The output side of a terminal. + @since(version = 0.2.0) + resource terminal-output; +} + +/// An interface providing an optional `terminal-input` for stdin as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdin { + @since(version = 0.2.0) + use terminal-input.{terminal-input}; + + /// If stdin is connected to a terminal, return a `terminal-input` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdin: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stdout as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stdout { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stdout is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stdout: func() -> option; +} + +/// An interface providing an optional `terminal-output` for stderr as a +/// link-time authority. +@since(version = 0.2.0) +interface terminal-stderr { + @since(version = 0.2.0) + use terminal-output.{terminal-output}; + + /// If stderr is connected to a terminal, return a `terminal-output` handle + /// allowing further interaction with it. + @since(version = 0.2.0) + get-terminal-stderr: func() -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/monotonic-clock.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/monotonic-clock.wit new file mode 100644 index 0000000000..c676fb84d8 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/monotonic-clock.wit @@ -0,0 +1,50 @@ +package wasi:clocks@0.2.3; +/// WASI Monotonic Clock is a clock API intended to let users measure elapsed +/// time. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A monotonic clock is a clock which has an unspecified initial value, and +/// successive reads of the clock will produce non-decreasing values. +@since(version = 0.2.0) +interface monotonic-clock { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + + /// An instant in time, in nanoseconds. An instant is relative to an + /// unspecified initial value, and can only be compared to instances from + /// the same monotonic-clock. + @since(version = 0.2.0) + type instant = u64; + + /// A duration of time, in nanoseconds. + @since(version = 0.2.0) + type duration = u64; + + /// Read the current value of the clock. + /// + /// The clock is monotonic, therefore calling this function repeatedly will + /// produce a sequence of non-decreasing values. + @since(version = 0.2.0) + now: func() -> instant; + + /// Query the resolution of the clock. Returns the duration of time + /// corresponding to a clock tick. + @since(version = 0.2.0) + resolution: func() -> duration; + + /// Create a `pollable` which will resolve once the specified instant + /// has occurred. + @since(version = 0.2.0) + subscribe-instant: func( + when: instant, + ) -> pollable; + + /// Create a `pollable` that will resolve after the specified duration has + /// elapsed from the time this function is invoked. + @since(version = 0.2.0) + subscribe-duration: func( + when: duration, + ) -> pollable; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/timezone.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/timezone.wit new file mode 100644 index 0000000000..b43e93b233 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/timezone.wit @@ -0,0 +1,55 @@ +package wasi:clocks@0.2.3; + +@unstable(feature = clocks-timezone) +interface timezone { + @unstable(feature = clocks-timezone) + use wall-clock.{datetime}; + + /// Return information needed to display the given `datetime`. This includes + /// the UTC offset, the time zone name, and a flag indicating whether + /// daylight saving time is active. + /// + /// If the timezone cannot be determined for the given `datetime`, return a + /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight + /// saving time. + @unstable(feature = clocks-timezone) + display: func(when: datetime) -> timezone-display; + + /// The same as `display`, but only return the UTC offset. + @unstable(feature = clocks-timezone) + utc-offset: func(when: datetime) -> s32; + + /// Information useful for displaying the timezone of a specific `datetime`. + /// + /// This information may vary within a single `timezone` to reflect daylight + /// saving time adjustments. + @unstable(feature = clocks-timezone) + record timezone-display { + /// The number of seconds difference between UTC time and the local + /// time of the timezone. + /// + /// The returned value will always be less than 86400 which is the + /// number of seconds in a day (24*60*60). + /// + /// In implementations that do not expose an actual time zone, this + /// should return 0. + utc-offset: s32, + + /// The abbreviated name of the timezone to display to a user. The name + /// `UTC` indicates Coordinated Universal Time. Otherwise, this should + /// reference local standards for the name of the time zone. + /// + /// In implementations that do not expose an actual time zone, this + /// should be the string `UTC`. + /// + /// In time zones that do not have an applicable name, a formatted + /// representation of the UTC offset may be returned, such as `-04:00`. + name: string, + + /// Whether daylight saving time is active. + /// + /// In implementations that do not expose an actual time zone, this + /// should return false. + in-daylight-saving-time: bool, + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/wall-clock.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/wall-clock.wit new file mode 100644 index 0000000000..e00ce08933 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/wall-clock.wit @@ -0,0 +1,46 @@ +package wasi:clocks@0.2.3; +/// WASI Wall Clock is a clock API intended to let users query the current +/// time. The name "wall" makes an analogy to a "clock on the wall", which +/// is not necessarily monotonic as it may be reset. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +/// +/// A wall clock is a clock which measures the date and time according to +/// some external reference. +/// +/// External references may be reset, so this clock is not necessarily +/// monotonic, making it unsuitable for measuring elapsed time. +/// +/// It is intended for reporting the current date and time for humans. +@since(version = 0.2.0) +interface wall-clock { + /// A time and date in seconds plus nanoseconds. + @since(version = 0.2.0) + record datetime { + seconds: u64, + nanoseconds: u32, + } + + /// Read the current value of the clock. + /// + /// This clock is not monotonic, therefore calling this function repeatedly + /// will not necessarily produce a sequence of non-decreasing values. + /// + /// The returned timestamps represent the number of seconds since + /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], + /// also known as [Unix Time]. + /// + /// The nanoseconds field of the output is always less than 1000000000. + /// + /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 + /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time + @since(version = 0.2.0) + now: func() -> datetime; + + /// Query the resolution of the clock. + /// + /// The nanoseconds field of the output is always less than 1000000000. + @since(version = 0.2.0) + resolution: func() -> datetime; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/world.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/world.wit new file mode 100644 index 0000000000..05f04f797d --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/clocks/world.wit @@ -0,0 +1,11 @@ +package wasi:clocks@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import monotonic-clock; + @since(version = 0.2.0) + import wall-clock; + @unstable(feature = clocks-timezone) + import timezone; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/preopens.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/preopens.wit new file mode 100644 index 0000000000..cea97495b5 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/preopens.wit @@ -0,0 +1,11 @@ +package wasi:filesystem@0.2.3; + +@since(version = 0.2.0) +interface preopens { + @since(version = 0.2.0) + use types.{descriptor}; + + /// Return the set of preopened directories, and their paths. + @since(version = 0.2.0) + get-directories: func() -> list>; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/types.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/types.wit new file mode 100644 index 0000000000..d229a21f48 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/types.wit @@ -0,0 +1,672 @@ +package wasi:filesystem@0.2.3; +/// WASI filesystem is a filesystem API primarily intended to let users run WASI +/// programs that access their files on their existing filesystems, without +/// significant overhead. +/// +/// It is intended to be roughly portable between Unix-family platforms and +/// Windows, though it does not hide many of the major differences. +/// +/// Paths are passed as interface-type `string`s, meaning they must consist of +/// a sequence of Unicode Scalar Values (USVs). Some filesystems may contain +/// paths which are not accessible by this API. +/// +/// The directory separator in WASI is always the forward-slash (`/`). +/// +/// All paths in WASI are relative paths, and are interpreted relative to a +/// `descriptor` referring to a base directory. If a `path` argument to any WASI +/// function starts with `/`, or if any step of resolving a `path`, including +/// `..` and symbolic link steps, reaches a directory outside of the base +/// directory, or reaches a symlink to an absolute or rooted path in the +/// underlying filesystem, the function fails with `error-code::not-permitted`. +/// +/// For more information about WASI path resolution and sandboxing, see +/// [WASI filesystem path resolution]. +/// +/// [WASI filesystem path resolution]: https://github.com/WebAssembly/wasi-filesystem/blob/main/path-resolution.md +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream, error}; + @since(version = 0.2.0) + use wasi:clocks/wall-clock@0.2.3.{datetime}; + + /// File size or length of a region within a file. + @since(version = 0.2.0) + type filesize = u64; + + /// The type of a filesystem object referenced by a descriptor. + /// + /// Note: This was called `filetype` in earlier versions of WASI. + @since(version = 0.2.0) + enum descriptor-type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, + } + + /// Descriptor flags. + /// + /// Note: This was called `fdflags` in earlier versions of WASI. + @since(version = 0.2.0) + flags descriptor-flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Request that writes be performed according to synchronized I/O file + /// integrity completion. The data stored in the file and the file's + /// metadata are synchronized. This is similar to `O_SYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + file-integrity-sync, + /// Request that writes be performed according to synchronized I/O data + /// integrity completion. Only the data stored in the file is + /// synchronized. This is similar to `O_DSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + data-integrity-sync, + /// Requests that reads be performed at the same level of integrity + /// requested for writes. This is similar to `O_RSYNC` in POSIX. + /// + /// The precise semantics of this operation have not yet been defined for + /// WASI. At this time, it should be interpreted as a request, and not a + /// requirement. + requested-write-sync, + /// Mutating directories mode: Directory contents may be mutated. + /// + /// When this flag is unset on a descriptor, operations using the + /// descriptor which would create, rename, delete, modify the data or + /// metadata of filesystem objects, or obtain another handle which + /// would permit any of those, shall fail with `error-code::read-only` if + /// they would otherwise succeed. + /// + /// This may only be set on directories. + mutate-directory, + } + + /// File attributes. + /// + /// Note: This was called `filestat` in earlier versions of WASI. + @since(version = 0.2.0) + record descriptor-stat { + /// File type. + %type: descriptor-type, + /// Number of hard links to the file. + link-count: link-count, + /// For regular files, the file size in bytes. For symbolic links, the + /// length in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + /// + /// If the `option` is none, the platform doesn't maintain an access + /// timestamp for this file. + data-access-timestamp: option, + /// Last data modification timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// modification timestamp for this file. + data-modification-timestamp: option, + /// Last file status-change timestamp. + /// + /// If the `option` is none, the platform doesn't maintain a + /// status-change timestamp for this file. + status-change-timestamp: option, + } + + /// Flags determining the method of how paths are resolved. + @since(version = 0.2.0) + flags path-flags { + /// As long as the resolved path corresponds to a symbolic link, it is + /// expanded. + symlink-follow, + } + + /// Open flags used by `open-at`. + @since(version = 0.2.0) + flags open-flags { + /// Create file if it does not exist, similar to `O_CREAT` in POSIX. + create, + /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX. + directory, + /// Fail if file already exists, similar to `O_EXCL` in POSIX. + exclusive, + /// Truncate file to size 0, similar to `O_TRUNC` in POSIX. + truncate, + } + + /// Number of hard links to an inode. + @since(version = 0.2.0) + type link-count = u64; + + /// When setting a timestamp, this gives the value to set it to. + @since(version = 0.2.0) + variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(datetime), + } + + /// A directory entry. + record directory-entry { + /// The type of the file referred to by this directory entry. + %type: descriptor-type, + + /// The name of the object. + name: string, + } + + /// Error codes returned by functions, similar to `errno` in POSIX. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + enum error-code { + /// Permission denied, similar to `EACCES` in POSIX. + access, + /// Resource unavailable, or operation would block, similar to `EAGAIN` and `EWOULDBLOCK` in POSIX. + would-block, + /// Connection already in progress, similar to `EALREADY` in POSIX. + already, + /// Bad descriptor, similar to `EBADF` in POSIX. + bad-descriptor, + /// Device or resource busy, similar to `EBUSY` in POSIX. + busy, + /// Resource deadlock would occur, similar to `EDEADLK` in POSIX. + deadlock, + /// Storage quota exceeded, similar to `EDQUOT` in POSIX. + quota, + /// File exists, similar to `EEXIST` in POSIX. + exist, + /// File too large, similar to `EFBIG` in POSIX. + file-too-large, + /// Illegal byte sequence, similar to `EILSEQ` in POSIX. + illegal-byte-sequence, + /// Operation in progress, similar to `EINPROGRESS` in POSIX. + in-progress, + /// Interrupted function, similar to `EINTR` in POSIX. + interrupted, + /// Invalid argument, similar to `EINVAL` in POSIX. + invalid, + /// I/O error, similar to `EIO` in POSIX. + io, + /// Is a directory, similar to `EISDIR` in POSIX. + is-directory, + /// Too many levels of symbolic links, similar to `ELOOP` in POSIX. + loop, + /// Too many links, similar to `EMLINK` in POSIX. + too-many-links, + /// Message too large, similar to `EMSGSIZE` in POSIX. + message-size, + /// Filename too long, similar to `ENAMETOOLONG` in POSIX. + name-too-long, + /// No such device, similar to `ENODEV` in POSIX. + no-device, + /// No such file or directory, similar to `ENOENT` in POSIX. + no-entry, + /// No locks available, similar to `ENOLCK` in POSIX. + no-lock, + /// Not enough space, similar to `ENOMEM` in POSIX. + insufficient-memory, + /// No space left on device, similar to `ENOSPC` in POSIX. + insufficient-space, + /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX. + not-directory, + /// Directory not empty, similar to `ENOTEMPTY` in POSIX. + not-empty, + /// State not recoverable, similar to `ENOTRECOVERABLE` in POSIX. + not-recoverable, + /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX. + unsupported, + /// Inappropriate I/O control operation, similar to `ENOTTY` in POSIX. + no-tty, + /// No such device or address, similar to `ENXIO` in POSIX. + no-such-device, + /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX. + overflow, + /// Operation not permitted, similar to `EPERM` in POSIX. + not-permitted, + /// Broken pipe, similar to `EPIPE` in POSIX. + pipe, + /// Read-only file system, similar to `EROFS` in POSIX. + read-only, + /// Invalid seek, similar to `ESPIPE` in POSIX. + invalid-seek, + /// Text file busy, similar to `ETXTBSY` in POSIX. + text-file-busy, + /// Cross-device link, similar to `EXDEV` in POSIX. + cross-device, + } + + /// File or memory access pattern advisory information. + @since(version = 0.2.0) + enum advice { + /// The application has no advice to give on its behavior with respect + /// to the specified data. + normal, + /// The application expects to access the specified data sequentially + /// from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random + /// order. + random, + /// The application expects to access the specified data in the near + /// future. + will-need, + /// The application expects that it will not access the specified data + /// in the near future. + dont-need, + /// The application expects to access the specified data once and then + /// not reuse it thereafter. + no-reuse, + } + + /// A 128-bit hash value, split into parts because wasm doesn't have a + /// 128-bit integer type. + @since(version = 0.2.0) + record metadata-hash-value { + /// 64 bits of a 128-bit hash value. + lower: u64, + /// Another 64 bits of a 128-bit hash value. + upper: u64, + } + + /// A descriptor is a reference to a filesystem object, which may be a file, + /// directory, named pipe, special file, or other object on which filesystem + /// calls may be made. + @since(version = 0.2.0) + resource descriptor { + /// Return a stream for reading from a file, if available. + /// + /// May fail with an error-code describing why the file cannot be read. + /// + /// Multiple read, write, and append streams may be active on the same open + /// file and they do not interfere with each other. + /// + /// Note: This allows using `read-stream`, which is similar to `read` in POSIX. + @since(version = 0.2.0) + read-via-stream: func( + /// The offset within the file at which to start reading. + offset: filesize, + ) -> result; + + /// Return a stream for writing to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be written. + /// + /// Note: This allows using `write-stream`, which is similar to `write` in + /// POSIX. + @since(version = 0.2.0) + write-via-stream: func( + /// The offset within the file at which to start writing. + offset: filesize, + ) -> result; + + /// Return a stream for appending to a file, if available. + /// + /// May fail with an error-code describing why the file cannot be appended. + /// + /// Note: This allows using `write-stream`, which is similar to `write` with + /// `O_APPEND` in POSIX. + @since(version = 0.2.0) + append-via-stream: func() -> result; + + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + @since(version = 0.2.0) + advise: func( + /// The offset within the file to which the advisory applies. + offset: filesize, + /// The length of the region to which the advisory applies. + length: filesize, + /// The advice. + advice: advice + ) -> result<_, error-code>; + + /// Synchronize the data of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fdatasync` in POSIX. + @since(version = 0.2.0) + sync-data: func() -> result<_, error-code>; + + /// Get flags associated with a descriptor. + /// + /// Note: This returns similar flags to `fcntl(fd, F_GETFL)` in POSIX. + /// + /// Note: This returns the value that was the `fs_flags` value returned + /// from `fdstat_get` in earlier versions of WASI. + @since(version = 0.2.0) + get-flags: func() -> result; + + /// Get the dynamic type of a descriptor. + /// + /// Note: This returns the same value as the `type` field of the `fd-stat` + /// returned by `stat`, `stat-at` and similar. + /// + /// Note: This returns similar flags to the `st_mode & S_IFMT` value provided + /// by `fstat` in POSIX. + /// + /// Note: This returns the value that was the `fs_filetype` value returned + /// from `fdstat_get` in earlier versions of WASI. + @since(version = 0.2.0) + get-type: func() -> result; + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + @since(version = 0.2.0) + set-size: func(size: filesize) -> result<_, error-code>; + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + @since(version = 0.2.0) + set-times: func( + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Read from a descriptor, without using and updating the descriptor's offset. + /// + /// This function returns a list of bytes containing the data that was + /// read, along with a bool which, when true, indicates that the end of the + /// file was reached. The returned list will contain up to `length` bytes; it + /// may return fewer than requested, if the end of the file is reached or + /// if the I/O operation is interrupted. + /// + /// In the future, this may change to return a `stream`. + /// + /// Note: This is similar to `pread` in POSIX. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read. + length: filesize, + /// The offset within the file at which to read. + offset: filesize, + ) -> result, bool>, error-code>; + + /// Write to a descriptor, without using and updating the descriptor's offset. + /// + /// It is valid to write past the end of a file; the file is extended to the + /// extent of the write, with bytes between the previous end and the start of + /// the write set to zero. + /// + /// In the future, this may change to take a `stream`. + /// + /// Note: This is similar to `pwrite` in POSIX. + @since(version = 0.2.0) + write: func( + /// Data to write + buffer: list, + /// The offset within the file at which to write. + offset: filesize, + ) -> result; + + /// Read directory entries from a directory. + /// + /// On filesystems where directories contain entries referring to themselves + /// and their parents, often named `.` and `..` respectively, these entries + /// are omitted. + /// + /// This always returns a new stream which starts at the beginning of the + /// directory. Multiple streams may be active on the same directory, and they + /// do not interfere with each other. + @since(version = 0.2.0) + read-directory: func() -> result; + + /// Synchronize the data and metadata of a file to disk. + /// + /// This function succeeds with no effect if the file descriptor is not + /// opened for writing. + /// + /// Note: This is similar to `fsync` in POSIX. + @since(version = 0.2.0) + sync: func() -> result<_, error-code>; + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + @since(version = 0.2.0) + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> result<_, error-code>; + + /// Return the attributes of an open file or directory. + /// + /// Note: This is similar to `fstat` in POSIX, except that it does not return + /// device and inode information. For testing whether two descriptors refer to + /// the same underlying filesystem object, use `is-same-object`. To obtain + /// additional data that can be used do determine whether a file has been + /// modified, use `metadata-hash`. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + @since(version = 0.2.0) + stat: func() -> result; + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX, except that it does not + /// return device and inode information. See the `stat` description for a + /// discussion of alternatives. + /// + /// Note: This was called `path_filestat_get` in earlier versions of WASI. + @since(version = 0.2.0) + stat-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of + /// WASI. + @since(version = 0.2.0) + set-times-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + data-access-timestamp: new-timestamp, + /// The desired values of the data modification timestamp. + data-modification-timestamp: new-timestamp, + ) -> result<_, error-code>; + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + @since(version = 0.2.0) + link-at: func( + /// Flags determining the method of how the path is resolved. + old-path-flags: path-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> result<_, error-code>; + + /// Open a file or directory. + /// + /// If `flags` contains `descriptor-flags::mutate-directory`, and the base + /// descriptor doesn't have `descriptor-flags::mutate-directory` set, + /// `open-at` fails with `error-code::read-only`. + /// + /// If `flags` contains `write` or `mutate-directory`, or `open-flags` + /// contains `truncate` or `create`, and the base descriptor doesn't have + /// `descriptor-flags::mutate-directory` set, `open-at` fails with + /// `error-code::read-only`. + /// + /// Note: This is similar to `openat` in POSIX. + @since(version = 0.2.0) + open-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + open-flags: open-flags, + /// Flags to use for the resulting descriptor. + %flags: descriptor-flags, + ) -> result; + + /// Read the contents of a symbolic link. + /// + /// If the contents contain an absolute or rooted path in the underlying + /// filesystem, this function fails with `error-code::not-permitted`. + /// + /// Note: This is similar to `readlinkat` in POSIX. + @since(version = 0.2.0) + readlink-at: func( + /// The relative path of the symbolic link from which to read. + path: string, + ) -> result; + + /// Remove a directory. + /// + /// Return `error-code::not-empty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + @since(version = 0.2.0) + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> result<_, error-code>; + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + @since(version = 0.2.0) + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: borrow, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> result<_, error-code>; + + /// Create a symbolic link (also known as a "symlink"). + /// + /// If `old-path` starts with `/`, the function fails with + /// `error-code::not-permitted`. + /// + /// Note: This is similar to `symlinkat` in POSIX. + @since(version = 0.2.0) + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> result<_, error-code>; + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `error-code::is-directory` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + @since(version = 0.2.0) + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> result<_, error-code>; + + /// Test whether two descriptors refer to the same filesystem object. + /// + /// In POSIX, this corresponds to testing whether the two descriptors have the + /// same device (`st_dev`) and inode (`st_ino` or `d_ino`) numbers. + /// wasi-filesystem does not expose device and inode numbers, so this function + /// may be used instead. + @since(version = 0.2.0) + is-same-object: func(other: borrow) -> bool; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a descriptor. + /// + /// This returns a hash of the last-modification timestamp and file size, and + /// may also include the inode number, device number, birth timestamp, and + /// other metadata fields that may change when the file is modified or + /// replaced. It may also include a secret value chosen by the + /// implementation and not otherwise exposed. + /// + /// Implementations are encouraged to provide the following properties: + /// + /// - If the file is not modified or replaced, the computed hash value should + /// usually not change. + /// - If the object is modified or replaced, the computed hash value should + /// usually change. + /// - The inputs to the hash should not be easily computable from the + /// computed hash. + /// + /// However, none of these is required. + @since(version = 0.2.0) + metadata-hash: func() -> result; + + /// Return a hash of the metadata associated with a filesystem object referred + /// to by a directory descriptor and a relative path. + /// + /// This performs the same hash computation as `metadata-hash`. + @since(version = 0.2.0) + metadata-hash-at: func( + /// Flags determining the method of how the path is resolved. + path-flags: path-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> result; + } + + /// A stream of directory entries. + @since(version = 0.2.0) + resource directory-entry-stream { + /// Read a single directory entry from a `directory-entry-stream`. + @since(version = 0.2.0) + read-directory-entry: func() -> result, error-code>; + } + + /// Attempts to extract a filesystem-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// filesystem-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are filesystem-related errors. + @since(version = 0.2.0) + filesystem-error-code: func(err: borrow) -> option; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/world.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/world.wit new file mode 100644 index 0000000000..29405bc2cc --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/filesystem/world.wit @@ -0,0 +1,9 @@ +package wasi:filesystem@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import types; + @since(version = 0.2.0) + import preopens; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/http/handler.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/http/handler.wit new file mode 100644 index 0000000000..6a6c62966f --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/http/handler.wit @@ -0,0 +1,49 @@ +/// This interface defines a handler of incoming HTTP Requests. It should +/// be exported by components which can respond to HTTP Requests. +@since(version = 0.2.0) +interface incoming-handler { + @since(version = 0.2.0) + use types.{incoming-request, response-outparam}; + + /// This function is invoked with an incoming HTTP Request, and a resource + /// `response-outparam` which provides the capability to reply with an HTTP + /// Response. The response is sent by calling the `response-outparam.set` + /// method, which allows execution to continue after the response has been + /// sent. This enables both streaming to the response body, and performing other + /// work. + /// + /// The implementor of this function must write a response to the + /// `response-outparam` before returning, or else the caller will respond + /// with an error on its behalf. + @since(version = 0.2.0) + handle: func( + request: incoming-request, + response-out: response-outparam + ); +} + +/// This interface defines a handler of outgoing HTTP Requests. It should be +/// imported by components which wish to make HTTP Requests. +@since(version = 0.2.0) +interface outgoing-handler { + @since(version = 0.2.0) + use types.{ + outgoing-request, request-options, future-incoming-response, error-code + }; + + /// This function is invoked with an outgoing HTTP Request, and it returns + /// a resource `future-incoming-response` which represents an HTTP Response + /// which may arrive in the future. + /// + /// The `options` argument accepts optional parameters for the HTTP + /// protocol's transport layer. + /// + /// This function may return an error if the `outgoing-request` is invalid + /// or not allowed to be made. Otherwise, protocol errors are reported + /// through the `future-incoming-response`. + @since(version = 0.2.0) + handle: func( + request: outgoing-request, + options: option + ) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/http/proxy.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/http/proxy.wit new file mode 100644 index 0000000000..de3bbe8ae0 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/http/proxy.wit @@ -0,0 +1,50 @@ +package wasi:http@0.2.3; + +/// The `wasi:http/imports` world imports all the APIs for HTTP proxies. +/// It is intended to be `include`d in other worlds. +@since(version = 0.2.0) +world imports { + /// HTTP proxies have access to time and randomness. + @since(version = 0.2.0) + import wasi:clocks/monotonic-clock@0.2.3; + @since(version = 0.2.0) + import wasi:clocks/wall-clock@0.2.3; + @since(version = 0.2.0) + import wasi:random/random@0.2.3; + + /// Proxies have standard output and error streams which are expected to + /// terminate in a developer-facing console provided by the host. + @since(version = 0.2.0) + import wasi:cli/stdout@0.2.3; + @since(version = 0.2.0) + import wasi:cli/stderr@0.2.3; + + /// TODO: this is a temporary workaround until component tooling is able to + /// gracefully handle the absence of stdin. Hosts must return an eof stream + /// for this import, which is what wasi-libc + tooling will do automatically + /// when this import is properly removed. + @since(version = 0.2.0) + import wasi:cli/stdin@0.2.3; + + /// This is the default handler to use when user code simply wants to make an + /// HTTP request (e.g., via `fetch()`). + @since(version = 0.2.0) + import outgoing-handler; +} + +/// The `wasi:http/proxy` world captures a widely-implementable intersection of +/// hosts that includes HTTP forward and reverse proxies. Components targeting +/// this world may concurrently stream in and out any number of incoming and +/// outgoing HTTP requests. +@since(version = 0.2.0) +world proxy { + @since(version = 0.2.0) + include imports; + + /// The host delivers incoming HTTP requests to a component by calling the + /// `handle` function of this exported interface. A host may arbitrarily reuse + /// or not reuse component instance when delivering incoming HTTP requests and + /// thus a component must be able to handle 0..N calls to `handle`. + @since(version = 0.2.0) + export incoming-handler; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/http/types.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/http/types.wit new file mode 100644 index 0000000000..2498f180ad --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/http/types.wit @@ -0,0 +1,673 @@ +/// This interface defines all of the types and methods for implementing +/// HTTP Requests and Responses, both incoming and outgoing, as well as +/// their headers, trailers, and bodies. +@since(version = 0.2.0) +interface types { + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.3.{duration}; + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/error@0.2.3.{error as io-error}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + + /// This type corresponds to HTTP standard Methods. + @since(version = 0.2.0) + variant method { + get, + head, + post, + put, + delete, + connect, + options, + trace, + patch, + other(string) + } + + /// This type corresponds to HTTP standard Related Schemes. + @since(version = 0.2.0) + variant scheme { + HTTP, + HTTPS, + other(string) + } + + /// These cases are inspired by the IANA HTTP Proxy Error Types: + /// + @since(version = 0.2.0) + variant error-code { + DNS-timeout, + DNS-error(DNS-error-payload), + destination-not-found, + destination-unavailable, + destination-IP-prohibited, + destination-IP-unroutable, + connection-refused, + connection-terminated, + connection-timeout, + connection-read-timeout, + connection-write-timeout, + connection-limit-reached, + TLS-protocol-error, + TLS-certificate-error, + TLS-alert-received(TLS-alert-received-payload), + HTTP-request-denied, + HTTP-request-length-required, + HTTP-request-body-size(option), + HTTP-request-method-invalid, + HTTP-request-URI-invalid, + HTTP-request-URI-too-long, + HTTP-request-header-section-size(option), + HTTP-request-header-size(option), + HTTP-request-trailer-section-size(option), + HTTP-request-trailer-size(field-size-payload), + HTTP-response-incomplete, + HTTP-response-header-section-size(option), + HTTP-response-header-size(field-size-payload), + HTTP-response-body-size(option), + HTTP-response-trailer-section-size(option), + HTTP-response-trailer-size(field-size-payload), + HTTP-response-transfer-coding(option), + HTTP-response-content-coding(option), + HTTP-response-timeout, + HTTP-upgrade-failed, + HTTP-protocol-error, + loop-detected, + configuration-error, + /// This is a catch-all error for anything that doesn't fit cleanly into a + /// more specific case. It also includes an optional string for an + /// unstructured description of the error. Users should not depend on the + /// string for diagnosing errors, as it's not required to be consistent + /// between implementations. + internal-error(option) + } + + /// Defines the case payload type for `DNS-error` above: + @since(version = 0.2.0) + record DNS-error-payload { + rcode: option, + info-code: option + } + + /// Defines the case payload type for `TLS-alert-received` above: + @since(version = 0.2.0) + record TLS-alert-received-payload { + alert-id: option, + alert-message: option + } + + /// Defines the case payload type for `HTTP-response-{header,trailer}-size` above: + @since(version = 0.2.0) + record field-size-payload { + field-name: option, + field-size: option + } + + /// Attempts to extract a http-related `error` from the wasi:io `error` + /// provided. + /// + /// Stream operations which return + /// `wasi:io/stream/stream-error::last-operation-failed` have a payload of + /// type `wasi:io/error/error` with more information about the operation + /// that failed. This payload can be passed through to this function to see + /// if there's http-related information about the error to return. + /// + /// Note that this function is fallible because not all io-errors are + /// http-related errors. + @since(version = 0.2.0) + http-error-code: func(err: borrow) -> option; + + /// This type enumerates the different kinds of errors that may occur when + /// setting or appending to a `fields` resource. + @since(version = 0.2.0) + variant header-error { + /// This error indicates that a `field-name` or `field-value` was + /// syntactically invalid when used with an operation that sets headers in a + /// `fields`. + invalid-syntax, + + /// This error indicates that a forbidden `field-name` was used when trying + /// to set a header in a `fields`. + forbidden, + + /// This error indicates that the operation on the `fields` was not + /// permitted because the fields are immutable. + immutable, + } + + /// Field names are always strings. + /// + /// Field names should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + @since(version = 0.2.1) + type field-name = field-key; + + /// Field keys are always strings. + /// + /// Field keys should always be treated as case insensitive by the `fields` + /// resource for the purposes of equality checking. + /// + /// # Deprecation + /// + /// This type has been deprecated in favor of the `field-name` type. + @since(version = 0.2.0) + @deprecated(version = 0.2.2) + type field-key = string; + + /// Field values should always be ASCII strings. However, in + /// reality, HTTP implementations often have to interpret malformed values, + /// so they are provided as a list of bytes. + @since(version = 0.2.0) + type field-value = list; + + /// This following block defines the `fields` resource which corresponds to + /// HTTP standard Fields. Fields are a common representation used for both + /// Headers and Trailers. + /// + /// A `fields` may be mutable or immutable. A `fields` created using the + /// constructor, `from-list`, or `clone` will be mutable, but a `fields` + /// resource given by other means (including, but not limited to, + /// `incoming-request.headers`, `outgoing-request.headers`) might be be + /// immutable. In an immutable fields, the `set`, `append`, and `delete` + /// operations will fail with `header-error.immutable`. + @since(version = 0.2.0) + resource fields { + + /// Construct an empty HTTP Fields. + /// + /// The resulting `fields` is mutable. + @since(version = 0.2.0) + constructor(); + + /// Construct an HTTP Fields. + /// + /// The resulting `fields` is mutable. + /// + /// The list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The tuple is a pair of the field name, represented as a string, and + /// Value, represented as a list of bytes. + /// + /// An error result will be returned if any `field-name` or `field-value` is + /// syntactically invalid, or if a field is forbidden. + @since(version = 0.2.0) + from-list: static func( + entries: list> + ) -> result; + + /// Get all of the values corresponding to a name. If the name is not present + /// in this `fields` or is syntactically invalid, an empty list is returned. + /// However, if the name is present but empty, this is represented by a list + /// with one or more empty field-values present. + @since(version = 0.2.0) + get: func(name: field-name) -> list; + + /// Returns `true` when the name is present in this `fields`. If the name is + /// syntactically invalid, `false` is returned. + @since(version = 0.2.0) + has: func(name: field-name) -> bool; + + /// Set all of the values for a name. Clears any existing values for that + /// name, if they have been set. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or any of + /// the `field-value`s are syntactically invalid. + @since(version = 0.2.0) + set: func(name: field-name, value: list) -> result<_, header-error>; + + /// Delete all values for a name. Does nothing if no values for the name + /// exist. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` is + /// syntactically invalid. + @since(version = 0.2.0) + delete: func(name: field-name) -> result<_, header-error>; + + /// Append a value for a name. Does not change or delete any existing + /// values for that name. + /// + /// Fails with `header-error.immutable` if the `fields` are immutable. + /// + /// Fails with `header-error.invalid-syntax` if the `field-name` or + /// `field-value` are syntactically invalid. + @since(version = 0.2.0) + append: func(name: field-name, value: field-value) -> result<_, header-error>; + + /// Retrieve the full set of names and values in the Fields. Like the + /// constructor, the list represents each name-value pair. + /// + /// The outer list represents each name-value pair in the Fields. Names + /// which have multiple values are represented by multiple entries in this + /// list with the same name. + /// + /// The names and values are always returned in the original casing and in + /// the order in which they will be serialized for transport. + @since(version = 0.2.0) + entries: func() -> list>; + + /// Make a deep copy of the Fields. Equivalent in behavior to calling the + /// `fields` constructor on the return value of `entries`. The resulting + /// `fields` is mutable. + @since(version = 0.2.0) + clone: func() -> fields; + } + + /// Headers is an alias for Fields. + @since(version = 0.2.0) + type headers = fields; + + /// Trailers is an alias for Fields. + @since(version = 0.2.0) + type trailers = fields; + + /// Represents an incoming HTTP Request. + @since(version = 0.2.0) + resource incoming-request { + + /// Returns the method of the incoming request. + @since(version = 0.2.0) + method: func() -> method; + + /// Returns the path with query parameters from the request, as a string. + @since(version = 0.2.0) + path-with-query: func() -> option; + + /// Returns the protocol scheme from the request. + @since(version = 0.2.0) + scheme: func() -> option; + + /// Returns the authority of the Request's target URI, if present. + @since(version = 0.2.0) + authority: func() -> option; + + /// Get the `headers` associated with the request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// The `headers` returned are a child resource: it must be dropped before + /// the parent `incoming-request` is dropped. Dropping this + /// `incoming-request` before all children are dropped will trap. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Gives the `incoming-body` associated with this request. Will only + /// return success at most once, and subsequent calls will return error. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an outgoing HTTP Request. + @since(version = 0.2.0) + resource outgoing-request { + + /// Construct a new `outgoing-request` with a default `method` of `GET`, and + /// `none` values for `path-with-query`, `scheme`, and `authority`. + /// + /// * `headers` is the HTTP Headers for the Request. + /// + /// It is possible to construct, or manipulate with the accessor functions + /// below, an `outgoing-request` with an invalid combination of `scheme` + /// and `authority`, or `headers` which are not permitted to be sent. + /// It is the obligation of the `outgoing-handler.handle` implementation + /// to reject invalid constructions of `outgoing-request`. + @since(version = 0.2.0) + constructor( + headers: headers + ); + + /// Returns the resource corresponding to the outgoing Body for this + /// Request. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-request` can be retrieved at most once. Subsequent + /// calls will return error. + @since(version = 0.2.0) + body: func() -> result; + + /// Get the Method for the Request. + @since(version = 0.2.0) + method: func() -> method; + /// Set the Method for the Request. Fails if the string present in a + /// `method.other` argument is not a syntactically valid method. + @since(version = 0.2.0) + set-method: func(method: method) -> result; + + /// Get the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. + @since(version = 0.2.0) + path-with-query: func() -> option; + /// Set the combination of the HTTP Path and Query for the Request. + /// When `none`, this represents an empty Path and empty Query. Fails is the + /// string given is not a syntactically valid path and query uri component. + @since(version = 0.2.0) + set-path-with-query: func(path-with-query: option) -> result; + + /// Get the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. + @since(version = 0.2.0) + scheme: func() -> option; + /// Set the HTTP Related Scheme for the Request. When `none`, the + /// implementation may choose an appropriate default scheme. Fails if the + /// string given is not a syntactically valid uri scheme. + @since(version = 0.2.0) + set-scheme: func(scheme: option) -> result; + + /// Get the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. + @since(version = 0.2.0) + authority: func() -> option; + /// Set the authority of the Request's target URI. A value of `none` may be used + /// with Related Schemes which do not require an authority. The HTTP and + /// HTTPS schemes always require an authority. Fails if the string given is + /// not a syntactically valid URI authority. + @since(version = 0.2.0) + set-authority: func(authority: option) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> headers; + } + + /// Parameters for making an HTTP Request. Each of these parameters is + /// currently an optional timeout applicable to the transport layer of the + /// HTTP protocol. + /// + /// These timeouts are separate from any the user may use to bound a + /// blocking call to `wasi:io/poll.poll`. + @since(version = 0.2.0) + resource request-options { + /// Construct a default `request-options` value. + @since(version = 0.2.0) + constructor(); + + /// The timeout for the initial connect to the HTTP Server. + @since(version = 0.2.0) + connect-timeout: func() -> option; + + /// Set the timeout for the initial connect to the HTTP Server. An error + /// return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-connect-timeout: func(duration: option) -> result; + + /// The timeout for receiving the first byte of the Response body. + @since(version = 0.2.0) + first-byte-timeout: func() -> option; + + /// Set the timeout for receiving the first byte of the Response body. An + /// error return value indicates that this timeout is not supported. + @since(version = 0.2.0) + set-first-byte-timeout: func(duration: option) -> result; + + /// The timeout for receiving subsequent chunks of bytes in the Response + /// body stream. + @since(version = 0.2.0) + between-bytes-timeout: func() -> option; + + /// Set the timeout for receiving subsequent chunks of bytes in the Response + /// body stream. An error return value indicates that this timeout is not + /// supported. + @since(version = 0.2.0) + set-between-bytes-timeout: func(duration: option) -> result; + } + + /// Represents the ability to send an HTTP Response. + /// + /// This resource is used by the `wasi:http/incoming-handler` interface to + /// allow a Response to be sent corresponding to the Request provided as the + /// other argument to `incoming-handler.handle`. + @since(version = 0.2.0) + resource response-outparam { + + /// Set the value of the `response-outparam` to either send a response, + /// or indicate an error. + /// + /// This method consumes the `response-outparam` to ensure that it is + /// called at most once. If it is never called, the implementation + /// will respond with an error. + /// + /// The user may provide an `error` to `response` to allow the + /// implementation determine how to respond with an HTTP error response. + @since(version = 0.2.0) + set: static func( + param: response-outparam, + response: result, + ); + } + + /// This type corresponds to the HTTP standard Status Code. + @since(version = 0.2.0) + type status-code = u16; + + /// Represents an incoming HTTP Response. + @since(version = 0.2.0) + resource incoming-response { + + /// Returns the status code from the incoming response. + @since(version = 0.2.0) + status: func() -> status-code; + + /// Returns the headers from the incoming response. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `incoming-response` is dropped. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the incoming body. May be called at most once. Returns error + /// if called additional times. + @since(version = 0.2.0) + consume: func() -> result; + } + + /// Represents an incoming HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, indicating that the full contents of the + /// body have been received. This resource represents the contents as + /// an `input-stream` and the delivery of trailers as a `future-trailers`, + /// and ensures that the user of this interface may only be consuming either + /// the body contents or waiting on trailers at any given time. + @since(version = 0.2.0) + resource incoming-body { + + /// Returns the contents of the body, as a stream of bytes. + /// + /// Returns success on first call: the stream representing the contents + /// can be retrieved at most once. Subsequent calls will return error. + /// + /// The returned `input-stream` resource is a child: it must be dropped + /// before the parent `incoming-body` is dropped, or consumed by + /// `incoming-body.finish`. + /// + /// This invariant ensures that the implementation can determine whether + /// the user is consuming the contents of the body, waiting on the + /// `future-trailers` to be ready, or neither. This allows for network + /// backpressure is to be applied when the user is consuming the body, + /// and for that backpressure to not inhibit delivery of the trailers if + /// the user does not read the entire body. + @since(version = 0.2.0) + %stream: func() -> result; + + /// Takes ownership of `incoming-body`, and returns a `future-trailers`. + /// This function will trap if the `input-stream` child is still alive. + @since(version = 0.2.0) + finish: static func(this: incoming-body) -> future-trailers; + } + + /// Represents a future which may eventually return trailers, or an error. + /// + /// In the case that the incoming HTTP Request or Response did not have any + /// trailers, this future will resolve to the empty set of trailers once the + /// complete Request or Response body has been received. + @since(version = 0.2.0) + resource future-trailers { + + /// Returns a pollable which becomes ready when either the trailers have + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the contents of the trailers, or an error which occurred, + /// once the future is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the trailers or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the HTTP Request or Response + /// body, as well as any trailers, were received successfully, or that an + /// error occurred receiving them. The optional `trailers` indicates whether + /// or not trailers were present in the body. + /// + /// When some `trailers` are returned by this method, the `trailers` + /// resource is immutable, and a child. Use of the `set`, `append`, or + /// `delete` methods will return an error, and the resource must be + /// dropped before the parent `future-trailers` is dropped. + @since(version = 0.2.0) + get: func() -> option, error-code>>>; + } + + /// Represents an outgoing HTTP Response. + @since(version = 0.2.0) + resource outgoing-response { + + /// Construct an `outgoing-response`, with a default `status-code` of `200`. + /// If a different `status-code` is needed, it must be set via the + /// `set-status-code` method. + /// + /// * `headers` is the HTTP Headers for the Response. + @since(version = 0.2.0) + constructor(headers: headers); + + /// Get the HTTP Status Code for the Response. + @since(version = 0.2.0) + status-code: func() -> status-code; + + /// Set the HTTP Status Code for the Response. Fails if the status-code + /// given is not a valid http status code. + @since(version = 0.2.0) + set-status-code: func(status-code: status-code) -> result; + + /// Get the headers associated with the Request. + /// + /// The returned `headers` resource is immutable: `set`, `append`, and + /// `delete` operations will fail with `header-error.immutable`. + /// + /// This headers resource is a child: it must be dropped before the parent + /// `outgoing-request` is dropped, or its ownership is transferred to + /// another component by e.g. `outgoing-handler.handle`. + @since(version = 0.2.0) + headers: func() -> headers; + + /// Returns the resource corresponding to the outgoing Body for this Response. + /// + /// Returns success on the first call: the `outgoing-body` resource for + /// this `outgoing-response` can be retrieved at most once. Subsequent + /// calls will return error. + @since(version = 0.2.0) + body: func() -> result; + } + + /// Represents an outgoing HTTP Request or Response's Body. + /// + /// A body has both its contents - a stream of bytes - and a (possibly + /// empty) set of trailers, inducating the full contents of the body + /// have been sent. This resource represents the contents as an + /// `output-stream` child resource, and the completion of the body (with + /// optional trailers) with a static function that consumes the + /// `outgoing-body` resource, and ensures that the user of this interface + /// may not write to the body contents after the body has been finished. + /// + /// If the user code drops this resource, as opposed to calling the static + /// method `finish`, the implementation should treat the body as incomplete, + /// and that an error has occurred. The implementation should propagate this + /// error to the HTTP protocol by whatever means it has available, + /// including: corrupting the body on the wire, aborting the associated + /// Request, or sending a late status code for the Response. + @since(version = 0.2.0) + resource outgoing-body { + + /// Returns a stream for writing the body contents. + /// + /// The returned `output-stream` is a child resource: it must be dropped + /// before the parent `outgoing-body` resource is dropped (or finished), + /// otherwise the `outgoing-body` drop or `finish` will trap. + /// + /// Returns success on the first call: the `output-stream` resource for + /// this `outgoing-body` may be retrieved at most once. Subsequent calls + /// will return error. + @since(version = 0.2.0) + write: func() -> result; + + /// Finalize an outgoing body, optionally providing trailers. This must be + /// called to signal that the response is complete. If the `outgoing-body` + /// is dropped without calling `outgoing-body.finalize`, the implementation + /// should treat the body as corrupted. + /// + /// Fails if the body's `outgoing-request` or `outgoing-response` was + /// constructed with a Content-Length header, and the contents written + /// to the body (via `write`) does not match the value given in the + /// Content-Length. + @since(version = 0.2.0) + finish: static func( + this: outgoing-body, + trailers: option + ) -> result<_, error-code>; + } + + /// Represents a future which may eventually return an incoming HTTP + /// Response, or an error. + /// + /// This resource is returned by the `wasi:http/outgoing-handler` interface to + /// provide the HTTP Response corresponding to the sent Request. + @since(version = 0.2.0) + resource future-incoming-response { + /// Returns a pollable which becomes ready when either the Response has + /// been received, or an error has occurred. When this pollable is ready, + /// the `get` method will return `some`. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Returns the incoming HTTP Response, or an error, once one is ready. + /// + /// The outer `option` represents future readiness. Users can wait on this + /// `option` to become `some` using the `subscribe` method. + /// + /// The outer `result` is used to retrieve the response or error at most + /// once. It will be success on the first call in which the outer option + /// is `some`, and error on subsequent calls. + /// + /// The inner `result` represents that either the incoming HTTP Response + /// status and headers have received successfully, or that an error + /// occurred. Errors may also occur while consuming the response body, + /// but those will be reported by the `incoming-body` and its + /// `output-stream` child. + @since(version = 0.2.0) + get: func() -> option>>; + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/io/error.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/io/error.wit new file mode 100644 index 0000000000..97c6068779 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/io/error.wit @@ -0,0 +1,34 @@ +package wasi:io@0.2.3; + +@since(version = 0.2.0) +interface error { + /// A resource which represents some error information. + /// + /// The only method provided by this resource is `to-debug-string`, + /// which provides some human-readable information about the error. + /// + /// In the `wasi:io` package, this resource is returned through the + /// `wasi:io/streams/stream-error` type. + /// + /// To provide more specific error information, other interfaces may + /// offer functions to "downcast" this error into more specific types. For example, + /// errors returned from streams derived from filesystem types can be described using + /// the filesystem's own error-code type. This is done using the function + /// `wasi:filesystem/types/filesystem-error-code`, which takes a `borrow` + /// parameter and returns an `option`. + /// + /// The set of functions which can "downcast" an `error` into a more + /// concrete type is open. + @since(version = 0.2.0) + resource error { + /// Returns a string that is suitable to assist humans in debugging + /// this error. + /// + /// WARNING: The returned string should not be consumed mechanically! + /// It may change across platforms, hosts, or other implementation + /// details. Parsing this string is a major platform-compatibility + /// hazard. + @since(version = 0.2.0) + to-debug-string: func() -> string; + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/io/poll.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/io/poll.wit new file mode 100644 index 0000000000..9bcbe8e036 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/io/poll.wit @@ -0,0 +1,47 @@ +package wasi:io@0.2.3; + +/// A poll API intended to let users wait for I/O events on multiple handles +/// at once. +@since(version = 0.2.0) +interface poll { + /// `pollable` represents a single I/O event which may be ready, or not. + @since(version = 0.2.0) + resource pollable { + + /// Return the readiness of a pollable. This function never blocks. + /// + /// Returns `true` when the pollable is ready, and `false` otherwise. + @since(version = 0.2.0) + ready: func() -> bool; + + /// `block` returns immediately if the pollable is ready, and otherwise + /// blocks until ready. + /// + /// This function is equivalent to calling `poll.poll` on a list + /// containing only this pollable. + @since(version = 0.2.0) + block: func(); + } + + /// Poll for completion on a set of pollables. + /// + /// This function takes a list of pollables, which identify I/O sources of + /// interest, and waits until one or more of the events is ready for I/O. + /// + /// The result `list` contains one or more indices of handles in the + /// argument list that is ready for I/O. + /// + /// This function traps if either: + /// - the list is empty, or: + /// - the list contains more elements than can be indexed with a `u32` value. + /// + /// A timeout can be implemented by adding a pollable from the + /// wasi-clocks API to the list. + /// + /// This function does not return a `result`; polling in itself does not + /// do any I/O so it doesn't fail. If any of the I/O sources identified by + /// the pollables has an error, it is indicated by marking the source as + /// being ready for I/O. + @since(version = 0.2.0) + poll: func(in: list>) -> list; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/io/streams.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/io/streams.wit new file mode 100644 index 0000000000..0de0846293 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/io/streams.wit @@ -0,0 +1,290 @@ +package wasi:io@0.2.3; + +/// WASI I/O is an I/O abstraction API which is currently focused on providing +/// stream types. +/// +/// In the future, the component model is expected to add built-in stream types; +/// when it does, they are expected to subsume this API. +@since(version = 0.2.0) +interface streams { + @since(version = 0.2.0) + use error.{error}; + @since(version = 0.2.0) + use poll.{pollable}; + + /// An error for input-stream and output-stream operations. + @since(version = 0.2.0) + variant stream-error { + /// The last operation (a write or flush) failed before completion. + /// + /// More information is available in the `error` payload. + /// + /// After this, the stream will be closed. All future operations return + /// `stream-error::closed`. + last-operation-failed(error), + /// The stream is closed: no more input will be accepted by the + /// stream. A closed output-stream will return this error on all + /// future operations. + closed + } + + /// An input bytestream. + /// + /// `input-stream`s are *non-blocking* to the extent practical on underlying + /// platforms. I/O operations always return promptly; if fewer bytes are + /// promptly available than requested, they return the number of bytes promptly + /// available, which could even be zero. To wait for data to be available, + /// use the `subscribe` function to obtain a `pollable` which can be polled + /// for using `wasi:io/poll`. + @since(version = 0.2.0) + resource input-stream { + /// Perform a non-blocking read from the stream. + /// + /// When the source of a `read` is binary data, the bytes from the source + /// are returned verbatim. When the source of a `read` is known to the + /// implementation to be text, bytes containing the UTF-8 encoding of the + /// text are returned. + /// + /// This function returns a list of bytes containing the read data, + /// when successful. The returned list will contain up to `len` bytes; + /// it may return fewer than requested, but not more. The list is + /// empty when no bytes are available for reading at this time. The + /// pollable given by `subscribe` will be ready when more bytes are + /// available. + /// + /// This function fails with a `stream-error` when the operation + /// encounters an error, giving `last-operation-failed`, or when the + /// stream is closed, giving `closed`. + /// + /// When the caller gives a `len` of 0, it represents a request to + /// read 0 bytes. If the stream is still open, this call should + /// succeed and return an empty list, or otherwise fail with `closed`. + /// + /// The `len` parameter is a `u64`, which could represent a list of u8 which + /// is not possible to allocate in wasm32, or not desirable to allocate as + /// as a return value by the callee. The callee may return a list of bytes + /// less than `len` in size while more bytes are available for reading. + @since(version = 0.2.0) + read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Read bytes from a stream, after blocking until at least one byte can + /// be read. Except for blocking, behavior is identical to `read`. + @since(version = 0.2.0) + blocking-read: func( + /// The maximum number of bytes to read + len: u64 + ) -> result, stream-error>; + + /// Skip bytes from a stream. Returns number of bytes skipped. + /// + /// Behaves identical to `read`, except instead of returning a list + /// of bytes, returns the number of bytes consumed from the stream. + @since(version = 0.2.0) + skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Skip bytes from a stream, after blocking until at least one byte + /// can be skipped. Except for blocking behavior, identical to `skip`. + @since(version = 0.2.0) + blocking-skip: func( + /// The maximum number of bytes to skip. + len: u64, + ) -> result; + + /// Create a `pollable` which will resolve once either the specified stream + /// has bytes available to read or the other end of the stream has been + /// closed. + /// The created `pollable` is a child resource of the `input-stream`. + /// Implementations may trap if the `input-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + + /// An output bytestream. + /// + /// `output-stream`s are *non-blocking* to the extent practical on + /// underlying platforms. Except where specified otherwise, I/O operations also + /// always return promptly, after the number of bytes that can be written + /// promptly, which could even be zero. To wait for the stream to be ready to + /// accept data, the `subscribe` function to obtain a `pollable` which can be + /// polled for using `wasi:io/poll`. + /// + /// Dropping an `output-stream` while there's still an active write in + /// progress may result in the data being lost. Before dropping the stream, + /// be sure to fully flush your writes. + @since(version = 0.2.0) + resource output-stream { + /// Check readiness for writing. This function never blocks. + /// + /// Returns the number of bytes permitted for the next call to `write`, + /// or an error. Calling `write` with more bytes than this function has + /// permitted will trap. + /// + /// When this function returns 0 bytes, the `subscribe` pollable will + /// become ready when this function will report at least 1 byte, or an + /// error. + @since(version = 0.2.0) + check-write: func() -> result; + + /// Perform a write. This function never blocks. + /// + /// When the destination of a `write` is binary data, the bytes from + /// `contents` are written verbatim. When the destination of a `write` is + /// known to the implementation to be text, the bytes of `contents` are + /// transcoded from UTF-8 into the encoding of the destination and then + /// written. + /// + /// Precondition: check-write gave permit of Ok(n) and contents has a + /// length of less than or equal to n. Otherwise, this function will trap. + /// + /// returns Err(closed) without writing if the stream has closed since + /// the last call to check-write provided a permit. + @since(version = 0.2.0) + write: func( + contents: list + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 bytes, and then flush the stream. Block + /// until all of these operations are complete, or an error occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write`, and `flush`, and is implemented with the + /// following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while !contents.is_empty() { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, contents.len()); + /// let (chunk, rest) = contents.split_at(len); + /// this.write(chunk ); // eliding error handling + /// contents = rest; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + @since(version = 0.2.0) + blocking-write-and-flush: func( + contents: list + ) -> result<_, stream-error>; + + /// Request to flush buffered output. This function never blocks. + /// + /// This tells the output-stream that the caller intends any buffered + /// output to be flushed. the output which is expected to be flushed + /// is all that has been passed to `write` prior to this call. + /// + /// Upon calling this function, the `output-stream` will not accept any + /// writes (`check-write` will return `ok(0)`) until the flush has + /// completed. The `subscribe` pollable will become ready when the + /// flush has completed and the stream can accept more writes. + @since(version = 0.2.0) + flush: func() -> result<_, stream-error>; + + /// Request to flush buffered output, and block until flush completes + /// and stream is ready for writing again. + @since(version = 0.2.0) + blocking-flush: func() -> result<_, stream-error>; + + /// Create a `pollable` which will resolve once the output-stream + /// is ready for more writing, or an error has occurred. When this + /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an + /// error. + /// + /// If the stream is closed, this pollable is always ready immediately. + /// + /// The created `pollable` is a child resource of the `output-stream`. + /// Implementations may trap if the `output-stream` is dropped before + /// all derived `pollable`s created with this function are dropped. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Write zeroes to a stream. + /// + /// This should be used precisely like `write` with the exact same + /// preconditions (must use check-write first), but instead of + /// passing a list of bytes, you simply pass the number of zero-bytes + /// that should be written. + @since(version = 0.2.0) + write-zeroes: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Perform a write of up to 4096 zeroes, and then flush the stream. + /// Block until all of these operations are complete, or an error + /// occurs. + /// + /// This is a convenience wrapper around the use of `check-write`, + /// `subscribe`, `write-zeroes`, and `flush`, and is implemented with + /// the following pseudo-code: + /// + /// ```text + /// let pollable = this.subscribe(); + /// while num_zeroes != 0 { + /// // Wait for the stream to become writable + /// pollable.block(); + /// let Ok(n) = this.check-write(); // eliding error handling + /// let len = min(n, num_zeroes); + /// this.write-zeroes(len); // eliding error handling + /// num_zeroes -= len; + /// } + /// this.flush(); + /// // Wait for completion of `flush` + /// pollable.block(); + /// // Check for any errors that arose during `flush` + /// let _ = this.check-write(); // eliding error handling + /// ``` + @since(version = 0.2.0) + blocking-write-zeroes-and-flush: func( + /// The number of zero-bytes to write + len: u64 + ) -> result<_, stream-error>; + + /// Read from one stream and write to another. + /// + /// The behavior of splice is equivalent to: + /// 1. calling `check-write` on the `output-stream` + /// 2. calling `read` on the `input-stream` with the smaller of the + /// `check-write` permitted length and the `len` provided to `splice` + /// 3. calling `write` on the `output-stream` with that read data. + /// + /// Any error reported by the call to `check-write`, `read`, or + /// `write` ends the splice and reports that error. + /// + /// This function returns the number of bytes transferred; it may be less + /// than `len`. + @since(version = 0.2.0) + splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + + /// Read from one stream and write to another, with blocking. + /// + /// This is similar to `splice`, except that it blocks until the + /// `output-stream` is ready for writing, and the `input-stream` + /// is ready for reading, before performing the `splice`. + @since(version = 0.2.0) + blocking-splice: func( + /// The stream to read from + src: borrow, + /// The number of bytes to splice + len: u64, + ) -> result; + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/io/world.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/io/world.wit new file mode 100644 index 0000000000..f1d2102dca --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/io/world.wit @@ -0,0 +1,10 @@ +package wasi:io@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import streams; + + @since(version = 0.2.0) + import poll; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure-seed.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure-seed.wit new file mode 100644 index 0000000000..67d024d5bf --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure-seed.wit @@ -0,0 +1,27 @@ +package wasi:random@0.2.3; +/// The insecure-seed interface for seeding hash-map DoS resistance. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface insecure-seed { + /// Return a 128-bit value that may contain a pseudo-random value. + /// + /// The returned value is not required to be computed from a CSPRNG, and may + /// even be entirely deterministic. Host implementations are encouraged to + /// provide pseudo-random values to any program exposed to + /// attacker-controlled content, to enable DoS protection built into many + /// languages' hash-map implementations. + /// + /// This function is intended to only be called once, by a source language + /// to initialize Denial Of Service (DoS) protection in its hash-map + /// implementation. + /// + /// # Expected future evolution + /// + /// This will likely be changed to a value import, to prevent it from being + /// called multiple times and potentially used for purposes other than DoS + /// protection. + @since(version = 0.2.0) + insecure-seed: func() -> tuple; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure.wit new file mode 100644 index 0000000000..a07dfab327 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/random/insecure.wit @@ -0,0 +1,25 @@ +package wasi:random@0.2.3; +/// The insecure interface for insecure pseudo-random numbers. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface insecure { + /// Return `len` insecure pseudo-random bytes. + /// + /// This function is not cryptographically secure. Do not use it for + /// anything related to security. + /// + /// There are no requirements on the values of the returned bytes, however + /// implementations are encouraged to return evenly distributed values with + /// a long period. + @since(version = 0.2.0) + get-insecure-random-bytes: func(len: u64) -> list; + + /// Return an insecure pseudo-random `u64` value. + /// + /// This function returns the same type of pseudo-random data as + /// `get-insecure-random-bytes`, represented as a `u64`. + @since(version = 0.2.0) + get-insecure-random-u64: func() -> u64; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/random/random.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/random/random.wit new file mode 100644 index 0000000000..91957e6330 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/random/random.wit @@ -0,0 +1,29 @@ +package wasi:random@0.2.3; +/// WASI Random is a random data API. +/// +/// It is intended to be portable at least between Unix-family platforms and +/// Windows. +@since(version = 0.2.0) +interface random { + /// Return `len` cryptographically-secure random or pseudo-random bytes. + /// + /// This function must produce data at least as cryptographically secure and + /// fast as an adequately seeded cryptographically-secure pseudo-random + /// number generator (CSPRNG). It must not block, from the perspective of + /// the calling program, under any circumstances, including on the first + /// request and on requests for numbers of bytes. The returned data must + /// always be unpredictable. + /// + /// This function must always return fresh data. Deterministic environments + /// must omit this function, rather than implementing it with deterministic + /// data. + @since(version = 0.2.0) + get-random-bytes: func(len: u64) -> list; + + /// Return a cryptographically-secure random or pseudo-random `u64` value. + /// + /// This function returns the same type of data as `get-random-bytes`, + /// represented as a `u64`. + @since(version = 0.2.0) + get-random-u64: func() -> u64; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/random/world.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/random/world.wit new file mode 100644 index 0000000000..0c1218f36e --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/random/world.wit @@ -0,0 +1,13 @@ +package wasi:random@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import random; + + @since(version = 0.2.0) + import insecure; + + @since(version = 0.2.0) + import insecure-seed; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/instance-network.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/instance-network.wit new file mode 100644 index 0000000000..5f6e6c1cc9 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/instance-network.wit @@ -0,0 +1,11 @@ + +/// This interface provides a value-export of the default network handle.. +@since(version = 0.2.0) +interface instance-network { + @since(version = 0.2.0) + use network.{network}; + + /// Get a handle to the default network. + @since(version = 0.2.0) + instance-network: func() -> network; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/ip-name-lookup.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/ip-name-lookup.wit new file mode 100644 index 0000000000..c1d8a47c16 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/ip-name-lookup.wit @@ -0,0 +1,56 @@ +@since(version = 0.2.0) +interface ip-name-lookup { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-address}; + + /// Resolve an internet host name to a list of IP addresses. + /// + /// Unicode domain names are automatically converted to ASCII using IDNA encoding. + /// If the input is an IP address string, the address is parsed and returned + /// as-is without making any external requests. + /// + /// See the wasi-socket proposal README.md for a comparison with getaddrinfo. + /// + /// This function never blocks. It either immediately fails or immediately + /// returns successfully with a `resolve-address-stream` that can be used + /// to (asynchronously) fetch the results. + /// + /// # Typical errors + /// - `invalid-argument`: `name` is a syntactically invalid domain name or IP address. + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + resolve-addresses: func(network: borrow, name: string) -> result; + + @since(version = 0.2.0) + resource resolve-address-stream { + /// Returns the next address from the resolver. + /// + /// This function should be called multiple times. On each call, it will + /// return the next address in connection order preference. If all + /// addresses have been exhausted, this function returns `none`. + /// + /// This function never returns IPv4-mapped IPv6 addresses. + /// + /// # Typical errors + /// - `name-unresolvable`: Name does not exist or has no suitable associated IP addresses. (EAI_NONAME, EAI_NODATA, EAI_ADDRFAMILY) + /// - `temporary-resolver-failure`: A temporary failure in name resolution occurred. (EAI_AGAIN) + /// - `permanent-resolver-failure`: A permanent failure in name resolution occurred. (EAI_FAIL) + /// - `would-block`: A result is not available yet. (EWOULDBLOCK, EAGAIN) + @since(version = 0.2.0) + resolve-next-address: func() -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/network.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/network.wit new file mode 100644 index 0000000000..f3f60a3709 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/network.wit @@ -0,0 +1,169 @@ +@since(version = 0.2.0) +interface network { + @unstable(feature = network-error-code) + use wasi:io/error@0.2.3.{error}; + + /// An opaque resource that represents access to (a subset of) the network. + /// This enables context-based security for networking. + /// There is no need for this to map 1:1 to a physical network interface. + @since(version = 0.2.0) + resource network; + + /// Error codes. + /// + /// In theory, every API can return any error code. + /// In practice, API's typically only return the errors documented per API + /// combined with a couple of errors that are always possible: + /// - `unknown` + /// - `access-denied` + /// - `not-supported` + /// - `out-of-memory` + /// - `concurrency-conflict` + /// + /// See each individual API for what the POSIX equivalents are. They sometimes differ per API. + @since(version = 0.2.0) + enum error-code { + /// Unknown error + unknown, + + /// Access denied. + /// + /// POSIX equivalent: EACCES, EPERM + access-denied, + + /// The operation is not supported. + /// + /// POSIX equivalent: EOPNOTSUPP + not-supported, + + /// One of the arguments is invalid. + /// + /// POSIX equivalent: EINVAL + invalid-argument, + + /// Not enough memory to complete the operation. + /// + /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY + out-of-memory, + + /// The operation timed out before it could finish completely. + timeout, + + /// This operation is incompatible with another asynchronous operation that is already in progress. + /// + /// POSIX equivalent: EALREADY + concurrency-conflict, + + /// Trying to finish an asynchronous operation that: + /// - has not been started yet, or: + /// - was already finished by a previous `finish-*` call. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + not-in-progress, + + /// The operation has been aborted because it could not be completed immediately. + /// + /// Note: this is scheduled to be removed when `future`s are natively supported. + would-block, + + + /// The operation is not valid in the socket's current state. + invalid-state, + + /// A new socket resource could not be created because of a system limit. + new-socket-limit, + + /// A bind operation failed because the provided address is not an address that the `network` can bind to. + address-not-bindable, + + /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available. + address-in-use, + + /// The remote address is not reachable + remote-unreachable, + + + /// The TCP connection was forcefully rejected + connection-refused, + + /// The TCP connection was reset. + connection-reset, + + /// A TCP connection was aborted. + connection-aborted, + + + /// The size of a datagram sent to a UDP socket exceeded the maximum + /// supported size. + datagram-too-large, + + + /// Name does not exist or has no suitable associated IP addresses. + name-unresolvable, + + /// A temporary failure in name resolution occurred. + temporary-resolver-failure, + + /// A permanent failure in name resolution occurred. + permanent-resolver-failure, + } + + /// Attempts to extract a network-related `error-code` from the stream + /// `error` provided. + /// + /// Stream operations which return `stream-error::last-operation-failed` + /// have a payload with more information about the operation that failed. + /// This payload can be passed through to this function to see if there's + /// network-related information about the error to return. + /// + /// Note that this function is fallible because not all stream-related + /// errors are network-related errors. + @unstable(feature = network-error-code) + network-error-code: func(err: borrow) -> option; + + @since(version = 0.2.0) + enum ip-address-family { + /// Similar to `AF_INET` in POSIX. + ipv4, + + /// Similar to `AF_INET6` in POSIX. + ipv6, + } + + @since(version = 0.2.0) + type ipv4-address = tuple; + @since(version = 0.2.0) + type ipv6-address = tuple; + + @since(version = 0.2.0) + variant ip-address { + ipv4(ipv4-address), + ipv6(ipv6-address), + } + + @since(version = 0.2.0) + record ipv4-socket-address { + /// sin_port + port: u16, + /// sin_addr + address: ipv4-address, + } + + @since(version = 0.2.0) + record ipv6-socket-address { + /// sin6_port + port: u16, + /// sin6_flowinfo + flow-info: u32, + /// sin6_addr + address: ipv6-address, + /// sin6_scope_id + scope-id: u32, + } + + @since(version = 0.2.0) + variant ip-socket-address { + ipv4(ipv4-socket-address), + ipv6(ipv6-socket-address), + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp-create-socket.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp-create-socket.wit new file mode 100644 index 0000000000..eedbd30768 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface tcp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + use tcp.{tcp-socket}; + + /// Create a new TCP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_STREAM, IPPROTO_TCP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind`/`connect` + /// is called, the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-tcp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp.wit new file mode 100644 index 0000000000..b4cd87fcef --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/tcp.wit @@ -0,0 +1,387 @@ +@since(version = 0.2.0) +interface tcp { + @since(version = 0.2.0) + use wasi:io/streams@0.2.3.{input-stream, output-stream}; + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use wasi:clocks/monotonic-clock@0.2.3.{duration}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + @since(version = 0.2.0) + enum shutdown-type { + /// Similar to `SHUT_RD` in POSIX. + receive, + + /// Similar to `SHUT_WR` in POSIX. + send, + + /// Similar to `SHUT_RDWR` in POSIX. + both, + } + + /// A TCP socket resource. + /// + /// The socket can be in one of the following states: + /// - `unbound` + /// - `bind-in-progress` + /// - `bound` (See note below) + /// - `listen-in-progress` + /// - `listening` + /// - `connect-in-progress` + /// - `connected` + /// - `closed` + /// See + /// for more information. + /// + /// Note: Except where explicitly mentioned, whenever this documentation uses + /// the term "bound" without backticks it actually means: in the `bound` state *or higher*. + /// (i.e. `bound`, `listen-in-progress`, `listening`, `connect-in-progress` or `connected`) + /// + /// In addition to the general error codes documented on the + /// `network::error-code` type, TCP socket methods may always return + /// `error(invalid-state)` when in the `closed` state. + @since(version = 0.2.0) + resource tcp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the TCP/UDP port is zero, the socket will be bound to a random free port. + /// + /// Bind can be attempted multiple times on the same socket, even with + /// different arguments on each iteration. But never concurrently and + /// only as long as the previous bind failed. Once a bind succeeds, the + /// binding can't be changed anymore. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-argument`: `local-address` is not a unicast address. (EINVAL) + /// - `invalid-argument`: `local-address` is an IPv4-mapped IPv6 address. (EINVAL) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// When binding to a non-zero port, this bind operation shouldn't be affected by the TIME_WAIT + /// state of a recently closed socket on the same local address. In practice this means that the SO_REUSEADDR + /// socket option should be set implicitly on all platforms, except on Windows where this is the default behavior + /// and SO_REUSEADDR performs something different entirely. + /// + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Connect to a remote endpoint. + /// + /// On success: + /// - the socket is transitioned into the `connected` state. + /// - a pair of streams is returned that can be used to read & write to the connection + /// + /// After a failed connection attempt, the socket will be in the `closed` + /// state and the only valid action left is to `drop` the socket. A single + /// socket can not be used to connect more than once. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: `remote-address` is not a unicast address. (EINVAL, ENETUNREACH on Linux, EAFNOSUPPORT on MacOS) + /// - `invalid-argument`: `remote-address` is an IPv4-mapped IPv6 address. (EINVAL, EADDRNOTAVAIL on Illumos) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EADDRNOTAVAIL on Windows) + /// - `invalid-argument`: The socket is already attached to a different network. The `network` passed to `connect` must be identical to the one passed to `bind`. + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN) + /// - `invalid-state`: The socket is already in the `listening` state. (EOPNOTSUPP, EINVAL on Windows) + /// - `timeout`: Connection timed out. (ETIMEDOUT) + /// - `connection-refused`: The connection was forcefully rejected. (ECONNREFUSED) + /// - `connection-reset`: The connection was reset. (ECONNRESET) + /// - `connection-aborted`: The connection was aborted. (ECONNABORTED) + /// - `remote-unreachable`: The remote address is not reachable. (EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `not-in-progress`: A connect operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// The POSIX equivalent of `start-connect` is the regular `connect` syscall. + /// Because all WASI sockets are non-blocking this is expected to return + /// EINPROGRESS, which should be translated to `ok()` in WASI. + /// + /// The POSIX equivalent of `finish-connect` is a `poll` for event `POLLOUT` + /// with a timeout of 0 on the socket descriptor. Followed by a check for + /// the `SO_ERROR` socket option, in case the poll signaled readiness. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-connect: func(network: borrow, remote-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-connect: func() -> result, error-code>; + + /// Start listening for new connections. + /// + /// Transitions the socket into the `listening` state. + /// + /// Unlike POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. (EDESTADDRREQ) + /// - `invalid-state`: The socket is already in the `connected` state. (EISCONN, EINVAL on BSD) + /// - `invalid-state`: The socket is already in the `listening` state. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE) + /// - `not-in-progress`: A listen operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the listen operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `listen` as part of either `start-listen` or `finish-listen`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-listen: func() -> result<_, error-code>; + @since(version = 0.2.0) + finish-listen: func() -> result<_, error-code>; + + /// Accept a new client socket. + /// + /// The returned socket is bound and in the `connected` state. The following properties are inherited from the listener socket: + /// - `address-family` + /// - `keep-alive-enabled` + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// - `hop-limit` + /// - `receive-buffer-size` + /// - `send-buffer-size` + /// + /// On success, this function returns the newly accepted client socket along with + /// a pair of streams that can be used to read & write to the connection. + /// + /// # Typical errors + /// - `invalid-state`: Socket is not in the `listening` state. (EINVAL) + /// - `would-block`: No pending connections at the moment. (EWOULDBLOCK, EAGAIN) + /// - `connection-aborted`: An incoming connection was pending, but was terminated by the client before this listener could accept it. (ECONNABORTED) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + accept: func() -> result, error-code>; + + /// Get the bound local address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the remote address. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not connected to a remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether the socket is in the `listening` state. + /// + /// Equivalent to the SO_ACCEPTCONN socket option. + @since(version = 0.2.0) + is-listening: func() -> bool; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// Hints the desired listen queue size. Implementations are free to ignore this. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// + /// # Typical errors + /// - `not-supported`: (set) The platform does not support changing the backlog size after the initial listen. + /// - `invalid-argument`: (set) The provided value was 0. + /// - `invalid-state`: (set) The socket is in the `connect-in-progress` or `connected` state. + @since(version = 0.2.0) + set-listen-backlog-size: func(value: u64) -> result<_, error-code>; + + /// Enables or disables keepalive. + /// + /// The keepalive behavior can be adjusted using: + /// - `keep-alive-idle-time` + /// - `keep-alive-interval` + /// - `keep-alive-count` + /// These properties can be configured while `keep-alive-enabled` is false, but only come into effect when `keep-alive-enabled` is true. + /// + /// Equivalent to the SO_KEEPALIVE socket option. + @since(version = 0.2.0) + keep-alive-enabled: func() -> result; + @since(version = 0.2.0) + set-keep-alive-enabled: func(value: bool) -> result<_, error-code>; + + /// Amount of time the connection has to be idle before TCP starts sending keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPIDLE socket option. (TCP_KEEPALIVE on MacOS) + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-idle-time: func() -> result; + @since(version = 0.2.0) + set-keep-alive-idle-time: func(value: duration) -> result<_, error-code>; + + /// The time between keepalive packets. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPINTVL socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-interval: func() -> result; + @since(version = 0.2.0) + set-keep-alive-interval: func(value: duration) -> result<_, error-code>; + + /// The maximum amount of keepalive packets TCP should send before aborting the connection. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the TCP_KEEPCNT socket option. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + keep-alive-count: func() -> result; + @since(version = 0.2.0) + set-keep-alive-count: func(value: u32) -> result<_, error-code>; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + @since(version = 0.2.0) + hop-limit: func() -> result; + @since(version = 0.2.0) + set-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which can be used to poll for, or block on, + /// completion of any of the asynchronous operations of this socket. + /// + /// When `finish-bind`, `finish-listen`, `finish-connect` or `accept` + /// return `error(would-block)`, this pollable can be used to wait for + /// their success or failure, after which the method can be retried. + /// + /// The pollable is not limited to the async operation that happens to be + /// in progress at the time of calling `subscribe` (if any). Theoretically, + /// `subscribe` only has to be called once per socket and can then be + /// (re)used for the remainder of the socket's lifetime. + /// + /// See + /// for more information. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + + /// Initiate a graceful shutdown. + /// + /// - `receive`: The socket is not expecting to receive any data from + /// the peer. The `input-stream` associated with this socket will be + /// closed. Any data still in the receive queue at time of calling + /// this method will be discarded. + /// - `send`: The socket has no more data to send to the peer. The `output-stream` + /// associated with this socket will be closed and a FIN packet will be sent. + /// - `both`: Same effect as `receive` & `send` combined. + /// + /// This function is idempotent; shutting down a direction more than once + /// has no effect and returns `ok`. + /// + /// The shutdown function does not close (drop) the socket. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not in the `connected` state. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + shutdown: func(shutdown-type: shutdown-type) -> result<_, error-code>; + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp-create-socket.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp-create-socket.wit new file mode 100644 index 0000000000..e8eeacbfef --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp-create-socket.wit @@ -0,0 +1,30 @@ +@since(version = 0.2.0) +interface udp-create-socket { + @since(version = 0.2.0) + use network.{network, error-code, ip-address-family}; + @since(version = 0.2.0) + use udp.{udp-socket}; + + /// Create a new UDP socket. + /// + /// Similar to `socket(AF_INET or AF_INET6, SOCK_DGRAM, IPPROTO_UDP)` in POSIX. + /// On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't be configured otherwise. + /// + /// This function does not require a network capability handle. This is considered to be safe because + /// at time of creation, the socket is not bound to any `network` yet. Up to the moment `bind` is called, + /// the socket is effectively an in-memory configuration object, unable to communicate with the outside world. + /// + /// All sockets are non-blocking. Use the wasi-poll interface to block on asynchronous operations. + /// + /// # Typical errors + /// - `not-supported`: The specified `address-family` is not supported. (EAFNOSUPPORT) + /// - `new-socket-limit`: The new socket resource could not be created because of a system limit. (EMFILE, ENFILE) + /// + /// # References: + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + create-udp-socket: func(address-family: ip-address-family) -> result; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp.wit new file mode 100644 index 0000000000..01901ca27f --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/udp.wit @@ -0,0 +1,288 @@ +@since(version = 0.2.0) +interface udp { + @since(version = 0.2.0) + use wasi:io/poll@0.2.3.{pollable}; + @since(version = 0.2.0) + use network.{network, error-code, ip-socket-address, ip-address-family}; + + /// A received datagram. + @since(version = 0.2.0) + record incoming-datagram { + /// The payload. + /// + /// Theoretical max size: ~64 KiB. In practice, typically less than 1500 bytes. + data: list, + + /// The source address. + /// + /// This field is guaranteed to match the remote address the stream was initialized with, if any. + /// + /// Equivalent to the `src_addr` out parameter of `recvfrom`. + remote-address: ip-socket-address, + } + + /// A datagram to be sent out. + @since(version = 0.2.0) + record outgoing-datagram { + /// The payload. + data: list, + + /// The destination address. + /// + /// The requirements on this field depend on how the stream was initialized: + /// - with a remote address: this field must be None or match the stream's remote address exactly. + /// - without a remote address: this field is required. + /// + /// If this value is None, the send operation is equivalent to `send` in POSIX. Otherwise it is equivalent to `sendto`. + remote-address: option, + } + + /// A UDP socket handle. + @since(version = 0.2.0) + resource udp-socket { + /// Bind the socket to a specific network on the provided IP address and port. + /// + /// If the IP address is zero (`0.0.0.0` in IPv4, `::` in IPv6), it is left to the implementation to decide which + /// network interface(s) to bind to. + /// If the port is zero, the socket will be bound to a random free port. + /// + /// # Typical errors + /// - `invalid-argument`: The `local-address` has the wrong address family. (EAFNOSUPPORT, EFAULT on Windows) + /// - `invalid-state`: The socket is already bound. (EINVAL) + /// - `address-in-use`: No ephemeral ports available. (EADDRINUSE, ENOBUFS on Windows) + /// - `address-in-use`: Address is already in use. (EADDRINUSE) + /// - `address-not-bindable`: `local-address` is not an address that the `network` can bind to. (EADDRNOTAVAIL) + /// - `not-in-progress`: A `bind` operation is not in progress. + /// - `would-block`: Can't finish the operation, it is still in progress. (EWOULDBLOCK, EAGAIN) + /// + /// # Implementors note + /// Unlike in POSIX, in WASI the bind operation is async. This enables + /// interactive WASI hosts to inject permission prompts. Runtimes that + /// don't want to make use of this ability can simply call the native + /// `bind` as part of either `start-bind` or `finish-bind`. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + start-bind: func(network: borrow, local-address: ip-socket-address) -> result<_, error-code>; + @since(version = 0.2.0) + finish-bind: func() -> result<_, error-code>; + + /// Set up inbound & outbound communication channels, optionally to a specific peer. + /// + /// This function only changes the local socket configuration and does not generate any network traffic. + /// On success, the `remote-address` of the socket is updated. The `local-address` may be updated as well, + /// based on the best network path to `remote-address`. + /// + /// When a `remote-address` is provided, the returned streams are limited to communicating with that specific peer: + /// - `send` can only be used to send to this destination. + /// - `receive` will only return datagrams sent from the provided `remote-address`. + /// + /// This method may be called multiple times on the same socket to change its association, but + /// only the most recently returned pair of streams will be operational. Implementations may trap if + /// the streams returned by a previous invocation haven't been dropped yet before calling `stream` again. + /// + /// The POSIX equivalent in pseudo-code is: + /// ```text + /// if (was previously connected) { + /// connect(s, AF_UNSPEC) + /// } + /// if (remote_address is Some) { + /// connect(s, remote_address) + /// } + /// ``` + /// + /// Unlike in POSIX, the socket must already be explicitly bound. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-state`: The socket is not bound. + /// - `address-in-use`: Tried to perform an implicit bind, but there were no ephemeral ports available. (EADDRINUSE, EADDRNOTAVAIL on Linux, EAGAIN on BSD) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + %stream: func(remote-address: option) -> result, error-code>; + + /// Get the current bound address. + /// + /// POSIX mentions: + /// > If the socket has not been bound to a local name, the value + /// > stored in the object pointed to by `address` is unspecified. + /// + /// WASI is stricter and requires `local-address` to return `invalid-state` when the socket hasn't been bound yet. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not bound to any local address. + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + local-address: func() -> result; + + /// Get the address the socket is currently streaming to. + /// + /// # Typical errors + /// - `invalid-state`: The socket is not streaming to a specific remote address. (ENOTCONN) + /// + /// # References + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + remote-address: func() -> result; + + /// Whether this is a IPv4 or IPv6 socket. + /// + /// Equivalent to the SO_DOMAIN socket option. + @since(version = 0.2.0) + address-family: func() -> ip-address-family; + + /// Equivalent to the IP_TTL & IPV6_UNICAST_HOPS socket options. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The TTL value must be 1 or higher. + @since(version = 0.2.0) + unicast-hop-limit: func() -> result; + @since(version = 0.2.0) + set-unicast-hop-limit: func(value: u8) -> result<_, error-code>; + + /// The kernel buffer space reserved for sends/receives on this socket. + /// + /// If the provided value is 0, an `invalid-argument` error is returned. + /// Any other value will never cause an error, but it might be silently clamped and/or rounded. + /// I.e. after setting a value, reading the same setting back may return a different value. + /// + /// Equivalent to the SO_RCVBUF and SO_SNDBUF socket options. + /// + /// # Typical errors + /// - `invalid-argument`: (set) The provided value was 0. + @since(version = 0.2.0) + receive-buffer-size: func() -> result; + @since(version = 0.2.0) + set-receive-buffer-size: func(value: u64) -> result<_, error-code>; + @since(version = 0.2.0) + send-buffer-size: func() -> result; + @since(version = 0.2.0) + set-send-buffer-size: func(value: u64) -> result<_, error-code>; + + /// Create a `pollable` which will resolve once the socket is ready for I/O. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + resource incoming-datagram-stream { + /// Receive messages on the socket. + /// + /// This function attempts to receive up to `max-results` datagrams on the socket without blocking. + /// The returned list may contain fewer elements than requested, but never more. + /// + /// This function returns successfully with an empty list when either: + /// - `max-results` is 0, or: + /// - `max-results` is greater than 0, but no results are immediately available. + /// This function never returns `error(would-block)`. + /// + /// # Typical errors + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + receive: func(max-results: u64) -> result, error-code>; + + /// Create a `pollable` which will resolve once the stream is ready to receive again. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } + + @since(version = 0.2.0) + resource outgoing-datagram-stream { + /// Check readiness for sending. This function never blocks. + /// + /// Returns the number of datagrams permitted for the next call to `send`, + /// or an error. Calling `send` with more datagrams than this function has + /// permitted will trap. + /// + /// When this function returns ok(0), the `subscribe` pollable will + /// become ready when this function will report at least ok(1), or an + /// error. + /// + /// Never returns `would-block`. + check-send: func() -> result; + + /// Send messages on the socket. + /// + /// This function attempts to send all provided `datagrams` on the socket without blocking and + /// returns how many messages were actually sent (or queued for sending). This function never + /// returns `error(would-block)`. If none of the datagrams were able to be sent, `ok(0)` is returned. + /// + /// This function semantically behaves the same as iterating the `datagrams` list and sequentially + /// sending each individual datagram until either the end of the list has been reached or the first error occurred. + /// If at least one datagram has been sent successfully, this function never returns an error. + /// + /// If the input list is empty, the function returns `ok(0)`. + /// + /// Each call to `send` must be permitted by a preceding `check-send`. Implementations must trap if + /// either `check-send` was not called or `datagrams` contains more items than `check-send` permitted. + /// + /// # Typical errors + /// - `invalid-argument`: The `remote-address` has the wrong address family. (EAFNOSUPPORT) + /// - `invalid-argument`: The IP address in `remote-address` is set to INADDR_ANY (`0.0.0.0` / `::`). (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The port in `remote-address` is set to 0. (EDESTADDRREQ, EADDRNOTAVAIL) + /// - `invalid-argument`: The socket is in "connected" mode and `remote-address` is `some` value that does not match the address passed to `stream`. (EISCONN) + /// - `invalid-argument`: The socket is not "connected" and no value for `remote-address` was provided. (EDESTADDRREQ) + /// - `remote-unreachable`: The remote address is not reachable. (ECONNRESET, ENETRESET on Windows, EHOSTUNREACH, EHOSTDOWN, ENETUNREACH, ENETDOWN, ENONET) + /// - `connection-refused`: The connection was refused. (ECONNREFUSED) + /// - `datagram-too-large`: The datagram is too large. (EMSGSIZE) + /// + /// # References + /// - + /// - + /// - + /// - + /// - + /// - + /// - + /// - + @since(version = 0.2.0) + send: func(datagrams: list) -> result; + + /// Create a `pollable` which will resolve once the stream is ready to send again. + /// + /// Note: this function is here for WASI 0.2 only. + /// It's planned to be removed when `future` is natively supported in Preview3. + @since(version = 0.2.0) + subscribe: func() -> pollable; + } +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/world.wit b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/world.wit new file mode 100644 index 0000000000..2f0ad0d7c9 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/deps/sockets/world.wit @@ -0,0 +1,19 @@ +package wasi:sockets@0.2.3; + +@since(version = 0.2.0) +world imports { + @since(version = 0.2.0) + import instance-network; + @since(version = 0.2.0) + import network; + @since(version = 0.2.0) + import udp; + @since(version = 0.2.0) + import udp-create-socket; + @since(version = 0.2.0) + import tcp; + @since(version = 0.2.0) + import tcp-create-socket; + @since(version = 0.2.0) + import ip-name-lookup; +} diff --git a/test-components/wasi-http-incoming-request-handler/wit/world.wit b/test-components/wasi-http-incoming-request-handler/wit/world.wit new file mode 100644 index 0000000000..85633a60d5 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler/wit/world.wit @@ -0,0 +1,6 @@ +package golem:handler; + +world api { + import wasi:http/types@0.2.3; + export wasi:http/incoming-handler@0.2.3; +} From 96d39d8df97e28f7970eb91b9b2f248e4563bea4 Mon Sep 17 00:00:00 2001 From: Daniel Vigovszky Date: Wed, 22 Jan 2025 15:27:32 +0100 Subject: [PATCH 08/17] Pinned internal dependencies (#1256) --- golem-api-grpc/Cargo.toml | 4 ++-- golem-cli/Cargo.toml | 16 +++++++------- golem-client/Cargo.toml | 6 ++--- golem-common/Cargo.toml | 8 +++---- .../Cargo.toml | 8 +++---- golem-component-service-base/Cargo.toml | 10 ++++----- golem-component-service/Cargo.toml | 14 ++++++------ golem-rib/Cargo.toml | 6 ++--- golem-service-base/Cargo.toml | 8 +++---- golem-shard-manager/Cargo.toml | 6 ++--- golem-test-framework/Cargo.toml | 10 ++++----- golem-worker-executor-base/Cargo.toml | 14 ++++++------ golem-worker-executor/Cargo.toml | 8 +++---- golem-worker-service-base/Cargo.toml | 4 ++-- golem-worker-service/Cargo.toml | 6 ++--- golem/Cargo.toml | 22 +++++++++---------- integration-tests/Cargo.toml | 8 +++---- wasm-rpc-stubgen/Cargo.toml | 4 ++-- wasm-rpc-stubgen/tests-integration/Cargo.toml | 4 ++-- wasm-rpc/Cargo.toml | 2 +- 20 files changed, 84 insertions(+), 84 deletions(-) diff --git a/golem-api-grpc/Cargo.toml b/golem-api-grpc/Cargo.toml index b5fb244bcf..798fd8101c 100644 --- a/golem-api-grpc/Cargo.toml +++ b/golem-api-grpc/Cargo.toml @@ -11,8 +11,8 @@ description = "GRPC API for Golem services" harness = false [dependencies] -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0", default-features = false, features = ["protobuf"] } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host-bindings", "protobuf"] } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", default-features = false, features = ["protobuf"] } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host-bindings", "protobuf"] } async-trait = { workspace = true } bincode = { workspace = true } diff --git a/golem-cli/Cargo.toml b/golem-cli/Cargo.toml index cc2c7fbd84..1192f9ddc2 100644 --- a/golem-cli/Cargo.toml +++ b/golem-cli/Cargo.toml @@ -23,12 +23,12 @@ path = "tests/main.rs" harness = false [dependencies] -golem-client = { path = "../golem-client", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0", default-features = false } -golem-rib = { path = "../golem-rib", version = "0.0.0", default-features = false } -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0", default-features = false, features = ["analysis"] } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false } -golem-wasm-rpc-stubgen = { path = "../wasm-rpc-stubgen", version = "0.0.0" } +golem-client = { path = "../golem-client", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0", default-features = false } +golem-rib = { path = "../golem-rib", version = "=0.0.0", default-features = false } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", default-features = false, features = ["analysis"] } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false } +golem-wasm-rpc-stubgen = { path = "../wasm-rpc-stubgen", version = "=0.0.0" } anyhow.workspace = true assert2 = { workspace = true } @@ -45,7 +45,7 @@ derive_more = { workspace = true } dirs = "5.0.1" futures-util = { workspace = true } glob = "0.3.1" -golem-examples = "1.1.1" +golem-examples = "=1.1.1" h2 = "0.4.7" http = { workspace = true } humansize = { workspace = true } @@ -84,7 +84,7 @@ walkdir = "2.5.0" wasm-wave = { workspace = true } [dev-dependencies] -golem-test-framework = { path = "../golem-test-framework", version = "0.0.0" } +golem-test-framework = { path = "../golem-test-framework", version = "=0.0.0" } async-recursion = { workspace = true } env_logger = "0.11.5" diff --git a/golem-client/Cargo.toml b/golem-client/Cargo.toml index e56ddd0b44..90b7541cc9 100644 --- a/golem-client/Cargo.toml +++ b/golem-client/Cargo.toml @@ -13,9 +13,9 @@ include = ["src/**/*", "Cargo.toml", "build.rs", "openapi/**/*"] harness = false [dependencies] -golem-common = { path = "../golem-common", version = "0.0.0", default-features = false } -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0", default-features = false, features = ["analysis"] } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false } +golem-common = { path = "../golem-common", version = "=0.0.0", default-features = false } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", default-features = false, features = ["analysis"] } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false } async-trait = { workspace = true } bytes = { workspace = true } diff --git a/golem-common/Cargo.toml b/golem-common/Cargo.toml index eb5cba0020..718ddde512 100644 --- a/golem-common/Cargo.toml +++ b/golem-common/Cargo.toml @@ -22,10 +22,10 @@ tokio = ["dep:tokio"] harness = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0", optional = true } -golem-rib = { path = "../golem-rib", version = "0.0.0", default-features = false, features = ["protobuf", "poem", "json_in_errors"] } # TODO: make these optionals -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0", default-features = false, features = ["metadata"] } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0", optional = true } +golem-rib = { path = "../golem-rib", version = "=0.0.0", default-features = false, features = ["protobuf", "poem", "json_in_errors"] } # TODO: make these optionals +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", default-features = false, features = ["metadata"] } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } async-trait = { workspace = true } diff --git a/golem-component-compilation-service/Cargo.toml b/golem-component-compilation-service/Cargo.toml index f378ce570c..56e8f9ccbd 100644 --- a/golem-component-compilation-service/Cargo.toml +++ b/golem-component-compilation-service/Cargo.toml @@ -14,10 +14,10 @@ path = "src/server.rs" test = false [dependencies] -golem-api-grpc = { version = "0.0.0", path = "../golem-api-grpc" } -golem-common = { version = "0.0.0", path = "../golem-common" } -golem-service-base = { path = "../golem-service-base" } -golem-worker-executor-base = { version = "0.0.0", path = "../golem-worker-executor-base" } +golem-api-grpc = { version = "=0.0.0", path = "../golem-api-grpc" } +golem-common = { version = "=0.0.0", path = "../golem-common" } +golem-service-base = { version = "=0.0.0", path = "../golem-service-base" } +golem-worker-executor-base = { version = "=0.0.0", path = "../golem-worker-executor-base" } async-trait = { workspace = true } console-subscriber = { workspace = true } diff --git a/golem-component-service-base/Cargo.toml b/golem-component-service-base/Cargo.toml index 989b730db1..163fbe1e62 100644 --- a/golem-component-service-base/Cargo.toml +++ b/golem-component-service-base/Cargo.toml @@ -11,11 +11,11 @@ name = "tests" harness = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-service-base = { path = "../golem-service-base" } -golem-rib = { path = "../golem-rib" } -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-service-base = { path = "../golem-service-base", version = "=0.0.0" } +golem-rib = { path = "../golem-rib", version = "=0.0.0" } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } anyhow = { workspace = true } async-trait = { workspace = true } diff --git a/golem-component-service/Cargo.toml b/golem-component-service/Cargo.toml index dc872edaca..96f01efe78 100644 --- a/golem-component-service/Cargo.toml +++ b/golem-component-service/Cargo.toml @@ -13,13 +13,13 @@ test = false harness = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-component-service-base = { version = "0.0.0", path = "../golem-component-service-base" } -golem-service-base = { path = "../golem-service-base" } -golem-rib = {path = "../golem-rib"} -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-component-service-base = { path = "../golem-component-service-base", version = "=0.0.0" } +golem-service-base = { path = "../golem-service-base", version = "=0.0.0" } +golem-rib = { path = "../golem-rib", version = "=0.0.0" } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } async-trait = { workspace = true } diff --git a/golem-rib/Cargo.toml b/golem-rib/Cargo.toml index 454bfda74e..7351f00900 100644 --- a/golem-rib/Cargo.toml +++ b/golem-rib/Cargo.toml @@ -14,9 +14,9 @@ protobuf = ["dep:golem-api-grpc", "golem-wasm-ast/protobuf", "golem-wasm-rpc/pro poem = ["dep:poem-openapi", "golem-wasm-ast/poem_openapi", "golem-wasm-ast/poem_openapi"] [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0", optional = true } # TODO: remove this dependency -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0", default-features = false, features = ["analysis", "bincode"] } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["bincode", "typeinfo", "text"] } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0", optional = true } # TODO: remove this dependency +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", default-features = false, features = ["analysis", "bincode"] } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["bincode", "typeinfo", "text"] } bigdecimal = { workspace = true } bincode = { workspace = true } diff --git a/golem-service-base/Cargo.toml b/golem-service-base/Cargo.toml index 96f4726612..3a4afed4ef 100644 --- a/golem-service-base/Cargo.toml +++ b/golem-service-base/Cargo.toml @@ -13,10 +13,10 @@ autotests = false harness = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } async-fs = { workspace = true } diff --git a/golem-shard-manager/Cargo.toml b/golem-shard-manager/Cargo.toml index fc485ef148..5f492dcaa5 100644 --- a/golem-shard-manager/Cargo.toml +++ b/golem-shard-manager/Cargo.toml @@ -14,9 +14,9 @@ harness = false test = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-service-base = { path = "../golem-service-base", version = "0.0.0" } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-service-base = { path = "../golem-service-base", version = "=0.0.0" } anyhow = { workspace = true } async-rwlock = "1.3.0" diff --git a/golem-test-framework/Cargo.toml b/golem-test-framework/Cargo.toml index 9c63b8bd84..485a275897 100644 --- a/golem-test-framework/Cargo.toml +++ b/golem-test-framework/Cargo.toml @@ -11,11 +11,11 @@ repository = "https://github.com/golemcloud/golem" harness = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-service-base = { path = "../golem-service-base", version = "0.0.0" } -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-service-base = { path = "../golem-service-base", version = "=0.0.0" } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } async-dropper = { version = "0.3.1", features = ["simple", "tokio"] } diff --git a/golem-worker-executor-base/Cargo.toml b/golem-worker-executor-base/Cargo.toml index bfecadd834..990e9dcbfb 100644 --- a/golem-worker-executor-base/Cargo.toml +++ b/golem-worker-executor-base/Cargo.toml @@ -17,12 +17,12 @@ harness = false [features] [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-rib = { path = "../golem-rib", version = "0.0.0" } -golem-service-base = { path = "../golem-service-base", version = "0.0.0" } -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-rib = { path = "../golem-rib", version = "=0.0.0" } +golem-service-base = { path = "../golem-service-base", version = "=0.0.0" } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } async-scoped = "0.9.0" @@ -93,7 +93,7 @@ zstd = "0.13" sqlx = { workspace = true } [dev-dependencies] -golem-test-framework = { path = "../golem-test-framework", version = "0.0.0" } +golem-test-framework = { path = "../golem-test-framework", version = "=0.0.0" } assert2 = { workspace = true } axum = { workspace = true } diff --git a/golem-worker-executor/Cargo.toml b/golem-worker-executor/Cargo.toml index e912c03092..5c394f4299 100644 --- a/golem-worker-executor/Cargo.toml +++ b/golem-worker-executor/Cargo.toml @@ -17,10 +17,10 @@ harness = false test = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } -golem-worker-executor-base = { path = "../golem-worker-executor-base", version = "0.0.0" } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } +golem-worker-executor-base = { path = "../golem-worker-executor-base", version = "=0.0.0" } anyhow = { workspace = true } async-trait = { workspace = true } diff --git a/golem-worker-service-base/Cargo.toml b/golem-worker-service-base/Cargo.toml index a3b43d7163..6870ec33b1 100644 --- a/golem-worker-service-base/Cargo.toml +++ b/golem-worker-service-base/Cargo.toml @@ -23,8 +23,8 @@ golem-common = { path = "../golem-common" } golem-api-grpc = { path = "../golem-api-grpc" } golem-service-base = { path = "../golem-service-base" } golem-rib = { path = "../golem-rib" } -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } async-trait = { workspace = true } diff --git a/golem-worker-service/Cargo.toml b/golem-worker-service/Cargo.toml index b3af371b50..80b83bec38 100644 --- a/golem-worker-service/Cargo.toml +++ b/golem-worker-service/Cargo.toml @@ -22,9 +22,9 @@ golem-api-grpc = { path = "../golem-api-grpc" } golem-common = { path = "../golem-common" } golem-service-base = { path = "../golem-service-base" } golem-rib = {path = "../golem-rib"} -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } -golem-worker-service-base = { path = "../golem-worker-service-base" } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } +golem-worker-service-base = { path = "../golem-worker-service-base", version = "=0.0.0" } anyhow = { workspace = true } async-trait = { workspace = true } diff --git a/golem/Cargo.toml b/golem/Cargo.toml index 3731c53ab3..aafe519884 100644 --- a/golem/Cargo.toml +++ b/golem/Cargo.toml @@ -17,17 +17,17 @@ path = "src/main.rs" test = false [dependencies] -golem-cli = { path = "../golem-cli", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-component-compilation-service = { path = "../golem-component-compilation-service", version = "0.0.0" } -golem-component-service = { path = "../golem-component-service", version = "0.0.0" } -golem-component-service-base = { path = "../golem-component-service-base", version = "0.0.0" } -golem-service-base = { path = "../golem-service-base", version = "0.0.0" } -golem-shard-manager = { path = "../golem-shard-manager", version = "0.0.0" } -golem-worker-executor = { path = "../golem-worker-executor", version = "0.0.0" } -golem-worker-executor-base = { path = "../golem-worker-executor-base", version = "0.0.0" } -golem-worker-service = { path = "../golem-worker-service", version = "0.0.0" } -golem-worker-service-base = { path = "../golem-worker-service-base", version = "0.0.0" } +golem-cli = { path = "../golem-cli", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-component-compilation-service = { path = "../golem-component-compilation-service", version = "=0.0.0" } +golem-component-service = { path = "../golem-component-service", version = "=0.0.0" } +golem-component-service-base = { path = "../golem-component-service-base", version = "=0.0.0" } +golem-service-base = { path = "../golem-service-base", version = "=0.0.0" } +golem-shard-manager = { path = "../golem-shard-manager", version = "=0.0.0" } +golem-worker-executor = { path = "../golem-worker-executor", version = "=0.0.0" } +golem-worker-executor-base = { path = "../golem-worker-executor-base", version = "=0.0.0" } +golem-worker-service = { path = "../golem-worker-service", version = "=0.0.0" } +golem-worker-service-base = { path = "../golem-worker-service-base", version = "=0.0.0" } anyhow = { workspace = true } bytes = { workspace = true } diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index fc2854bdc6..04762042b0 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -10,10 +10,10 @@ description = "Integration tests for Golem" autotests = false [dependencies] -golem-api-grpc = { path = "../golem-api-grpc", version = "0.0.0" } -golem-common = { path = "../golem-common", version = "0.0.0" } -golem-test-framework = { path = "../golem-test-framework", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-api-grpc = { path = "../golem-api-grpc", version = "=0.0.0" } +golem-common = { path = "../golem-common", version = "=0.0.0" } +golem-test-framework = { path = "../golem-test-framework", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } assert2 = { workspace = true } diff --git a/wasm-rpc-stubgen/Cargo.toml b/wasm-rpc-stubgen/Cargo.toml index 27f8ae35c9..de81307ec2 100644 --- a/wasm-rpc-stubgen/Cargo.toml +++ b/wasm-rpc-stubgen/Cargo.toml @@ -35,8 +35,8 @@ colored = "2.1.0" dir-diff = "0.3.3" fs_extra = { workspace = true } glob = "0.3.1" -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0" } -golem-wasm-rpc = { path = "../wasm-rpc", version = "0.0.0", default-features = false, features = ["host"] } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } heck = "0.5.0" id-arena = "2.2.1" indexmap = "2.7.0" diff --git a/wasm-rpc-stubgen/tests-integration/Cargo.toml b/wasm-rpc-stubgen/tests-integration/Cargo.toml index 61dcf0ad32..d2ce01dd82 100644 --- a/wasm-rpc-stubgen/tests-integration/Cargo.toml +++ b/wasm-rpc-stubgen/tests-integration/Cargo.toml @@ -26,8 +26,8 @@ harness = false [dependencies] assert2 = { workspace = true } fs_extra = { workspace = true } -golem-wasm-ast = { path = "../../wasm-ast", version = "0.0.0" } -golem-wasm-rpc-stubgen = { path = "../../wasm-rpc-stubgen", version = "0.0.0" } +golem-wasm-ast = { path = "../../wasm-ast", version = "=0.0.0" } +golem-wasm-rpc-stubgen = { path = "../../wasm-rpc-stubgen", version = "=0.0.0" } tempfile = { workspace = true } tokio = { workspace = true } diff --git a/wasm-rpc/Cargo.toml b/wasm-rpc/Cargo.toml index d51e4d3650..e581b600ac 100644 --- a/wasm-rpc/Cargo.toml +++ b/wasm-rpc/Cargo.toml @@ -23,7 +23,7 @@ async-trait = { workspace = true, optional = true } bigdecimal = { workspace = true, optional = true } bincode = { workspace = true, optional = true } git-version = "0.3.9" -golem-wasm-ast = { path = "../wasm-ast", version = "0.0.0", optional = true } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", optional = true } poem-openapi = { workspace = true, optional = true } serde = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } From 6839a109c0bfceb0bc137cab85989394533d4a8a Mon Sep 17 00:00:00 2001 From: Maxim Schuwalow Date: Wed, 22 Jan 2025 15:53:52 +0100 Subject: [PATCH 09/17] Explicitly enable use-tokio feature flag for async-scoped (#1257) --- golem-worker-executor-base/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/golem-worker-executor-base/Cargo.toml b/golem-worker-executor-base/Cargo.toml index 990e9dcbfb..6ebf23362c 100644 --- a/golem-worker-executor-base/Cargo.toml +++ b/golem-worker-executor-base/Cargo.toml @@ -25,7 +25,7 @@ golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0" } golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false, features = ["host"] } anyhow = { workspace = true } -async-scoped = "0.9.0" +async-scoped = { version = "0.9.0", features = [ "use-tokio" ] } async-fs = { workspace = true } async-lock = "3.4.0" async-mutex = "1.4.0" From 4b61586d2bbc424e7ee9492ce8532bd7e17200be Mon Sep 17 00:00:00 2001 From: Maxim Schuwalow Date: Thu, 23 Jan 2025 14:07:24 +0100 Subject: [PATCH 10/17] Add http-handler binding type (#1253) * Add http-handler binding type * add tests and various cleanups * remove unused --- Cargo.lock | 1 + Cargo.toml | 2 + .../golem/apidefinition/api_definition.proto | 1 + .../tests/api_deployment_http_handler.rs | 132 ++++++ golem-cli/tests/main.rs | 1 + golem-common/src/model/mod.rs | 1 + golem-common/src/model/protobuf.rs | 6 + .../virtual_exports/http_incoming_handler.rs | 398 +++++++++++++----- golem-worker-executor-base/Cargo.toml | 4 +- golem-worker-executor-base/src/invocation.rs | 20 +- .../http_incoming_handler.rs | 44 +- golem-worker-executor-base/tests/wasi.rs | 28 +- golem-worker-service-base/Cargo.toml | 1 + .../src/api/custom_http_request_api.rs | 3 + .../src/api/register_api_definition_api.rs | 98 ++++- .../http/http_api_definition.rs | 24 +- .../http/http_oas_api_definition.rs | 33 +- .../gateway_binding_compiled.rs | 130 +++++- .../gateway_binding/http_handler_binding.rs | 77 ++++ .../src/gateway_binding/mod.rs | 106 ++++- .../src/gateway_binding/worker_binding.rs | 86 +++- .../worker_binding_compiled.rs | 134 ------ .../file_server_binding_handler.rs | 184 ++++---- .../gateway_binding_resolver.rs | 154 +++++-- .../gateway_http_input_executor.rs | 37 ++ .../http_handler_binding_handler.rs | 229 ++++++++++ .../src/gateway_execution/mod.rs | 1 + .../rib_input_value_resolver.rs | 4 +- .../src/gateway_execution/to_response.rs | 25 ++ .../src/gateway_request/http_request.rs | 6 +- .../src/gateway_request/request_details.rs | 64 +-- .../src/service/gateway/api_definition.rs | 5 +- .../gateway/http_api_definition_validator.rs | 2 +- .../tests/api_gateway_end_to_end_tests.rs | 23 + golem-worker-service/src/api/mod.rs | 1 + golem-worker-service/src/service/mod.rs | 12 + openapi/golem-service.yaml | 1 + .../golem.yaml | 7 + 38 files changed, 1615 insertions(+), 470 deletions(-) create mode 100644 golem-cli/tests/api_deployment_http_handler.rs create mode 100644 golem-worker-service-base/src/gateway_binding/http_handler_binding.rs delete mode 100644 golem-worker-service-base/src/gateway_binding/worker_binding_compiled.rs create mode 100644 golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs create mode 100644 test-components/wasi-http-incoming-request-handler-echo/golem.yaml diff --git a/Cargo.lock b/Cargo.lock index 02f5a3c779..88214a2566 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4386,6 +4386,7 @@ dependencies = [ "golem-wasm-ast", "golem-wasm-rpc", "http 1.2.0", + "http-body-util", "humantime-serde", "hyper 1.5.2", "lazy_static 1.5.0", diff --git a/Cargo.toml b/Cargo.toml index 618edab19b..be254b5ca0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -115,6 +115,8 @@ git-version = "0.3.9" golem-wit = { version = "=1.1.2" } hex = "0.4.3" http = "1.2.0" # keep in sync with wasmtime +http-body = "1.0.1" # keep in sync with wasmtime +http-body-util = "0.1.0" # keep in sync with wasmtime humansize = "2.1.3" humantime-serde = "1.1.1" hyper = { version = "1.5.1", features = ["full"] } # keep in sync with wasmtime diff --git a/golem-api-grpc/proto/golem/apidefinition/api_definition.proto b/golem-api-grpc/proto/golem/apidefinition/api_definition.proto index edb5a6b0d0..36a4ba7e35 100644 --- a/golem-api-grpc/proto/golem/apidefinition/api_definition.proto +++ b/golem-api-grpc/proto/golem/apidefinition/api_definition.proto @@ -119,6 +119,7 @@ enum GatewayBindingType { FILE_SERVER = 1; CORS_PREFLIGHT = 2; AUTH_CALL_BACK = 3; + HTTP_HANDLER = 4; } // Used in api definition repo and needs to be backward compatible diff --git a/golem-cli/tests/api_deployment_http_handler.rs b/golem-cli/tests/api_deployment_http_handler.rs new file mode 100644 index 0000000000..01fad328b6 --- /dev/null +++ b/golem-cli/tests/api_deployment_http_handler.rs @@ -0,0 +1,132 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::cli::{Cli, CliLive}; +use crate::Tracing; +use golem_cli::model::component::ComponentView; +use golem_client::model::{ApiDeployment, HttpApiDefinitionRequest, HttpApiDefinitionResponseData}; +use golem_common::model::ComponentId; +use golem_common::uri::oss::urn::WorkerUrn; +use golem_test_framework::config::{EnvBasedTestDependencies, TestDependencies}; +use std::io::Write; +use std::sync::Arc; +use test_r::{inherit_test_dep, test, test_dep}; + +inherit_test_dep!(EnvBasedTestDependencies); +inherit_test_dep!(Tracing); + +#[test_dep] +fn cli(deps: &EnvBasedTestDependencies) -> CliLive { + CliLive::make("api_deployment", Arc::new(deps.clone())).unwrap() +} + +#[test] +async fn api_deployment_http_handler( + deps: &EnvBasedTestDependencies, + cli: &CliLive, +) -> anyhow::Result<()> { + let host = format!( + "localhost:{}", + deps.worker_service().private_custom_request_port() + ); + let component_name = "wasi-http-incoming-request-handler-echo".to_string(); + let golem_yaml = deps + .component_directory() + .join("wasi-http-incoming-request-handler-echo/golem.yaml"); + let cfg = &cli.config; + let component: ComponentView = cli.run_trimmed(&[ + "component", + "add", + &cfg.arg('a', "app"), + golem_yaml.to_str().unwrap(), + &cfg.arg('c', "component-name"), + &component_name, + ])?; + let component_urn = component.component_urn; + let component_id = component_urn.id.clone(); + + let worker_name = format!("{component_name}-worker"); + + let _: WorkerUrn = cli.run(&[ + "worker", + "add", + &cfg.arg('w', "worker-name"), + &worker_name, + &cfg.arg('C', "component"), + &component_urn.to_string(), + ])?; + + let temp_dir = tempfile::tempdir()?; + let api_definition = make_http_handler_api_definition(&component_id, &worker_name)?; + let api_path = temp_dir.path().join("api-definition.json"); + { + let mut api_file = std::fs::File::create_new(&api_path)?; + let mut writer = std::io::BufWriter::new(&mut api_file); + serde_json::to_writer(&mut writer, &api_definition)?; + writer.flush()?; + } + + let definition: HttpApiDefinitionResponseData = + cli.run(&["api-definition", "add", api_path.to_str().unwrap()])?; + + let _: ApiDeployment = cli.run(&[ + "api-deployment", + "deploy", + &cfg.arg('d', "definition"), + &format!("{}/{}", definition.id, definition.version), + &cfg.arg('H', "host"), + &host, + ])?; + + let res = { + let client = reqwest::Client::new(); + + client + .post(format!("http://{host}/test?foo=baz")) + .header("test-header", "test-header-value") + .body("\"test-body\"") + .send() + .await + }?; + assert_eq!(res.status().as_u16(), 200); + assert_eq!( + res.headers().get("echo-test-header").unwrap(), + "\"test-header-value\"" + ); + assert_eq!(res.text().await?, "\"test-body\""); + + Ok(()) +} + +fn make_http_handler_api_definition( + component_id: &ComponentId, + worker_name: &str, +) -> anyhow::Result { + Ok(serde_yaml::from_str(&format!( + r#" + id: "{component_id}" + version: "0.1.0" + draft: true + routes: + - method: Post + path: "/test" + binding: + bindingType: http-handler + componentId: + componentId: '{component_id}' + version: 0 + workerName: 'let name: string = "{worker_name}"; name' + "#, + ))?) +} diff --git a/golem-cli/tests/main.rs b/golem-cli/tests/main.rs index 21c705b50b..226938e4d7 100644 --- a/golem-cli/tests/main.rs +++ b/golem-cli/tests/main.rs @@ -27,6 +27,7 @@ pub mod cli; mod api_definition; mod api_deployment; mod api_deployment_fileserver; +mod api_deployment_http_handler; mod component; mod get; mod profile; diff --git a/golem-common/src/model/mod.rs b/golem-common/src/model/mod.rs index 33ade7dfd5..e9916891ba 100644 --- a/golem-common/src/model/mod.rs +++ b/golem-common/src/model/mod.rs @@ -2186,6 +2186,7 @@ pub enum GatewayBindingType { #[default] Default, FileServer, + HttpHandler, CorsPreflight, } diff --git a/golem-common/src/model/protobuf.rs b/golem-common/src/model/protobuf.rs index 8b57eeb398..13ca6ca05f 100644 --- a/golem-common/src/model/protobuf.rs +++ b/golem-common/src/model/protobuf.rs @@ -736,6 +736,9 @@ impl From for G golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::FileServer => { GatewayBindingType::FileServer } + golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::HttpHandler => { + GatewayBindingType::HttpHandler + } golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::CorsPreflight => { GatewayBindingType::CorsPreflight } @@ -755,6 +758,9 @@ impl From for golem_api_grpc::proto::golem::apidefinition::G GatewayBindingType::FileServer => { golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::FileServer } + GatewayBindingType::HttpHandler => { + golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::HttpHandler + } GatewayBindingType::CorsPreflight => { golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::CorsPreflight } diff --git a/golem-common/src/virtual_exports/http_incoming_handler.rs b/golem-common/src/virtual_exports/http_incoming_handler.rs index ef3b6333b2..349a5d2558 100644 --- a/golem-common/src/virtual_exports/http_incoming_handler.rs +++ b/golem-common/src/virtual_exports/http_incoming_handler.rs @@ -15,23 +15,44 @@ use bytes::Bytes; use golem_wasm_ast::analysis::AnalysedType; use golem_wasm_ast::analysis::{AnalysedExport, AnalysedFunction, AnalysedInstance}; +use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; use golem_wasm_rpc::Value; -use lazy_static::lazy_static; -use semver::Version; +use std::sync::LazyLock; // The following wit is modelled here: // // type fields = list>>; // type body = list; // +// variant method { +// get, +// head, +// post, +// put, +// delete, +// connect, +// options, +// trace, +// patch, +// custom(string) +// } +// +// variant scheme { +// HTTP, +// HTTPS, +// custom(string) +// } +// // record body-and-trailers { // body: body, // trailers: option // } // // record request { -// uri: string // method: method, +// scheme: scheme, +// authority: string, +// path-with-query: string, // headers: fields, // body-and-trailers: option // } @@ -45,92 +66,61 @@ use semver::Version; // handle: func(request: request) -> response; // -lazy_static! { - pub static ref REQUIRED_FUNCTIONS: Vec = vec![ - rib::ParsedFunctionName { - site: rib::ParsedFunctionSite::PackagedInterface { - namespace: "wasi".to_string(), - package: "http".to_string(), - interface: "incoming-handler".to_string(), - version: Some(rib::SemVer(Version::new(0, 2, 0))) - }, - function: rib::ParsedFunctionReference::Function { - function: "handle".to_string() - } - }, - rib::ParsedFunctionName { - site: rib::ParsedFunctionSite::PackagedInterface { - namespace: "wasi".to_string(), - package: "http".to_string(), - interface: "incoming-handler".to_string(), - version: Some(rib::SemVer(Version::new(0, 2, 1))) - }, - function: rib::ParsedFunctionReference::Function { - function: "handle".to_string() - } - }, - rib::ParsedFunctionName { - site: rib::ParsedFunctionSite::PackagedInterface { - namespace: "wasi".to_string(), - package: "http".to_string(), - interface: "incoming-handler".to_string(), - version: Some(rib::SemVer(Version::new(0, 2, 2))) - }, - function: rib::ParsedFunctionReference::Function { - function: "handle".to_string() - } - }, - rib::ParsedFunctionName { - site: rib::ParsedFunctionSite::PackagedInterface { - namespace: "wasi".to_string(), - package: "http".to_string(), - interface: "incoming-handler".to_string(), - version: Some(rib::SemVer(Version::new(0, 2, 3))) - }, - function: rib::ParsedFunctionReference::Function { - function: "handle".to_string() - } - } - ]; - pub static ref PARSED_FUNCTION_NAME: rib::ParsedFunctionName = rib::ParsedFunctionName { +pub static PARSED_FUNCTION_NAME: LazyLock = + LazyLock::new(|| rib::ParsedFunctionName { site: rib::ParsedFunctionSite::PackagedInterface { namespace: "golem".to_string(), package: "http".to_string(), interface: "incoming-handler".to_string(), - version: None + version: None, }, function: rib::ParsedFunctionReference::Function { - function: "handle".to_string() - } - }; - pub static ref ANALYZED_FUNCTION_PARAMETERS: Vec = { - use golem_wasm_ast::analysis::*; + function: "handle".to_string(), + }, + }); + +pub static ANALYZED_FUNCTION_PARAMETERS: LazyLock< + Vec, +> = { + use golem_wasm_ast::analysis::*; + LazyLock::new(|| { vec![AnalysedFunctionParameter { name: "request".to_string(), typ: IncomingHttpRequest::analysed_type(), }] - }; - pub static ref ANALYZED_FUNCTION_RESULTS: Vec = { - use golem_wasm_ast::analysis::*; + }) +}; + +pub static ANALYZED_FUNCTION_RESULTS: LazyLock< + Vec, +> = { + use golem_wasm_ast::analysis::*; + LazyLock::new(|| { vec![AnalysedFunctionResult { name: None, typ: HttpResponse::analysed_type(), }] - }; - pub static ref ANALYZED_FUNCTION: AnalysedFunction = { - use golem_wasm_ast::analysis::*; + }) +}; - AnalysedFunction { - name: "handle".to_string(), - parameters: ANALYZED_FUNCTION_PARAMETERS.clone(), - results: ANALYZED_FUNCTION_RESULTS.clone(), - } - }; - pub static ref ANALYZED_EXPORT: AnalysedExport = AnalysedExport::Instance(AnalysedInstance { +pub static ANALYZED_FUNCTION: LazyLock = { + use golem_wasm_ast::analysis::*; + + LazyLock::new(|| AnalysedFunction { + name: "handle".to_string(), + parameters: ANALYZED_FUNCTION_PARAMETERS.clone(), + results: ANALYZED_FUNCTION_RESULTS.clone(), + }) +}; + +pub const FUNCTION_NAME: &str = "golem:http/incoming-handler.{handle}"; + +pub static ANALYZED_EXPORT: LazyLock = LazyLock::new(|| { + AnalysedExport::Instance(AnalysedInstance { name: "golem:http/incoming-handler".to_string(), - functions: vec![ANALYZED_FUNCTION.clone()] - }); -} + functions: vec![ANALYZED_FUNCTION.clone()], + }) +}); pub fn implements_required_interfaces(exports: &[AnalysedExport]) -> bool { let compatible_interfaces = [ @@ -157,6 +147,85 @@ macro_rules! extract { }; } +pub enum HttpScheme { + HTTP, + HTTPS, + Custom(String), +} + +impl HttpScheme { + pub fn analyzed_type() -> AnalysedType { + use golem_wasm_ast::analysis::*; + AnalysedType::Variant(TypeVariant { + cases: vec![ + NameOptionTypePair { + name: "HTTP".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "HTTPS".to_string(), + typ: None, + }, + NameOptionTypePair { + name: "custom".to_string(), + typ: Some(AnalysedType::Str(TypeStr)), + }, + ], + }) + } + + pub fn from_value(value: &Value) -> Result { + let (case_idx, case_value) = extract!( + value, + Value::Variant { + case_idx, + case_value + }, + (case_idx, case_value), + "not a variant" + )?; + + match case_idx { + 0 => Ok(Self::HTTP), + 1 => Ok(Self::HTTPS), + 2 => { + let value = case_value.as_ref().ok_or("no case_value provided")?; + let custom_method = + extract!(*value.clone(), Value::String(inner), inner, "not a string")?; + Ok(Self::Custom(custom_method)) + } + _ => Err("unknown case")?, + } + } + + pub fn to_value(self) -> Value { + match self { + Self::HTTP => Value::Variant { + case_idx: 0, + case_value: None, + }, + Self::HTTPS => Value::Variant { + case_idx: 1, + case_value: None, + }, + Self::Custom(custom_method) => Value::Variant { + case_idx: 2, + case_value: Some(Box::new(Value::String(custom_method))), + }, + } + } +} + +impl From for HttpScheme { + fn from(value: http::uri::Scheme) -> Self { + match value { + well_known if well_known == http::uri::Scheme::HTTP => Self::HTTP, + well_known if well_known == http::uri::Scheme::HTTPS => Self::HTTPS, + other => Self::Custom(other.to_string()), + } + } +} + pub enum HttpMethod { GET, HEAD, @@ -212,7 +281,7 @@ impl HttpMethod { typ: None, }, NameOptionTypePair { - name: "Custom".to_string(), + name: "custom".to_string(), typ: Some(AnalysedType::Str(TypeStr)), }, ], @@ -231,24 +300,86 @@ impl HttpMethod { )?; match case_idx { - 0 => Ok(HttpMethod::GET), - 1 => Ok(HttpMethod::HEAD), - 2 => Ok(HttpMethod::POST), - 3 => Ok(HttpMethod::PUT), - 4 => Ok(HttpMethod::DELETE), - 5 => Ok(HttpMethod::CONNECT), - 6 => Ok(HttpMethod::OPTIONS), - 7 => Ok(HttpMethod::TRACE), - 8 => Ok(HttpMethod::PATCH), + 0 => Ok(Self::GET), + 1 => Ok(Self::HEAD), + 2 => Ok(Self::POST), + 3 => Ok(Self::PUT), + 4 => Ok(Self::DELETE), + 5 => Ok(Self::CONNECT), + 6 => Ok(Self::OPTIONS), + 7 => Ok(Self::TRACE), + 8 => Ok(Self::PATCH), 9 => { let value = case_value.as_ref().ok_or("no case_value provided")?; let custom_method = extract!(*value.clone(), Value::String(inner), inner, "not a string")?; - Ok(HttpMethod::Custom(custom_method)) + Ok(Self::Custom(custom_method)) } _ => Err("unknown case")?, } } + + pub fn to_value(self) -> Value { + match self { + Self::GET => Value::Variant { + case_idx: 0, + case_value: None, + }, + Self::HEAD => Value::Variant { + case_idx: 1, + case_value: None, + }, + Self::POST => Value::Variant { + case_idx: 2, + case_value: None, + }, + Self::PUT => Value::Variant { + case_idx: 3, + case_value: None, + }, + Self::DELETE => Value::Variant { + case_idx: 4, + case_value: None, + }, + Self::CONNECT => Value::Variant { + case_idx: 5, + case_value: None, + }, + Self::OPTIONS => Value::Variant { + case_idx: 6, + case_value: None, + }, + Self::TRACE => Value::Variant { + case_idx: 7, + case_value: None, + }, + Self::PATCH => Value::Variant { + case_idx: 8, + case_value: None, + }, + Self::Custom(custom_method) => Value::Variant { + case_idx: 9, + case_value: Some(Box::new(Value::String(custom_method))), + }, + } + } + + pub fn from_http_method(value: http::Method) -> Self { + use http::Method as M; + + match value { + M::GET => Self::GET, + M::CONNECT => Self::CONNECT, + M::DELETE => Self::DELETE, + M::HEAD => Self::HEAD, + M::OPTIONS => Self::OPTIONS, + M::PATCH => Self::PATCH, + M::POST => Self::POST, + M::PUT => Self::PUT, + M::TRACE => Self::TRACE, + other => Self::Custom(other.to_string()), + } + } } impl TryInto for HttpMethod { @@ -413,8 +544,10 @@ impl HttpBodyAndTrailers { } pub struct IncomingHttpRequest { - pub uri: String, pub method: HttpMethod, + pub scheme: HttpScheme, + pub authority: String, + pub path_with_query: String, pub headers: HttpFields, pub body: Option, } @@ -426,12 +559,20 @@ impl IncomingHttpRequest { AnalysedType::Record(TypeRecord { fields: vec![ NameTypePair { - name: "uri".to_string(), + name: "method".to_string(), + typ: HttpMethod::analyzed_type(), + }, + NameTypePair { + name: "scheme".to_string(), + typ: HttpScheme::analyzed_type(), + }, + NameTypePair { + name: "authority".to_string(), typ: AnalysedType::Str(TypeStr), }, NameTypePair { - name: "method".to_string(), - typ: HttpMethod::analyzed_type(), + name: "path-with-query".to_string(), + typ: AnalysedType::Str(TypeStr), }, NameTypePair { name: "headers".to_string(), @@ -458,20 +599,27 @@ impl IncomingHttpRequest { fn from_value(value: &Value) -> Result { let record_values = extract!(value, Value::Record(inner), inner, "not a record")?; - if record_values.len() != 4 { + if record_values.len() != 6 { Err("wrong length of record data")?; }; - let uri = extract!( - record_values[0].clone(), + let method = HttpMethod::from_value(&record_values[0])?; + let scheme = HttpScheme::from_value(&record_values[1])?; + let authority = extract!( + record_values[2].clone(), + Value::String(inner), + inner, + "not a string" + )?; + let path_with_query = extract!( + record_values[3].clone(), Value::String(inner), inner, "not a string" )?; - let method = HttpMethod::from_value(&record_values[1])?; - let headers = HttpFields::from_value(&record_values[2])?; + let headers = HttpFields::from_value(&record_values[4])?; let body = extract!( - &record_values[3], + &record_values[5], Value::Option(inner), match inner { Some(v) => Some(HttpBodyAndTrailers::from_value(v)?), @@ -481,12 +629,25 @@ impl IncomingHttpRequest { )?; Ok(IncomingHttpRequest { - uri, method, + scheme, + authority, + path_with_query, headers, body, }) } + + pub fn to_value(self) -> Value { + Value::Record(vec![ + self.method.to_value(), + self.scheme.to_value(), + Value::String(self.authority), + Value::String(self.path_with_query), + self.headers.to_value(), + Value::Option(self.body.map(|b| Box::new(b.to_value()))), + ]) + } } pub struct HttpResponse { @@ -519,6 +680,53 @@ impl HttpResponse { }) } + pub fn from_value(value: Value) -> Result { + let record_values = extract!(value, Value::Record(inner), inner, "not a record")?; + + if record_values.len() != 3 { + Err("wrong length of record data")?; + }; + + let status = extract!( + record_values[0].clone(), + Value::U16(inner), + inner, + "not a u16" + )?; + + let headers = HttpFields::from_value(&record_values[1])?; + + let body = extract!( + &record_values[2], + Value::Option(inner), + inner.as_ref(), + "not an option" + )?; + let body = if let Some(b) = body { + Some(HttpBodyAndTrailers::from_value(b)?) + } else { + None + }; + + Ok(HttpResponse { + status, + headers, + body, + }) + } + + pub fn from_function_output(output: TypeAnnotatedValue) -> Result { + let value: Value = output.try_into()?; + + let mut tuple_values = extract!(value, Value::Tuple(inner), inner, "not a tuple")?; + + if tuple_values.len() != 1 { + Err("unexpected number of outputs")? + }; + + Self::from_value(tuple_values.remove(0)) + } + pub fn to_value(self) -> Value { let converted_status: Value = Value::U16(self.status); let converted_headers: Value = self.headers.to_value(); diff --git a/golem-worker-executor-base/Cargo.toml b/golem-worker-executor-base/Cargo.toml index 6ebf23362c..73b71188ad 100644 --- a/golem-worker-executor-base/Cargo.toml +++ b/golem-worker-executor-base/Cargo.toml @@ -52,8 +52,8 @@ futures-util = { workspace = true } gethostname = "0.5.0" hex = { workspace = true } http = { workspace = true } -http-body = "1.0.1" # keep in sync with wasmtime -http-body-util = "0.1.0" # keep in sync with wasmtime +http-body = { workspace = true } +http-body-util = { workspace = true } humansize = { workspace = true } humantime-serde = { workspace = true } hyper = { workspace = true } diff --git a/golem-worker-executor-base/src/invocation.rs b/golem-worker-executor-base/src/invocation.rs index d411765e51..f5fcbc54e8 100644 --- a/golem-worker-executor-base/src/invocation.rs +++ b/golem-worker-executor-base/src/invocation.rs @@ -454,9 +454,8 @@ async fn invoke_http_handler( tracing::debug!("Invoking wasi:http/incoming-http-handler handle"); let (_, mut task_exits) = { - let hyper_request = + let (scheme, hyper_request) = virtual_export_compat::http_incoming_handler::input_to_hyper_request(function_input)?; - let scheme = wasi_http_scheme_from_request(&hyper_request)?; let incoming = store_context .data_mut() .as_wasi_http_view() @@ -747,20 +746,3 @@ enum FindFunctionResult { ResourceDrop, IncomingHttpHandlerBridge, } - -fn wasi_http_scheme_from_request( - req: &hyper::Request, -) -> Result { - use http::uri::*; - use wasmtime_wasi_http::bindings::http::types::Scheme as WasiScheme; - - let raw_scheme = req.uri().scheme().ok_or(GolemError::invalid_request( - "Could not extract scheme from uri".to_string(), - ))?; - - match raw_scheme { - scheme if *scheme == Scheme::HTTP => Ok(WasiScheme::Http), - scheme if *scheme == Scheme::HTTPS => Ok(WasiScheme::Https), - scheme => Ok(WasiScheme::Other(scheme.to_string())), - } -} diff --git a/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs b/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs index 197f3f31d4..11a48afb48 100644 --- a/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs +++ b/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs @@ -23,16 +23,42 @@ use http_body_util::combinators::BoxBody; use http_body_util::BodyExt; use wasmtime_wasi_http::bindings::http::types::ErrorCode; -pub fn input_to_hyper_request( - inputs: &[Value], -) -> Result>, GolemError> { +pub type SchemeAndRequest = ( + wasmtime_wasi_http::bindings::wasi::http::types::Scheme, + hyper::Request>, +); + +pub fn input_to_hyper_request(inputs: &[Value]) -> Result { let request = IncomingHttpRequest::from_function_input(inputs).map_err(|e| { GolemError::invalid_request(format!("Failed contructing incoming request: {e}")) })?; - let mut builder = hyper::Request::builder() - .uri(request.uri) - .method(request.method); + let wasmtime_scheme = match request.scheme { + HttpScheme::HTTP => wasmtime_wasi_http::bindings::wasi::http::types::Scheme::Http, + HttpScheme::HTTPS => wasmtime_wasi_http::bindings::wasi::http::types::Scheme::Https, + HttpScheme::Custom(ref custom) => { + wasmtime_wasi_http::bindings::wasi::http::types::Scheme::Other(custom.clone()) + } + }; + + let converted_scheme = match request.scheme { + HttpScheme::HTTP => http::uri::Scheme::HTTP, + HttpScheme::HTTPS => http::uri::Scheme::HTTPS, + HttpScheme::Custom(custom) => custom.as_str().try_into().map_err(|e| { + GolemError::invalid_request(format!("Not a valid scheme: {custom} ({e})")) + })?, + }; + + let uri = http::Uri::builder() + .scheme(converted_scheme) + .authority(request.authority) + .path_and_query(request.path_with_query) + .build() + .map_err(|e| { + GolemError::invalid_request(format!("Failed to construct a valid url: {e}")) + })?; + + let mut builder = hyper::Request::builder().uri(uri).method(request.method); for (name, value) in request.headers.0 { let converted = http::HeaderValue::from_bytes(&value) @@ -69,9 +95,11 @@ pub fn input_to_hyper_request( BoxBody::new(http_body_util::Empty::new().map_err(hyper_error_from_infallible)) }; - builder + let hyper_request = builder .body(body) - .map_err(|e| GolemError::invalid_request(format!("Failed to attach body {e}"))) + .map_err(|e| GolemError::invalid_request(format!("Failed to attach body {e}")))?; + + Ok((wasmtime_scheme, hyper_request)) } pub async fn http_response_to_output( diff --git a/golem-worker-executor-base/tests/wasi.rs b/golem-worker-executor-base/tests/wasi.rs index 976e169dfb..edf113df1e 100644 --- a/golem-worker-executor-base/tests/wasi.rs +++ b/golem-worker-executor-base/tests/wasi.rs @@ -1868,11 +1868,16 @@ async fn wasi_incoming_request_handler( .await; let args: Value = Value::Record(vec![ - Value::String("http://localhost:8000".to_string()), Value::Variant { case_idx: 0, case_value: None, }, + Value::Variant { + case_idx: 0, + case_value: None, + }, + Value::String("localhost:8000".to_string()), + Value::String("/".to_string()), Value::List(vec![]), Value::Option(None), ]); @@ -1918,11 +1923,16 @@ async fn wasi_incoming_request_handler_echo( .await; let args: Value = Value::Record(vec![ - Value::String("http://localhost:8000/foo?bar=baz".to_string()), Value::Variant { case_idx: 2, case_value: None, }, + Value::Variant { + case_idx: 0, + case_value: None, + }, + Value::String("localhost:8000".to_string()), + Value::String("/foo?bar=baz".to_string()), Value::List(vec![Value::Tuple(vec![ Value::String("test-header".to_string()), Value::List( @@ -2052,11 +2062,16 @@ async fn wasi_incoming_request_handler_state( .await; let args_put: Value = Value::Record(vec![ - Value::String("http://localhost:8000".to_string()), Value::Variant { case_idx: 3, case_value: None, }, + Value::Variant { + case_idx: 0, + case_value: None, + }, + Value::String("localhost:8000".to_string()), + Value::String("/".to_string()), Value::List(vec![]), Value::Option(Some(Box::new(Value::Record(vec![ Value::List( @@ -2071,11 +2086,16 @@ async fn wasi_incoming_request_handler_state( ]); let args_get: Value = Value::Record(vec![ - Value::String("http://localhost:8000".to_string()), Value::Variant { case_idx: 0, case_value: None, }, + Value::Variant { + case_idx: 0, + case_value: None, + }, + Value::String("localhost:8000".to_string()), + Value::String("/".to_string()), Value::List(vec![]), Value::Option(None), ]); diff --git a/golem-worker-service-base/Cargo.toml b/golem-worker-service-base/Cargo.toml index 6870ec33b1..2ac17095ff 100644 --- a/golem-worker-service-base/Cargo.toml +++ b/golem-worker-service-base/Cargo.toml @@ -39,6 +39,7 @@ figment = { workspace = true } futures = { workspace = true } futures-util = { workspace = true } http = { workspace = true } +http-body-util = { workspace = true } humantime-serde = { workspace = true } hyper = { workspace = true } lazy_static = { workspace = true } diff --git a/golem-worker-service-base/src/api/custom_http_request_api.rs b/golem-worker-service-base/src/api/custom_http_request_api.rs index 365f05130f..d444182ed2 100644 --- a/golem-worker-service-base/src/api/custom_http_request_api.rs +++ b/golem-worker-service-base/src/api/custom_http_request_api.rs @@ -23,6 +23,7 @@ use crate::gateway_execution::gateway_http_input_executor::{ DefaultGatewayInputExecutor, GatewayHttpInputExecutor, }; use crate::gateway_execution::gateway_session::GatewaySession; +use crate::gateway_execution::http_handler_binding_handler::HttpHandlerBindingHandler; use crate::gateway_execution::GatewayWorkerRequestExecutor; use crate::gateway_request::http_request::InputHttpRequest; use crate::gateway_rib_interpreter::DefaultRibInterpreter; @@ -47,6 +48,7 @@ impl CustomHttpRequestApi { + Send, >, file_server_binding_handler: Arc + Sync + Send>, + http_handler_binding_handler: Arc + Sync + Send>, gateway_session_store: Arc, ) -> Self { let evaluator = Arc::new(DefaultRibInterpreter::from_worker_request_executor( @@ -59,6 +61,7 @@ impl CustomHttpRequestApi { evaluator, file_server_binding_handler, auth_call_back_binding_handler, + http_handler_binding_handler, api_definition_lookup_service, gateway_session_store, identity_provider: Arc::new(DefaultIdentityProvider), diff --git a/golem-worker-service-base/src/api/register_api_definition_api.rs b/golem-worker-service-base/src/api/register_api_definition_api.rs index 0e8038bb7b..b2ace03476 100644 --- a/golem-worker-service-base/src/api/register_api_definition_api.rs +++ b/golem-worker-service-base/src/api/register_api_definition_api.rs @@ -18,7 +18,8 @@ use crate::gateway_api_definition::http::{ use crate::gateway_api_definition::{ApiDefinitionId, ApiVersion}; use crate::gateway_api_deployment::ApiSite; use crate::gateway_binding::{ - GatewayBinding, GatewayBindingCompiled, StaticBinding, WorkerBinding, WorkerBindingCompiled, + GatewayBinding, GatewayBindingCompiled, HttpHandlerBinding, HttpHandlerBindingCompiled, + StaticBinding, WorkerBinding, WorkerBindingCompiled, }; use crate::gateway_middleware::{CorsPreflightExpr, HttpCors, HttpMiddleware, HttpMiddlewares}; use crate::gateway_security::{ @@ -373,6 +374,36 @@ impl GatewayBindingData { allow_credentials: None, }) } + + pub fn from_http_handler_binding( + http_handler_binding: HttpHandlerBinding, + binding_type: GatewayBindingType, + ) -> Result { + let worker_id = http_handler_binding + .worker_name + .map(|expr| rib::to_string(&expr).map_err(|e| e.to_string())) + .transpose()?; + + let idempotency_key = if let Some(key) = &http_handler_binding.idempotency_key { + Some(rib::to_string(key).map_err(|e| e.to_string())?) + } else { + None + }; + + Ok(Self { + binding_type: Some(binding_type), + component_id: Some(http_handler_binding.component_id), + worker_name: worker_id, + idempotency_key, + response: None, + allow_origin: None, + allow_methods: None, + allow_headers: None, + expose_headers: None, + max_age: None, + allow_credentials: None, + }) + } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Object)] @@ -493,6 +524,33 @@ impl GatewayBindingResponseData { response_mapping_output: worker_binding.response_compiled.rib_output, } } + + pub fn from_http_handler_binding_compiled( + http_handler_binding: HttpHandlerBindingCompiled, + binding_type: GatewayBindingType, + ) -> Self { + GatewayBindingResponseData { + component_id: Some(http_handler_binding.component_id), + worker_name: http_handler_binding + .worker_name_compiled + .clone() + .map(|compiled| compiled.worker_name.to_string()), + idempotency_key: http_handler_binding.idempotency_key_compiled.clone().map( + |idempotency_key_compiled| idempotency_key_compiled.idempotency_key.to_string(), + ), + response: None, + binding_type: Some(binding_type), + response_mapping_input: None, + worker_name_input: http_handler_binding + .worker_name_compiled + .map(|compiled| compiled.rib_input_type_info), + idempotency_key_input: http_handler_binding + .idempotency_key_compiled + .map(|idempotency_key_compiled| idempotency_key_compiled.rib_input), + cors_preflight: None, + response_mapping_output: None, + } + } } impl TryFrom for GatewayBindingResponseData { @@ -514,6 +572,12 @@ impl TryFrom for GatewayBindingResponseData { GatewayBindingType::Default, )) } + GatewayBindingCompiled::HttpHandler(http_handler_binding) => Ok( + GatewayBindingResponseData::from_http_handler_binding_compiled( + http_handler_binding, + GatewayBindingType::HttpHandler, + ), + ), GatewayBindingCompiled::Static(static_binding) => { let binding_type = match static_binding.deref() { StaticBinding::HttpCorsPreflight(_) => GatewayBindingType::CorsPreflight, @@ -631,6 +695,13 @@ impl TryFrom for GatewayBindingData { GatewayBindingType::FileServer, ), + GatewayBinding::HttpHandler(http_handler_binding) => { + GatewayBindingData::from_http_handler_binding( + http_handler_binding, + GatewayBindingType::HttpHandler, + ) + } + GatewayBinding::Static(static_binding) => match static_binding.deref() { StaticBinding::HttpCorsPreflight(cors) => Ok(GatewayBindingData { binding_type: Some(GatewayBindingType::CorsPreflight), @@ -699,6 +770,31 @@ impl TryFrom for GatewayBinding { } } + Some(GatewayBindingType::HttpHandler) => { + let component_id = gateway_binding_data + .component_id + .ok_or("Missing componentId field in binding")?; + + let worker_name = gateway_binding_data + .worker_name + .map(|name| rib::from_string(name.as_str()).map_err(|e| e.to_string())) + .transpose()?; + + let idempotency_key = if let Some(key) = &gateway_binding_data.idempotency_key { + Some(rib::from_string(key).map_err(|e| e.to_string())?) + } else { + None + }; + + let binding = HttpHandlerBinding { + component_id, + worker_name, + idempotency_key, + }; + + Ok(GatewayBinding::HttpHandler(binding)) + } + Some(GatewayBindingType::CorsPreflight) => { let response_mapping = gateway_binding_data.response; diff --git a/golem-worker-service-base/src/gateway_api_definition/http/http_api_definition.rs b/golem-worker-service-base/src/gateway_api_definition/http/http_api_definition.rs index bce8fb41d1..be563f1f83 100644 --- a/golem-worker-service-base/src/gateway_api_definition/http/http_api_definition.rs +++ b/golem-worker-service-base/src/gateway_api_definition/http/http_api_definition.rs @@ -16,8 +16,8 @@ use crate::gateway_api_definition::http::path_pattern_parser::parse_path_pattern use crate::gateway_api_definition::http::{HttpApiDefinitionRequest, RouteRequest}; use crate::gateway_api_definition::{ApiDefinitionId, ApiVersion, HasGolemBindings}; use crate::gateway_api_definition_transformer::transform_http_api_definition; -use crate::gateway_binding::WorkerBindingCompiled; use crate::gateway_binding::{GatewayBinding, GatewayBindingCompiled}; +use crate::gateway_binding::{HttpHandlerBindingCompiled, WorkerBindingCompiled}; use crate::gateway_middleware::{ HttpAuthenticationMiddleware, HttpCors, HttpMiddleware, HttpMiddlewares, }; @@ -624,6 +624,28 @@ impl CompiledRoute { }) } + GatewayBinding::HttpHandler(http_handler_binding) => { + let metadata = metadata_dictionary + .metadata + .get(&http_handler_binding.component_id) + .ok_or(RouteCompilationErrors::MetadataNotFoundError( + http_handler_binding.component_id.clone(), + ))?; + + let binding = HttpHandlerBindingCompiled::from_raw_http_handler_binding( + http_handler_binding, + metadata, + ) + .map_err(RouteCompilationErrors::RibCompilationError)?; + + Ok(CompiledRoute { + method: route.method.clone(), + path: route.path.clone(), + binding: GatewayBindingCompiled::HttpHandler(binding), + middlewares: route.middlewares.clone(), + }) + } + GatewayBinding::Static(static_binding) => Ok(CompiledRoute { method: route.method.clone(), path: route.path.clone(), diff --git a/golem-worker-service-base/src/gateway_api_definition/http/http_oas_api_definition.rs b/golem-worker-service-base/src/gateway_api_definition/http/http_oas_api_definition.rs index 8dc3e2c8dc..379a7f1db0 100644 --- a/golem-worker-service-base/src/gateway_api_definition/http/http_oas_api_definition.rs +++ b/golem-worker-service-base/src/gateway_api_definition/http/http_oas_api_definition.rs @@ -123,7 +123,9 @@ mod internal { use rib::Expr; use serde_json::Value; - use crate::gateway_binding::{GatewayBinding, ResponseMapping, StaticBinding, WorkerBinding}; + use crate::gateway_binding::{ + GatewayBinding, HttpHandlerBinding, ResponseMapping, StaticBinding, WorkerBinding, + }; use crate::gateway_middleware::{CorsPreflightExpr, HttpCors}; use crate::gateway_security::{SecuritySchemeIdentifier, SecuritySchemeReference}; use golem_service_base::model::VersionedComponentId; @@ -256,7 +258,7 @@ mod internal { } (GatewayBindingType::Default, _) => { - let binding = get_gateway_binding(worker_gateway_info)?; + let binding = get_worker_binding(worker_gateway_info)?; Ok(RouteRequest { path: path_pattern.clone(), @@ -267,7 +269,7 @@ mod internal { }) } (GatewayBindingType::FileServer, _) => { - let binding = get_gateway_binding(worker_gateway_info)?; + let binding = get_worker_binding(worker_gateway_info)?; Ok(RouteRequest { path: path_pattern.clone(), @@ -277,6 +279,17 @@ mod internal { cors: None }) } + (GatewayBindingType::HttpHandler, _) => { + let binding = get_http_handler_binding(worker_gateway_info)?; + + Ok(RouteRequest { + path: path_pattern.clone(), + method, + binding: GatewayBinding::HttpHandler(binding), + security, + cors: None + }) + } (GatewayBindingType::CorsPreflight, method) => { Err(format!("cors-preflight binding type is supported only for 'options' method, but found method '{}'", method)) } @@ -304,7 +317,7 @@ mod internal { } } - pub(crate) fn get_gateway_binding( + pub(crate) fn get_worker_binding( gateway_binding_value: &Value, ) -> Result { let binding = WorkerBinding { @@ -317,6 +330,18 @@ mod internal { Ok(binding) } + pub(crate) fn get_http_handler_binding( + gateway_binding_value: &Value, + ) -> Result { + let binding = HttpHandlerBinding { + worker_name: get_worker_id_expr(gateway_binding_value)?, + component_id: get_component_id(gateway_binding_value)?, + idempotency_key: get_idempotency_key(gateway_binding_value)?, + }; + + Ok(binding) + } + pub(crate) fn get_cors_static_binding( worker_gateway_info: &Value, ) -> Result { diff --git a/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs b/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs index d84518cad9..b75e7174ec 100644 --- a/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs +++ b/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs @@ -22,6 +22,9 @@ use golem_common::model::GatewayBindingType; use rib::RibOutputTypeInfo; use std::ops::Deref; +use super::http_handler_binding::HttpHandlerBindingCompiled; +use super::HttpHandlerBinding; + // A compiled binding is a binding with all existence of Rib Expr // get replaced with their compiled form - RibByteCode. #[derive(Debug, Clone, PartialEq)] @@ -29,6 +32,7 @@ pub enum GatewayBindingCompiled { Worker(WorkerBindingCompiled), Static(Box), FileServer(WorkerBindingCompiled), + HttpHandler(HttpHandlerBindingCompiled), } impl GatewayBindingCompiled { @@ -36,6 +40,7 @@ impl GatewayBindingCompiled { match self { GatewayBindingCompiled::Worker(_) => false, GatewayBindingCompiled::FileServer(_) => false, + GatewayBindingCompiled::HttpHandler(_) => false, GatewayBindingCompiled::Static(static_binding) => match static_binding.deref() { StaticBinding::HttpCorsPreflight(_) => false, StaticBinding::HttpAuthCallBack(_) => true, @@ -64,6 +69,13 @@ impl From for GatewayBinding { GatewayBinding::FileServer(worker_binding) } + GatewayBindingCompiled::HttpHandler(value) => { + let http_handler_binding = value.clone(); + + let worker_binding = HttpHandlerBinding::from(http_handler_binding); + + GatewayBinding::HttpHandler(worker_binding) + } } } } @@ -75,19 +87,26 @@ impl TryFrom fn try_from(value: GatewayBindingCompiled) -> Result { match value { GatewayBindingCompiled::Worker(worker_binding) => { - Ok(internal::to_gateway_binding_compiled_proto( + Ok(internal::worker_binding_to_gateway_binding_compiled_proto( worker_binding, GatewayBindingType::Default, )?) } GatewayBindingCompiled::FileServer(worker_binding) => { - Ok(internal::to_gateway_binding_compiled_proto( + Ok(internal::worker_binding_to_gateway_binding_compiled_proto( worker_binding, GatewayBindingType::FileServer, )?) } + GatewayBindingCompiled::HttpHandler(http_handler_binding) => { + Ok(internal::http_handler_to_gateway_binding_compiled_proto( + http_handler_binding, + GatewayBindingType::HttpHandler, + )?) + } + GatewayBindingCompiled::Static(static_binding) => { let binding_type = match static_binding.deref() { StaticBinding::HttpCorsPreflight(_) => golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::CorsPreflight, @@ -218,6 +237,55 @@ impl TryFrom { + // Convert fields for the Worker variant + let component_id = value + .component + .ok_or("Missing component_id for Worker")? + .try_into()?; + + let worker_name_compiled = match ( + value.worker_name, + value.compiled_worker_name_expr, + value.worker_name_rib_input, + ) { + (Some(worker_name), Some(compiled_worker_name), Some(rib_input_type_info)) => { + Some(WorkerNameCompiled { + worker_name: rib::Expr::try_from(worker_name)?, + compiled_worker_name: rib::RibByteCode::try_from(compiled_worker_name)?, + rib_input_type_info: rib::RibInputTypeInfo::try_from( + rib_input_type_info, + )?, + }) + } + _ => None, + }; + + let idempotency_key_compiled = match ( + value.idempotency_key, + value.compiled_idempotency_key_expr, + value.idempotency_key_rib_input, + ) { + (Some(idempotency_key), Some(compiled_idempotency_key), Some(rib_input)) => { + Some(IdempotencyKeyCompiled { + idempotency_key: rib::Expr::try_from(idempotency_key)?, + compiled_idempotency_key: rib::RibByteCode::try_from( + compiled_idempotency_key, + )?, + rib_input: rib::RibInputTypeInfo::try_from(rib_input)?, + }) + } + _ => None, + }; + + Ok(GatewayBindingCompiled::HttpHandler( + HttpHandlerBindingCompiled { + component_id, + worker_name_compiled, + idempotency_key_compiled, + }, + )) + } ProtoGatewayBindingType::CorsPreflight | ProtoGatewayBindingType::AuthCallBack => { let static_binding = value .static_binding @@ -232,11 +300,11 @@ impl TryFrom Result { @@ -290,6 +358,7 @@ mod internal { GatewayBindingType::Default => 0, GatewayBindingType::FileServer => 1, GatewayBindingType::CorsPreflight => 2, + GatewayBindingType::HttpHandler => 4, }; Ok( @@ -311,4 +380,57 @@ mod internal { }, ) } + + pub(crate) fn http_handler_to_gateway_binding_compiled_proto( + http_handler_binding: HttpHandlerBindingCompiled, + binding_type: GatewayBindingType, + ) -> Result { + let component = Some(http_handler_binding.component_id.into()); + let worker_name = http_handler_binding + .worker_name_compiled + .clone() + .map(|w| w.worker_name.into()); + let compiled_worker_name_expr = http_handler_binding + .worker_name_compiled + .clone() + .map(|w| w.compiled_worker_name.try_into()) + .transpose()?; + let worker_name_rib_input = http_handler_binding + .worker_name_compiled + .map(|w| w.rib_input_type_info.into()); + let (idempotency_key, compiled_idempotency_key_expr, idempotency_key_rib_input) = + match http_handler_binding.idempotency_key_compiled { + Some(x) => ( + Some(x.idempotency_key.into()), + Some(x.compiled_idempotency_key.try_into()?), + Some(x.rib_input.into()), + ), + None => (None, None, None), + }; + let binding_type = match binding_type { + GatewayBindingType::Default => 0, + GatewayBindingType::FileServer => 1, + GatewayBindingType::CorsPreflight => 2, + GatewayBindingType::HttpHandler => 4, + }; + + Ok( + golem_api_grpc::proto::golem::apidefinition::CompiledGatewayBinding { + component, + worker_name, + compiled_worker_name_expr, + worker_name_rib_input, + idempotency_key, + compiled_idempotency_key_expr, + idempotency_key_rib_input, + response: None, + compiled_response_expr: None, + response_rib_input: None, + worker_functions_in_response: None, + binding_type: Some(binding_type), + static_binding: None, + response_rib_output: None, + }, + ) + } } diff --git a/golem-worker-service-base/src/gateway_binding/http_handler_binding.rs b/golem-worker-service-base/src/gateway_binding/http_handler_binding.rs new file mode 100644 index 0000000000..c280e4df54 --- /dev/null +++ b/golem-worker-service-base/src/gateway_binding/http_handler_binding.rs @@ -0,0 +1,77 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::{IdempotencyKeyCompiled, WorkerNameCompiled}; +use golem_service_base::model::VersionedComponentId; +use golem_wasm_ast::analysis::AnalysedExport; +use rib::Expr; + +#[derive(Debug, Clone, PartialEq)] +pub struct HttpHandlerBinding { + pub component_id: VersionedComponentId, + pub worker_name: Option, + pub idempotency_key: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct HttpHandlerBindingCompiled { + pub component_id: VersionedComponentId, + pub worker_name_compiled: Option, + pub idempotency_key_compiled: Option, +} + +impl HttpHandlerBindingCompiled { + pub fn from_raw_http_handler_binding( + http_handler_binding: &HttpHandlerBinding, + export_metadata: &[AnalysedExport], + ) -> Result { + let worker_name_compiled: Option = http_handler_binding + .worker_name + .clone() + .map(|worker_name_expr| { + WorkerNameCompiled::from_worker_name(&worker_name_expr, export_metadata) + }) + .transpose()?; + + let idempotency_key_compiled = match &http_handler_binding.idempotency_key { + Some(idempotency_key) => Some(IdempotencyKeyCompiled::from_idempotency_key( + idempotency_key, + export_metadata, + )?), + None => None, + }; + + Ok(HttpHandlerBindingCompiled { + component_id: http_handler_binding.component_id.clone(), + worker_name_compiled, + idempotency_key_compiled, + }) + } +} + +impl From for HttpHandlerBinding { + fn from(value: HttpHandlerBindingCompiled) -> Self { + let worker_binding = value.clone(); + + HttpHandlerBinding { + component_id: worker_binding.component_id, + worker_name: worker_binding + .worker_name_compiled + .map(|compiled| compiled.worker_name), + idempotency_key: worker_binding + .idempotency_key_compiled + .map(|compiled| compiled.idempotency_key), + } + } +} diff --git a/golem-worker-service-base/src/gateway_binding/mod.rs b/golem-worker-service-base/src/gateway_binding/mod.rs index 9fea9b52d9..9c7d917045 100644 --- a/golem-worker-service-base/src/gateway_binding/mod.rs +++ b/golem-worker-service-base/src/gateway_binding/mod.rs @@ -12,22 +12,26 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub(crate) use self::http_handler_binding::*; +pub(crate) use self::worker_binding::*; pub(crate) use crate::gateway_execution::gateway_binding_resolver::*; pub(crate) use crate::gateway_execution::rib_input_value_resolver::*; pub(crate) use crate::gateway_request::request_details::*; +use crate::gateway_rib_compiler::DefaultWorkerServiceRibCompiler; +use crate::gateway_rib_compiler::WorkerServiceRibCompiler; pub(crate) use gateway_binding_compiled::*; use golem_api_grpc::proto::golem::apidefinition::GatewayBindingType; use golem_service_base::model::VersionedComponentId; -use rib::Expr; +use golem_wasm_ast::analysis::AnalysedExport; +use rib::{Expr, RibByteCode, RibInputTypeInfo}; pub use static_binding::*; use std::ops::Deref; -pub(crate) use worker_binding::*; -pub(crate) use worker_binding_compiled::*; mod gateway_binding_compiled; +mod http_handler_binding; mod static_binding; mod worker_binding; -mod worker_binding_compiled; + // A gateway binding is integration to the backend. This is similar to AWS's x-amazon-gateway-integration // where it holds the details of where to re-route. @@ -39,6 +43,7 @@ pub enum GatewayBinding { Default(WorkerBinding), FileServer(WorkerBinding), Static(Box), + HttpHandler(HttpHandlerBinding), } impl GatewayBinding { @@ -46,6 +51,7 @@ impl GatewayBinding { match self { Self::Default(_) => false, Self::FileServer(_) => false, + Self::HttpHandler(_) => false, Self::Static(s) => match s.deref() { StaticBinding::HttpCorsPreflight(_) => true, StaticBinding::HttpAuthCallBack(_) => false, @@ -57,6 +63,7 @@ impl GatewayBinding { match self { Self::Default(_) => false, Self::FileServer(_) => false, + Self::HttpHandler(_) => false, Self::Static(s) => match s.deref() { StaticBinding::HttpCorsPreflight(_) => false, StaticBinding::HttpAuthCallBack(_) => true, @@ -68,18 +75,13 @@ impl GatewayBinding { GatewayBinding::Static(Box::new(value)) } - pub fn get_worker_binding(&self) -> Option { - match self { - Self::Default(worker_binding) => Some(worker_binding.clone()), - Self::FileServer(worker_binding) => Some(worker_binding.clone()), - Self::Static(_) => None, - } - } - - pub fn get_worker_binding_mut(&mut self) -> Option<&mut WorkerBinding> { + pub fn get_component_id(&self) -> Option { match self { - Self::Default(worker_binding) => Some(worker_binding), - Self::FileServer(worker_binding) => Some(worker_binding), + Self::Default(worker_binding) => Some(worker_binding.component_id.clone()), + Self::FileServer(worker_binding) => Some(worker_binding.component_id.clone()), + Self::HttpHandler(http_handler_binding) => { + Some(http_handler_binding.component_id.clone()) + } Self::Static(_) => None, } } @@ -91,7 +93,7 @@ impl TryFrom for golem_api_grpc::proto::golem::apidefinition::Ga match value { GatewayBinding::Default(worker_binding) => Ok( golem_api_grpc::proto::golem::apidefinition::GatewayBinding { - binding_type: Some(0), + binding_type: Some(GatewayBindingType::Default.into()), component: Some(worker_binding.component_id.into()), worker_name: worker_binding.worker_name.map(|x| x.into()), response: Some(worker_binding.response_mapping.0.into()), @@ -101,7 +103,7 @@ impl TryFrom for golem_api_grpc::proto::golem::apidefinition::Ga ), GatewayBinding::FileServer(worker_binding) => Ok( golem_api_grpc::proto::golem::apidefinition::GatewayBinding { - binding_type: Some(1), + binding_type: Some(GatewayBindingType::FileServer.into()), component: Some(worker_binding.component_id.into()), worker_name: worker_binding.worker_name.map(|x| x.into()), response: Some(worker_binding.response_mapping.0.into()), @@ -127,7 +129,7 @@ impl TryFrom for golem_api_grpc::proto::golem::apidefinition::Ga Ok( golem_api_grpc::proto::golem::apidefinition::GatewayBinding { - binding_type: Some(gateway_binding_type as i32), + binding_type: Some(gateway_binding_type.into()), component: None, worker_name: None, response: None, @@ -136,6 +138,16 @@ impl TryFrom for golem_api_grpc::proto::golem::apidefinition::Ga }, ) } + GatewayBinding::HttpHandler(worker_binding) => Ok( + golem_api_grpc::proto::golem::apidefinition::GatewayBinding { + binding_type: Some(GatewayBindingType::HttpHandler.into()), + component: Some(worker_binding.component_id.into()), + worker_name: worker_binding.worker_name.map(|x| x.into()), + response: None, + idempotency_key: worker_binding.idempotency_key.map(|x| x.into()), + static_binding: None, + }, + ), } } } @@ -185,6 +197,19 @@ impl TryFrom for Ga response_mapping: ResponseMapping(response), })) } + golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::HttpHandler => { + let component_id = VersionedComponentId::try_from( + value.component.ok_or("Missing component id".to_string())?, + )?; + let worker_name = value.worker_name.map(Expr::try_from).transpose()?; + let idempotency_key = value.idempotency_key.map(Expr::try_from).transpose()?; + + Ok(GatewayBinding::HttpHandler(HttpHandlerBinding { + component_id, + worker_name, + idempotency_key, + })) + } golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::CorsPreflight => { let static_binding = value.static_binding.ok_or("Missing static binding")?; @@ -203,3 +228,48 @@ impl TryFrom for Ga } } } + +#[derive(Debug, Clone, PartialEq)] +pub struct WorkerNameCompiled { + pub worker_name: Expr, + pub compiled_worker_name: RibByteCode, + pub rib_input_type_info: RibInputTypeInfo, +} + +impl WorkerNameCompiled { + pub fn from_worker_name( + worker_name: &Expr, + exports: &[AnalysedExport], + ) -> Result { + let compiled_worker_name = DefaultWorkerServiceRibCompiler::compile(worker_name, exports)?; + + Ok(WorkerNameCompiled { + worker_name: worker_name.clone(), + compiled_worker_name: compiled_worker_name.byte_code, + rib_input_type_info: compiled_worker_name.rib_input_type_info, + }) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct IdempotencyKeyCompiled { + pub idempotency_key: Expr, + pub compiled_idempotency_key: RibByteCode, + pub rib_input: RibInputTypeInfo, +} + +impl IdempotencyKeyCompiled { + pub fn from_idempotency_key( + idempotency_key: &Expr, + exports: &[AnalysedExport], + ) -> Result { + let idempotency_key_compiled = + DefaultWorkerServiceRibCompiler::compile(idempotency_key, exports)?; + + Ok(IdempotencyKeyCompiled { + idempotency_key: idempotency_key.clone(), + compiled_idempotency_key: idempotency_key_compiled.byte_code, + rib_input: idempotency_key_compiled.rib_input_type_info, + }) + } +} diff --git a/golem-worker-service-base/src/gateway_binding/worker_binding.rs b/golem-worker-service-base/src/gateway_binding/worker_binding.rs index 3d5295e38a..336923335f 100644 --- a/golem-worker-service-base/src/gateway_binding/worker_binding.rs +++ b/golem-worker-service-base/src/gateway_binding/worker_binding.rs @@ -12,11 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -use serde::{Deserialize, Serialize}; - -use crate::gateway_binding::WorkerBindingCompiled; +use super::{IdempotencyKeyCompiled, WorkerNameCompiled}; +use crate::gateway_rib_compiler::DefaultWorkerServiceRibCompiler; +use crate::gateway_rib_compiler::WorkerServiceRibCompiler; use golem_service_base::model::VersionedComponentId; -use rib::Expr; +use golem_wasm_ast::analysis::AnalysedExport; +use rib::{Expr, RibByteCode, RibInputTypeInfo, RibOutputTypeInfo, WorkerFunctionsInRib}; +use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq)] pub struct WorkerBinding { @@ -26,9 +28,47 @@ pub struct WorkerBinding { pub response_mapping: ResponseMapping, } -// ResponseMapping will consist of actual logic such as invoking worker functions -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct ResponseMapping(pub Expr); +#[derive(Debug, Clone, PartialEq)] +pub struct WorkerBindingCompiled { + pub component_id: VersionedComponentId, + pub worker_name_compiled: Option, + pub idempotency_key_compiled: Option, + pub response_compiled: ResponseMappingCompiled, +} + +impl WorkerBindingCompiled { + pub fn from_raw_worker_binding( + gateway_worker_binding: &WorkerBinding, + export_metadata: &[AnalysedExport], + ) -> Result { + let worker_name_compiled: Option = gateway_worker_binding + .worker_name + .clone() + .map(|worker_name_expr| { + WorkerNameCompiled::from_worker_name(&worker_name_expr, export_metadata) + }) + .transpose()?; + + let idempotency_key_compiled = match &gateway_worker_binding.idempotency_key { + Some(idempotency_key) => Some(IdempotencyKeyCompiled::from_idempotency_key( + idempotency_key, + export_metadata, + )?), + None => None, + }; + let response_compiled = ResponseMappingCompiled::from_response_mapping( + &gateway_worker_binding.response_mapping, + export_metadata, + )?; + + Ok(WorkerBindingCompiled { + component_id: gateway_worker_binding.component_id.clone(), + worker_name_compiled, + idempotency_key_compiled, + response_compiled, + }) + } +} impl From for WorkerBinding { fn from(value: WorkerBindingCompiled) -> Self { @@ -48,3 +88,35 @@ impl From for WorkerBinding { } } } + +// ResponseMapping will consist of actual logic such as invoking worker functions +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ResponseMapping(pub Expr); + +#[derive(Debug, Clone, PartialEq)] +pub struct ResponseMappingCompiled { + pub response_mapping_expr: Expr, + pub response_mapping_compiled: RibByteCode, + pub rib_input: RibInputTypeInfo, + pub worker_calls: Option, + // Optional to keep backward compatibility + pub rib_output: Option, +} + +impl ResponseMappingCompiled { + pub fn from_response_mapping( + response_mapping: &ResponseMapping, + exports: &[AnalysedExport], + ) -> Result { + let response_compiled = + DefaultWorkerServiceRibCompiler::compile(&response_mapping.0, exports)?; + + Ok(ResponseMappingCompiled { + response_mapping_expr: response_mapping.0.clone(), + response_mapping_compiled: response_compiled.byte_code, + rib_input: response_compiled.rib_input_type_info, + worker_calls: response_compiled.worker_invoke_calls, + rib_output: response_compiled.rib_output_type_info, + }) + } +} diff --git a/golem-worker-service-base/src/gateway_binding/worker_binding_compiled.rs b/golem-worker-service-base/src/gateway_binding/worker_binding_compiled.rs deleted file mode 100644 index 842afa611e..0000000000 --- a/golem-worker-service-base/src/gateway_binding/worker_binding_compiled.rs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2024-2025 Golem Cloud -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::gateway_binding::{ResponseMapping, WorkerBinding}; -use crate::gateway_rib_compiler::{DefaultWorkerServiceRibCompiler, WorkerServiceRibCompiler}; -use golem_service_base::model::VersionedComponentId; -use golem_wasm_ast::analysis::AnalysedExport; -use rib::{Expr, RibByteCode, RibInputTypeInfo, RibOutputTypeInfo, WorkerFunctionsInRib}; - -#[derive(Debug, Clone, PartialEq)] -pub struct WorkerBindingCompiled { - pub component_id: VersionedComponentId, - pub worker_name_compiled: Option, - pub idempotency_key_compiled: Option, - pub response_compiled: ResponseMappingCompiled, -} - -impl WorkerBindingCompiled { - pub fn from_raw_worker_binding( - gateway_worker_binding: &WorkerBinding, - export_metadata: &[AnalysedExport], - ) -> Result { - let worker_name_compiled: Option = gateway_worker_binding - .worker_name - .clone() - .map(|worker_name_expr| { - WorkerNameCompiled::from_worker_name(&worker_name_expr, export_metadata) - }) - .transpose()?; - - let idempotency_key_compiled = match &gateway_worker_binding.idempotency_key { - Some(idempotency_key) => Some(IdempotencyKeyCompiled::from_idempotency_key( - idempotency_key, - export_metadata, - )?), - None => None, - }; - let response_compiled = ResponseMappingCompiled::from_response_mapping( - &gateway_worker_binding.response_mapping, - export_metadata, - )?; - - Ok(WorkerBindingCompiled { - component_id: gateway_worker_binding.component_id.clone(), - worker_name_compiled, - idempotency_key_compiled, - response_compiled, - }) - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct WorkerNameCompiled { - pub worker_name: Expr, - pub compiled_worker_name: RibByteCode, - pub rib_input_type_info: RibInputTypeInfo, -} - -impl WorkerNameCompiled { - pub fn from_worker_name( - worker_name: &Expr, - exports: &[AnalysedExport], - ) -> Result { - let compiled_worker_name = DefaultWorkerServiceRibCompiler::compile(worker_name, exports)?; - - Ok(WorkerNameCompiled { - worker_name: worker_name.clone(), - compiled_worker_name: compiled_worker_name.byte_code, - rib_input_type_info: compiled_worker_name.rib_input_type_info, - }) - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct IdempotencyKeyCompiled { - pub idempotency_key: Expr, - pub compiled_idempotency_key: RibByteCode, - pub rib_input: RibInputTypeInfo, -} - -impl IdempotencyKeyCompiled { - pub fn from_idempotency_key( - idempotency_key: &Expr, - exports: &[AnalysedExport], - ) -> Result { - let idempotency_key_compiled = - DefaultWorkerServiceRibCompiler::compile(idempotency_key, exports)?; - - Ok(IdempotencyKeyCompiled { - idempotency_key: idempotency_key.clone(), - compiled_idempotency_key: idempotency_key_compiled.byte_code, - rib_input: idempotency_key_compiled.rib_input_type_info, - }) - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ResponseMappingCompiled { - pub response_mapping_expr: Expr, - pub response_mapping_compiled: RibByteCode, - pub rib_input: RibInputTypeInfo, - pub worker_calls: Option, - // Optional to keep backward compatibility - pub rib_output: Option, -} - -impl ResponseMappingCompiled { - pub fn from_response_mapping( - response_mapping: &ResponseMapping, - exports: &[AnalysedExport], - ) -> Result { - let response_compiled = - DefaultWorkerServiceRibCompiler::compile(&response_mapping.0, exports)?; - - Ok(ResponseMappingCompiled { - response_mapping_expr: response_mapping.0.clone(), - response_mapping_compiled: response_compiled.byte_code, - rib_input: response_compiled.rib_input_type_info, - worker_calls: response_compiled.worker_invoke_calls, - rib_output: response_compiled.rib_output_type_info, - }) - } -} diff --git a/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs b/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs index af0ecb26c9..0a5507ac5e 100644 --- a/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs +++ b/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs @@ -65,6 +65,97 @@ pub struct FileServerBindingDetails { pub file_path: ComponentFilePath, } +impl FileServerBindingDetails { + pub fn from_rib_result(result: RibResult) -> Result { + // Three supported formats: + // 1. A string path. Mime type is guessed from the path. Status code is 200. + // 2. A record with a 'file-path' field. Mime type and status are optionally taken from the record, otherwise guessed. + // 3. A result of either of the above, with the same rules applied. + match result { + RibResult::Val(value) => match value { + ValueAndType { + value: Value::Result(value), + typ: AnalysedType::Result(typ), + } => match value { + Ok(ok) => { + let ok = ValueAndType::new( + *ok.ok_or("ok unset".to_string())?, + (*typ.ok.ok_or("Missing 'ok' type")?).clone(), + ); + Self::from_rib_happy(ok) + } + Err(err) => { + let value = err.ok_or("err unset".to_string())?; + Err(format!("Error result: {value:?}")) + } + }, + other => Self::from_rib_happy(other), + }, + RibResult::Unit => Err("Expected a value".to_string()), + } + } + + /// Like the above, just without the result case. + fn from_rib_happy(value: ValueAndType) -> Result { + match &value { + ValueAndType { + value: Value::String(raw_path), + .. + } => Self::make_from(raw_path.clone(), None, None), + ValueAndType { + value: Value::Record(field_values), + typ: AnalysedType::Record(record), + } => { + let path_position = record + .fields + .iter() + .position(|pair| &pair.name == "file-path") + .ok_or("Record must contain 'file-path' field")?; + + let path = if let Value::String(path) = &field_values[path_position] { + path + } else { + return Err("file-path must be a string".to_string()); + }; + + let status = get_status_code(field_values, record)?; + let headers = get_response_headers_or_default(&value)?; + let content_type = headers.get_content_type(); + + Self::make_from(path.to_string(), content_type, status) + } + _ => Err("Response value expected".to_string()), + } + } + + fn make_from( + path: String, + content_type: Option, + status_code: Option, + ) -> Result { + let file_path = ComponentFilePath::from_either_str(&path)?; + + let content_type = match content_type { + Some(content_type) => content_type, + None => { + let mime_type = mime_guess::from_path(&path) + .first() + .ok_or("Could not determine mime type")?; + ContentType::from_str(mime_type.as_ref()) + .map_err(|e| format!("Invalid mime type: {}", e))? + } + }; + + let status_code = status_code.unwrap_or(StatusCode::OK); + + Ok(FileServerBindingDetails { + status_code, + content_type, + file_path, + }) + } +} + pub struct DefaultFileServerBindingHandler { component_service: Arc + Sync + Send>, initial_component_files_service: Arc, @@ -77,7 +168,7 @@ impl DefaultFileServerBindingHandler { initial_component_files_service: Arc, worker_service: Arc, ) -> Self { - DefaultFileServerBindingHandler { + Self { component_service, initial_component_files_service, worker_service, @@ -177,94 +268,3 @@ impl FileServerBindingHandler Result { - // Three supported formats: - // 1. A string path. Mime type is guessed from the path. Status code is 200. - // 2. A record with a 'file-path' field. Mime type and status are optionally taken from the record, otherwise guessed. - // 3. A result of either of the above, with the same rules applied. - match result { - RibResult::Val(value) => match value { - ValueAndType { - value: Value::Result(value), - typ: AnalysedType::Result(typ), - } => match value { - Ok(ok) => { - let ok = ValueAndType::new( - *ok.ok_or("ok unset".to_string())?, - (*typ.ok.ok_or("Missing 'ok' type")?).clone(), - ); - Self::from_rib_happy(ok) - } - Err(err) => { - let value = err.ok_or("err unset".to_string())?; - Err(format!("Error result: {value:?}")) - } - }, - other => Self::from_rib_happy(other), - }, - RibResult::Unit => Err("Expected a value".to_string()), - } - } - - /// Like the above, just without the result case. - fn from_rib_happy(value: ValueAndType) -> Result { - match &value { - ValueAndType { - value: Value::String(raw_path), - .. - } => Self::make_from(raw_path.clone(), None, None), - ValueAndType { - value: Value::Record(field_values), - typ: AnalysedType::Record(record), - } => { - let path_position = record - .fields - .iter() - .position(|pair| &pair.name == "file-path") - .ok_or("Record must contain 'file-path' field")?; - - let path = if let Value::String(path) = &field_values[path_position] { - path - } else { - return Err("file-path must be a string".to_string()); - }; - - let status = get_status_code(field_values, record)?; - let headers = get_response_headers_or_default(&value)?; - let content_type = headers.get_content_type(); - - Self::make_from(path.to_string(), content_type, status) - } - _ => Err("Response value expected".to_string()), - } - } - - fn make_from( - path: String, - content_type: Option, - status_code: Option, - ) -> Result { - let file_path = ComponentFilePath::from_either_str(&path)?; - - let content_type = match content_type { - Some(content_type) => content_type, - None => { - let mime_type = mime_guess::from_path(&path) - .first() - .ok_or("Could not determine mime type")?; - ContentType::from_str(mime_type.as_ref()) - .map_err(|e| format!("Invalid mime type: {}", e))? - } - }; - - let status_code = status_code.unwrap_or(StatusCode::OK); - - Ok(FileServerBindingDetails { - status_code, - content_type, - file_path, - }) - } -} diff --git a/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs b/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs index e3ba9a318f..6d978a1dc9 100644 --- a/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs +++ b/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs @@ -118,6 +118,7 @@ pub enum ResolvedBinding { Static(StaticBinding), Worker(ResolvedWorkerBinding), FileServer(ResolvedWorkerBinding), + HttpHandler(ResolvedHttpHandlerBinding), } #[derive(Clone, Debug)] @@ -198,6 +199,12 @@ impl ResolvedGatewayBinding { } } +#[derive(Debug, Clone)] +pub struct ResolvedHttpHandlerBinding { + pub worker_detail: WorkerDetail, + pub namespace: Namespace, +} + pub struct DefaultGatewayBindingResolver { input: InputHttpRequest, gateway_session_store: GatewaySessionStore, @@ -273,6 +280,7 @@ impl let mut http_request_details = HttpRequestDetails::from_input_http_request( &self.input.scheme, &self.input.host, + self.input.req_method.clone(), &self.input.api_input_path, &zipped_path_params, &request_query_variables, @@ -306,28 +314,45 @@ impl } match binding { - GatewayBindingCompiled::FileServer(worker_binding) => internal::get_resolved_binding( - worker_binding, - &http_request_details, - namespace, - headers, - ) - .await - .map(|resolved_binding| ResolvedGatewayBinding { - request_details: GatewayRequestDetails::Http(http_request_details), - resolved_binding: ResolvedBinding::FileServer(resolved_binding), - }), - GatewayBindingCompiled::Worker(worker_binding) => internal::get_resolved_binding( - worker_binding, - &http_request_details, - namespace, - headers, - ) - .await - .map(|resolved_binding| ResolvedGatewayBinding { - request_details: GatewayRequestDetails::Http(http_request_details), - resolved_binding: ResolvedBinding::Worker(resolved_binding), - }), + GatewayBindingCompiled::FileServer(worker_binding) => { + internal::get_resolved_worker_binding( + worker_binding, + &http_request_details, + namespace, + headers, + ) + .await + .map(|resolved_binding| ResolvedGatewayBinding { + request_details: GatewayRequestDetails::Http(http_request_details), + resolved_binding: ResolvedBinding::FileServer(resolved_binding), + }) + } + GatewayBindingCompiled::Worker(worker_binding) => { + internal::get_resolved_worker_binding( + worker_binding, + &http_request_details, + namespace, + headers, + ) + .await + .map(|resolved_binding| ResolvedGatewayBinding { + request_details: GatewayRequestDetails::Http(http_request_details), + resolved_binding: ResolvedBinding::Worker(resolved_binding), + }) + } + GatewayBindingCompiled::HttpHandler(http_handler_binding) => { + internal::get_resolved_http_handler_binding( + http_handler_binding, + &http_request_details, + namespace, + headers, + ) + .await + .map(|resolved_binding| ResolvedGatewayBinding { + request_details: GatewayRequestDetails::Http(http_request_details), + resolved_binding: ResolvedBinding::HttpHandler(resolved_binding), + }) + } GatewayBindingCompiled::Static(static_binding) => { Ok(ResolvedGatewayBinding::from_static_binding( &GatewayRequestDetails::Http(http_request_details), @@ -340,8 +365,8 @@ impl mod internal { use crate::gateway_binding::{ - ErrorOrRedirect, HttpRequestDetails, ResolvedWorkerBinding, RibInputValueResolver, - WorkerBindingCompiled, WorkerDetail, + ErrorOrRedirect, HttpHandlerBindingCompiled, HttpRequestDetails, ResolvedWorkerBinding, + RibInputValueResolver, WorkerBindingCompiled, WorkerDetail, }; use crate::gateway_execution::gateway_session::GatewaySessionStore; use crate::gateway_middleware::{HttpMiddlewares, MiddlewareError, MiddlewareSuccess}; @@ -350,6 +375,8 @@ mod internal { use http::HeaderMap; use std::sync::Arc; + use super::ResolvedHttpHandlerBinding; + pub async fn redirect_or_continue( input: &mut HttpRequestDetails, middlewares: &HttpMiddlewares, @@ -380,7 +407,7 @@ mod internal { } } - pub async fn get_resolved_binding( + pub async fn get_resolved_worker_binding( binding: &WorkerBindingCompiled, http_request_details: &HttpRequestDetails, namespace: &Namespace, @@ -457,4 +484,81 @@ mod internal { Ok(resolved_binding) } + + pub async fn get_resolved_http_handler_binding( + binding: &HttpHandlerBindingCompiled, + http_request_details: &HttpRequestDetails, + namespace: &Namespace, + headers: &HeaderMap, + ) -> Result, ErrorOrRedirect> { + let worker_name_opt = if let Some(worker_name_compiled) = &binding.worker_name_compiled { + let resolve_rib_input = http_request_details + .resolve_rib_input_value(&worker_name_compiled.rib_input_type_info) + .map_err(ErrorOrRedirect::rib_input_type_mismatch)?; + + let worker_name = rib::interpret_pure( + &worker_name_compiled.compiled_worker_name, + &resolve_rib_input, + ) + .await + .map_err(|err| { + ErrorOrRedirect::internal(format!( + "Failed to evaluate worker name rib expression. {}", + err + )) + })? + .get_literal() + .ok_or(ErrorOrRedirect::internal( + "Worker name is not a Rib expression that resolves to String".to_string(), + ))? + .as_string(); + + Some(worker_name) + } else { + None + }; + + let component_id = &binding.component_id; + + let idempotency_key = + if let Some(idempotency_key_compiled) = &binding.idempotency_key_compiled { + let resolve_rib_input = http_request_details + .resolve_rib_input_value(&idempotency_key_compiled.rib_input) + .map_err(ErrorOrRedirect::rib_input_type_mismatch)?; + + let idempotency_key_value = rib::interpret_pure( + &idempotency_key_compiled.compiled_idempotency_key, + &resolve_rib_input, + ) + .await + .map_err(|err| ErrorOrRedirect::internal(err.to_string()))?; + + let idempotency_key = idempotency_key_value + .get_literal() + .ok_or(ErrorOrRedirect::internal( + "Idempotency Key is not a string".to_string(), + ))? + .as_string(); + + Some(IdempotencyKey::new(idempotency_key)) + } else { + headers + .get("idempotency-key") + .and_then(|h| h.to_str().ok()) + .map(|value| IdempotencyKey::new(value.to_string())) + }; + + let worker_detail = WorkerDetail { + component_id: component_id.clone(), + worker_name: worker_name_opt, + idempotency_key, + }; + + let resolved_binding = ResolvedHttpHandlerBinding { + worker_detail, + namespace: namespace.clone(), + }; + + Ok(resolved_binding) + } } diff --git a/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs b/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs index 0a8bf8c870..df7804c83a 100644 --- a/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs +++ b/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs @@ -37,6 +37,8 @@ use rib::{RibInput, RibResult}; use std::sync::Arc; use tracing::error; +use super::http_handler_binding_handler::HttpHandlerBindingHandler; + #[async_trait] pub trait GatewayHttpInputExecutor { async fn execute_http_request(&self, input: poem::Request) -> poem::Response; @@ -46,6 +48,7 @@ pub struct DefaultGatewayInputExecutor { pub evaluator: Arc + Sync + Send>, pub file_server_binding_handler: Arc + Sync + Send>, pub auth_call_back_binding_handler: Arc, + pub http_handler_binding_handler: Arc + Sync + Send>, pub api_definition_lookup_service: Arc< dyn ApiDefinitionsLookup< InputHttpRequest, @@ -62,6 +65,7 @@ impl DefaultGatewayInputExecutor { evaluator: Arc + Sync + Send>, file_server_binding_handler: Arc + Sync + Send>, auth_call_back_binding_handler: Arc, + http_handler_binding_handler: Arc + Sync + Send>, api_definition_lookup_service: Arc< dyn ApiDefinitionsLookup< InputHttpRequest, @@ -76,6 +80,7 @@ impl DefaultGatewayInputExecutor { evaluator, file_server_binding_handler, auth_call_back_binding_handler, + http_handler_binding_handler, api_definition_lookup_service, gateway_session_store, identity_provider, @@ -128,6 +133,38 @@ impl DefaultGatewayInputExecutor { } } + ResolvedBinding::HttpHandler(http_handler_binding) => { + let result = self + .http_handler_binding_handler + .handle_http_handler_binding( + &http_handler_binding.namespace, + &http_handler_binding.worker_detail, + &request_details, + ) + .await; + + match result { + Ok(_) => tracing::debug!("http handler binding successful"), + Err(ref e) => tracing::warn!("http handler binding failed: {e:?}"), + } + + let mut response = result + .to_response(&request_details, &self.gateway_session_store) + .await; + + if let Some(middleware) = middleware_opt { + let result = middleware.process_middleware_out(&mut response).await; + match result { + Ok(_) => response, + Err(err) => { + err.to_response_from_safe_display(|_| StatusCode::INTERNAL_SERVER_ERROR) + } + } + } else { + response + } + } + ResolvedBinding::FileServer(resolved_file_server_binding) => { self.handle_file_server_binding( &self.gateway_session_store, diff --git a/golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs b/golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs new file mode 100644 index 0000000000..f1347c9f7e --- /dev/null +++ b/golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs @@ -0,0 +1,229 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::gateway_binding::{HttpRequestDetails, WorkerDetail}; +use crate::gateway_execution::GatewayResolvedWorkerRequest; +use async_trait::async_trait; +use bytes::Bytes; +use golem_common::model::HasAccountId; +use golem_common::virtual_exports; +use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; +use golem_wasm_rpc::TypeAnnotatedValueConstructors; +use http::StatusCode; +use http_body_util::combinators::BoxBody; +use http_body_util::BodyExt; +use std::convert::Infallible; +use std::str::FromStr; +use std::sync::Arc; + +use super::{GatewayWorkerRequestExecutor, WorkerRequestExecutorError}; + +#[async_trait] +pub trait HttpHandlerBindingHandler { + async fn handle_http_handler_binding( + &self, + namespace: &Namespace, + worker_detail: &WorkerDetail, + request_details: &HttpRequestDetails, + ) -> HttpHandlerBindingResult; +} + +pub type HttpHandlerBindingResult = Result; + +pub struct HttpHandlerBindingSuccess { + pub response: poem::Response, +} + +#[derive(Debug)] +pub enum HttpHandlerBindingError { + InternalError(String), + WorkerRequestExecutorError(WorkerRequestExecutorError), +} + +pub struct DefaultHttpHandlerBindingHandler { + worker_request_executor: Arc + Sync + Send>, +} + +impl DefaultHttpHandlerBindingHandler { + pub fn new( + worker_request_executor: Arc + Sync + Send>, + ) -> Self { + Self { + worker_request_executor, + } + } +} + +#[async_trait] +impl HttpHandlerBindingHandler + for DefaultHttpHandlerBindingHandler +{ + async fn handle_http_handler_binding( + &self, + namespace: &Namespace, + worker_detail: &WorkerDetail, + request_details: &HttpRequestDetails, + ) -> HttpHandlerBindingResult { + let component_id = worker_detail.component_id.component_id.clone(); + + let http_request_function_param = { + use golem_common::virtual_exports::http_incoming_handler as hic; + + let headers = { + let mut acc = Vec::new(); + for header in request_details.request_headers.0.fields.iter() { + acc.push(( + header.name.clone(), + Bytes::from(header.value.to_string().into_bytes()), + )); + } + hic::HttpFields(acc) + }; + + let body = hic::HttpBodyAndTrailers { + content: hic::HttpBodyContent(Bytes::from( + request_details + .request_body_value + .0 + .to_string() + .into_bytes(), + )), + trailers: None, + }; + + hic::IncomingHttpRequest { + scheme: request_details.scheme.clone().into(), + authority: request_details.host.to_string(), + path_with_query: request_details.get_api_input_path(), + method: hic::HttpMethod::from_http_method(request_details.request_method.clone()), + headers, + body: Some(body), + } + }; + + let typ: golem_wasm_ast::analysis::protobuf::Type = (&golem_common::virtual_exports::http_incoming_handler::IncomingHttpRequest::analysed_type()).into(); + + let type_annotated_param = + TypeAnnotatedValue::create(&http_request_function_param.to_value(), typ).map_err( + |e| { + HttpHandlerBindingError::InternalError(format!( + "Failed converting request into wasm rpc: {:?}", + e + )) + }, + )?; + + let resolved_request: GatewayResolvedWorkerRequest = + GatewayResolvedWorkerRequest { + component_id, + worker_name: worker_detail.worker_name.clone(), + function_name: virtual_exports::http_incoming_handler::FUNCTION_NAME.to_string(), + function_params: vec![type_annotated_param], + idempotency_key: worker_detail.idempotency_key.clone(), + namespace: namespace.clone(), + }; + + let response = self.worker_request_executor.execute(resolved_request).await; + + // log outcome + match response { + Ok(_) => { + tracing::debug!("http_handler received successful response from worker invocation") + } + Err(ref e) => tracing::warn!("worker invocation of http_handler failed: {}", e), + } + + let response = response.map_err(HttpHandlerBindingError::WorkerRequestExecutorError)?; + + let poem_response = { + use golem_common::virtual_exports::http_incoming_handler as hic; + + let parsed_response = hic::HttpResponse::from_function_output(response.result) + .map_err(|e| { + HttpHandlerBindingError::InternalError(format!( + "Failed parsing response: {}", + e + )) + })?; + + let converted_status_code = + StatusCode::from_u16(parsed_response.status).map_err(|e| { + HttpHandlerBindingError::InternalError(format!( + "Failed to parse response status: {}", + e + )) + })?; + + let mut builder = poem::Response::builder().status(converted_status_code); + + for (header_name, header_value) in parsed_response.headers.0 { + let converted_header_value = + http::HeaderValue::from_bytes(&header_value).map_err(|e| { + HttpHandlerBindingError::InternalError(format!( + "Failed to parse response header: {}", + e + )) + })?; + builder = builder.header(header_name, converted_header_value); + } + + if let Some(body) = parsed_response.body { + let converted_body = http_body_util::Full::new(body.content.0); + + let trailers = if let Some(trailers) = body.trailers { + let mut acc = http::HeaderMap::new(); + for (header_name, header_value) in trailers.0.into_iter() { + let converted_header_name = http::HeaderName::from_str(&header_name) + .map_err(|e| { + HttpHandlerBindingError::InternalError(format!( + "Failed to parse response trailer name: {}", + e + )) + })?; + let converted_header_value = http::HeaderValue::from_bytes(&header_value) + .map_err(|e| { + HttpHandlerBindingError::InternalError(format!( + "Failed to parse response trailer value: {}", + e + )) + })?; + + acc.insert(converted_header_name, converted_header_value); + } + Some(Ok(acc)) + } else { + None + }; + + let body_with_trailers = converted_body.with_trailers(async { trailers }); + + let boxed: BoxBody = BoxBody::new( + body_with_trailers.map_err(error_from_infallible::), + ); + + builder.body(boxed) + } else { + builder.body(poem::Body::empty()) + } + }; + + Ok(HttpHandlerBindingSuccess { + response: poem_response, + }) + } +} + +fn error_from_infallible(_infallible: Infallible) -> E { + unreachable!() +} diff --git a/golem-worker-service-base/src/gateway_execution/mod.rs b/golem-worker-service-base/src/gateway_execution/mod.rs index e34ddbdd09..8e84cd2dfb 100644 --- a/golem-worker-service-base/src/gateway_execution/mod.rs +++ b/golem-worker-service-base/src/gateway_execution/mod.rs @@ -23,6 +23,7 @@ pub mod gateway_http_input_executor; pub mod gateway_session; mod gateway_worker_request_executor; mod http_content_type_mapper; +pub mod http_handler_binding_handler; pub mod rib_input_value_resolver; pub mod router; pub mod to_response; diff --git a/golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs b/golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs index 32ea8a442e..beff51e1c6 100644 --- a/golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs +++ b/golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs @@ -19,7 +19,7 @@ use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; use rib::{RibInput, RibInputTypeInfo}; use std::collections::HashMap; use std::fmt::Display; -use tracing::warn; +use tracing::debug; // `RibInputValueResolver` is responsible // for extracting `RibInputValue` from any input, given the requirements as `RibInputTypeInfo`. @@ -58,7 +58,7 @@ impl RibInputValueResolver for HttpRequestDetails { match request_type_info { Some(request_type) => { - warn!("received: {:?}", rib_input_with_request_content); + debug!("received: {:?}", rib_input_with_request_content); let input = TypeAnnotatedValue::parse_with_type(rib_input_with_request_content, request_type) .map_err(|err| RibInputTypeMismatch(format!("Input request details don't match the requirements for rib expression to execute: {}. Requirements. {:?}", err.join(", "), request_type)))?; let input = input.try_into().map_err(|err| { diff --git a/golem-worker-service-base/src/gateway_execution/to_response.rs b/golem-worker-service-base/src/gateway_execution/to_response.rs index 37b7cfec64..8b160853d2 100644 --- a/golem-worker-service-base/src/gateway_execution/to_response.rs +++ b/golem-worker-service-base/src/gateway_execution/to_response.rs @@ -28,6 +28,8 @@ use poem::Body; use poem::IntoResponse; use rib::RibResult; +use super::http_handler_binding_handler::{HttpHandlerBindingError, HttpHandlerBindingResult}; + #[async_trait] pub trait ToHttpResponse { async fn to_response( @@ -67,6 +69,29 @@ impl ToHttpResponse for FileServerBindingResult { } } +#[async_trait] +impl ToHttpResponse for HttpHandlerBindingResult { + async fn to_response( + self, + _request_details: &HttpRequestDetails, + _session_store: &GatewaySessionStore, + ) -> poem::Response { + match self { + Ok(inner) => inner.response, + Err(HttpHandlerBindingError::InternalError(e)) => poem::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from_string(format!("Error {}", e).to_string())), + Err(HttpHandlerBindingError::WorkerRequestExecutorError(e)) => { + poem::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from_string( + format!("Error calling worker executor {}", e).to_string(), + )) + } + } + } +} + // Preflight (OPTIONS) response that will consist of all configured CORS headers #[async_trait] impl ToHttpResponse for CorsPreflight { diff --git a/golem-worker-service-base/src/gateway_request/http_request.rs b/golem-worker-service-base/src/gateway_request/http_request.rs index 03643754c9..3cae96c429 100644 --- a/golem-worker-service-base/src/gateway_request/http_request.rs +++ b/golem-worker-service-base/src/gateway_request/http_request.rs @@ -25,7 +25,7 @@ use tracing::error; #[derive(Clone, Debug)] pub struct InputHttpRequest { - pub scheme: Option, + pub scheme: Scheme, pub host: ApiSiteString, pub api_input_path: ApiInputPath, pub headers: HeaderMap, @@ -44,10 +44,10 @@ impl From for Response { impl InputHttpRequest { pub async fn from_request(request: poem::Request) -> Result { + let scheme = request.scheme().clone(); let (req_parts, body) = request.into_parts(); let headers = req_parts.headers; let uri = req_parts.uri; - let scheme = uri.scheme(); let host = match headers.get(HOST).and_then(|h| h.to_str().ok()) { Some(host) => ApiSiteString(host.to_string()), @@ -77,7 +77,7 @@ impl InputHttpRequest { }; Ok(InputHttpRequest { - scheme: scheme.cloned(), + scheme: scheme.clone(), host, api_input_path: ApiInputPath { base_path: uri.path().to_string(), diff --git a/golem-worker-service-base/src/gateway_request/request_details.rs b/golem-worker-service-base/src/gateway_request/request_details.rs index e92db4e8c5..882158e7fc 100644 --- a/golem-worker-service-base/src/gateway_request/request_details.rs +++ b/golem-worker-service-base/src/gateway_request/request_details.rs @@ -20,7 +20,7 @@ use crate::gateway_middleware::HttpMiddlewares; use crate::gateway_request::http_request::ApiInputPath; use golem_common::SafeDisplay; use http::uri::Scheme; -use http::HeaderMap; +use http::{HeaderMap, Method}; use serde_json::Value; use std::collections::HashMap; use url::Url; @@ -30,37 +30,6 @@ use url::Url; pub enum GatewayRequestDetails { Http(HttpRequestDetails), } -impl GatewayRequestDetails { - // Form the HttpRequestDetails based on what's required by - // ApiDefinition. If there are query or path parameters that are not required - // by API definition, they will be discarded here. - // If there is a need to fetch any query values or path values that are required - // in the workflow but not through API definition, use poem::Request directly - // as it will be better performing in the hot path - pub fn from( - scheme: &Option, - host: &ApiSiteString, - api_input_path: &ApiInputPath, - path_params: &HashMap, - query_variable_values: &HashMap, - query_variable_names: &[QueryInfo], - request_body: &Value, - headers: HeaderMap, - middlewares: &Option, - ) -> Result> { - Ok(Self::Http(HttpRequestDetails::from_input_http_request( - scheme, - host, - api_input_path, - path_params, - query_variable_values, - query_variable_names, - request_body, - headers, - middlewares, - )?)) - } -} // A structure that holds the incoming request details // along with parameters that are required by the route in API definition @@ -69,8 +38,9 @@ impl GatewayRequestDetails { // api_input_path is still available. #[derive(Debug, Clone)] pub struct HttpRequestDetails { - pub scheme: Option, + pub scheme: Scheme, pub host: ApiSiteString, + pub request_method: Method, pub api_input_path: ApiInputPath, pub request_path_params: RequestPathValues, pub request_body_value: RequestBody, @@ -140,24 +110,21 @@ impl HttpRequestDetails { } pub fn url(&self) -> Result { - let url_str = if let Some(scheme) = &self.scheme { - format!( - "{}://{}{}", - scheme, - &self.host, - &self.api_input_path.to_string() - ) - } else { - format!("{}{}", &self.host, &self.api_input_path.to_string()) - }; + let url_str = format!( + "{}://{}{}", + &self.scheme, + &self.host, + &self.api_input_path.to_string() + ); Url::parse(&url_str).map_err(|err| err.to_string()) } pub fn empty() -> HttpRequestDetails { HttpRequestDetails { - scheme: Some(Scheme::HTTP), + scheme: Scheme::HTTP, host: ApiSiteString("".to_string()), + request_method: Method::GET, api_input_path: ApiInputPath { base_path: "".to_string(), query_path: None, @@ -249,8 +216,9 @@ impl HttpRequestDetails { } pub fn from_input_http_request( - scheme: &Option, + scheme: &Scheme, host: &ApiSiteString, + method: Method, api_input_path: &ApiInputPath, path_params: &HashMap, query_variable_values: &HashMap, @@ -267,6 +235,7 @@ impl HttpRequestDetails { Ok(Self { scheme: scheme.clone(), host: host.clone(), + request_method: method, api_input_path: api_input_path.clone(), request_path_params: path_params, request_body_value: request_body, @@ -335,7 +304,8 @@ impl RequestQueryValues { } #[derive(Debug, Clone)] -pub struct RequestHeaderValues(JsonKeyValues); +pub struct RequestHeaderValues(pub JsonKeyValues); + impl RequestHeaderValues { fn from(headers: &HeaderMap) -> Result> { let mut headers_map: JsonKeyValues = JsonKeyValues::default(); @@ -353,7 +323,7 @@ impl RequestHeaderValues { } #[derive(Debug, Clone)] -pub struct RequestBody(Value); +pub struct RequestBody(pub Value); impl RequestBody { fn from(request_body: &Value) -> Result> { diff --git a/golem-worker-service-base/src/service/gateway/api_definition.rs b/golem-worker-service-base/src/service/gateway/api_definition.rs index 9dab6a4ec3..27aee1ff9e 100644 --- a/golem-worker-service-base/src/service/gateway/api_definition.rs +++ b/golem-worker-service-base/src/service/gateway/api_definition.rs @@ -201,9 +201,8 @@ impl ApiDefinitionServiceDefault { .get_bindings() .iter() .cloned() - .filter_map(|binding| binding.get_worker_binding()) - .map(|binding| async move { - let id = &binding.component_id; + .filter_map(|binding| binding.get_component_id()) + .map(|id| async move { self.component_service .get_by_version(&id.component_id, id.version, auth_ctx) .await diff --git a/golem-worker-service-base/src/service/gateway/http_api_definition_validator.rs b/golem-worker-service-base/src/service/gateway/http_api_definition_validator.rs index c57a66efa4..dc60e3dc9a 100644 --- a/golem-worker-service-base/src/service/gateway/http_api_definition_validator.rs +++ b/golem-worker-service-base/src/service/gateway/http_api_definition_validator.rs @@ -101,7 +101,7 @@ fn unique_routes(routes: &[Route]) -> Vec { errors.push(RouteValidationError { method: route.method.clone(), path: route.path.to_string(), - component: route.binding.get_worker_binding().map(|w| w.component_id), + component: route.binding.get_component_id(), detail, }); } diff --git a/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs b/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs index 4abe1c49d1..5d1fc6805f 100644 --- a/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs +++ b/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs @@ -74,6 +74,7 @@ async fn execute( internal::get_test_rib_interpreter(), internal::get_test_file_server_binding_handler(), Arc::new(DefaultAuthCallBack), + internal::get_test_http_handler_binding_handler(), Arc::new(internal::TestApiDefinitionLookup::new(compiled)), Arc::clone(session_store), Arc::new(test_identity_provider.clone()), @@ -1594,12 +1595,16 @@ mod internal { FileServerBindingHandler, FileServerBindingResult, }; use golem_worker_service_base::gateway_execution::gateway_binding_resolver::WorkerDetail; + use golem_worker_service_base::gateway_execution::http_handler_binding_handler::{ + HttpHandlerBindingHandler, HttpHandlerBindingResult, + }; use golem_worker_service_base::gateway_execution::{ GatewayResolvedWorkerRequest, GatewayWorkerRequestExecutor, WorkerRequestExecutorError, WorkerResponse, }; use golem_worker_service_base::gateway_middleware::HttpCors; + use golem_worker_service_base::gateway_request::request_details::HttpRequestDetails; use golem_worker_service_base::gateway_rib_interpreter::{ DefaultRibInterpreter, EvaluationError, WorkerServiceRibInterpreter, }; @@ -1675,6 +1680,19 @@ mod internal { } } + struct TestHttpHandlerBindingHandler {} + #[async_trait] + impl HttpHandlerBindingHandler for TestHttpHandlerBindingHandler { + async fn handle_http_handler_binding( + &self, + _namespace: &Namespace, + _worker_detail: &WorkerDetail, + _request_details: &HttpRequestDetails, + ) -> HttpHandlerBindingResult { + unimplemented!() + } + } + #[derive(Debug, Clone)] pub struct DefaultResult { pub worker_name: String, @@ -1828,6 +1846,11 @@ mod internal { Arc::new(TestFileServerBindingHandler {}) } + pub fn get_test_http_handler_binding_handler( + ) -> Arc + Sync + Send> { + Arc::new(TestHttpHandlerBindingHandler {}) + } + pub fn get_preflight_from_response(response: Response) -> HttpCors { let headers = response.headers(); diff --git a/golem-worker-service/src/api/mod.rs b/golem-worker-service/src/api/mod.rs index 3755c95080..92562dfe5b 100644 --- a/golem-worker-service/src/api/mod.rs +++ b/golem-worker-service/src/api/mod.rs @@ -46,6 +46,7 @@ pub fn custom_request_route(services: &Services) -> Route { services.worker_to_http_service.clone(), services.http_definition_lookup_service.clone(), services.fileserver_binding_handler.clone(), + services.http_handler_binding_handler.clone(), services.gateway_session_store.clone(), ); diff --git a/golem-worker-service/src/service/mod.rs b/golem-worker-service/src/service/mod.rs index cedbdebf6b..e0eb4f7890 100644 --- a/golem-worker-service/src/service/mod.rs +++ b/golem-worker-service/src/service/mod.rs @@ -22,6 +22,9 @@ use golem_service_base::storage::blob::BlobStorage; use golem_service_base::storage::sqlite::SqlitePool; use golem_worker_service_base::gateway_execution::file_server_binding_handler::DefaultFileServerBindingHandler; use golem_worker_service_base::gateway_execution::file_server_binding_handler::FileServerBindingHandler; +use golem_worker_service_base::gateway_execution::http_handler_binding_handler::{ + DefaultHttpHandlerBindingHandler, HttpHandlerBindingHandler, +}; use worker_request_executor::UnauthorisedWorkerRequestExecutor; use golem_worker_service_base::gateway_api_definition::http::{ @@ -92,6 +95,8 @@ pub struct Services { Arc + Sync + Send>, pub fileserver_binding_handler: Arc + Sync + Send>, + pub http_handler_binding_handler: + Arc + Sync + Send>, } impl Services { @@ -254,6 +259,12 @@ impl Services { worker_service.clone(), )); + let http_handler_binding_handler: Arc< + dyn HttpHandlerBindingHandler + Sync + Send, + > = Arc::new(DefaultHttpHandlerBindingHandler::new( + worker_to_http_service.clone(), + )); + let api_definition_validator_service = Arc::new(HttpApiDefinitionValidator {}); let identity_provider = Arc::new(DefaultIdentityProvider); @@ -295,6 +306,7 @@ impl Services { api_definition_validator_service, fileserver_binding_handler, gateway_session_store, + http_handler_binding_handler, }) } } diff --git a/openapi/golem-service.yaml b/openapi/golem-service.yaml index dd0db86075..ef24e400fc 100644 --- a/openapi/golem-service.yaml +++ b/openapi/golem-service.yaml @@ -4062,6 +4062,7 @@ components: enum: - default - file-server + - http-handler - cors-preflight GetFilesResponse: type: object diff --git a/test-components/wasi-http-incoming-request-handler-echo/golem.yaml b/test-components/wasi-http-incoming-request-handler-echo/golem.yaml new file mode 100644 index 0000000000..ea0035e9d9 --- /dev/null +++ b/test-components/wasi-http-incoming-request-handler-echo/golem.yaml @@ -0,0 +1,7 @@ +components: + wasi-http-incoming-request-handler-echo: + sourceWit: wit + generatedWit: generated-wit + componentWasm: ../wasi-http-incoming-request-handler-echo.wasm + linkedWasm: ../wasi-http-incoming-request-handler-echo.wasm + componentType: durable From 629c34dafd9ece934d8f566ad1ce2246bb5fb4e5 Mon Sep 17 00:00:00 2001 From: Daniel Vigovszky Date: Thu, 23 Jan 2025 14:13:31 +0100 Subject: [PATCH 11/17] Update markdowns (#1260) --- CONTRIBUTING.md | 250 ++++++++++++++----------------------- README.md | 43 +------ golem-cli/Cargo.toml | 5 +- golem-cli/README.md | 38 ------ wasm-rpc-stubgen/README.md | 128 +------------------ wasm-rpc/README.md | 11 +- 6 files changed, 110 insertions(+), 365 deletions(-) delete mode 100644 golem-cli/README.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77b2cd90b8..435a01eae2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,217 +1,155 @@ -## Running integration tests +# Golem development -Install [cargo make](https://github.com/sagiegurari/cargo-make) +To work on **Golem** you need to install the following tools: -```shell -cargo install --force cargo-make -``` +- Latest **stable** rust compiler + - use [rustup](https://rustup.rs/) + - then run `rustup update stable` + - and `rustup default stable` +- Install the `wasm32-wasip1` target + - `rustup target add wasm32-wasip1` +- Install [cargo-make](https://github.com/sagiegurari/cargo-make) + - `cargo install --force cargo-make` +- The [prost crate](https://crates.io/crates/prost) requires `protoc` to be installed. + - Requires **version 28** or later + - `brew install protobuf` on OSX + - Otherwise follow the [official instructions](https://github.com/protocolbuffers/protobuf#protobuf-compiler-installation) -runs all unit tests, worker executor tests and integration tests +To be able to run all integration tests: + - Install redis + - `brew install redis` on OSX + - Install [docker](https://www.docker.com) (for running PostgreSQL container in tests) -```shell -cargo make test -``` +To be able to run all services with `cargo-make run` with a merged log view: +- Install [lnav](https://lnav.org) + - `brew install lnav` on OSX +- Install [nginx](https://nginx.org) + - `brew install nginx` on OSX -runs unit tests only +Everything else is managed by `cargo-make`. -```shell -cargo make unit-tests -``` +## Development workflow -runs worker executor tests only +### Building +To compile everything use ```shell -cargo make integration-tests +cargo make build ``` - -runs CLI tests only +It is recommended to do a full build before starting working on Golem and opening it with an IDE. During development it is usually enough to recompile only the crate you are working on, for example: ```shell -cargo make cli-tests +cargo build -p golem-worker-service-base ``` -runs sharding integration tests only +#### If cargo runs out of memory +Depending on the number of CPU cores and available memory, building everything can use a lot of memory. If cargo runs out of memory or just uses too much, you can limit the number of parallel jobs by providing a cargo `config.toml` file, for example: -```shell -cargo make sharding-tests +```toml +[build] +jobs = 4 ``` -## Running Benchmarks +in `~/.cargo/config.toml`. For other options and possibilities check [the cargo documentation](https://doc.rust-lang.org/cargo/reference/config.html). -1. Raise PR -2. Reviewer or author of PR can run benchmarks by typing in a PR comment as follows -```shell - /run-benchmark -``` +### Running tests -3. For all new benchmark types (meaning, those for which there is no baseline to compare), it should generate a report as below, as a PR comment +Tests are using the [test-r library](https://test-r.vigoo.dev). -## Benchmark Report -| Benchmark Type | Cluster Size | Size | Length | Avg Time | -|---------------|--------------|------|--------|----------| -| benchmark_cold_start_large.json | 3 | 10 | 100 | 201.255108ms | -| benchmark_cold_start_large_no_compilation.json | 3 | 10 | 100 | 123.000794122s | -| benchmark_cold_start_medium.json | 3 | 10 | 100 | 121.566283ms | -| benchmark_cold_start_medium_no_compilation.json | 3 | 10 | 100 | 178.508111048s | -| benchmark_cold_start_small.json | 3 | 10 | 100 | 75.379351ms | -| benchmark_cold_start_small_no_compilation.json | 3 | 10 | 100 | 423.142651ms | -| benchmark_durability_overhead.json | 3 | 10 | 100 | 57.51445ms | -| benchmark_latency_large.json | 3 | 10 | 100 | 61.586289ms | -| benchmark_latency_medium.json | 3 | 10 | 100 | 60.646373ms | -| benchmark_latency_small.json | 3 | 10 | 100 | 54.76123ms | -| benchmark_suspend_worker.json | 3 | 10 | 100 | 10.03030193s | - -RunID: 9435476881 - -4. The underlying data used to created the above report will be automatically pushed back to the PR branch -5. If there exists a baseline to compare for the benchmark type, then a comparison report will be generated for those benchmarks -6. If there is no need to compare with any baseline, regardless of a baseline exist or not, then simply run - -```bash - -/run-benchmark-refresh +During development you can run the involved tests in the usual ways: from the IDE, or using `cargo test` command selecting a specific crate and test module, for example: +```shell +cargo test -p golem-worker-executor-base api::promise -- --report-time ``` -7. Refresh message can be useful in the event of comparison failures (Example: A failure due to schema mismatch especially when a developer refactor the benchmark code itself) - -## Starting all services locally - -There is a simple `cargo make run` task that starts all the debug executables of the services locally, using the default configuration. The prerequisites are: - -- `nginx` installed (on OSX can be installed with `brew install nginx`) -- `redis` installed (on OSX can be installed with `brew install redis`) -- `lnav` installed (on OSX can be installed with `brew install lnav`) - -The `cargo make run` command will start all the services and show a unified view of the logs using `lnav`. Quitting `lnav` kills the spawned processes. - -## Local Testing using Docker containers - -To spin up services using the latest code - -```bash -# Clone golem -cd golem -# Find more info below if you are having issues running this command(example: Running from MAC may fail) -# Target has to be x86_64-unknown-linux-gnu or aarch64-unknown-linux-gnu-gcc -cargo build --release --target x86_64-unknown-linux-gnu +#### Running all unit tests +To run all unit tests use -docker compose -f docker-compose-sqlite.yaml up --build +```shell +cargo make unit-tests ``` -To start the service without a rebuild - -```bash - -docker compose -f docker-compose-sqlite.yaml up +#### Running all worker executor tests +The **worker executor tests** are testing the Golem Worker Executor standalone without any of the other services. These tests require `redis`. To run all of them use +```shell +cargo make worker-executor-tests ``` -To compose down, - -```bash - -docker compose -f docker-compose-sqlite.yaml down +As there are many of these tests, they are organized into **groups** that are executed in parallel on CI. You can run only a specific group with cargo make, for example: +```shell +cargo make worker-executor-tests-group1 ``` -To compose down including persistence volume - -```bash +#### Running all integration tests +The **integration tests** are starting up several Golem services and testing them together. These tests also require `docker` and `redis` to be available. -docker compose -f docker-compose-sqlite.yaml down -v +To run all integration tests use +```shell +cargo make integration-tests ``` -Note that, if you are using MAC, the persistence volumes may be present in the Linux VM. You can inspect this using the following command: - -```bash - -docker run -it --rm --privileged --pid=host alpine:latest nsenter -t 1 -m -u -n -i sh +#### Running all the CLI tests +The **CLI tests** are similar to the integration tests but interact with the running services only through the Golem CLI application. -# As an example: cd /var/lib/docker/volumes/golem-services_redis_data/_data -/var/lib/docker/volumes/golem-services_redis_data/_data # ls -lrt -total 4 --rw------- 1 999 ping 3519 Jan 19 02:32 dump.rdb -/var/lib/docker/volumes/golem-services_redis_data/_data # +To run all CLI tests use +```shell +cargo make cli-tests ``` -If you have issues running the above cargo build command, then read on: +#### Using a debugger +When using a debugger with the tests, make sure to pass the `--nocapture` option to the test runner, otherwise the debugger will not be usable (when capturing is on, the test framework spawns child processes to run the actual tests). -Make sure to do `docker-compose pull` next time to make sure you are pulling the latest images than the cached ones +### Updating the REST API +Golem **generates OpenAPI specs** from the Rust code (using the [poem-openapi crate](https://crates.io/crates/poem-openapi), and the generated OpenAPI yaml file is also stored in the repository and a Rust Client crate is generated from it, used by the CLI app and also published into crates.io. -### Cargo Build +When changing anything that affects the user facing REST API, this YAML needs to be explicitly regenerated. If this does not happen, the CI process will fail and ask for doing it. -### MAC +To regenerate the OpenAPI spec use -If you are running ` cargo build --target ARCH-unknown-linux-gnu` (cross compiling to Linux) from MAC, you may encounter -some missing dependencies. If interested, refer, https://github.com/messense/homebrew-macos-cross-toolchains +```shell +cargo make generate-openapi +``` -### Intel MAC +### Updating the config files +Service config files are also generated from code similarly to OpenAPI specs. When changing any of the service configuration data types, they have to be regeneraetd otherwise the CI process fails and asks for doing it. -Typically, the following should allow you to run it successfully. +To regenerate these files, use -```bash -brew tap messense/macos-cross-toolchains -brew install messense/macos-cross-toolchains/x86_64-unknown-linux-gnu -# If openssl is not in system -# brew install openssl -export OPENSSL_DIR=$(brew --prefix openssl) -export CC_X86_64_UNKNOWN_LINUX_GNU=x86_64-unknown-linux-gnu-gcc -export CXX_X86_64_UNKNOWN_LINUX_GNU=x86_64-unknown-linux-gnu-g++ -export AR_X86_64_UNKNOWN_LINUX_GNU=x86_64-unknown-linux-gnu-ar -export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-unknown-linux-gnu-gcc +```shell +cargo make generate-configs ``` -From the root of the project +### Preparing the pull request +Golem CI checks the pull requests with `rustfmt` and `cargo clippy`. To make sure these checks pass, before opening a pull request run -```bash -rustup target add x86_64-unknown-linux-gnu -cargo build --release --target x86_64-unknown-linux-gnu --package golem-shard-manager -cargo build --release --target x86_64-unknown-linux-gnu --package golem-component-service -cargo build --release --target x86_64-unknown-linux-gnu --package golem-worker-service -cargo build --release --target x86_64-unknown-linux-gnu --package golem-component-compilation-service -cargo build --release --target x86_64-unknown-linux-gnu --package golem-worker-executor +```shell +cargo make fix ``` -### ARM MAC +and fix any possible errors and warnings reported by it. -Typically, the following should allow you to run it successfully. +## Running Golem locally -```bash -brew tap messense/macos-cross-toolchains -brew install aarch64-unknown-linux-gnu -# If openssl is not in system -# brew install openssl -export OPENSSL_DIR=$(brew --prefix openssl) -export CC_AARCH64_UNKNOWN_LINUX_GNU=aarch64-unknown-linux-gnu-gcc -export CXX_AARCH64_UNKNOWN_LINUX_GNU=aarch64-unknown-linux-gnu-g++ -export AR_AARCH64_UNKNOWN_LINUX_GNU=aarch64-unknown-linux-gnu-ar -export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-unknown-linux-gnu-gcc -``` +There are two ways now to run Golem locally: + +### Using cargo make run -From the root of the project +By running -```bash -rustup target add aarch64-unknown-linux-gnu -cargo build --release --target aarch64-unknown-linux-gnu --package golem-shard-manager -cargo build --release --target aarch64-unknown-linux-gnu --package golem-component-service -cargo build --release --target aarch64-unknown-linux-gnu --package golem-worker-service -cargo build --release --target aarch64-unknown-linux-gnu --package golem-component-compilation-service -cargo build --release --target aarch64-unknown-linux-gnu --package golem-worker-executor +```shell +cargo make run ``` -### LINUX +all the services are going to be built and started as individual native processes, configured to communicate with each other. Beside that, an `nginx` process is going to be started to unify the various processes' HTTP APIs, and `lnav` is started to merge their logs. -From the root of the project +### Using the Single Golem Executable -```bash -rustup target add x86_64-unknown-linux-gnu -cargo build --release --target x86_64-unknown-linux-gnu --package golem-shard-manager -cargo build --release --target x86_64-unknown-linux-gnu --package golem-component-service -cargo build --release --target x86_64-unknown-linux-gnu --package golem-worker-service -cargo build --release --target x86_64-unknown-linux-gnu --package golem-component-compilation-service -cargo build --release --target x86_64-unknown-linux-gnu --package golem-worker-executor -``` +Golem now contains a **single executable** crate, called `golem`, that links all the services into a single binary. This binary is built using a regular `cargo make build` run and can be executed with +```shell +cargo run -p golem +``` diff --git a/README.md b/README.md index 05f5f64dfd..e5e8c1dd2a 100644 --- a/README.md +++ b/README.md @@ -4,45 +4,8 @@ This repository contains Golem - a set of services enable you to run WebAssembly components in a distributed cloud environment. -See [Golem Cloud](https://golem.cloud) for more information. +## Getting started with Golem +See [Golem Cloud](https://golem.cloud) for more information, and [the Golem Developer Documentation](https://learn.golem.cloud) for getting started. -## Getting Started - -It is possible to start using Golem locally by using our published Docker containers. Please refer to the document link below on how to get golem OSS running using docker. -https://learn.golem.cloud/docs/quickstart#setting-up-golem - -Once you have Golem running locally, you can use `golem-cli` to interact with Golem services. - -```bash - -cargo install golem-cli - -# component is your compiled code written in Rust, C, etc -# https://learn.golem.cloud/docs/building-templates helps you write some code and create a component - as an example -golem-cli component add --compnent-name - -# Now we need a worker corresponding from component, that can execute one of the functions in component -# If worker doesn't exist, it is created on the fly whey you invoke a function in component -golem-cli worker invoke-and-await --component-name --worker-name --function golem:it/api.{add-item} --parameters '[{"product-id" : "foo", "name" : "foo" , "price" : 10, "quantity" : 1}]' - -``` - -Internally, it is as simple as `golem-cli` using `golem-client` sending requests to Golem Services hosted in Docker container. -Therefore, you can see what's going on and troubleshoot things by inspecting docker containers. - -``` - - -+-----------------------+ +-----------------------+ -| | | | -| Use golem-cli | ---> | Golem Services | -| | | hosted in | -| commands | | Docker container | -| (Send Requests) | | | -+-----------------------+ +-----------------------+ - -``` - - -## Compiling Golem locally +## Developing Golem Find details in the [contribution guide](CONTRIBUTING.md) about how to compile the Golem services locally. diff --git a/golem-cli/Cargo.toml b/golem-cli/Cargo.toml index 1192f9ddc2..f5d556fc93 100644 --- a/golem-cli/Cargo.toml +++ b/golem-cli/Cargo.toml @@ -5,7 +5,6 @@ edition = "2021" license = "Apache-2.0" homepage = "https://golem.cloud/" repository = "https://github.com/golemcloud/golem" -readme = "README.md" description = "Command line interface for Golem." autotests = false @@ -26,7 +25,9 @@ harness = false golem-client = { path = "../golem-client", version = "=0.0.0" } golem-common = { path = "../golem-common", version = "=0.0.0", default-features = false } golem-rib = { path = "../golem-rib", version = "=0.0.0", default-features = false } -golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", default-features = false, features = ["analysis"] } +golem-wasm-ast = { path = "../wasm-ast", version = "=0.0.0", default-features = false, features = [ + "analysis", +] } golem-wasm-rpc = { path = "../wasm-rpc", version = "=0.0.0", default-features = false } golem-wasm-rpc-stubgen = { path = "../wasm-rpc-stubgen", version = "=0.0.0" } diff --git a/golem-cli/README.md b/golem-cli/README.md deleted file mode 100644 index b837a13706..0000000000 --- a/golem-cli/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# golem-cli - -Command line interface for [Golem OSS](https://golem.cloud). - -For Golem Cloud version client see [Golem Cloud CLI](https://github.com/golemcloud/golem-cloud-cli). - -## Installation - -To install `golem-cli` you currently need to use `cargo`, Rust's build tool. - -To get `cargo` on your system, we recommend to use [rustup](https://rustup.rs/): - -```shell -curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -rustup install stable -rustup default stable -``` - -Another external dependency is `protobuf`, with a minimum version of `3.15`, -which can be installed as described on http://google.github.io/proto-lens/installing-protoc.html. On macOS, you can install it with Homebrew: - -```shell -brew install protobuf -``` - -Then you can install `golem-cli` with the following command: - -```shell -cargo install golem-cli -``` - -## More information - -Please check the [Golem Cloud developer documentation portal](https://learn.golem.cloud) to learn more about how to get started with _Golem Cloud_! - -## Contributing - -Find details [here](CONTRIBUTING.md) diff --git a/wasm-rpc-stubgen/README.md b/wasm-rpc-stubgen/README.md index ffd44d10d0..b6a65efb80 100644 --- a/wasm-rpc-stubgen/README.md +++ b/wasm-rpc-stubgen/README.md @@ -1,128 +1,4 @@ # golem-wasm-rpc-stubgen -The `golem-wasm-rpc-stubgen` is a CLI tool to generate the RPC stubs from a component's WIT definition. - -## Generate - -```shell -Usage: wasm-rpc-stubgen generate [OPTIONS] --source-wit-root --dest-crate-root - -Options: - -s, --source-wit-root - -d, --dest-crate-root - -w, --world - --stub-crate-version [default: 0.0.1] - --wasm-rpc-path-override - -h, --help Print help - -V, --version Print version -``` - -- `source-wit-root`: The root directory of the component's WIT definition to be called via RPC -- `dest-crate-root`: The target path to generate a new stub crate to -- `world`: The world name to be used in the generated stub crate. If there is only a single world in the source root - package, no need to specify. -- `stub-crate-version`: The crate version of the generated stub crate -- `wasm-rpc-path-override`: The path to the `wasm-rpc` crate to be used in the generated stub crate. If not specified, - the latest version of `wasm-rpc` will be used. - -The command creates a new Rust crate that is ready to be compiled with - -```shell -cargo component build --release -``` - -The resulting WASM component implements the **stub interface** corresponding to the source interface, found in the -target directory's -`wit/stub.wit` file. This WASM component is to be composed together with another component that calls the original -interface via WASM RPC. - -## Build - -``` -Usage: wasm-rpc-stubgen build [OPTIONS] --source-wit-root --dest-wasm --dest-wit-root - -Options: - -s, --source-wit-root - --dest-wasm - --dest-wit-root - -w, --world - --stub-crate-version [default: 0.0.1] - --wasm-rpc-path-override - -h, --help Print help - -V, --version Print version -``` - -- `source-wit-root`: The root directory of the component's WIT definition to be called via RPC -- `dest-wasm`: The name of the stub WASM file to be generated -- `dest-wit-root`: The directory name where the generated WIT files should be placed -- `world`: The world name to be used in the generated stub crate. If there is only a single world in the source root - package, no need to specify. -- `stub-crate-version`: The crate version of the generated stub crate -- `wasm-rpc-path-override`: The path to the `wasm-rpc` crate to be used in the generated stub crate. If not specified, - the latest version of `wasm-rpc` will be used. It needs to be an **absolute path**. - -## Add stub WIT dependency - -```shell -Usage: wasm-rpc-stubgen add-stub-dependency [OPTIONS] --stub-wit-root --dest-wit-root - -Options: - -s, --stub-wit-root - -d, --dest-wit-root - -o, --overwrite - -u, --update-cargo-toml - -h, --help Print help - -V, --version Print version -``` - -The command merges a generated RPC stub as a WIT dependency into an other component's WIT root. - -- `stub-wit-root`: The WIT root generated by either `generate` or `build` command -- `dest-wit-root`: The WIT root of the component where the stub should be added as a dependency -- `overwrite`: This command would not do anything if it detects that it would change an existing WIT file's contents at - the destination. With this flag, it can be forced to overwrite those files. -- `update-cargo-toml`: Enables updating the Cargo.toml file in the parent directory of `dest-wit-root` with the copied dependencies. -- -## Compose the stub with the caller component - -```shell -Usage: wasm-rpc-stubgen compose --source-wasm --stub-wasm --dest-wasm - -Options: - --source-wasm - --stub-wasm - --dest-wasm - -h, --help Print help - -V, --version Print version -``` - -The command composes a caller component's WASM (which uses the generated stub to call a remote worker) with the -generated stub WASM, writing out a composed WASM which no longer depends on the stub interface, ready to use. - -- `source-wasm`: The WASM file of the caller component -- `stub-wasm`: The WASM file of the generated stub. Multiple stubs can be listed. -- `dest-wasm`: The name of the composed WASM file to be generated - - -## Initialize cargo make tasks for a workspace - -```shell -Usage: wasm-rpc-stubgen initialize-workspace [OPTIONS] --targets --callers - -Options: - --targets - List of subprojects to be called via RPC - --callers - List of subprojects using the generated stubs for calling remote workers - --wasm-rpc-path-override -``` - -When both the target and the caller components are in the same Cargo workspace, this command can initialize a `cargo-make` file with dependent tasks -performing the stub generation, WIT merging and WASM composition. - -Once the workspace is initialized, the following two commands become available: - -```shell -cargo make build-flow -cargo make release-build-flow -``` +The `golem-wasm-rpc-stubgen` is a library and CLI tool to generate the RPC stubs from a component's WIT definition +and handle Golem's application manifests. diff --git a/wasm-rpc/README.md b/wasm-rpc/README.md index 970a19ba37..0da86db3e4 100644 --- a/wasm-rpc/README.md +++ b/wasm-rpc/README.md @@ -18,19 +18,24 @@ The `golem-wasm-rpc` crate can be both used in host and guest environments: To compile the host version: ```shell -cargo build -p wasm-rpc --no-default-features --features host +cargo build -p golem-wasm-rpc --no-default-features --features host ``` To compile the guest version, has minimal dependencies and feature set to be used in generated stubs: ```shell -cargo component build -p wasm-rpc --no-default-features --features stub +cargo component build -p golem-wasm-rpc --no-default-features --features stub ``` ## Feature flags - `arbitrary` adds an `Arbitrary` instance for `Value` +- `bincode` adds Bincode codecs for some types +- `host-bindings` enables WIT-generated types for wasmtime hosts - `json` adds conversion functions for mapping of a WIT value and type definition to/from JSON +- `poem_openapi` adds poem OpenAPI type class instances for some of the types - `protobuf` adds the protobuf message types +- `serde` adds serde JSON serialization for some of the types +- `text` enables `wasm-wave` based text representation for values - `wasmtime` adds conversion to `wasmtime` `Val` values -- `host` enables all features: `arbitrary`, `json`, `protobuf`, `typeinfo`, and `wasmtime` +- `host` enables all features: `arbitrary`, `bincode`, `host-bindings`, `json`, `poem_openapi`, `protobuf`, `serde`, `text`, `typeinfo`, and `wasmtime` - `stub` is to be used in generated WASM stubs and disables all features, and generates guest bindings instead of host bindings From 81857da784e7b2e6f80dbb41bd3abb98d3026421 Mon Sep 17 00:00:00 2001 From: Afsal Thaj Date: Fri, 24 Jan 2025 19:45:50 +1100 Subject: [PATCH 12/17] Use ubuntu latest in docker (#1264) --- golem-component-compilation-service/docker/Dockerfile | 2 +- golem-component-service/docker/Dockerfile | 2 +- golem-shard-manager/docker/Dockerfile | 2 +- golem-worker-executor/docker/Dockerfile | 2 +- golem-worker-service/docker/Dockerfile | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/golem-component-compilation-service/docker/Dockerfile b/golem-component-compilation-service/docker/Dockerfile index 89636e5624..e580aae2ba 100644 --- a/golem-component-compilation-service/docker/Dockerfile +++ b/golem-component-compilation-service/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim as base +FROM ubuntu:latest as base ARG TARGETARCH diff --git a/golem-component-service/docker/Dockerfile b/golem-component-service/docker/Dockerfile index 1d988954f7..d2c406e87a 100644 --- a/golem-component-service/docker/Dockerfile +++ b/golem-component-service/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim as base +FROM ubuntu:latest as base ARG TARGETARCH diff --git a/golem-shard-manager/docker/Dockerfile b/golem-shard-manager/docker/Dockerfile index 0431445537..cc05c0c3f7 100644 --- a/golem-shard-manager/docker/Dockerfile +++ b/golem-shard-manager/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim as base +FROM ubuntu:latest as base ARG TARGETARCH diff --git a/golem-worker-executor/docker/Dockerfile b/golem-worker-executor/docker/Dockerfile index 6ffdd769c0..45ab96b7ad 100644 --- a/golem-worker-executor/docker/Dockerfile +++ b/golem-worker-executor/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim as base +FROM ubuntu:latest as base ARG TARGETARCH diff --git a/golem-worker-service/docker/Dockerfile b/golem-worker-service/docker/Dockerfile index 6cc9d89226..349d935e43 100644 --- a/golem-worker-service/docker/Dockerfile +++ b/golem-worker-service/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim as base +FROM ubuntu:latest as base ARG TARGETARCH From 0b27c9d5018893078da0c0f48f823d7111594d87 Mon Sep 17 00:00:00 2001 From: Peter Kotula Date: Mon, 27 Jan 2025 07:40:55 +0100 Subject: [PATCH 13/17] docker examples - add depends on and restart policy (#1267) * docker compose - add depends on * docker compose - restart on failure --- docker-examples/docker-compose-postgres.yaml | 16 +++++++++++++++- docker-examples/docker-compose-sqlite.yaml | 13 ++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/docker-examples/docker-compose-postgres.yaml b/docker-examples/docker-compose-postgres.yaml index 6e38ccdc74..34823b2072 100644 --- a/docker-examples/docker-compose-postgres.yaml +++ b/docker-examples/docker-compose-postgres.yaml @@ -43,6 +43,7 @@ services: golem-shard-manager: image: golemservices/golem-shard-manager:latest pull_policy: always + restart: on-failure environment: - WASMTIME_BACKTRACE_DETAILS=1 - RUST_BACKTRACE=1 @@ -58,6 +59,7 @@ services: golem-component-service: image: golemservices/golem-component-service:latest pull_policy: always + restart: on-failure environment: - ENVIRONMENT=local - WASMTIME_BACKTRACE_DETAILS=1 @@ -91,6 +93,7 @@ services: golem-worker-service: image: golemservices/golem-worker-service:latest pull_policy: always + restart: on-failure environment: - RUST_BACKTRACE=1 - RUST_LOG=info,h2=warn,hyper=warn,tower=warn @@ -121,10 +124,19 @@ services: depends_on: postgres: condition: service_healthy + redis: + condition: service_started + golem-worker-executor: + condition: service_started + golem-component-service: + condition: service_started + golem-shard-manager: + condition: service_started golem-component-compilation-service: image: golemservices/golem-component-compilation-service:latest pull_policy: always + restart: on-failure environment: - RUST_BACKTRACE=1 - RUST_LOG=info,h2=warn,hyper=warn,tower=warn @@ -147,6 +159,7 @@ services: golem-worker-executor: image: golemservices/golem-worker-executor:latest pull_policy: always + restart: on-failure environment: - ENVIRONMENT=local - WASMTIME_BACKTRACE_DETAILS=1 @@ -173,7 +186,6 @@ services: - GOLEM__PUBLIC_WORKER_API__PORT=${WORKER_SERVICE_GRPC_PORT} - GOLEM__PUBLIC_WORKER_API__ACCESS_TOKEN="2A354594-7A63-4091-A46B-CC58D379F677" - GOLEM__COMPILED_COMPONENT_SERVICE__TYPE="Enabled" - - GOLEM__SHARD_MANAGER_SERVICE__TYPE="Grpc" volumes: - worker_executor_store:/worker_executor_store @@ -181,6 +193,8 @@ services: - "${WORKER_EXECUTOR_HTTP_PORT}:${WORKER_EXECUTOR_HTTP_PORT}" depends_on: - redis + - golem-shard-manager + - golem-component-service volumes: redis_data: diff --git a/docker-examples/docker-compose-sqlite.yaml b/docker-examples/docker-compose-sqlite.yaml index b429e44921..c387001b29 100644 --- a/docker-examples/docker-compose-sqlite.yaml +++ b/docker-examples/docker-compose-sqlite.yaml @@ -26,6 +26,7 @@ services: golem-shard-manager: image: golemservices/golem-shard-manager:latest pull_policy: always + restart: on-failure environment: - WASMTIME_BACKTRACE_DETAILS=1 - RUST_BACKTRACE=1 @@ -41,6 +42,7 @@ services: golem-component-service: image: golemservices/golem-component-service:latest pull_policy: always + restart: on-failure environment: - ENVIRONMENT=local - WASMTIME_BACKTRACE_DETAILS=1 @@ -67,6 +69,7 @@ services: golem-worker-service: image: golemservices/golem-worker-service:latest pull_policy: always + restart: on-failure environment: - RUST_BACKTRACE=1 - RUST_LOG=info,h2=warn,hyper=warn,tower=warn @@ -91,10 +94,16 @@ services: - "${WORKER_SERVICE_GRPC_PORT}:${WORKER_SERVICE_GRPC_PORT}" volumes: - golem_db:/app/golem_db + depends_on: + - redis + - golem-worker-executor + - golem-component-service + - golem-shard-manager golem-component-compilation-service: image: golemservices/golem-component-compilation-service:latest pull_policy: always + restart: on-failure environment: - RUST_BACKTRACE=1 - RUST_LOG=info,h2=warn,hyper=warn,tower=warn @@ -117,6 +126,7 @@ services: golem-worker-executor: image: golemservices/golem-worker-executor:latest pull_policy: always + restart: on-failure environment: - ENVIRONMENT=local - WASMTIME_BACKTRACE_DETAILS=1 @@ -143,7 +153,6 @@ services: - GOLEM__PUBLIC_WORKER_API__PORT=${WORKER_SERVICE_GRPC_PORT} - GOLEM__PUBLIC_WORKER_API__ACCESS_TOKEN="2A354594-7A63-4091-A46B-CC58D379F677" - GOLEM__COMPILED_COMPONENT_SERVICE__TYPE="Enabled" - - GOLEM__SHARD_MANAGER_SERVICE__TYPE="Grpc" volumes: - worker_executor_store:/worker_executor_store @@ -151,6 +160,8 @@ services: - "${WORKER_EXECUTOR_HTTP_PORT}:${WORKER_EXECUTOR_HTTP_PORT}" depends_on: - redis + - golem-shard-manager + - golem-component-service volumes: redis_data: From a6f0729adbdd48dab7bbd220c07137a119383855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Mon, 27 Jan 2025 09:46:42 +0100 Subject: [PATCH 14/17] Fixes for "cargo make build" and "cargo make check" on windows (#1266) --- Cargo.lock | 49 +++++++++++++++++++------ Cargo.toml | 3 +- golem-cli/Cargo.toml | 2 +- golem-worker-executor-base/Cargo.toml | 1 + golem-worker-executor-base/tests/api.rs | 2 +- golem/Cargo.toml | 7 ++-- golem/src/command.rs | 13 +++++-- golem/src/launch.rs | 5 +-- golem/src/proxy.rs | 28 ++++++++++++-- 9 files changed, 82 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 88214a2566..2a008e5e71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2641,6 +2641,15 @@ dependencies = [ "dirs-sys 0.4.1", ] +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs-next" version = "2.0.0" @@ -2658,7 +2667,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" dependencies = [ "libc", - "redox_users", + "redox_users 0.4.6", "winapi", ] @@ -2670,10 +2679,22 @@ checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" dependencies = [ "libc", "option-ext", - "redox_users", + "redox_users 0.4.6", "windows-sys 0.48.0", ] +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.5.0", + "windows-sys 0.59.0", +] + [[package]] name = "dirs-sys-next" version = "0.1.2" @@ -2681,7 +2702,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" dependencies = [ "libc", - "redox_users", + "redox_users 0.4.6", "winapi", ] @@ -3559,6 +3580,7 @@ dependencies = [ "anyhow", "bytes 1.9.0", "clap", + "dirs 6.0.0", "futures", "golem-cli", "golem-common", @@ -3590,7 +3612,6 @@ dependencies = [ "test-r", "tokio", "tracing", - "xdg", ] [[package]] @@ -3632,7 +3653,7 @@ dependencies = [ "cli-table", "colored", "derive_more", - "dirs 5.0.1", + "dirs 6.0.0", "env_logger 0.11.6", "futures-util", "glob", @@ -4286,6 +4307,7 @@ dependencies = [ "serde_json", "sqlx", "sysinfo", + "system-interface", "tempfile", "test-r", "testcontainers", @@ -7880,6 +7902,17 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "redox_users" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" +dependencies = [ + "getrandom", + "libredox", + "thiserror 2.0.11", +] + [[package]] name = "regalloc2" version = "0.10.2" @@ -12219,12 +12252,6 @@ dependencies = [ "rustix", ] -[[package]] -name = "xdg" -version = "2.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213b7324336b53d2414b2db8537e56544d981803139155afa84f76eeebb7a546" - [[package]] name = "xdg-home" version = "1.3.0" diff --git a/Cargo.toml b/Cargo.toml index be254b5ca0..f9ba0fafde 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -100,6 +100,7 @@ console-subscriber = "0.4.1" ctor = "0.2.9" dashmap = "6.1.0" derive_more = { version = "1.0.0", features = ["display", "into", "from_str"] } +dirs = "6.0.0" drop-stream = "0.3.2" figment = { version = "0.10.19", features = ["toml", "env"] } fred = { version = "=9.4.0", features = [ @@ -178,6 +179,7 @@ sqlx = { version = "0.8", features = [ ] } strum = "0.26.3" strum_macros = "0.26.4" +system-interface = "0.27.3" tap = "1.0.1" tempfile = "3.14.0" testcontainers = { version = "0.23.1" } @@ -223,7 +225,6 @@ wasmtime = { version = "=27.0.0", features = ["component-model"] } wasmtime-wasi = { version = "=27.0.0" } wasmtime-wasi-http = { version = "=27.0.0" } webpki-roots = { version = "0.26.7" } -xdg = "2.5.2" [patch.crates-io] redis-protocol = { git = "https://github.com/golemcloud/redis-protocol.rs.git", branch = "unpin-cookie-factory" } diff --git a/golem-cli/Cargo.toml b/golem-cli/Cargo.toml index f5d556fc93..d2e702a36f 100644 --- a/golem-cli/Cargo.toml +++ b/golem-cli/Cargo.toml @@ -43,7 +43,7 @@ clap_complete = { version = "4.5.38" } cli-table = { workspace = true } colored = "2.1.0" derive_more = { workspace = true } -dirs = "5.0.1" +dirs = { workspace = true } futures-util = { workspace = true } glob = "0.3.1" golem-examples = "=1.1.1" diff --git a/golem-worker-executor-base/Cargo.toml b/golem-worker-executor-base/Cargo.toml index 73b71188ad..ff0ed7e3d0 100644 --- a/golem-worker-executor-base/Cargo.toml +++ b/golem-worker-executor-base/Cargo.toml @@ -108,6 +108,7 @@ testcontainers = { workspace = true } testcontainers-modules = { workspace = true } test-r = { workspace = true } tracing-subscriber = { workspace = true } +system-interface = { workspace = true } [build-dependencies] cargo_metadata = "0.19.1" diff --git a/golem-worker-executor-base/tests/api.rs b/golem-worker-executor-base/tests/api.rs index 99fd5fa56a..cb56771843 100644 --- a/golem-worker-executor-base/tests/api.rs +++ b/golem-worker-executor-base/tests/api.rs @@ -39,10 +39,10 @@ use std::collections::HashMap; use std::env; use std::io::Write; use std::net::SocketAddr; -use std::os::unix::fs::FileExt; use std::path::Path; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use system_interface::fs::FileIoExt; use tokio::time::sleep; use tracing::{debug, info}; use wasmtime_wasi::runtime::spawn; diff --git a/golem/Cargo.toml b/golem/Cargo.toml index aafe519884..1337628bdf 100644 --- a/golem/Cargo.toml +++ b/golem/Cargo.toml @@ -32,6 +32,7 @@ golem-worker-service-base = { path = "../golem-worker-service-base", version = " anyhow = { workspace = true } bytes = { workspace = true } clap = { workspace = true } +dirs = { workspace = true } http-body-util = "0.1.2" hyper = { workspace = true } futures = { workspace = true } @@ -49,15 +50,15 @@ sqlx = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } -xdg = { workspace = true } # Sozu builds with simd support by default, but it only works on x86_64 +# Sozu does not support windows, until we find an alternative we exclude suzo deps, and build a dummy binary -[target.'cfg(target_arch = "x86_64")'.dependencies] +[target.'cfg(all(target_arch = "x86_64", not(windows)))'.dependencies] sozu-command-lib = { workspace = true } sozu-lib = { workspace = true } -[target.'cfg(not(target_arch = "x86_64"))'.dependencies] +[target.'cfg(all(not(target_arch = "x86_64"), not(windows)))'.dependencies] sozu-command-lib = { workspace = true, default-features = false } sozu-lib = { workspace = true, default-features = false } diff --git a/golem/src/command.rs b/golem/src/command.rs index 6676ea9ded..b863583b87 100644 --- a/golem/src/command.rs +++ b/golem/src/command.rs @@ -56,10 +56,15 @@ impl CliCommand for SingleExecutableCommand { data_dir, clean, } => { - let base_directories = xdg::BaseDirectories::with_prefix("golem") - .map_err(|_| GolemError("Failed to get XDG base directories".to_string()))?; - - let data_dir = data_dir.unwrap_or_else(|| base_directories.get_state_home()); + let data_dir = { + if let Some(data_dir) = data_dir { + data_dir + } else { + dirs::data_local_dir() + .ok_or_else(|| GolemError("Failed to get data dir".to_string()))? + .join("golem") + } + }; if clean && tokio::fs::metadata(&data_dir).await.is_ok() { tokio::fs::remove_dir_all(&data_dir) diff --git a/golem/src/launch.rs b/golem/src/launch.rs index 7ad4a00d67..748291452c 100644 --- a/golem/src/launch.rs +++ b/golem/src/launch.rs @@ -14,6 +14,7 @@ use crate::health; use crate::migration::IncludedMigrationsDir; +use crate::proxy; use crate::AllRunDetails; use anyhow::Context; use golem_common::config::DbConfig; @@ -46,8 +47,6 @@ use tokio::runtime::Handle; use tokio::task::JoinSet; use tracing::Instrument; -use crate::proxy; - pub struct LaunchArgs { pub router_host: String, pub router_port: u16, @@ -195,7 +194,7 @@ fn worker_executor_config( ..ComponentServiceGrpcConfig::default() } ), - compiled_component_service: CompiledComponentServiceConfig::Disabled(golem_worker_executor_base::services::golem_config::CompiledComponentServiceDisabledConfig { }), + compiled_component_service: CompiledComponentServiceConfig::Disabled(golem_worker_executor_base::services::golem_config::CompiledComponentServiceDisabledConfig {}), shard_manager_service: ShardManagerServiceConfig::Grpc(ShardManagerServiceGrpcConfig { host: args.router_host.clone(), port: shard_manager_run_details.grpc_port, diff --git a/golem/src/proxy.rs b/golem/src/proxy.rs index 01a79b1c25..4cfb4866ae 100644 --- a/golem/src/proxy.rs +++ b/golem/src/proxy.rs @@ -12,8 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::AllRunDetails; +use tokio::task::JoinSet; +use tracing::info; + +#[cfg(not(windows))] use anyhow::Context; +#[cfg(not(windows))] use sozu_command_lib::proto::command::WorkerResponse; +#[cfg(not(windows))] use sozu_command_lib::{ channel::Channel, config::ListenerBuilder, @@ -22,12 +29,10 @@ use sozu_command_lib::{ RequestHttpFrontend, RulePosition, SocketAddress, WorkerRequest, }, }; +#[cfg(not(windows))] use std::net::Ipv4Addr; -use tokio::task::JoinSet; -use tracing::info; - -use crate::AllRunDetails; +#[cfg(not(windows))] pub fn start_proxy( listener_addr: &str, listener_port: u16, @@ -163,3 +168,18 @@ pub fn start_proxy( Ok(command_channel) } + +#[cfg(windows)] +pub struct Dummy; + +#[cfg(windows)] +pub fn start_proxy( + _listener_addr: &str, + _listener_port: u16, + _healthcheck_port: u16, + _all_run_details: &AllRunDetails, + _join_set: &mut JoinSet>, +) -> Result { + info!("Proxy is not supported on windows yet"); + Ok(Dummy) +} From 40d35d2f928f41e69c8ff3c123310714ffa5e2b6 Mon Sep 17 00:00:00 2001 From: Peter Kotula Date: Mon, 27 Jan 2025 09:47:17 +0100 Subject: [PATCH 15/17] kube - fix redis config for shard manager and worker service (#1268) Co-authored-by: Daniel Vigovszky --- kube/golem-chart/templates/deployment.yaml | 43 +++++++++++++++++----- kube/golem-chart/values.yaml | 11 ++++++ 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/kube/golem-chart/templates/deployment.yaml b/kube/golem-chart/templates/deployment.yaml index 9b122b691e..9b3f7b217a 100644 --- a/kube/golem-chart/templates/deployment.yaml +++ b/kube/golem-chart/templates/deployment.yaml @@ -30,26 +30,26 @@ spec: env: - name: ENVIRONMENT value: {{.Values.env}} - - name: REDIS_HOST + - name: GOLEM__PERSISTENCE__TYPE + value: "Redis" + - name: GOLEM__PERSISTENCE__CONFIG__HOST value: {{ .Values.shardManager.redis.host }} - - name: GOLEM__REDIS__KEY_PREFIX + - name: GOLEM__PERSISTENCE__CONFIG__KEY_PREFIX value: {{.Values.env}} - - name: GOLEM__REDIS__HOST - value: {{ .Values.shardManager.redis.host }} - - name: GOLEM__REDIS__PORT + - name: GOLEM__PERSISTENCE__CONFIG__PORT value: "{{ .Values.shardManager.redis.port }}" - - name: GOLEM__REDIS__DATABASE + - name: GOLEM__PERSISTENCE__CONFIG__DATABASE value: "{{ .Values.shardManager.redis.database }}" {{- if .Values.shardManager.redis.username }} - - name: GOLEM__REDIS__USERNAME + - name: GOLEM__PERSISTENCE__CONFIG__USERNAME value: "{{ .Values.shardManager.redis.username }}" {{- end }} {{- if eq .Values.shardManager.redis.password.type "plain" }} - - name: GOLEM__REDIS__PASSWORD + - name: GOLEM__PERSISTENCE__CONFIG__PASSWORD value: "{{ .Values.shardManager.redis.password.plain }}" {{- end }} {{- if eq .Values.shardManager.redis.password.type "secret" }} - - name: GOLEM__REDIS__PASSWORD + - name: GOLEM__PERSISTENCE__CONFIG__PASSWORD valueFrom: secretKeyRef: name: {{ .Values.shardManager.redis.password.secret.name }} @@ -304,6 +304,31 @@ spec: value: "{{ .Values.workerService.postgres.port }}" - name: GOLEM__DB__CONFIG__USERNAME value: {{ .Values.workerService.postgres.username }} + - name: GOLEM__GATEWAY_SESSION_STORAGE__TYPE + value: "Redis" + - name: GOLEM__GATEWAY_SESSION_STORAGE__CONFIG__HOST + value: {{ .Values.workerService.redis.host }} + - name: GOLEM__GATEWAY_SESSION_STORAGE__CONFIG__KEY_PREFIX + value: {{.Values.env}} + - name: GOLEM__GATEWAY_SESSION_STORAGE__CONFIG__PORT + value: "{{ .Values.workerService.redis.port }}" + - name: GOLEM__GATEWAY_SESSION_STORAGE__CONFIG__DATABASE + value: "{{ .Values.workerService.redis.database }}" + {{- if .Values.workerService.redis.username }} + - name: GOLEM__GATEWAY_SESSION_STORAGE__CONFIG__USERNAME + value: "{{ .Values.workerService.redis.username }}" + {{- end }} + {{- if eq .Values.workerService.redis.password.type "plain" }} + - name: GOLEM__GATEWAY_SESSION_STORAGE__CONFIG__PASSWORD + value: "{{ .Values.workerService.redis.password.plain }}" + {{- end }} + {{- if eq .Values.workerService.redis.password.type "secret" }} + - name: GOLEM__GATEWAY_SESSION_STORAGE__CONFIG__PASSWORD + valueFrom: + secretKeyRef: + name: {{ .Values.workerService.redis.password.secret.name }} + key: {{ .Values.workerService.redis.password.secret.key }} + {{- end }} - name: WASMTIME_BACKTRACE_DETAILS value: "1" - name: RUST_BACKTRACE diff --git a/kube/golem-chart/values.yaml b/kube/golem-chart/values.yaml index a3a6bcb270..3ed853e465 100644 --- a/kube/golem-chart/values.yaml +++ b/kube/golem-chart/values.yaml @@ -68,6 +68,17 @@ workerService: secret: # password from kubernetes secret name: golem-postgres-postgresql key: password + redis: + port: 6379 + host: golem-redis-master + username: "" + database: 0 + password: + type: secret # secret or plain, or none if no auth + plain: "" + secret: # password from kubernetes secret + name: golem-redis + key: redis-password # nodeSelector: # added, if defined, see: https://kubernetes.io/docs/tasks/configure-pod-container/assign-pods-nodes/ # component service configuration From bafdfe449a507c76548f489eaae6b19f948bbcac Mon Sep 17 00:00:00 2001 From: Afsal Thaj Date: Mon, 27 Jan 2025 20:02:12 +0800 Subject: [PATCH 16/17] Add fork as a host function (#1255) * Add fork * Fix durability package * Update to api1_1_1 * Add fork function * Update v11.rs Co-authored-by: Daniel Vigovszky * Depend on golem-wit 1.1.7 * Reformat and run clippy --------- Co-authored-by: Daniel Vigovszky --- Cargo.lock | 4 +- Cargo.toml | 2 +- golem-worker-executor-base/build.rs | 6 +- .../src/durable_host/durability.rs | 91 ++++++++----------- .../src/durable_host/golem/v11.rs | 87 +++++++++++++----- .../src/model/public_oplog/wit.rs | 2 +- .../src/services/worker_proxy.rs | 48 +++++++++- .../tests/common/mod.rs | 8 +- golem-worker-executor/src/lib.rs | 8 +- 9 files changed, 162 insertions(+), 94 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2a008e5e71..5bd6d3fa20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4200,9 +4200,9 @@ dependencies = [ [[package]] name = "golem-wit" -version = "1.1.2" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf53fc25db491f96c480d7f195175f6da5f18dcc6ef548d04b2ae648b7796bbf" +checksum = "04cb9d855d8604587ccf16a402f759ee6e85b555201b6d6b1c9f0764a0fbc6d2" [[package]] name = "golem-worker-executor" diff --git a/Cargo.toml b/Cargo.toml index f9ba0fafde..a9e18f52b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -113,7 +113,7 @@ futures = "0.3" futures-core = "0.3.31" futures-util = "0.3.31" git-version = "0.3.9" -golem-wit = { version = "=1.1.2" } +golem-wit = { version = "=1.1.7" } hex = "0.4.3" http = "1.2.0" # keep in sync with wasmtime http-body = "1.0.1" # keep in sync with wasmtime diff --git a/golem-worker-executor-base/build.rs b/golem-worker-executor-base/build.rs index f48566249e..e234ce8b30 100644 --- a/golem-worker-executor-base/build.rs +++ b/golem-worker-executor-base/build.rs @@ -64,9 +64,9 @@ fn preview2_mod_gen(golem_wit_path: &str) -> String { world golem {{ import golem:api/host@0.2.0; - import golem:api/host@1.1.0; - import golem:api/oplog@1.1.0; - import golem:api/durability@1.2.0; + import golem:api/host@1.1.1; + import golem:api/oplog@1.1.1; + import golem:durability/durability@1.2.0; import wasi:blobstore/blobstore; import wasi:blobstore/container; diff --git a/golem-worker-executor-base/src/durable_host/durability.rs b/golem-worker-executor-base/src/durable_host/durability.rs index ab0807cedb..a8cbdc4a79 100644 --- a/golem-worker-executor-base/src/durable_host/durability.rs +++ b/golem-worker-executor-base/src/durable_host/durability.rs @@ -17,7 +17,7 @@ use crate::error::GolemError; use crate::metrics::wasm::record_host_function_call; use crate::model::PersistenceLevel; use crate::preview2::golem; -use crate::preview2::golem::api1_2_0; +use crate::preview2::golem::durability::durability; use crate::services::oplog::{CommitLevel, OplogOps}; use crate::workerctx::WorkerCtx; use async_trait::async_trait; @@ -105,62 +105,48 @@ pub trait DurabilityHost { ) -> Result; } -impl From for DurableFunctionType { - fn from(value: api1_2_0::durability::DurableFunctionType) -> Self { +impl From for DurableFunctionType { + fn from(value: durability::DurableFunctionType) -> Self { match value { - api1_2_0::durability::DurableFunctionType::WriteRemote => { - DurableFunctionType::WriteRemote - } - api1_2_0::durability::DurableFunctionType::WriteLocal => { - DurableFunctionType::WriteLocal - } - api1_2_0::durability::DurableFunctionType::WriteRemoteBatched(oplog_index) => { + durability::DurableFunctionType::WriteRemote => DurableFunctionType::WriteRemote, + durability::DurableFunctionType::WriteLocal => DurableFunctionType::WriteLocal, + durability::DurableFunctionType::WriteRemoteBatched(oplog_index) => { DurableFunctionType::WriteRemoteBatched(oplog_index.map(OplogIndex::from_u64)) } - api1_2_0::durability::DurableFunctionType::ReadRemote => { - DurableFunctionType::ReadRemote - } - api1_2_0::durability::DurableFunctionType::ReadLocal => DurableFunctionType::ReadLocal, + durability::DurableFunctionType::ReadRemote => DurableFunctionType::ReadRemote, + durability::DurableFunctionType::ReadLocal => DurableFunctionType::ReadLocal, } } } -impl From for api1_2_0::durability::DurableFunctionType { +impl From for durability::DurableFunctionType { fn from(value: DurableFunctionType) -> Self { match value { - DurableFunctionType::WriteRemote => { - api1_2_0::durability::DurableFunctionType::WriteRemote - } - DurableFunctionType::WriteLocal => { - api1_2_0::durability::DurableFunctionType::WriteLocal - } + DurableFunctionType::WriteRemote => durability::DurableFunctionType::WriteRemote, + DurableFunctionType::WriteLocal => durability::DurableFunctionType::WriteLocal, DurableFunctionType::WriteRemoteBatched(oplog_index) => { - api1_2_0::durability::DurableFunctionType::WriteRemoteBatched( + durability::DurableFunctionType::WriteRemoteBatched( oplog_index.map(|idx| idx.into()), ) } - DurableFunctionType::ReadRemote => { - api1_2_0::durability::DurableFunctionType::ReadRemote - } - DurableFunctionType::ReadLocal => api1_2_0::durability::DurableFunctionType::ReadLocal, + DurableFunctionType::ReadRemote => durability::DurableFunctionType::ReadRemote, + DurableFunctionType::ReadLocal => durability::DurableFunctionType::ReadLocal, } } } -impl From for api1_2_0::durability::OplogEntryVersion { +impl From for durability::OplogEntryVersion { fn from(value: OplogEntryVersion) -> Self { match value { - OplogEntryVersion::V1 => api1_2_0::durability::OplogEntryVersion::V1, - OplogEntryVersion::V2 => api1_2_0::durability::OplogEntryVersion::V2, + OplogEntryVersion::V1 => durability::OplogEntryVersion::V1, + OplogEntryVersion::V2 => durability::OplogEntryVersion::V2, } } } -impl From - for api1_2_0::durability::PersistedDurableFunctionInvocation -{ +impl From for durability::PersistedDurableFunctionInvocation { fn from(value: PersistedDurableFunctionInvocation) -> Self { - api1_2_0::durability::PersistedDurableFunctionInvocation { + durability::PersistedDurableFunctionInvocation { timestamp: value.timestamp.into(), function_name: value.function_name, response: value.response, @@ -171,7 +157,7 @@ impl From } #[async_trait] -impl api1_2_0::durability::Host for DurableWorkerCtx { +impl durability::Host for DurableWorkerCtx { async fn observe_function_call( &mut self, iface: String, @@ -183,16 +169,17 @@ impl api1_2_0::durability::Host for DurableWorkerCtx { async fn begin_durable_function( &mut self, - function_type: api1_2_0::durability::DurableFunctionType, - ) -> anyhow::Result { + function_type: durability::DurableFunctionType, + ) -> anyhow::Result { let oplog_idx = DurabilityHost::begin_durable_function(self, &function_type.into()).await?; Ok(oplog_idx.into()) } async fn end_durable_function( &mut self, - function_type: api1_2_0::durability::DurableFunctionType, - begin_index: api1_2_0::durability::OplogIndex, + function_type: durability::DurableFunctionType, + begin_index: durability::OplogIndex, + _forced_commit: bool, ) -> anyhow::Result<()> { DurabilityHost::end_durable_function( self, @@ -205,11 +192,11 @@ impl api1_2_0::durability::Host for DurableWorkerCtx { async fn current_durable_execution_state( &mut self, - ) -> anyhow::Result { + ) -> anyhow::Result { let state = DurabilityHost::durable_execution_state(self); let persistence_level: golem::api0_2_0::host::PersistenceLevel = state.persistence_level.into(); - Ok(api1_2_0::durability::DurableExecutionState { + Ok(durability::DurableExecutionState { is_live: state.is_live, persistence_level: persistence_level.into(), }) @@ -220,7 +207,7 @@ impl api1_2_0::durability::Host for DurableWorkerCtx { function_name: String, request: Vec, response: Vec, - function_type: api1_2_0::durability::DurableFunctionType, + function_type: durability::DurableFunctionType, ) -> anyhow::Result<()> { DurabilityHost::persist_durable_function_invocation( self, @@ -236,21 +223,19 @@ impl api1_2_0::durability::Host for DurableWorkerCtx { async fn persist_typed_durable_function_invocation( &mut self, function_name: String, - request: api1_2_0::durability::ValueAndType, - response: api1_2_0::durability::ValueAndType, - function_type: api1_2_0::durability::DurableFunctionType, + request: durability::ValueAndType, + response: durability::ValueAndType, + function_type: durability::DurableFunctionType, ) -> anyhow::Result<()> { let request = unsafe { - transmute::< - api1_2_0::durability::ValueAndType, - golem_wasm_rpc::golem::rpc::types::ValueAndType, - >(request) + transmute::( + request, + ) }; let response = unsafe { - transmute::< - api1_2_0::durability::ValueAndType, - golem_wasm_rpc::golem::rpc::types::ValueAndType, - >(response) + transmute::( + response, + ) }; DurabilityHost::persist_typed_durable_function_invocation( self, @@ -265,7 +250,7 @@ impl api1_2_0::durability::Host for DurableWorkerCtx { async fn read_persisted_durable_function_invocation( &mut self, - ) -> anyhow::Result { + ) -> anyhow::Result { let invocation = DurabilityHost::read_persisted_durable_function_invocation(self).await?; Ok(invocation.into()) } diff --git a/golem-worker-executor-base/src/durable_host/golem/v11.rs b/golem-worker-executor-base/src/durable_host/golem/v11.rs index f7971cf027..765af02805 100644 --- a/golem-worker-executor-base/src/durable_host/golem/v11.rs +++ b/golem-worker-executor-base/src/durable_host/golem/v11.rs @@ -12,26 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::durable_host::{DurabilityHost, DurableWorkerCtx}; +use crate::durable_host::serialized::SerializableError; +use crate::durable_host::{Durability, DurabilityHost, DurableWorkerCtx}; use crate::model::public_oplog::{ find_component_version_at, get_public_oplog_chunk, search_public_oplog, }; use crate::preview2::golem; use crate::preview2::golem::api0_2_0::host::GetWorkers; -use crate::preview2::golem::api1_1_0::host::{ +use crate::preview2::golem::api1_1_1::host::{ ComponentId, ComponentVersion, FilterComparator, Host, HostGetWorkers, OplogIndex, PersistenceLevel, PromiseId, RetryPolicy, StringFilterComparator, UpdateMode, Uuid, WorkerAllFilter, WorkerAnyFilter, WorkerCreatedAtFilter, WorkerEnvFilter, WorkerId, WorkerMetadata, WorkerNameFilter, WorkerPropertyFilter, WorkerStatus, WorkerStatusFilter, WorkerVersionFilter, }; -use crate::preview2::golem::api1_1_0::oplog::{ +use crate::preview2::golem::api1_1_1::oplog::{ Host as OplogHost, HostGetOplog, HostSearchOplog, OplogEntry, SearchOplog, }; use crate::services::{HasOplogService, HasPlugins}; use crate::workerctx::WorkerCtx; use anyhow::anyhow; use async_trait::async_trait; +use golem_common::model::oplog::DurableFunctionType; use golem_common::model::OwnedWorkerId; use golem_common::model::RetryConfig; use std::time::Duration; @@ -180,14 +182,55 @@ impl Host for DurableWorkerCtx { .await .map(|x| x.map(|x| x.into())) } + + async fn fork_worker( + &mut self, + source_worker_id: WorkerId, + target_worker_id: WorkerId, + oplog_idx_cut_off: OplogIndex, + ) -> anyhow::Result<()> { + let durability = Durability::<(), SerializableError>::new( + self, + "golem::api", + "fork_worker", + DurableFunctionType::WriteRemote, + ) + .await?; + + let source_worker_id: golem_common::model::WorkerId = source_worker_id.into(); + + let target_worker_id: golem_common::model::WorkerId = target_worker_id.into(); + + let oplog_index_cut_off: golem_common::model::oplog::OplogIndex = + golem_common::model::oplog::OplogIndex::from_u64(oplog_idx_cut_off); + + if durability.is_live() { + let result = self + .state + .worker_proxy + .fork_worker(&source_worker_id, &target_worker_id, &oplog_index_cut_off) + .await; + durability + .persist( + self, + (source_worker_id, target_worker_id, oplog_idx_cut_off), + result, + ) + .await + } else { + durability.replay(self).await + }?; + + Ok(()) + } } #[async_trait] impl HostGetOplog for DurableWorkerCtx { async fn new( &mut self, - worker_id: crate::preview2::golem::api1_1_0::oplog::WorkerId, - start: crate::preview2::golem::api1_1_0::oplog::OplogIndex, + worker_id: crate::preview2::golem::api1_1_1::oplog::WorkerId, + start: crate::preview2::golem::api1_1_1::oplog::OplogIndex, ) -> anyhow::Result> { self.observe_function_call("golem::api::get-oplog", "new"); @@ -289,7 +332,7 @@ impl crate::durable_host::golem::v11::GetOplogEntry { impl HostSearchOplog for DurableWorkerCtx { async fn new( &mut self, - worker_id: golem::api1_1_0::oplog::WorkerId, + worker_id: golem::api1_1_1::oplog::WorkerId, text: String, ) -> anyhow::Result> { self.observe_function_call("golem::api::search-oplog", "new"); @@ -311,7 +354,7 @@ impl HostSearchOplog for DurableWorkerCtx { async fn get_next( &mut self, self_: Resource, - ) -> anyhow::Result>> { + ) -> anyhow::Result>> { self.observe_function_call("golem::api::search-oplog", "get-next"); let component_service = self.state.component_service.clone(); @@ -343,7 +386,7 @@ impl HostSearchOplog for DurableWorkerCtx { .entries .into_iter() .map(|(idx, entry)| { - let idx: golem::api1_1_0::oplog::OplogIndex = idx.into(); + let idx: golem::api1_1_1::oplog::OplogIndex = idx.into(); let entry: OplogEntry = entry.into(); (idx, entry) }) @@ -705,17 +748,17 @@ impl From for golem::api0_2_0::host::WorkerAnyFilter { } } -impl From for golem::api1_1_0::host::WorkerId { +impl From for golem::api1_1_1::host::WorkerId { fn from(worker_id: golem_common::model::WorkerId) -> Self { - golem::api1_1_0::host::WorkerId { + golem::api1_1_1::host::WorkerId { component_id: worker_id.component_id.into(), worker_name: worker_id.worker_name, } } } -impl From for golem_common::model::WorkerId { - fn from(host: golem::api1_1_0::host::WorkerId) -> Self { +impl From for golem_common::model::WorkerId { + fn from(host: golem::api1_1_1::host::WorkerId) -> Self { Self { component_id: host.component_id.into(), worker_name: host.worker_name, @@ -723,8 +766,8 @@ impl From for golem_common::model::WorkerId { } } -impl From for golem_common::model::ComponentId { - fn from(host: golem::api1_1_0::host::ComponentId) -> Self { +impl From for golem_common::model::ComponentId { + fn from(host: golem::api1_1_1::host::ComponentId) -> Self { let high_bits = host.uuid.high_bits; let low_bits = host.uuid.low_bits; @@ -732,12 +775,12 @@ impl From for golem_common::model::Component } } -impl From for golem::api1_1_0::host::ComponentId { +impl From for golem::api1_1_1::host::ComponentId { fn from(component_id: golem_common::model::ComponentId) -> Self { let (high_bits, low_bits) = component_id.0.as_u64_pair(); - golem::api1_1_0::host::ComponentId { - uuid: golem::api1_1_0::host::Uuid { + golem::api1_1_1::host::ComponentId { + uuid: golem::api1_1_1::host::Uuid { high_bits, low_bits, }, @@ -745,17 +788,17 @@ impl From for golem::api1_1_0::host::Component } } -impl From for golem::api1_1_0::host::PromiseId { +impl From for golem::api1_1_1::host::PromiseId { fn from(promise_id: golem_common::model::PromiseId) -> Self { - golem::api1_1_0::host::PromiseId { + golem::api1_1_1::host::PromiseId { worker_id: promise_id.worker_id.into(), oplog_idx: promise_id.oplog_idx.into(), } } } -impl From for golem_common::model::PromiseId { - fn from(host: golem::api1_1_0::host::PromiseId) -> Self { +impl From for golem_common::model::PromiseId { + fn from(host: golem::api1_1_1::host::PromiseId) -> Self { Self { worker_id: host.worker_id.into(), oplog_idx: golem_common::model::oplog::OplogIndex::from_u64(host.oplog_idx), @@ -763,7 +806,7 @@ impl From for golem_common::model::PromiseId { } } -impl From<&RetryConfig> for crate::preview2::golem::api1_1_0::host::RetryPolicy { +impl From<&RetryConfig> for crate::preview2::golem::api1_1_1::host::RetryPolicy { fn from(value: &RetryConfig) -> Self { Self { max_attempts: value.max_attempts, diff --git a/golem-worker-executor-base/src/model/public_oplog/wit.rs b/golem-worker-executor-base/src/model/public_oplog/wit.rs index e64ace1606..5ff38c3627 100644 --- a/golem-worker-executor-base/src/model/public_oplog/wit.rs +++ b/golem-worker-executor-base/src/model/public_oplog/wit.rs @@ -13,7 +13,7 @@ // limitations under the License. use crate::model::public_oplog::{PublicOplogEntry, PublicUpdateDescription}; -use crate::preview2::golem::api1_1_0::oplog; +use crate::preview2::golem::api1_1_1::oplog; use crate::preview2::wasi::clocks::wall_clock::Datetime; use golem_common::model::public_oplog::{ ActivatePluginParameters, ChangeRetryPolicyParameters, CreateParameters, diff --git a/golem-worker-executor-base/src/services/worker_proxy.rs b/golem-worker-executor-base/src/services/worker_proxy.rs index 97c56d438f..fa6ebef30b 100644 --- a/golem-worker-executor-base/src/services/worker_proxy.rs +++ b/golem-worker-executor-base/src/services/worker_proxy.rs @@ -18,13 +18,14 @@ use async_trait::async_trait; use bincode::{Decode, Encode}; use golem_api_grpc::proto::golem::worker::v1::worker_service_client::WorkerServiceClient; use golem_api_grpc::proto::golem::worker::v1::{ - invoke_and_await_typed_response, invoke_response, resume_worker_response, - update_worker_response, worker_error, InvokeAndAwaitRequest, InvokeAndAwaitTypedResponse, - InvokeRequest, InvokeResponse, ResumeWorkerRequest, ResumeWorkerResponse, UpdateWorkerRequest, - UpdateWorkerResponse, WorkerError, + fork_worker_response, invoke_and_await_typed_response, invoke_response, resume_worker_response, + update_worker_response, worker_error, ForkWorkerRequest, InvokeAndAwaitRequest, + InvokeAndAwaitTypedResponse, InvokeRequest, InvokeResponse, ResumeWorkerRequest, + ResumeWorkerResponse, UpdateWorkerRequest, UpdateWorkerResponse, WorkerError, }; use golem_api_grpc::proto::golem::worker::{InvocationContext, InvokeParameters, UpdateMode}; use golem_common::client::GrpcClient; +use golem_common::model::oplog::OplogIndex; use golem_common::model::{ComponentVersion, IdempotencyKey, OwnedWorkerId, WorkerId}; use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; use golem_wasm_rpc::{Value, WitValue}; @@ -70,6 +71,13 @@ pub trait WorkerProxy { async fn resume(&self, owned_worker_id: &WorkerId, force: bool) -> Result<(), WorkerProxyError>; + + async fn fork_worker( + &self, + source_worker_id: &WorkerId, + target_worker_id: &WorkerId, + oplog_index_cutoff: &OplogIndex, + ) -> Result<(), WorkerProxyError>; } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -337,6 +345,38 @@ impl WorkerProxy for RemoteWorkerProxy { } } + async fn fork_worker( + &self, + source_worker_id: &WorkerId, + target_worker_id: &WorkerId, + oplog_index_cutoff: &OplogIndex, + ) -> Result<(), WorkerProxyError> { + debug!("Forking remote worker"); + + let response = self + .client + .call("fork_worker", move |client| { + Box::pin(client.fork_worker(authorised_grpc_request( + ForkWorkerRequest { + source_worker_id: Some(source_worker_id.clone().into()), + target_worker_id: Some(target_worker_id.clone().into()), + oplog_index_cutoff: u64::from(*oplog_index_cutoff), + }, + &self.access_token, + ))) + }) + .await? + .into_inner(); + + match response.result { + Some(fork_worker_response::Result::Success(_)) => Ok(()), + Some(fork_worker_response::Result::Error(error)) => Err(error.into()), + None => Err(WorkerProxyError::InternalError(GolemError::unknown( + "Empty response through the worker API during fork".to_string(), + ))), + } + } + async fn resume(&self, worker_id: &WorkerId, force: bool) -> Result<(), WorkerProxyError> { debug!("Resuming remote worker"); diff --git a/golem-worker-executor-base/tests/common/mod.rs b/golem-worker-executor-base/tests/common/mod.rs index 8655c1ae6e..86e1a0e370 100644 --- a/golem-worker-executor-base/tests/common/mod.rs +++ b/golem-worker-executor-base/tests/common/mod.rs @@ -82,7 +82,7 @@ use golem_test_framework::dsl::to_worker_metadata; use golem_wasm_rpc::golem::rpc::types::{FutureInvokeResult, WasmRpc}; use golem_wasm_rpc::golem::rpc::types::{HostFutureInvokeResult, Pollable}; use golem_worker_executor_base::preview2::golem; -use golem_worker_executor_base::preview2::golem::{api1_1_0, api1_2_0}; +use golem_worker_executor_base::preview2::golem::{api1_1_1, durability}; use golem_worker_executor_base::services::events::Events; use golem_worker_executor_base::services::oplog::plugin::OplogProcessorPlugin; use golem_worker_executor_base::services::plugins::{Plugins, PluginsObservations}; @@ -1019,9 +1019,9 @@ impl Bootstrap for ServerBootstrap { fn create_wasmtime_linker(&self, engine: &Engine) -> anyhow::Result> { let mut linker = create_linker(engine, get_durable_ctx)?; api0_2_0::host::add_to_linker_get_host(&mut linker, get_durable_ctx)?; - api1_1_0::host::add_to_linker_get_host(&mut linker, get_durable_ctx)?; - api1_1_0::oplog::add_to_linker_get_host(&mut linker, get_durable_ctx)?; - api1_2_0::durability::add_to_linker_get_host(&mut linker, get_durable_ctx)?; + api1_1_1::host::add_to_linker_get_host(&mut linker, get_durable_ctx)?; + api1_1_1::oplog::add_to_linker_get_host(&mut linker, get_durable_ctx)?; + durability::durability::add_to_linker_get_host(&mut linker, get_durable_ctx)?; golem_wasm_rpc::golem::rpc::types::add_to_linker_get_host(&mut linker, get_durable_ctx)?; Ok(linker) } diff --git a/golem-worker-executor/src/lib.rs b/golem-worker-executor/src/lib.rs index 6db2782df0..6b568d243e 100644 --- a/golem-worker-executor/src/lib.rs +++ b/golem-worker-executor/src/lib.rs @@ -23,7 +23,7 @@ use async_trait::async_trait; use golem_common::model::component::ComponentOwner; use golem_common::model::plugin::{DefaultPluginOwner, DefaultPluginScope}; use golem_worker_executor_base::durable_host::DurableWorkerCtx; -use golem_worker_executor_base::preview2::golem::{api0_2_0, api1_1_0, api1_2_0}; +use golem_worker_executor_base::preview2::golem::{api0_2_0, api1_1_1, durability}; use golem_worker_executor_base::services::active_workers::ActiveWorkers; use golem_worker_executor_base::services::blob_store::BlobStoreService; use golem_worker_executor_base::services::component::ComponentService; @@ -203,9 +203,9 @@ impl Bootstrap for ServerBootstrap { fn create_wasmtime_linker(&self, engine: &Engine) -> anyhow::Result> { let mut linker = create_linker(engine, get_durable_ctx)?; api0_2_0::host::add_to_linker_get_host(&mut linker, get_durable_ctx)?; - api1_1_0::host::add_to_linker_get_host(&mut linker, get_durable_ctx)?; - api1_1_0::oplog::add_to_linker_get_host(&mut linker, get_durable_ctx)?; - api1_2_0::durability::add_to_linker_get_host(&mut linker, get_durable_ctx)?; + api1_1_1::host::add_to_linker_get_host(&mut linker, get_durable_ctx)?; + api1_1_1::oplog::add_to_linker_get_host(&mut linker, get_durable_ctx)?; + durability::durability::add_to_linker_get_host(&mut linker, get_durable_ctx)?; golem_wasm_rpc::golem::rpc::types::add_to_linker_get_host(&mut linker, get_durable_ctx)?; Ok(linker) } From db7e73ff9455cd8f3b5b1e6eb6f66e1a19946108 Mon Sep 17 00:00:00 2001 From: Maxim Schuwalow Date: Tue, 28 Jan 2025 13:26:54 +0100 Subject: [PATCH 17/17] Support non-json bodies in api-gateway (#1275) * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * wip * cleanups * fix tests --- .../tests/api_deployment_http_handler.rs | 6 +- .../virtual_exports/http_incoming_handler.rs | 12 +- .../http_incoming_handler.rs | 2 +- .../src/api/custom_http_request_api.rs | 12 +- .../src/api/register_api_definition_api.rs | 5 +- .../gateway_binding_compiled.rs | 13 +- .../src/gateway_binding/mod.rs | 13 +- .../api_definition_lookup.rs | 26 +- .../auth_call_back_binding_handler.rs | 10 +- .../file_server_binding_handler.rs | 2 +- .../gateway_binding_resolver.rs | 562 +------------- .../gateway_http_input_executor.rs | 712 +++++++++++------- .../http_handler_binding_handler.rs | 61 +- .../src/gateway_execution/mod.rs | 87 ++- .../src/gateway_execution/request.rs | 406 ++++++++++ .../rib_input_value_resolver.rs | 109 --- .../src/gateway_execution/to_response.rs | 268 ++++--- .../gateway_middleware/http/authentication.rs | 21 +- .../src/gateway_middleware/mod.rs | 6 +- .../src/gateway_request/http_request.rs | 69 +- .../src/gateway_request/mod.rs | 1 - .../src/gateway_request/request_details.rs | 373 --------- .../tests/api_gateway_end_to_end_tests.rs | 94 ++- golem-worker-service/src/service/mod.rs | 21 +- 24 files changed, 1264 insertions(+), 1627 deletions(-) create mode 100644 golem-worker-service-base/src/gateway_execution/request.rs delete mode 100644 golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs delete mode 100644 golem-worker-service-base/src/gateway_request/request_details.rs diff --git a/golem-cli/tests/api_deployment_http_handler.rs b/golem-cli/tests/api_deployment_http_handler.rs index 01fad328b6..072159d0bc 100644 --- a/golem-cli/tests/api_deployment_http_handler.rs +++ b/golem-cli/tests/api_deployment_http_handler.rs @@ -95,16 +95,16 @@ async fn api_deployment_http_handler( client .post(format!("http://{host}/test?foo=baz")) .header("test-header", "test-header-value") - .body("\"test-body\"") + .body("test-body") .send() .await }?; assert_eq!(res.status().as_u16(), 200); assert_eq!( res.headers().get("echo-test-header").unwrap(), - "\"test-header-value\"" + "test-header-value" ); - assert_eq!(res.text().await?, "\"test-body\""); + assert_eq!(res.text().await?, "test-body"); Ok(()) } diff --git a/golem-common/src/virtual_exports/http_incoming_handler.rs b/golem-common/src/virtual_exports/http_incoming_handler.rs index 349a5d2558..43a0221d6a 100644 --- a/golem-common/src/virtual_exports/http_incoming_handler.rs +++ b/golem-common/src/virtual_exports/http_incoming_handler.rs @@ -52,7 +52,7 @@ use std::sync::LazyLock; // method: method, // scheme: scheme, // authority: string, -// path-with-query: string, +// path-and-query: string, // headers: fields, // body-and-trailers: option // } @@ -547,7 +547,7 @@ pub struct IncomingHttpRequest { pub method: HttpMethod, pub scheme: HttpScheme, pub authority: String, - pub path_with_query: String, + pub path_and_query: String, pub headers: HttpFields, pub body: Option, } @@ -571,7 +571,7 @@ impl IncomingHttpRequest { typ: AnalysedType::Str(TypeStr), }, NameTypePair { - name: "path-with-query".to_string(), + name: "path-and-query".to_string(), typ: AnalysedType::Str(TypeStr), }, NameTypePair { @@ -611,7 +611,7 @@ impl IncomingHttpRequest { inner, "not a string" )?; - let path_with_query = extract!( + let path_and_query = extract!( record_values[3].clone(), Value::String(inner), inner, @@ -632,7 +632,7 @@ impl IncomingHttpRequest { method, scheme, authority, - path_with_query, + path_and_query, headers, body, }) @@ -643,7 +643,7 @@ impl IncomingHttpRequest { self.method.to_value(), self.scheme.to_value(), Value::String(self.authority), - Value::String(self.path_with_query), + Value::String(self.path_and_query), self.headers.to_value(), Value::Option(self.body.map(|b| Box::new(b.to_value()))), ]) diff --git a/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs b/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs index 11a48afb48..c77ee3578c 100644 --- a/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs +++ b/golem-worker-executor-base/src/virtual_export_compat/http_incoming_handler.rs @@ -52,7 +52,7 @@ pub fn input_to_hyper_request(inputs: &[Value]) -> Result + Sync + Send, >, - api_definition_lookup_service: Arc< - dyn ApiDefinitionsLookup< - InputHttpRequest, - ApiDefinition = CompiledHttpApiDefinition, - > + Sync - + Send, - >, + api_definition_lookup_service: Arc + Sync + Send>, file_server_binding_handler: Arc + Sync + Send>, http_handler_binding_handler: Arc + Sync + Send>, gateway_session_store: Arc, diff --git a/golem-worker-service-base/src/api/register_api_definition_api.rs b/golem-worker-service-base/src/api/register_api_definition_api.rs index b2ace03476..a19d228386 100644 --- a/golem-worker-service-base/src/api/register_api_definition_api.rs +++ b/golem-worker-service-base/src/api/register_api_definition_api.rs @@ -33,7 +33,6 @@ use openidconnect::{ClientId, ClientSecret, RedirectUrl, Scope}; use poem_openapi::*; use rib::{RibInputTypeInfo, RibOutputTypeInfo}; use serde::{Deserialize, Serialize}; -use std::ops::Deref; use std::result::Result; use std::time::SystemTime; @@ -579,7 +578,7 @@ impl TryFrom for GatewayBindingResponseData { ), ), GatewayBindingCompiled::Static(static_binding) => { - let binding_type = match static_binding.deref() { + let binding_type = match static_binding { StaticBinding::HttpCorsPreflight(_) => GatewayBindingType::CorsPreflight, StaticBinding::HttpAuthCallBack(_) => { return Err( @@ -702,7 +701,7 @@ impl TryFrom for GatewayBindingData { ) } - GatewayBinding::Static(static_binding) => match static_binding.deref() { + GatewayBinding::Static(static_binding) => match static_binding { StaticBinding::HttpCorsPreflight(cors) => Ok(GatewayBindingData { binding_type: Some(GatewayBindingType::CorsPreflight), component_id: None, diff --git a/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs b/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs index b75e7174ec..314da2af58 100644 --- a/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs +++ b/golem-worker-service-base/src/gateway_binding/gateway_binding_compiled.rs @@ -20,7 +20,6 @@ use crate::gateway_binding::{ use golem_api_grpc::proto::golem::apidefinition::GatewayBindingType as ProtoGatewayBindingType; use golem_common::model::GatewayBindingType; use rib::RibOutputTypeInfo; -use std::ops::Deref; use super::http_handler_binding::HttpHandlerBindingCompiled; use super::HttpHandlerBinding; @@ -30,7 +29,7 @@ use super::HttpHandlerBinding; #[derive(Debug, Clone, PartialEq)] pub enum GatewayBindingCompiled { Worker(WorkerBindingCompiled), - Static(Box), + Static(StaticBinding), FileServer(WorkerBindingCompiled), HttpHandler(HttpHandlerBindingCompiled), } @@ -41,7 +40,7 @@ impl GatewayBindingCompiled { GatewayBindingCompiled::Worker(_) => false, GatewayBindingCompiled::FileServer(_) => false, GatewayBindingCompiled::HttpHandler(_) => false, - GatewayBindingCompiled::Static(static_binding) => match static_binding.deref() { + GatewayBindingCompiled::Static(static_binding) => match static_binding { StaticBinding::HttpCorsPreflight(_) => false, StaticBinding::HttpAuthCallBack(_) => true, }, @@ -108,7 +107,7 @@ impl TryFrom } GatewayBindingCompiled::Static(static_binding) => { - let binding_type = match static_binding.deref() { + let binding_type = match static_binding { StaticBinding::HttpCorsPreflight(_) => golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::CorsPreflight, StaticBinding::HttpAuthCallBack(_) => golem_api_grpc::proto::golem::apidefinition::GatewayBindingType::AuthCallBack, }; @@ -129,7 +128,7 @@ impl TryFrom binding_type: Some(binding_type as i32), static_binding: Some( golem_api_grpc::proto::golem::apidefinition::StaticBinding::try_from( - *static_binding, + static_binding, )?, ), response_rib_output: None, @@ -291,9 +290,7 @@ impl TryFrom), + Static(StaticBinding), HttpHandler(HttpHandlerBinding), } @@ -52,7 +49,7 @@ impl GatewayBinding { Self::Default(_) => false, Self::FileServer(_) => false, Self::HttpHandler(_) => false, - Self::Static(s) => match s.deref() { + Self::Static(s) => match s { StaticBinding::HttpCorsPreflight(_) => true, StaticBinding::HttpAuthCallBack(_) => false, }, @@ -64,7 +61,7 @@ impl GatewayBinding { Self::Default(_) => false, Self::FileServer(_) => false, Self::HttpHandler(_) => false, - Self::Static(s) => match s.deref() { + Self::Static(s) => match s { StaticBinding::HttpCorsPreflight(_) => false, StaticBinding::HttpAuthCallBack(_) => true, }, @@ -72,7 +69,7 @@ impl GatewayBinding { } pub fn static_binding(value: StaticBinding) -> GatewayBinding { - GatewayBinding::Static(Box::new(value)) + GatewayBinding::Static(value) } pub fn get_component_id(&self) -> Option { @@ -114,7 +111,7 @@ impl TryFrom for golem_api_grpc::proto::golem::apidefinition::Ga GatewayBinding::Static(static_binding) => { let static_binding = golem_api_grpc::proto::golem::apidefinition::StaticBinding::try_from( - static_binding.deref().clone(), + static_binding.clone(), )?; let inner = static_binding diff --git a/golem-worker-service-base/src/gateway_execution/api_definition_lookup.rs b/golem-worker-service-base/src/gateway_execution/api_definition_lookup.rs index eb7f39816f..f8066816f2 100644 --- a/golem-worker-service-base/src/gateway_execution/api_definition_lookup.rs +++ b/golem-worker-service-base/src/gateway_execution/api_definition_lookup.rs @@ -16,7 +16,7 @@ use std::fmt::Display; use std::sync::Arc; use crate::gateway_api_definition::http::CompiledHttpApiDefinition; -use crate::gateway_request::http_request::InputHttpRequest; +use crate::gateway_api_deployment::ApiSiteString; use crate::service::gateway::api_deployment::ApiDeploymentService; use async_trait::async_trait; use golem_common::model::HasAccountId; @@ -27,12 +27,11 @@ use tracing::error; // depends on what is the input. There cannot be multiple types of ApiDefinition // for a given input type. #[async_trait] -pub trait ApiDefinitionsLookup { - type ApiDefinition; +pub trait HttpApiDefinitionsLookup { async fn get( &self, - input: &Input, - ) -> Result, ApiDefinitionLookupError>; + host: &ApiSiteString, + ) -> Result>, ApiDefinitionLookupError>; } pub struct ApiDefinitionLookupError(pub String); @@ -43,11 +42,11 @@ impl Display for ApiDefinitionLookupError { } } -pub struct HttpApiDefinitionLookup { +pub struct DefaultHttpApiDefinitionLookup { deployment_service: Arc + Sync + Send>, } -impl HttpApiDefinitionLookup { +impl DefaultHttpApiDefinitionLookup { pub fn new( deployment_service: Arc + Sync + Send>, ) -> Self { @@ -56,18 +55,13 @@ impl HttpApiDefinitionLookup { } #[async_trait] -impl ApiDefinitionsLookup - for HttpApiDefinitionLookup +impl HttpApiDefinitionsLookup + for DefaultHttpApiDefinitionLookup { - type ApiDefinition = CompiledHttpApiDefinition; - async fn get( &self, - input_http_request: &InputHttpRequest, - ) -> Result, ApiDefinitionLookupError> { - // HOST should exist in Http Request - let host = &input_http_request.host; - + host: &ApiSiteString, + ) -> Result>, ApiDefinitionLookupError> { let http_api_defs = self .deployment_service .get_definitions_by_site(host) diff --git a/golem-worker-service-base/src/gateway_execution/auth_call_back_binding_handler.rs b/golem-worker-service-base/src/gateway_execution/auth_call_back_binding_handler.rs index 722a24d501..dc064ebbaf 100644 --- a/golem-worker-service-base/src/gateway_execution/auth_call_back_binding_handler.rs +++ b/golem-worker-service-base/src/gateway_execution/auth_call_back_binding_handler.rs @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::gateway_binding::HttpRequestDetails; use crate::gateway_execution::gateway_session::{ DataKey, DataValue, GatewaySessionError, GatewaySessionStore, SessionId, }; @@ -24,6 +23,7 @@ use golem_common::SafeDisplay; use openidconnect::core::CoreTokenResponse; use openidconnect::{AuthorizationCode, OAuth2TokenResponse}; use std::sync::Arc; +use url::Url; pub type AuthCallBackResult = Result; @@ -31,7 +31,7 @@ pub type AuthCallBackResult = Result; pub trait AuthCallBackBindingHandler { async fn handle_auth_call_back( &self, - http_request_details: &HttpRequestDetails, + api_url: &Url, security_scheme: &SecuritySchemeWithProviderMetadata, gateway_session_store: &GatewaySessionStore, identity_provider: &Arc, @@ -123,15 +123,11 @@ pub struct DefaultAuthCallBack; impl AuthCallBackBindingHandler for DefaultAuthCallBack { async fn handle_auth_call_back( &self, - http_request_details: &HttpRequestDetails, + api_url: &Url, security_scheme_with_metadata: &SecuritySchemeWithProviderMetadata, session_store: &GatewaySessionStore, identity_provider: &Arc, ) -> Result { - let api_url = &http_request_details - .url() - .map_err(AuthorisationError::Internal)?; - let query_pairs = api_url.query_pairs(); let mut code = None; diff --git a/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs b/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs index 0a5507ac5e..d4e1d6c89d 100644 --- a/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs +++ b/golem-worker-service-base/src/gateway_execution/file_server_binding_handler.rs @@ -13,7 +13,7 @@ // limitations under the License. use crate::empty_worker_metadata; -use crate::gateway_binding::WorkerDetail; +use crate::gateway_execution::WorkerDetail; use crate::getter::{get_response_headers_or_default, get_status_code}; use crate::service::component::{ComponentService, ComponentServiceError}; use crate::service::worker::{WorkerService, WorkerServiceError}; diff --git a/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs b/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs index 6d978a1dc9..9a35c94ed3 100644 --- a/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs +++ b/golem-worker-service-base/src/gateway_execution/gateway_binding_resolver.rs @@ -12,553 +12,33 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::gateway_api_definition::http::{CompiledHttpApiDefinition, VarInfo}; -use crate::gateway_binding::{ - GatewayBindingCompiled, HttpRequestDetails, RibInputTypeMismatch, StaticBinding, -}; -use crate::gateway_binding::{GatewayRequestDetails, ResponseMappingCompiled}; -use crate::gateway_execution::gateway_session::GatewaySessionStore; +use crate::gateway_api_definition::http::CompiledHttpApiDefinition; use crate::gateway_execution::router::RouterPattern; -use crate::gateway_execution::to_response_failure::ToHttpResponseFromSafeDisplay; -use crate::gateway_middleware::{MiddlewareError, MiddlewareSuccess}; -use crate::gateway_request::http_request::{router, InputHttpRequest}; -use crate::gateway_security::{IdentityProvider, OpenIdClient}; -use async_trait::async_trait; -use golem_common::model::IdempotencyKey; -use golem_common::SafeDisplay; -use golem_service_base::model::VersionedComponentId; -use http::StatusCode; -use openidconnect::{CsrfToken, Nonce}; -use poem::Body; -use serde_json::Value; -use std::collections::HashMap; -use std::fmt::Debug; -use std::sync::Arc; +use crate::gateway_request::http_request::router; +use crate::gateway_request::http_request::router::RouteEntry; -// Every type of request (example: InputHttpRequest (which corresponds to a Route)) can have an instance of this resolver, -// which will resolve the gateway binding equired for that request. -#[async_trait] -pub trait GatewayBindingResolver { - async fn resolve_gateway_binding( - &self, - api_definitions: Vec, - ) -> Result, ErrorOrRedirect>; +pub struct ResolvedRouteEntry { + pub path_segments: Vec, + pub route_entry: RouteEntry, } -#[derive(Debug)] -pub enum ErrorOrRedirect { - Error(GatewayBindingResolverError), - Redirect(poem::Response), -} - -impl ErrorOrRedirect { - pub fn internal(err: String) -> Self { - ErrorOrRedirect::Error(GatewayBindingResolverError::Internal(err)) - } - - pub fn route_not_found() -> Self { - ErrorOrRedirect::Error(GatewayBindingResolverError::RouteNotFound) - } - - pub fn rib_input_type_mismatch(err: RibInputTypeMismatch) -> Self { - ErrorOrRedirect::Error(GatewayBindingResolverError::RibInputTypeMismatch(err)) - } -} - -#[derive(Debug)] -pub enum GatewayBindingResolverError { - RibInputTypeMismatch(RibInputTypeMismatch), - Internal(String), - RouteNotFound, - MiddlewareError(MiddlewareError), -} - -impl SafeDisplay for GatewayBindingResolverError { - fn to_safe_string(&self) -> String { - match self { - GatewayBindingResolverError::RibInputTypeMismatch(err) => { - format!("Input type mismatch: {}", err) - } - GatewayBindingResolverError::Internal(err) => format!("Internal: {}", err), - GatewayBindingResolverError::RouteNotFound => "RouteNotFound".to_string(), - GatewayBindingResolverError::MiddlewareError(err) => err.to_safe_string(), - } - } -} - -impl GatewayBindingResolverError { - pub fn to_http_response(self) -> poem::Response { - match self { - GatewayBindingResolverError::Internal(str) => poem::Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from_string(str)), - GatewayBindingResolverError::RouteNotFound => poem::Response::builder() - .status(StatusCode::NOT_FOUND) - .body(Body::from_string("Route not found".to_string())), - GatewayBindingResolverError::RibInputTypeMismatch(_) => poem::Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from_string("Rib input type mismatch".to_string())), - GatewayBindingResolverError::MiddlewareError(error) => error - .to_response_from_safe_display(|error| match error { - MiddlewareError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR, - MiddlewareError::Unauthorized(_) => StatusCode::UNAUTHORIZED, - }), - } - } -} - -#[derive(Clone, Debug)] -pub struct ResolvedGatewayBinding { - pub request_details: GatewayRequestDetails, - pub resolved_binding: ResolvedBinding, -} - -#[derive(Clone, Debug)] -pub enum ResolvedBinding { - Static(StaticBinding), - Worker(ResolvedWorkerBinding), - FileServer(ResolvedWorkerBinding), - HttpHandler(ResolvedHttpHandlerBinding), -} - -#[derive(Clone, Debug)] -pub struct AuthParams { - pub client: OpenIdClient, - pub csrf_state: CsrfToken, - pub nonce: Nonce, - pub original_uri: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct WorkerDetail { - pub component_id: VersionedComponentId, - pub worker_name: Option, - pub idempotency_key: Option, -} - -impl WorkerDetail { - pub fn as_json(&self) -> Value { - let mut worker_detail_content = HashMap::new(); - worker_detail_content.insert( - "component_id".to_string(), - Value::String(self.component_id.component_id.0.to_string()), - ); - - if let Some(worker_name) = &self.worker_name { - worker_detail_content - .insert("name".to_string(), Value::String(worker_name.to_string())); - } - - if let Some(idempotency_key) = &self.idempotency_key { - worker_detail_content.insert( - "idempotency_key".to_string(), - Value::String(idempotency_key.value.clone()), - ); - } - - let map = serde_json::Map::from_iter(worker_detail_content); - - Value::Object(map) - } -} - -#[derive(Debug, Clone)] -pub struct ResolvedWorkerBinding { - pub worker_detail: WorkerDetail, - pub compiled_response_mapping: ResponseMappingCompiled, - pub namespace: Namespace, -} - -impl ResolvedGatewayBinding { - pub fn get_worker_detail(&self) -> Option { - match &self.resolved_binding { - ResolvedBinding::Worker(resolved_worker_binding) => { - Some(resolved_worker_binding.worker_detail.clone()) - } - _ => None, - } - } - pub fn from_static_binding( - request_details: &GatewayRequestDetails, - static_binding: &StaticBinding, - ) -> ResolvedGatewayBinding { - ResolvedGatewayBinding { - request_details: request_details.clone(), - resolved_binding: ResolvedBinding::Static(static_binding.clone()), - } - } - - pub fn from_resolved_worker_binding( - request_details: &GatewayRequestDetails, - resolved_worker_binding: ResolvedWorkerBinding, - ) -> ResolvedGatewayBinding { - ResolvedGatewayBinding { - request_details: request_details.clone(), - resolved_binding: ResolvedBinding::Worker(resolved_worker_binding), - } - } -} - -#[derive(Debug, Clone)] -pub struct ResolvedHttpHandlerBinding { - pub worker_detail: WorkerDetail, - pub namespace: Namespace, -} - -pub struct DefaultGatewayBindingResolver { - input: InputHttpRequest, - gateway_session_store: GatewaySessionStore, - identity_provider: Arc, -} - -impl DefaultGatewayBindingResolver { - pub fn new( - input: InputHttpRequest, - gateway_session_store: &GatewaySessionStore, - identity_provider: &Arc, - ) -> Self { - DefaultGatewayBindingResolver { - input, - gateway_session_store: Arc::clone(gateway_session_store), - identity_provider: Arc::clone(identity_provider), - } - } -} - -#[async_trait] -impl - GatewayBindingResolver> - for DefaultGatewayBindingResolver -{ - async fn resolve_gateway_binding( - &self, - compiled_api_definitions: Vec>, - ) -> Result, ErrorOrRedirect> { - let compiled_routes = compiled_api_definitions - .iter() - .flat_map(|x| x.routes.iter().map(|y| (x.namespace.clone(), y.clone()))) - .collect::>(); - - let api_request = self; - let router = router::build(compiled_routes); - - let path: Vec<&str> = - RouterPattern::split(&api_request.input.api_input_path.base_path).collect(); - let request_query_variables = self - .input - .api_input_path - .query_components() - .unwrap_or_default(); - let request_body = &self.input.req_body; - let headers = &self.input.headers; - - let router::RouteEntry { - path_params, - query_params, - namespace, - binding, - middlewares, - } = router - .check_path(&api_request.input.req_method, &path) - .ok_or(ErrorOrRedirect::route_not_found())?; - - let zipped_path_params: HashMap = { - path_params - .iter() - .map(|param| match param { - router::PathParamExtractor::Single { var_info, index } => { - (var_info.clone(), path[*index].to_string()) - } - router::PathParamExtractor::AllFollowing { var_info, index } => { - let value = path[*index..].join("/"); - (var_info.clone(), value) - } - }) - .collect() - }; - - let mut http_request_details = HttpRequestDetails::from_input_http_request( - &self.input.scheme, - &self.input.host, - self.input.req_method.clone(), - &self.input.api_input_path, - &zipped_path_params, - &request_query_variables, - query_params, - request_body, - headers.clone(), - middlewares, - ) - .map_err(|err| { - ErrorOrRedirect::internal(format!( - "Failed to fetch input request details {}", - err.join(", ") - )) - })?; - - if let Some(middlewares) = middlewares { - let middleware_result = internal::redirect_or_continue( - &mut http_request_details, - middlewares, - &self.gateway_session_store, - &self.identity_provider, - ) - .await - .map_err(|err| { - ErrorOrRedirect::Error(GatewayBindingResolverError::MiddlewareError(err)) - })?; - - if let MiddlewareSuccess::Redirect(response) = middleware_result { - return Err(ErrorOrRedirect::Redirect(response)); - } - } - - match binding { - GatewayBindingCompiled::FileServer(worker_binding) => { - internal::get_resolved_worker_binding( - worker_binding, - &http_request_details, - namespace, - headers, - ) - .await - .map(|resolved_binding| ResolvedGatewayBinding { - request_details: GatewayRequestDetails::Http(http_request_details), - resolved_binding: ResolvedBinding::FileServer(resolved_binding), - }) - } - GatewayBindingCompiled::Worker(worker_binding) => { - internal::get_resolved_worker_binding( - worker_binding, - &http_request_details, - namespace, - headers, - ) - .await - .map(|resolved_binding| ResolvedGatewayBinding { - request_details: GatewayRequestDetails::Http(http_request_details), - resolved_binding: ResolvedBinding::Worker(resolved_binding), - }) - } - GatewayBindingCompiled::HttpHandler(http_handler_binding) => { - internal::get_resolved_http_handler_binding( - http_handler_binding, - &http_request_details, - namespace, - headers, - ) - .await - .map(|resolved_binding| ResolvedGatewayBinding { - request_details: GatewayRequestDetails::Http(http_request_details), - resolved_binding: ResolvedBinding::HttpHandler(resolved_binding), - }) - } - GatewayBindingCompiled::Static(static_binding) => { - Ok(ResolvedGatewayBinding::from_static_binding( - &GatewayRequestDetails::Http(http_request_details), - static_binding, - )) - } - } - } -} - -mod internal { - use crate::gateway_binding::{ - ErrorOrRedirect, HttpHandlerBindingCompiled, HttpRequestDetails, ResolvedWorkerBinding, - RibInputValueResolver, WorkerBindingCompiled, WorkerDetail, - }; - use crate::gateway_execution::gateway_session::GatewaySessionStore; - use crate::gateway_middleware::{HttpMiddlewares, MiddlewareError, MiddlewareSuccess}; - use crate::gateway_security::IdentityProvider; - use golem_common::model::IdempotencyKey; - use http::HeaderMap; - use std::sync::Arc; - - use super::ResolvedHttpHandlerBinding; - - pub async fn redirect_or_continue( - input: &mut HttpRequestDetails, - middlewares: &HttpMiddlewares, - session_store: &GatewaySessionStore, - identity_provider: &Arc, - ) -> Result { - let input_middleware_result = middlewares - .process_middleware_in(input, session_store, identity_provider) - .await; - - match input_middleware_result { - Ok(incoming_middleware_result) => match incoming_middleware_result { - MiddlewareSuccess::Redirect(response) => Ok(MiddlewareSuccess::Redirect(response)), - MiddlewareSuccess::PassThrough { session_id } => { - if let Some(session_id) = &session_id { - let result = input.inject_auth_details(session_id, session_store).await; - - if let Err(err_response) = result { - return Err(MiddlewareError::InternalError(err_response)); - } - } - - Ok(MiddlewareSuccess::PassThrough { session_id }) - } - }, - - Err(err) => Err(err), - } - } - - pub async fn get_resolved_worker_binding( - binding: &WorkerBindingCompiled, - http_request_details: &HttpRequestDetails, - namespace: &Namespace, - headers: &HeaderMap, - ) -> Result, ErrorOrRedirect> { - let worker_name_opt = if let Some(worker_name_compiled) = &binding.worker_name_compiled { - let resolve_rib_input = http_request_details - .resolve_rib_input_value(&worker_name_compiled.rib_input_type_info) - .map_err(ErrorOrRedirect::rib_input_type_mismatch)?; - - let worker_name = rib::interpret_pure( - &worker_name_compiled.compiled_worker_name, - &resolve_rib_input, - ) - .await - .map_err(|err| { - ErrorOrRedirect::internal(format!( - "Failed to evaluate worker name rib expression. {}", - err - )) - })? - .get_literal() - .ok_or(ErrorOrRedirect::internal( - "Worker name is not a Rib expression that resolves to String".to_string(), - ))? - .as_string(); - - Some(worker_name) - } else { - None - }; - - let component_id = &binding.component_id; - - let idempotency_key = - if let Some(idempotency_key_compiled) = &binding.idempotency_key_compiled { - let resolve_rib_input = http_request_details - .resolve_rib_input_value(&idempotency_key_compiled.rib_input) - .map_err(ErrorOrRedirect::rib_input_type_mismatch)?; - - let idempotency_key_value = rib::interpret_pure( - &idempotency_key_compiled.compiled_idempotency_key, - &resolve_rib_input, - ) - .await - .map_err(|err| ErrorOrRedirect::internal(err.to_string()))?; - - let idempotency_key = idempotency_key_value - .get_literal() - .ok_or(ErrorOrRedirect::internal( - "Idempotency Key is not a string".to_string(), - ))? - .as_string(); - - Some(IdempotencyKey::new(idempotency_key)) - } else { - headers - .get("idempotency-key") - .and_then(|h| h.to_str().ok()) - .map(|value| IdempotencyKey::new(value.to_string())) - }; - - let worker_detail = WorkerDetail { - component_id: component_id.clone(), - worker_name: worker_name_opt, - idempotency_key, - }; - - let resolved_binding = ResolvedWorkerBinding { - worker_detail, - compiled_response_mapping: binding.response_compiled.clone(), - namespace: namespace.clone(), - }; - - Ok(resolved_binding) - } - - pub async fn get_resolved_http_handler_binding( - binding: &HttpHandlerBindingCompiled, - http_request_details: &HttpRequestDetails, - namespace: &Namespace, - headers: &HeaderMap, - ) -> Result, ErrorOrRedirect> { - let worker_name_opt = if let Some(worker_name_compiled) = &binding.worker_name_compiled { - let resolve_rib_input = http_request_details - .resolve_rib_input_value(&worker_name_compiled.rib_input_type_info) - .map_err(ErrorOrRedirect::rib_input_type_mismatch)?; - - let worker_name = rib::interpret_pure( - &worker_name_compiled.compiled_worker_name, - &resolve_rib_input, - ) - .await - .map_err(|err| { - ErrorOrRedirect::internal(format!( - "Failed to evaluate worker name rib expression. {}", - err - )) - })? - .get_literal() - .ok_or(ErrorOrRedirect::internal( - "Worker name is not a Rib expression that resolves to String".to_string(), - ))? - .as_string(); - - Some(worker_name) - } else { - None - }; - - let component_id = &binding.component_id; - - let idempotency_key = - if let Some(idempotency_key_compiled) = &binding.idempotency_key_compiled { - let resolve_rib_input = http_request_details - .resolve_rib_input_value(&idempotency_key_compiled.rib_input) - .map_err(ErrorOrRedirect::rib_input_type_mismatch)?; - - let idempotency_key_value = rib::interpret_pure( - &idempotency_key_compiled.compiled_idempotency_key, - &resolve_rib_input, - ) - .await - .map_err(|err| ErrorOrRedirect::internal(err.to_string()))?; - - let idempotency_key = idempotency_key_value - .get_literal() - .ok_or(ErrorOrRedirect::internal( - "Idempotency Key is not a string".to_string(), - ))? - .as_string(); +pub async fn resolve_gateway_binding( + compiled_api_definitions: Vec>, + request: &poem::Request, +) -> Option> { + let compiled_routes = compiled_api_definitions + .iter() + .flat_map(|x| x.routes.iter().map(|y| (x.namespace.clone(), y.clone()))) + .collect::>(); - Some(IdempotencyKey::new(idempotency_key)) - } else { - headers - .get("idempotency-key") - .and_then(|h| h.to_str().ok()) - .map(|value| IdempotencyKey::new(value.to_string())) - }; + let router = router::build(compiled_routes); - let worker_detail = WorkerDetail { - component_id: component_id.clone(), - worker_name: worker_name_opt, - idempotency_key, - }; + let path_segments: Vec<&str> = RouterPattern::split(request.uri().path()).collect(); - let resolved_binding = ResolvedHttpHandlerBinding { - worker_detail, - namespace: namespace.clone(), - }; + let route_entry = router.check_path(request.method(), &path_segments)?; - Ok(resolved_binding) - } + Some(ResolvedRouteEntry { + path_segments: path_segments.into_iter().map(|s| s.to_string()).collect(), + route_entry: route_entry.clone(), + }) } diff --git a/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs b/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs index df7804c83a..c828981184 100644 --- a/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs +++ b/golem-worker-service-base/src/gateway_execution/gateway_http_input_executor.rs @@ -12,33 +12,43 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::gateway_api_definition::http::CompiledHttpApiDefinition; -use crate::gateway_binding::{ - DefaultGatewayBindingResolver, ErrorOrRedirect, GatewayBindingResolver, GatewayRequestDetails, - HttpRequestDetails, ResolvedBinding, ResolvedWorkerBinding, RibInputValueResolver, - StaticBinding, +use super::auth_call_back_binding_handler::AuthorisationSuccess; +use super::file_server_binding_handler::FileServerBindingSuccess; +use super::http_handler_binding_handler::{HttpHandlerBindingHandler, HttpHandlerBindingResult}; +use super::request::{ + authority_from_request, split_resolved_route_entry, RichRequest, SplitResolvedRouteEntryResult, }; -use crate::gateway_execution::api_definition_lookup::ApiDefinitionsLookup; -use crate::gateway_execution::auth_call_back_binding_handler::{ - AuthCallBackBindingHandler, AuthCallBackResult, +use super::to_response::GatewayHttpResult; +use super::WorkerDetail; +use crate::gateway_api_deployment::ApiSiteString; +use crate::gateway_binding::{ + resolve_gateway_binding, GatewayBindingCompiled, HttpHandlerBindingCompiled, + IdempotencyKeyCompiled, ResponseMappingCompiled, StaticBinding, WorkerBindingCompiled, + WorkerNameCompiled, }; +use crate::gateway_execution::api_definition_lookup::HttpApiDefinitionsLookup; +use crate::gateway_execution::auth_call_back_binding_handler::AuthCallBackBindingHandler; use crate::gateway_execution::file_server_binding_handler::FileServerBindingHandler; use crate::gateway_execution::gateway_session::GatewaySessionStore; -use crate::gateway_execution::to_response::ToHttpResponse; +use crate::gateway_execution::to_response::{GatewayHttpError, ToHttpResponse}; use crate::gateway_execution::to_response_failure::ToHttpResponseFromSafeDisplay; -use crate::gateway_request::http_request::InputHttpRequest; -use crate::gateway_rib_interpreter::{EvaluationError, WorkerServiceRibInterpreter}; +use crate::gateway_middleware::{HttpMiddlewares, MiddlewareError, MiddlewareSuccess}; +use crate::gateway_rib_interpreter::WorkerServiceRibInterpreter; use crate::gateway_security::{IdentityProvider, SecuritySchemeWithProviderMetadata}; use async_trait::async_trait; -use golem_common::SafeDisplay; +use golem_common::model::IdempotencyKey; +use golem_service_base::model::VersionedComponentId; +use golem_wasm_rpc::json::TypeAnnotatedValueJsonExtensions; +use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; +use golem_wasm_rpc::ValueAndType; use http::StatusCode; use poem::Body; -use rib::{RibInput, RibResult}; +use rib::{RibInput, RibInputTypeInfo, RibResult}; +use serde_json::Value; +use std::collections::HashMap; use std::sync::Arc; use tracing::error; -use super::http_handler_binding_handler::HttpHandlerBindingHandler; - #[async_trait] pub trait GatewayHttpInputExecutor { async fn execute_http_request(&self, input: poem::Request) -> poem::Response; @@ -49,13 +59,7 @@ pub struct DefaultGatewayInputExecutor { pub file_server_binding_handler: Arc + Sync + Send>, pub auth_call_back_binding_handler: Arc, pub http_handler_binding_handler: Arc + Sync + Send>, - pub api_definition_lookup_service: Arc< - dyn ApiDefinitionsLookup< - InputHttpRequest, - ApiDefinition = CompiledHttpApiDefinition, - > + Sync - + Send, - >, + pub api_definition_lookup_service: Arc + Sync + Send>, pub gateway_session_store: GatewaySessionStore, pub identity_provider: Arc, } @@ -66,13 +70,7 @@ impl DefaultGatewayInputExecutor { file_server_binding_handler: Arc + Sync + Send>, auth_call_back_binding_handler: Arc, http_handler_binding_handler: Arc + Sync + Send>, - api_definition_lookup_service: Arc< - dyn ApiDefinitionsLookup< - InputHttpRequest, - ApiDefinition = CompiledHttpApiDefinition, - > + Sync - + Send, - >, + api_definition_lookup_service: Arc + Sync + Send>, gateway_session_store: GatewaySessionStore, identity_provider: Arc, ) -> Self { @@ -87,224 +85,317 @@ impl DefaultGatewayInputExecutor { } } - pub async fn execute( + async fn handle_worker_binding( &self, - http_request_details: &HttpRequestDetails, - binding: ResolvedBinding, - ) -> poem::Response { - let middleware_opt = &http_request_details.http_middlewares; - let mut request_details = http_request_details.clone(); - - match &binding { - ResolvedBinding::Static(StaticBinding::HttpCorsPreflight(cors_preflight)) => { - cors_preflight - .clone() - .to_response(http_request_details, &self.gateway_session_store) - .await - } + namespace: &Namespace, + request: &mut RichRequest, + binding: &WorkerBindingCompiled, + ) -> GatewayHttpResult { + let mut rib_input: serde_json::Map = serde_json::Map::new(); - ResolvedBinding::Static(StaticBinding::HttpAuthCallBack(auth_call_back)) => { - self.handle_http_auth_call_binding( - &auth_call_back.security_scheme_with_metadata, - http_request_details, - ) + // phase 1. we only have the request details available + { + let request_value = request + .as_json_with_body() .await - } + .map_err(GatewayHttpError::BadRequest)?; + rib_input.insert("request".to_string(), request_value); + } - ResolvedBinding::Worker(resolved_worker_binding) => { - let mut response = self - .handle_worker_binding( - &self.gateway_session_store, - &mut request_details, - resolved_worker_binding, - ) - .await; + let worker_detail = self + .get_worker_detail( + request, + &rib_input, + &binding.worker_name_compiled, + &binding.idempotency_key_compiled, + &binding.component_id, + ) + .await?; - if let Some(middleware) = middleware_opt { - let result = middleware.process_middleware_out(&mut response).await; - match result { - Ok(_) => response, - Err(err) => { - err.to_response_from_safe_display(|_| StatusCode::INTERNAL_SERVER_ERROR) - } - } - } else { - response - } - } + // phase 2. we have both the request and the worker details available + { + let worker_value: Value = worker_detail.as_json(); + rib_input.insert("worker".to_string(), worker_value); + } - ResolvedBinding::HttpHandler(http_handler_binding) => { - let result = self - .http_handler_binding_handler - .handle_http_handler_binding( - &http_handler_binding.namespace, - &http_handler_binding.worker_detail, - &request_details, - ) - .await; + self.get_response_script_result( + namespace, + &binding.response_compiled, + &rib_input, + &worker_detail, + ) + .await + } - match result { - Ok(_) => tracing::debug!("http handler binding successful"), - Err(ref e) => tracing::warn!("http handler binding failed: {e:?}"), - } + async fn handle_http_handler_binding( + &self, + namespace: &Namespace, + request: &mut RichRequest, + binding: &HttpHandlerBindingCompiled, + ) -> GatewayHttpResult { + let mut rib_input: serde_json::Map = serde_json::Map::new(); - let mut response = result - .to_response(&request_details, &self.gateway_session_store) - .await; + { + let request_value = request.as_json().map_err(GatewayHttpError::BadRequest)?; + rib_input.insert("request".to_string(), request_value); + } - if let Some(middleware) = middleware_opt { - let result = middleware.process_middleware_out(&mut response).await; - match result { - Ok(_) => response, - Err(err) => { - err.to_response_from_safe_display(|_| StatusCode::INTERNAL_SERVER_ERROR) - } - } - } else { - response - } - } + let worker_detail = self + .get_worker_detail( + request, + &rib_input, + &binding.worker_name_compiled, + &binding.idempotency_key_compiled, + &binding.component_id, + ) + .await?; - ResolvedBinding::FileServer(resolved_file_server_binding) => { - self.handle_file_server_binding( - &self.gateway_session_store, - &mut request_details, - resolved_file_server_binding, - ) - .await - } + let incoming_http_request = request + .as_wasi_http_input() + .await + .map_err(GatewayHttpError::BadRequest)?; + + let result = self + .http_handler_binding_handler + .handle_http_handler_binding(namespace, &worker_detail, incoming_http_request) + .await; + + match result { + Ok(_) => tracing::debug!("http handler binding successful"), + Err(ref e) => tracing::warn!("http handler binding failed: {e:?}"), } - } - async fn resolve_rib_inputs( - &self, - request_details: &HttpRequestDetails, - resolved_worker_binding: &ResolvedWorkerBinding, - ) -> Result<(RibInput, RibInput), poem::Response> { - let rib_input_from_request_details = request_details - .resolve_rib_input_value(&resolved_worker_binding.compiled_response_mapping.rib_input) - .map_err(|err| err.to_response_from_safe_display(|_| StatusCode::BAD_REQUEST))?; - - let rib_input_from_worker_details = resolved_worker_binding - .worker_detail - .resolve_rib_input_value(&resolved_worker_binding.compiled_response_mapping.rib_input) - .map_err(|err| err.to_response_from_safe_display(|_| StatusCode::BAD_REQUEST))?; - - Ok(( - rib_input_from_request_details, - rib_input_from_worker_details, - )) + Ok(result) } - async fn get_rib_result( + async fn handle_file_server_binding( &self, - request_rib_input: RibInput, - worker_rib_input: RibInput, - resolved_worker_binding: &ResolvedWorkerBinding, - ) -> Result { - let rib_input = request_rib_input.merge(worker_rib_input); - self.evaluator - .evaluate( - resolved_worker_binding.worker_detail.worker_name.as_deref(), - &resolved_worker_binding - .worker_detail - .component_id - .component_id, - &resolved_worker_binding.worker_detail.idempotency_key, - &resolved_worker_binding - .compiled_response_mapping - .response_mapping_compiled, + namespace: &Namespace, + request: &mut RichRequest, + binding: &WorkerBindingCompiled, // TODO make separate type + ) -> GatewayHttpResult { + let mut rib_input: serde_json::Map = serde_json::Map::new(); + + // phase 1. we only have the request details available + { + let request_value = request + .as_json_with_body() + .await + .map_err(GatewayHttpError::BadRequest)?; + rib_input.insert("request".to_string(), request_value); + } + + let worker_detail = self + .get_worker_detail( + request, &rib_input, - resolved_worker_binding.namespace.clone(), + &binding.worker_name_compiled, + &binding.idempotency_key_compiled, + &binding.component_id, ) - .await - } + .await?; - async fn handle_worker_binding( - &self, - session_store: &GatewaySessionStore, - request_details: &mut HttpRequestDetails, - resolved_binding: &ResolvedWorkerBinding, - ) -> poem::Response { - match self - .resolve_rib_inputs(request_details, resolved_binding) - .await + // phase 2. we have both the request and the worker details available { - Ok((rib_input_from_request_details, rib_input_from_worker_details)) => { - match self - .get_rib_result( - rib_input_from_request_details, - rib_input_from_worker_details, - resolved_binding, - ) - .await - { - Ok(result) => result.to_response(request_details, session_store).await, - Err(err) => { - err.to_response_from_safe_display(|_| StatusCode::INTERNAL_SERVER_ERROR) - } - } - } - Err(err_response) => err_response, + let worker_value: Value = worker_detail.as_json(); + rib_input.insert("worker".to_string(), worker_value); } - } - async fn handle_file_server_binding( - &self, - session_store: &GatewaySessionStore, - request_details: &mut HttpRequestDetails, - resolved_binding: &ResolvedWorkerBinding, - ) -> poem::Response { - match self - .resolve_rib_inputs(request_details, resolved_binding) + let response_script_result = self + .get_response_script_result( + namespace, + &binding.response_compiled, + &rib_input, + &worker_detail, + ) + .await?; + + self.file_server_binding_handler + .handle_file_server_binding_result(namespace, &worker_detail, response_script_result) .await - { - Ok((request_rib_input, worker_rib_input)) => { - match self - .get_rib_result(request_rib_input, worker_rib_input, resolved_binding) - .await - { - Ok(worker_response) => { - self.file_server_binding_handler - .handle_file_server_binding_result( - &resolved_binding.namespace, - &resolved_binding.worker_detail, - worker_response, - ) - .await - .to_response(request_details, session_store) - .await - } - Err(err) => { - err.to_response_from_safe_display(|_| StatusCode::INTERNAL_SERVER_ERROR) - } - } - } - Err(err_response) => err_response, - } + .map_err(GatewayHttpError::FileServerBindingError) } - async fn handle_http_auth_call_binding( + async fn handle_http_auth_callback_binding( &self, security_scheme_with_metadata: &SecuritySchemeWithProviderMetadata, - http_request: &HttpRequestDetails, - ) -> poem::Response - where - AuthCallBackResult: ToHttpResponse, - { - let authorisation_result = self - .auth_call_back_binding_handler + request: &RichRequest, + ) -> GatewayHttpResult { + let url = request + .url() + .map_err(|e| GatewayHttpError::BadRequest(format!("Failed getting url: {e}")))?; + + self.auth_call_back_binding_handler .handle_auth_call_back( - http_request, + &url, security_scheme_with_metadata, &self.gateway_session_store, &self.identity_provider, ) - .await; + .await + .map_err(GatewayHttpError::AuthorisationError) + } - authorisation_result - .to_response(http_request, &self.gateway_session_store) + async fn evaluate_worker_name_rib_script( + &self, + script: &WorkerNameCompiled, + request_value: &serde_json::Map, + ) -> GatewayHttpResult { + let rib_input: RibInput = resolve_rib_input(request_value, &script.rib_input_type_info) + .await + .map_err(GatewayHttpError::BadRequest)?; + + let result = rib::interpret_pure(&script.compiled_worker_name, &rib_input) .await + .map_err(GatewayHttpError::RibInterpretPureError)? + .get_literal() + .ok_or(GatewayHttpError::BadRequest( + "Worker name is not a Rib expression that resolves to String".to_string(), + ))? + .as_string(); + + Ok(result) + } + + async fn evaluate_idempotency_key_rib_script( + &self, + script: &IdempotencyKeyCompiled, + request_value: &serde_json::Map, + ) -> GatewayHttpResult { + let rib_input: RibInput = resolve_rib_input(request_value, &script.rib_input) + .await + .map_err(GatewayHttpError::BadRequest)?; + + let value = rib::interpret_pure(&script.compiled_idempotency_key, &rib_input) + .await + .map_err(GatewayHttpError::RibInterpretPureError)? + .get_literal() + .ok_or(GatewayHttpError::BadRequest( + "Idempotency key is not a Rib expression that resolves to String".to_string(), + ))? + .as_string(); + + Ok(IdempotencyKey::new(value)) + } + + async fn get_worker_detail( + &self, + request: &RichRequest, + request_value: &serde_json::Map, + worker_name_compiled: &Option, + idempotency_key_compiled: &Option, + component_id: &VersionedComponentId, + ) -> GatewayHttpResult { + let worker_name = if let Some(worker_name_compiled) = worker_name_compiled { + let result = self + .evaluate_worker_name_rib_script(worker_name_compiled, request_value) + .await?; + Some(result) + } else { + None + }; + + // We prefer to take idempotency key from the rib script, + // if that is not available we fall back to our custom header. + // If neither are available, the worker-executor will later generate an idempotency key. + let idempotency_key = if let Some(idempotency_key_compiled) = idempotency_key_compiled { + let result = self + .evaluate_idempotency_key_rib_script(idempotency_key_compiled, request_value) + .await?; + Some(result) + } else { + request + .underlying + .headers() + .get("idempotency-key") + .and_then(|h| h.to_str().ok()) + .map(|value| IdempotencyKey::new(value.to_string())) + }; + + Ok(WorkerDetail { + component_id: component_id.clone(), + worker_name, + idempotency_key, + }) + } + + async fn get_response_script_result( + &self, + namespace: &Namespace, + compiled_response_mapping: &ResponseMappingCompiled, + request_value: &serde_json::Map, + worker_detail: &WorkerDetail, + ) -> GatewayHttpResult { + let rib_input = resolve_rib_input(request_value, &compiled_response_mapping.rib_input) + .await + .map_err(GatewayHttpError::BadRequest)?; + + self.evaluator + .evaluate( + worker_detail.worker_name.as_deref(), + &worker_detail.component_id.component_id, + &worker_detail.idempotency_key, + &compiled_response_mapping.response_mapping_compiled, + &rib_input, + namespace.clone(), + ) + .await + .map_err(GatewayHttpError::EvaluationError) + } + + async fn maybe_apply_middlewares_in( + &self, + mut request: RichRequest, + middlewares: &Option, + ) -> Result { + if let Some(middlewares) = middlewares { + let input_middleware_result = middlewares + .process_middleware_in( + &request, + &self.gateway_session_store, + &self.identity_provider, + ) + .await; + + let input_middleware_result = match input_middleware_result { + Ok(MiddlewareSuccess::PassThrough { + session_id: session_id_opt, + }) => { + if let Some(session_id) = session_id_opt.as_ref() { + let result = request + .add_auth_details(session_id, &self.gateway_session_store) + .await; + + if let Err(err_response) = result { + Err(MiddlewareError::InternalError(err_response)) + } else { + Ok(MiddlewareSuccess::PassThrough { + session_id: session_id_opt, + }) + } + } else { + Ok(MiddlewareSuccess::PassThrough { + session_id: session_id_opt, + }) + } + } + other => other, + }; + + match input_middleware_result { + Ok(MiddlewareSuccess::Redirect(response)) => Err(response)?, + Ok(MiddlewareSuccess::PassThrough { .. }) => Ok(request), + Err(err) => { + let response = err.to_response_from_safe_display(|error| match error { + MiddlewareError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR, + MiddlewareError::Unauthorized(_) => StatusCode::UNAUTHORIZED, + }); + Err(response)? + } + } + } else { + Ok(request) + } } } @@ -313,61 +404,166 @@ impl GatewayHttpInputExecutor for DefaultGatewayInputExecutor { async fn execute_http_request(&self, request: poem::Request) -> poem::Response { - let input_http_request_result = InputHttpRequest::from_request(request).await; + let authority = match authority_from_request(&request) { + Ok(success) => success, + Err(err) => { + return poem::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from_string(err)); + } + }; - match input_http_request_result { - Ok(input_http_request) => { - let possible_api_definitions = match self - .api_definition_lookup_service - .get(&input_http_request) - .await - { - Ok(api_defs) => api_defs, - Err(api_defs_lookup_error) => { - error!( - "API request host: {} - error: {}", - input_http_request.host, api_defs_lookup_error - ); - return poem::Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from_string("Internal error".to_string())); - } - }; + let possible_api_definitions = self + .api_definition_lookup_service + .get(&ApiSiteString(authority.clone())) + .await; - let resolver = DefaultGatewayBindingResolver::new( - input_http_request, - &self.gateway_session_store, - &self.identity_provider, + let possible_api_definitions = match possible_api_definitions { + Ok(api_defs) => api_defs, + Err(api_defs_lookup_error) => { + error!( + "API request host: {} - error: {}", + authority, api_defs_lookup_error ); + return poem::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from_string("Internal error".to_string())); + } + }; - match resolver - .resolve_gateway_binding(possible_api_definitions) + let resolved_route_entry = if let Some(resolved_route_entry) = + resolve_gateway_binding(possible_api_definitions, &request).await + { + resolved_route_entry + } else { + return poem::Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::from_string("Route not found".to_string())); + }; + + let SplitResolvedRouteEntryResult { + namespace, + binding, + middlewares, + rich_request, + } = split_resolved_route_entry(request, resolved_route_entry); + + let mut rich_request = match self + .maybe_apply_middlewares_in(rich_request, &middlewares) + .await + { + Ok(req) => req, + Err(resp) => { + tracing::debug!("Middleware short-circuited the request handling"); + return resp; + } + }; + + match binding { + GatewayBindingCompiled::Static(StaticBinding::HttpCorsPreflight(cors_preflight)) => { + cors_preflight + .clone() + .to_response(&rich_request, &self.gateway_session_store) .await - { - Ok(resolved_gateway_binding) => { - let GatewayRequestDetails::Http(request) = - resolved_gateway_binding.request_details; + } - let response: poem::Response = self - .execute(&request, resolved_gateway_binding.resolved_binding) - .await; + GatewayBindingCompiled::Static(StaticBinding::HttpAuthCallBack(auth_call_back)) => { + let result = self + .handle_http_auth_callback_binding( + &auth_call_back.security_scheme_with_metadata, + &rich_request, + ) + .await; - response - } + result + .to_response(&rich_request, &self.gateway_session_store) + .await + } - Err(ErrorOrRedirect::Error(error)) => { - error!( - "Failed to resolve the API definition; error: {}", - error.to_safe_string() - ); + GatewayBindingCompiled::Worker(resolved_worker_binding) => { + let result = self + .handle_worker_binding(&namespace, &mut rich_request, &resolved_worker_binding) + .await; - error.to_http_response() - } + let response = result + .to_response(&rich_request, &self.gateway_session_store) + .await; - Err(ErrorOrRedirect::Redirect(response)) => response, - } + maybe_apply_middlewares_out(response, &middlewares).await } - Err(response) => response.into(), + + GatewayBindingCompiled::HttpHandler(http_handler_binding) => { + let result = self + .handle_http_handler_binding( + &namespace, + &mut rich_request, + &http_handler_binding, + ) + .await; + + let response = result + .to_response(&rich_request, &self.gateway_session_store) + .await; + + maybe_apply_middlewares_out(response, &middlewares).await + } + + GatewayBindingCompiled::FileServer(resolved_file_server_binding) => { + let result = self + .handle_file_server_binding( + &namespace, + &mut rich_request, + &resolved_file_server_binding, + ) + .await; + + let response = result + .to_response(&rich_request, &self.gateway_session_store) + .await; + + maybe_apply_middlewares_out(response, &middlewares).await + } + } + } +} + +async fn resolve_rib_input( + input: &serde_json::Map, + required_types: &RibInputTypeInfo, +) -> Result { + let mut result_map: HashMap = HashMap::new(); + + for (key, analysed_type) in required_types.types.iter() { + let input_value = input + .get(key) + .ok_or(format!("Required input not available: {key}"))?; + + let parsed_value = TypeAnnotatedValue::parse_with_type( + input_value, + analysed_type + ).map_err(|err| format!("Input {key} doesn't match the requirements for rib expression to execute: {}. Requirements. {:?}", err.join(", "), analysed_type))?; + + let converted_value = parsed_value.try_into().map_err(|err| { + format!("Internal error converting between value representations: {err}") + })?; + + result_map.insert(key.clone(), converted_value); + } + + Ok(RibInput { input: result_map }) +} + +async fn maybe_apply_middlewares_out( + mut response: poem::Response, + middlewares: &Option, +) -> poem::Response { + if let Some(middlewares) = middlewares { + let result = middlewares.process_middleware_out(&mut response).await; + match result { + Ok(_) => response, + Err(err) => err.to_response_from_safe_display(|_| StatusCode::INTERNAL_SERVER_ERROR), } + } else { + response } } diff --git a/golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs b/golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs index f1347c9f7e..5d14a5f7fd 100644 --- a/golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs +++ b/golem-worker-service-base/src/gateway_execution/http_handler_binding_handler.rs @@ -12,12 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::gateway_binding::{HttpRequestDetails, WorkerDetail}; -use crate::gateway_execution::GatewayResolvedWorkerRequest; +use super::{GatewayWorkerRequestExecutor, WorkerRequestExecutorError}; +use crate::gateway_execution::{GatewayResolvedWorkerRequest, WorkerDetail}; use async_trait::async_trait; use bytes::Bytes; use golem_common::model::HasAccountId; use golem_common::virtual_exports; +use golem_common::virtual_exports::http_incoming_handler::IncomingHttpRequest; use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; use golem_wasm_rpc::TypeAnnotatedValueConstructors; use http::StatusCode; @@ -27,15 +28,13 @@ use std::convert::Infallible; use std::str::FromStr; use std::sync::Arc; -use super::{GatewayWorkerRequestExecutor, WorkerRequestExecutorError}; - #[async_trait] pub trait HttpHandlerBindingHandler { async fn handle_http_handler_binding( &self, namespace: &Namespace, worker_detail: &WorkerDetail, - request_details: &HttpRequestDetails, + incoming_http_request: IncomingHttpRequest, ) -> HttpHandlerBindingResult; } @@ -73,56 +72,19 @@ impl HttpHandlerBinding &self, namespace: &Namespace, worker_detail: &WorkerDetail, - request_details: &HttpRequestDetails, + incoming_http_request: IncomingHttpRequest, ) -> HttpHandlerBindingResult { let component_id = worker_detail.component_id.component_id.clone(); - let http_request_function_param = { - use golem_common::virtual_exports::http_incoming_handler as hic; - - let headers = { - let mut acc = Vec::new(); - for header in request_details.request_headers.0.fields.iter() { - acc.push(( - header.name.clone(), - Bytes::from(header.value.to_string().into_bytes()), - )); - } - hic::HttpFields(acc) - }; - - let body = hic::HttpBodyAndTrailers { - content: hic::HttpBodyContent(Bytes::from( - request_details - .request_body_value - .0 - .to_string() - .into_bytes(), - )), - trailers: None, - }; - - hic::IncomingHttpRequest { - scheme: request_details.scheme.clone().into(), - authority: request_details.host.to_string(), - path_with_query: request_details.get_api_input_path(), - method: hic::HttpMethod::from_http_method(request_details.request_method.clone()), - headers, - body: Some(body), - } - }; - let typ: golem_wasm_ast::analysis::protobuf::Type = (&golem_common::virtual_exports::http_incoming_handler::IncomingHttpRequest::analysed_type()).into(); let type_annotated_param = - TypeAnnotatedValue::create(&http_request_function_param.to_value(), typ).map_err( - |e| { - HttpHandlerBindingError::InternalError(format!( - "Failed converting request into wasm rpc: {:?}", - e - )) - }, - )?; + TypeAnnotatedValue::create(&incoming_http_request.to_value(), typ).map_err(|e| { + HttpHandlerBindingError::InternalError(format!( + "Failed converting request into wasm rpc: {:?}", + e + )) + })?; let resolved_request: GatewayResolvedWorkerRequest = GatewayResolvedWorkerRequest { @@ -136,7 +98,6 @@ impl HttpHandlerBinding let response = self.worker_request_executor.execute(resolved_request).await; - // log outcome match response { Ok(_) => { tracing::debug!("http_handler received successful response from worker invocation") diff --git a/golem-worker-service-base/src/gateway_execution/mod.rs b/golem-worker-service-base/src/gateway_execution/mod.rs index 8e84cd2dfb..deaf02c48c 100644 --- a/golem-worker-service-base/src/gateway_execution/mod.rs +++ b/golem-worker-service-base/src/gateway_execution/mod.rs @@ -13,8 +13,11 @@ // limitations under the License. use golem_common::model::{ComponentId, IdempotencyKey}; +use golem_common::SafeDisplay; +use golem_service_base::model::VersionedComponentId; use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; - +use std::collections::HashMap; +use std::fmt::Display; pub mod api_definition_lookup; pub mod auth_call_back_binding_handler; pub mod file_server_binding_handler; @@ -24,12 +27,14 @@ pub mod gateway_session; mod gateway_worker_request_executor; mod http_content_type_mapper; pub mod http_handler_binding_handler; -pub mod rib_input_value_resolver; +pub mod request; pub mod router; pub mod to_response; pub mod to_response_failure; - pub use gateway_worker_request_executor::*; +use golem_wasm_rpc::json::TypeAnnotatedValueJsonExtensions; +use rib::{RibInput, RibInputTypeInfo}; +use serde_json::Value; #[derive(PartialEq, Debug, Clone)] pub struct GatewayResolvedWorkerRequest { @@ -40,3 +45,79 @@ pub struct GatewayResolvedWorkerRequest { pub idempotency_key: Option, pub namespace: Namespace, } + +#[derive(Debug, Clone, PartialEq)] +pub struct WorkerDetail { + pub component_id: VersionedComponentId, + pub worker_name: Option, + pub idempotency_key: Option, +} + +impl WorkerDetail { + fn as_json(&self) -> Value { + let mut worker_detail_content = HashMap::new(); + worker_detail_content.insert( + "component_id".to_string(), + Value::String(self.component_id.component_id.0.to_string()), + ); + + if let Some(worker_name) = &self.worker_name { + worker_detail_content + .insert("name".to_string(), Value::String(worker_name.to_string())); + } + + if let Some(idempotency_key) = &self.idempotency_key { + worker_detail_content.insert( + "idempotency_key".to_string(), + Value::String(idempotency_key.value.clone()), + ); + } + + let map = serde_json::Map::from_iter(worker_detail_content); + + Value::Object(map) + } + + pub fn resolve_rib_input_value( + &self, + required_types: &RibInputTypeInfo, + ) -> Result { + let request_type_info = required_types.types.get("worker"); + + match request_type_info { + Some(worker_details_type) => { + let rib_input_with_request_content = &self.as_json(); + let request_value = + TypeAnnotatedValue::parse_with_type(rib_input_with_request_content, worker_details_type) + .map_err(|err| RibInputTypeMismatch(format!("Worker details don't match the requirements for rib expression to execute: {}. Requirements. {:?}", err.join(", "), worker_details_type)))?; + let request_value = request_value.try_into().map_err(|err| { + RibInputTypeMismatch(format!( + "Internal error converting between value representations: {err}" + )) + })?; + + let mut rib_input_map = HashMap::new(); + rib_input_map.insert("worker".to_string(), request_value); + Ok(RibInput { + input: rib_input_map, + }) + } + None => Ok(RibInput::default()), + } + } +} + +#[derive(Debug)] +pub struct RibInputTypeMismatch(pub String); + +impl Display for RibInputTypeMismatch { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Rib input type mismatch: {}", self.0) + } +} + +impl SafeDisplay for RibInputTypeMismatch { + fn to_safe_string(&self) -> String { + self.0.clone() + } +} diff --git a/golem-worker-service-base/src/gateway_execution/request.rs b/golem-worker-service-base/src/gateway_execution/request.rs new file mode 100644 index 0000000000..0626f1c372 --- /dev/null +++ b/golem-worker-service-base/src/gateway_execution/request.rs @@ -0,0 +1,406 @@ +// Copyright 2024-2025 Golem Cloud +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::gateway_session::{DataKey, GatewaySessionStore, SessionId}; +use crate::gateway_api_definition::http::{QueryInfo, VarInfo}; +use crate::gateway_binding::{GatewayBindingCompiled, ResolvedRouteEntry}; +use crate::gateway_middleware::HttpMiddlewares; +use crate::gateway_request::http_request::router::PathParamExtractor; +use bytes::Bytes; +use golem_common::SafeDisplay; +use http::HeaderMap; +use serde_json::Value; +use std::collections::HashMap; + +const COOKIE_HEADER_NAMES: [&str; 2] = ["cookie", "Cookie"]; + +/// Thin wrapper around a poem::Request that is used to evaluate all binding types when coming from an http gateway. +pub struct RichRequest { + pub underlying: poem::Request, + pub path_segments: Vec, + pub path_param_extractors: Vec, + pub query_info: Vec, + pub auth_data: Option, +} + +impl RichRequest { + pub fn url(&self) -> Result { + url::Url::parse(&self.underlying.uri().to_string()) + .map_err(|e| format!("Failed parsing url: {e}")) + } + + pub async fn add_auth_details( + &mut self, + session_id: &SessionId, + gateway_session_store: &GatewaySessionStore, + ) -> Result<(), String> { + let claims = gateway_session_store + .get(session_id, &DataKey::claims()) + .await + .map_err(|err| err.to_safe_string())?; + + self.auth_data = Some(claims.0); + + Ok(()) + } + + fn path_and_query(&self) -> Result { + self.underlying + .uri() + .path_and_query() + .map(|paq| paq.to_string()) + .ok_or("No path and query provided".to_string()) + } + + fn request_path_values(&self) -> RequestPathValues { + use crate::gateway_request::http_request::router; + + let path_param_values: HashMap = self + .path_param_extractors + .iter() + .map(|param| match param { + router::PathParamExtractor::Single { var_info, index } => { + (var_info.clone(), self.path_segments[*index].clone()) + } + router::PathParamExtractor::AllFollowing { var_info, index } => { + let value = self.path_segments[*index..].join("/"); + (var_info.clone(), value) + } + }) + .collect(); + + RequestPathValues::from(path_param_values) + } + + fn request_query_values(&self) -> Result { + let query_key_values = self + .underlying + .uri() + .query() + .map(query_components_from_str) + .unwrap_or_default(); + + RequestQueryValues::from(&query_key_values, &self.query_info) + .map_err(|e| format!("Failed to extract query values, missing: [{}]", e.join(","))) + } + + fn request_header_values(&self) -> Result { + RequestHeaderValues::from(self.underlying.headers()) + .map_err(|e| format!("Found malformed headers: [{}]", e.join(","))) + } + + /// consumes the body of the underlying request + async fn request_body_value(&mut self) -> Result { + let body = self.underlying.take_body(); + + let json_request_body: Value = if body.is_empty() { + Value::Null + } else { + match body.into_json().await { + Ok(json_request_body) => json_request_body, + Err(err) => { + tracing::error!("Failed reading http request body as json: {}", err); + Err(format!("Request body parse error: {err}"))? + } + } + }; + + Ok(RequestBodyValue(json_request_body)) + } + + fn as_basic_json_hashmap(&self) -> Result, String> { + let typed_path_values = self.request_path_values(); + let typed_query_values = self.request_query_values()?; + let typed_header_values = self.request_header_values()?; + + let mut path_values = serde_json::Map::new(); + + for field in typed_path_values.0.fields.into_iter() { + path_values.insert(field.name, field.value); + } + + for field in typed_query_values.0.fields.into_iter() { + path_values.insert(field.name, field.value); + } + + let merged_request_path_and_query = Value::Object(path_values); + + let mut header_records = serde_json::Map::new(); + + for field in typed_header_values.0.fields.iter() { + header_records.insert(field.name.clone(), field.value.clone()); + } + + let header_value = Value::Object(header_records); + + let mut basic = serde_json::Map::from_iter(vec![ + ("path".to_string(), merged_request_path_and_query), + ("headers".to_string(), header_value), + ]); + + if let Some(auth_data) = self.auth_data.as_ref() { + basic.insert("auth".to_string(), auth_data.clone()); + }; + + Ok(basic) + } + + pub fn as_json(&self) -> Result { + Ok(Value::Object(self.as_basic_json_hashmap()?)) + } + + /// consumes the body of the underlying request + pub async fn as_json_with_body(&mut self) -> Result { + let mut basic = self.as_basic_json_hashmap()?; + let body = self.request_body_value().await?; + + basic.insert("body".to_string(), body.0); + + Ok(Value::Object(basic)) + } + + /// consumes the body of the underlying request + pub async fn as_wasi_http_input( + &mut self, + ) -> Result + { + use golem_common::virtual_exports::http_incoming_handler as hic; + + let headers = { + let mut acc = Vec::new(); + for (header_name, header_value) in self.underlying.headers().iter() { + let header_bytes: Vec = header_value.as_bytes().into(); + acc.push((header_name.clone().to_string(), Bytes::from(header_bytes))); + } + hic::HttpFields(acc) + }; + + let body_bytes = self + .underlying + .take_body() + .into_bytes() + .await + .map_err(|e| format!("Failed reading request body: ${e}"))?; + + let body = hic::HttpBodyAndTrailers { + content: hic::HttpBodyContent(body_bytes), + trailers: None, + }; + + let authority = authority_from_request(&self.underlying)?; + + let path_and_query = self.path_and_query()?; + + Ok(hic::IncomingHttpRequest { + scheme: self.underlying.scheme().clone().into(), + authority, + path_and_query, + method: hic::HttpMethod::from_http_method(self.underlying.method().into()), + headers, + body: Some(body), + }) + } + + pub fn get_cookie_values(&self) -> HashMap<&str, &str> { + let mut result = HashMap::new(); + + for header_name in COOKIE_HEADER_NAMES.iter() { + if let Some(value) = self.underlying.header(header_name) { + let parts: Vec<&str> = value.split(';').collect(); + for part in parts { + let key_value: Vec<&str> = part.split('=').collect(); + if let (Some(key), Some(value)) = (key_value.first(), key_value.get(1)) { + result.insert(key.trim(), value.trim()); + } + } + } + } + + result + } +} + +pub struct SplitResolvedRouteEntryResult { + pub namespace: Namespace, + pub binding: GatewayBindingCompiled, + pub middlewares: Option, + pub rich_request: RichRequest, +} + +pub fn split_resolved_route_entry( + request: poem::Request, + entry: ResolvedRouteEntry, +) -> SplitResolvedRouteEntryResult { + // helper function to save a few clones + + let namespace = entry.route_entry.namespace; + let binding = entry.route_entry.binding; + let middlewares = entry.route_entry.middlewares; + + let rich_request = RichRequest { + underlying: request, + path_segments: entry.path_segments, + path_param_extractors: entry.route_entry.path_params, + query_info: entry.route_entry.query_params, + auth_data: None, + }; + + SplitResolvedRouteEntryResult { + namespace, + binding, + middlewares, + rich_request, + } +} + +fn query_components_from_str(query_path: &str) -> HashMap { + let mut query_components: HashMap = HashMap::new(); + let query_parts = query_path.split('&').map(|x| x.trim()); + + for part in query_parts { + let key_value: Vec<&str> = part.split('=').map(|x| x.trim()).collect(); + + if let (Some(key), Some(value)) = (key_value.first(), key_value.get(1)) { + query_components.insert(key.to_string(), value.to_string()); + } + } + + query_components +} + +pub fn authority_from_request(request: &poem::Request) -> Result { + request + .header(http::header::HOST) + .map(|h| h.to_string()) + .ok_or("No host header provided".to_string()) +} + +#[derive(Debug, Clone)] +pub struct RequestQueryValues(pub JsonKeyValues); + +impl RequestQueryValues { + pub fn from( + query_key_values: &HashMap, + query_keys: &[QueryInfo], + ) -> Result> { + let mut unavailable_query_variables: Vec = vec![]; + let mut query_variable_map: JsonKeyValues = JsonKeyValues::default(); + + for spec_query_variable in query_keys.iter() { + let key = &spec_query_variable.key_name; + if let Some(query_value) = query_key_values.get(key) { + let typed_value = internal::refine_json_str_value(query_value); + query_variable_map.push(key.clone(), typed_value); + } else { + unavailable_query_variables.push(spec_query_variable.to_string()); + } + } + + if unavailable_query_variables.is_empty() { + Ok(RequestQueryValues(query_variable_map)) + } else { + Err(unavailable_query_variables) + } + } +} + +#[derive(Debug, Clone)] +pub struct RequestHeaderValues(pub JsonKeyValues); + +impl RequestHeaderValues { + pub fn from(headers: &HeaderMap) -> Result> { + let mut headers_map: JsonKeyValues = JsonKeyValues::default(); + + for (header_name, header_value) in headers { + let header_value_str = header_value.to_str().map_err(|err| vec![err.to_string()])?; + + let typed_header_value = internal::refine_json_str_value(header_value_str); + + headers_map.push(header_name.to_string(), typed_header_value); + } + + Ok(RequestHeaderValues(headers_map)) + } +} + +#[derive(Debug, Clone)] +pub struct RequestBodyValue(pub Value); + +#[derive(Clone, Debug, Default)] +pub struct JsonKeyValues { + pub fields: Vec, +} + +impl JsonKeyValues { + pub fn push(&mut self, key: String, value: Value) { + self.fields.push(JsonKeyValue { name: key, value }); + } +} + +#[derive(Clone, Debug)] +pub struct JsonKeyValue { + pub name: String, + pub value: Value, +} + +mod internal { + use rib::{CoercedNumericValue, LiteralValue}; + use serde_json::Value; + + pub(crate) fn refine_json_str_value(value: impl AsRef) -> Value { + let primitive = LiteralValue::from(value.as_ref().to_string()); + match primitive { + LiteralValue::Num(number) => match number { + CoercedNumericValue::PosInt(value) => { + Value::Number(serde_json::Number::from(value)) + } + CoercedNumericValue::NegInt(value) => { + Value::Number(serde_json::Number::from(value)) + } + CoercedNumericValue::Float(value) => { + Value::Number(serde_json::Number::from_f64(value).unwrap()) + } + }, + LiteralValue::String(value) => Value::String(value), + LiteralValue::Bool(value) => Value::Bool(value), + } + } +} + +#[derive(Clone, Debug, Default)] +pub struct RequestPathValues(pub JsonKeyValues); + +impl RequestPathValues { + pub fn get(&self, key: &str) -> Option<&Value> { + self.0 + .fields + .iter() + .find(|field| field.name == key) + .map(|field| &field.value) + } + + fn from(path_variables: HashMap) -> RequestPathValues { + let record_fields: Vec = path_variables + .into_iter() + .map(|(key, value)| JsonKeyValue { + name: key.key_name, + value: internal::refine_json_str_value(value), + }) + .collect(); + + RequestPathValues(JsonKeyValues { + fields: record_fields, + }) + } +} diff --git a/golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs b/golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs deleted file mode 100644 index beff51e1c6..0000000000 --- a/golem-worker-service-base/src/gateway_execution/rib_input_value_resolver.rs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2024-2025 Golem Cloud -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::gateway_binding::{HttpRequestDetails, WorkerDetail}; -use golem_common::SafeDisplay; -use golem_wasm_rpc::json::TypeAnnotatedValueJsonExtensions; -use golem_wasm_rpc::protobuf::type_annotated_value::TypeAnnotatedValue; -use rib::{RibInput, RibInputTypeInfo}; -use std::collections::HashMap; -use std::fmt::Display; -use tracing::debug; - -// `RibInputValueResolver` is responsible -// for extracting `RibInputValue` from any input, given the requirements as `RibInputTypeInfo`. -// Example: HttpRequestDetails can be converted to RibInputValue -// Note that `RibInputTypeInfo` is obtained from compiling a rib script. -pub trait RibInputValueResolver { - fn resolve_rib_input_value( - &self, - required_type: &RibInputTypeInfo, - ) -> Result; -} - -#[derive(Debug)] -pub struct RibInputTypeMismatch(pub String); - -impl Display for RibInputTypeMismatch { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "Rib input type mismatch: {}", self.0) - } -} - -impl SafeDisplay for RibInputTypeMismatch { - fn to_safe_string(&self) -> String { - self.0.clone() - } -} - -impl RibInputValueResolver for HttpRequestDetails { - fn resolve_rib_input_value( - &self, - required_types: &RibInputTypeInfo, - ) -> Result { - let request_type_info = required_types.types.get("request"); - - let rib_input_with_request_content = &self.as_json(); - - match request_type_info { - Some(request_type) => { - debug!("received: {:?}", rib_input_with_request_content); - let input = TypeAnnotatedValue::parse_with_type(rib_input_with_request_content, request_type) - .map_err(|err| RibInputTypeMismatch(format!("Input request details don't match the requirements for rib expression to execute: {}. Requirements. {:?}", err.join(", "), request_type)))?; - let input = input.try_into().map_err(|err| { - RibInputTypeMismatch(format!( - "Internal error converting between value representations: {err}" - )) - })?; - - let mut rib_input_map = HashMap::new(); - rib_input_map.insert("request".to_string(), input); - Ok(RibInput { - input: rib_input_map, - }) - } - None => Ok(RibInput::default()), - } - } -} - -impl RibInputValueResolver for WorkerDetail { - fn resolve_rib_input_value( - &self, - required_types: &RibInputTypeInfo, - ) -> Result { - let request_type_info = required_types.types.get("worker"); - - match request_type_info { - Some(worker_details_type) => { - let rib_input_with_request_content = &self.as_json(); - let request_value = - TypeAnnotatedValue::parse_with_type(rib_input_with_request_content, worker_details_type) - .map_err(|err| RibInputTypeMismatch(format!("Worker details don't match the requirements for rib expression to execute: {}. Requirements. {:?}", err.join(", "), worker_details_type)))?; - let request_value = request_value.try_into().map_err(|err| { - RibInputTypeMismatch(format!( - "Internal error converting between value representations: {err}" - )) - })?; - - let mut rib_input_map = HashMap::new(); - rib_input_map.insert("worker".to_string(), request_value); - Ok(RibInput { - input: rib_input_map, - }) - } - None => Ok(RibInput::default()), - } - } -} diff --git a/golem-worker-service-base/src/gateway_execution/to_response.rs b/golem-worker-service-base/src/gateway_execution/to_response.rs index 8b160853d2..60051812f3 100644 --- a/golem-worker-service-base/src/gateway_execution/to_response.rs +++ b/golem-worker-service-base/src/gateway_execution/to_response.rs @@ -12,15 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. +use super::auth_call_back_binding_handler::{AuthorisationError, AuthorisationSuccess}; +use super::file_server_binding_handler::FileServerBindingSuccess; +use super::http_handler_binding_handler::{HttpHandlerBindingError, HttpHandlerBindingSuccess}; +use super::RibInputTypeMismatch; use crate::api::WorkerApiBaseError; -use crate::gateway_binding::HttpRequestDetails; -use crate::gateway_execution::auth_call_back_binding_handler::AuthCallBackResult; -use crate::gateway_execution::file_server_binding_handler::{ - FileServerBindingError, FileServerBindingResult, -}; +use crate::gateway_execution::file_server_binding_handler::FileServerBindingError; use crate::gateway_execution::gateway_session::GatewaySessionStore; +use crate::gateway_execution::request::RichRequest; use crate::gateway_execution::to_response_failure::ToHttpResponseFromSafeDisplay; use crate::gateway_middleware::HttpCors as CorsPreflight; +use crate::gateway_rib_interpreter::EvaluationError; use async_trait::async_trait; use http::header::*; use http::StatusCode; @@ -28,66 +30,143 @@ use poem::Body; use poem::IntoResponse; use rib::RibResult; -use super::http_handler_binding_handler::{HttpHandlerBindingError, HttpHandlerBindingResult}; - #[async_trait] pub trait ToHttpResponse { async fn to_response( self, - request_details: &HttpRequestDetails, + request: &RichRequest, session_store: &GatewaySessionStore, ) -> poem::Response; } #[async_trait] -impl ToHttpResponse for FileServerBindingResult { +impl ToHttpResponse for Result { + async fn to_response( + self, + request: &RichRequest, + session_store: &GatewaySessionStore, + ) -> poem::Response { + match self { + Ok(t) => t.to_response(request, session_store).await, + Err(e) => e.to_response(request, session_store).await, + } + } +} + +pub type GatewayHttpResult = Result; + +pub enum GatewayHttpError { + BadRequest(String), + RibInputTypeMismatch(RibInputTypeMismatch), + EvaluationError(EvaluationError), + RibInterpretPureError(String), + HttpHandlerBindingError(HttpHandlerBindingError), + FileServerBindingError(FileServerBindingError), + AuthorisationError(AuthorisationError), +} + +#[async_trait] +impl ToHttpResponse for GatewayHttpError { + async fn to_response( + self, + request_details: &RichRequest, + session_store: &GatewaySessionStore, + ) -> poem::Response { + match self { + GatewayHttpError::BadRequest(e) => poem::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from_string(format!("Invalid input: {e}"))), + GatewayHttpError::RibInputTypeMismatch(err) => { + err.to_response_from_safe_display(|_| StatusCode::BAD_REQUEST) + } + GatewayHttpError::RibInterpretPureError(err) => poem::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from_string(format!( + "Failed interpreting pure rib expression: {err}" + ))), + GatewayHttpError::EvaluationError(err) => { + err.to_response_from_safe_display(|_| StatusCode::INTERNAL_SERVER_ERROR) + } + GatewayHttpError::HttpHandlerBindingError(inner) => { + inner.to_response(request_details, session_store).await + } + GatewayHttpError::FileServerBindingError(inner) => { + inner.to_response(request_details, session_store).await + } + GatewayHttpError::AuthorisationError(inner) => { + inner.to_response(request_details, session_store).await + } + } + } +} + +#[async_trait] +impl ToHttpResponse for FileServerBindingSuccess { + async fn to_response( + self, + _request_details: &RichRequest, + _session_store: &GatewaySessionStore, + ) -> poem::Response { + Body::from_bytes_stream(self.data) + .with_content_type(self.binding_details.content_type.to_string()) + .with_status(self.binding_details.status_code) + .into_response() + } +} + +#[async_trait] +impl ToHttpResponse for FileServerBindingError { async fn to_response( self, - _request_details: &HttpRequestDetails, + _request_details: &RichRequest, _session_store: &GatewaySessionStore, ) -> poem::Response { match self { - Ok(data) => Body::from_bytes_stream(data.data) - .with_content_type(data.binding_details.content_type.to_string()) - .with_status(data.binding_details.status_code) - .into_response(), - Err(FileServerBindingError::InternalError(e)) => poem::Response::builder() + FileServerBindingError::InternalError(e) => poem::Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from_string(format!("Error {}", e).to_string())), - Err(FileServerBindingError::ComponentServiceError(inner)) => { + .body(Body::from_string(format!("Error {e}"))), + FileServerBindingError::ComponentServiceError(inner) => { WorkerApiBaseError::from(inner).into_response() } - Err(FileServerBindingError::WorkerServiceError(inner)) => { + FileServerBindingError::WorkerServiceError(inner) => { WorkerApiBaseError::from(inner).into_response() } - Err(FileServerBindingError::InvalidRibResult(e)) => poem::Response::builder() + FileServerBindingError::InvalidRibResult(e) => poem::Response::builder() .status(StatusCode::BAD_REQUEST) - .body(Body::from_string( - format!("Error while processing rib result: {}", e).to_string(), - )), + .body(Body::from_string(format!( + "Error while processing rib result: {e}" + ))), } } } #[async_trait] -impl ToHttpResponse for HttpHandlerBindingResult { +impl ToHttpResponse for HttpHandlerBindingSuccess { async fn to_response( self, - _request_details: &HttpRequestDetails, + _request_details: &RichRequest, + _session_store: &GatewaySessionStore, + ) -> poem::Response { + self.response + } +} + +#[async_trait] +impl ToHttpResponse for HttpHandlerBindingError { + async fn to_response( + self, + _request_details: &RichRequest, _session_store: &GatewaySessionStore, ) -> poem::Response { match self { - Ok(inner) => inner.response, - Err(HttpHandlerBindingError::InternalError(e)) => poem::Response::builder() + HttpHandlerBindingError::InternalError(e) => poem::Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from_string(format!("Error {}", e).to_string())), - Err(HttpHandlerBindingError::WorkerRequestExecutorError(e)) => { - poem::Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from_string( - format!("Error calling worker executor {}", e).to_string(), - )) - } + .body(Body::from_string(format!("Error {e}"))), + HttpHandlerBindingError::WorkerRequestExecutorError(e) => poem::Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from_string(format!( + "Error calling worker executor {e}" + ))), } } } @@ -97,7 +176,7 @@ impl ToHttpResponse for HttpHandlerBindingResult { impl ToHttpResponse for CorsPreflight { async fn to_response( self, - _request_details: &HttpRequestDetails, + _request_details: &RichRequest, _session_store: &GatewaySessionStore, ) -> poem::Response { let mut response = poem::Response::builder().status(StatusCode::OK).finish(); @@ -143,7 +222,7 @@ impl ToHttpResponse for CorsPreflight { impl ToHttpResponse for RibResult { async fn to_response( self, - request_details: &HttpRequestDetails, + request_details: &RichRequest, _session_store: &GatewaySessionStore, ) -> poem::Response { match internal::IntermediateHttpResponse::from(&self) { @@ -154,63 +233,68 @@ impl ToHttpResponse for RibResult { } #[async_trait] -impl ToHttpResponse for AuthCallBackResult { +impl ToHttpResponse for AuthorisationSuccess { async fn to_response( self, - _request_details: &HttpRequestDetails, + _request_details: &RichRequest, _session_store: &GatewaySessionStore, ) -> poem::Response { - match self { - Ok(success) => { - let access_token = success.access_token; - let id_token = success.id_token; - let session_id = success.session; - - let mut response = poem::Response::builder() - .status(StatusCode::FOUND) - .header("Location", success.target_path) - .header( - "Set-Cookie", - format!( - "access_token={}; HttpOnly; Secure; Path=/; SameSite=None", - access_token - ) - .as_str(), - ); - - if let Some(id_token) = id_token { - response = response.header( - "Set-Cookie", - format!( - "id_token={}; HttpOnly; Secure; Path=/; SameSite=None", - id_token - ) - .as_str(), - ) - } + let access_token = self.access_token; + let id_token = self.id_token; + let session_id = self.session; + + let mut response = poem::Response::builder() + .status(StatusCode::FOUND) + .header("Location", self.target_path) + .header( + "Set-Cookie", + format!( + "access_token={}; HttpOnly; Secure; Path=/; SameSite=None", + access_token + ) + .as_str(), + ); - response = response.header( - "Set-Cookie", - format!( - "session_id={}; HttpOnly; Secure; Path=/; SameSite=None", - session_id - ) - .as_str(), - ); + if let Some(id_token) = id_token { + response = response.header( + "Set-Cookie", + format!( + "id_token={}; HttpOnly; Secure; Path=/; SameSite=None", + id_token + ) + .as_str(), + ) + } - response.body(()) - } + response = response.header( + "Set-Cookie", + format!( + "session_id={}; HttpOnly; Secure; Path=/; SameSite=None", + session_id + ) + .as_str(), + ); - Err(err) => err.to_response_from_safe_display(|_| StatusCode::UNAUTHORIZED), - } + response.body(()) + } +} + +#[async_trait] +impl ToHttpResponse for AuthorisationError { + async fn to_response( + self, + _request_details: &RichRequest, + _session_store: &GatewaySessionStore, + ) -> poem::Response { + self.to_response_from_safe_display(|_| StatusCode::UNAUTHORIZED) } } mod internal { - use crate::gateway_binding::HttpRequestDetails; use crate::gateway_execution::http_content_type_mapper::{ ContentTypeHeaders, HttpContentTypeResponseMapper, }; + use crate::gateway_execution::request::RichRequest; use crate::gateway_rib_interpreter::EvaluationError; use http::StatusCode; @@ -263,17 +347,17 @@ mod internal { } } - pub(crate) fn to_http_response( - &self, - request_details: &HttpRequestDetails, - ) -> poem::Response { + pub(crate) fn to_http_response(&self, request_details: &RichRequest) -> poem::Response { let response_content_type = self.headers.get_content_type(); let response_headers = self.headers.headers.clone(); let status = &self.status; let evaluation_result = &self.body; - let accepted_content_types = request_details.get_accept_content_type_header(); + let accepted_content_types = request_details + .underlying + .header(http::header::ACCEPT) + .map(|s| s.to_string()); let content_type = ContentTypeHeaders::from(response_content_type, accepted_content_types); @@ -315,10 +399,10 @@ mod test { use std::sync::Arc; use test_r::test; - use crate::gateway_binding::HttpRequestDetails; use crate::gateway_execution::gateway_session::{ DataKey, DataValue, GatewaySession, GatewaySessionError, SessionId, }; + use crate::gateway_execution::request::RichRequest; use crate::gateway_execution::to_response::ToHttpResponse; use golem_wasm_ast::analysis::analysed_type::record; use golem_wasm_ast::analysis::NameTypePair; @@ -345,6 +429,16 @@ mod test { } } + fn test_request() -> RichRequest { + RichRequest { + underlying: poem::Request::default(), + path_segments: vec![], + path_param_extractors: vec![], + query_info: vec![], + auth_data: None, + } + } + #[test] async fn test_evaluation_result_to_response_with_http_specifics() { let record = create_record(vec![ @@ -364,7 +458,7 @@ mod test { let session_store: Arc = Arc::new(TestSessionStore); let http_response: poem::Response = evaluation_result - .to_response(&HttpRequestDetails::empty(), &session_store) + .to_response(&test_request(), &session_store) .await; let (response_parts, body) = http_response.into_parts(); @@ -392,7 +486,7 @@ mod test { let session_store: Arc = Arc::new(TestSessionStore); let http_response: poem::Response = evaluation_result - .to_response(&HttpRequestDetails::empty(), &session_store) + .to_response(&test_request(), &session_store) .await; let (response_parts, body) = http_response.into_parts(); diff --git a/golem-worker-service-base/src/gateway_middleware/http/authentication.rs b/golem-worker-service-base/src/gateway_middleware/http/authentication.rs index 9e41d5f513..da277155d2 100644 --- a/golem-worker-service-base/src/gateway_middleware/http/authentication.rs +++ b/golem-worker-service-base/src/gateway_middleware/http/authentication.rs @@ -1,6 +1,6 @@ -use crate::gateway_binding::HttpRequestDetails; use crate::gateway_execution::auth_call_back_binding_handler::AuthorisationError; use crate::gateway_execution::gateway_session::GatewaySessionStore; +use crate::gateway_execution::request::RichRequest; use crate::gateway_middleware::{MiddlewareError, MiddlewareSuccess}; use crate::gateway_security::{IdentityProvider, SecuritySchemeWithProviderMetadata}; use openidconnect::Scope; @@ -18,7 +18,7 @@ impl HttpAuthenticationMiddleware { pub async fn apply_http_auth( &self, - input: &HttpRequestDetails, + input: &RichRequest, session_store: &GatewaySessionStore, identity_provider: &Arc, ) -> Result { @@ -62,11 +62,11 @@ impl HttpAuthenticationMiddleware { } mod internal { - use crate::gateway_binding::HttpRequestDetails; use crate::gateway_execution::auth_call_back_binding_handler::AuthorisationError; use crate::gateway_execution::gateway_session::{ DataKey, DataValue, GatewaySessionError, GatewaySessionStore, SessionId, }; + use crate::gateway_execution::request::RichRequest; use crate::gateway_middleware::http::middleware_error::MiddlewareSuccess; use crate::gateway_middleware::{HttpAuthenticationMiddleware, MiddlewareError}; use crate::gateway_security::{IdentityProvider, OpenIdClient}; @@ -83,7 +83,7 @@ mod internal { identity_token_verifier: CoreIdTokenVerifier<'_>, id_token: &str, session_store: &GatewaySessionStore, - input: &HttpRequestDetails, + input: &RichRequest, identity_provider: &Arc, open_id_client: &OpenIdClient, http_authentication_details: &HttpAuthenticationMiddleware, @@ -142,7 +142,7 @@ mod internal { identity_token_verifier: CoreIdTokenVerifier<'_>, session_id: &SessionId, session_store: &GatewaySessionStore, - input: &HttpRequestDetails, + input: &RichRequest, identity_provider: &Arc, open_id_client: &OpenIdClient, http_authentication_details: &HttpAuthenticationMiddleware, @@ -186,12 +186,19 @@ mod internal { pub(crate) async fn redirect( session_store: &GatewaySessionStore, - input: &HttpRequestDetails, + input: &RichRequest, identity_provider: &Arc, client: &OpenIdClient, http_authorizer: &HttpAuthenticationMiddleware, ) -> Result { - let redirect_uri = input.get_api_input_path(); + let redirect_uri = input + .underlying + .uri() + .path_and_query() + .ok_or(MiddlewareError::InternalError( + "Failed to get redirect uri".to_string(), + ))? + .to_string(); let authorization = identity_provider.get_authorization_url( client, diff --git a/golem-worker-service-base/src/gateway_middleware/mod.rs b/golem-worker-service-base/src/gateway_middleware/mod.rs index f37d38e4d7..348046068c 100644 --- a/golem-worker-service-base/src/gateway_middleware/mod.rs +++ b/golem-worker-service-base/src/gateway_middleware/mod.rs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::gateway_binding::HttpRequestDetails; use crate::gateway_execution::gateway_session::GatewaySessionStore; +use crate::gateway_execution::request::RichRequest; use crate::gateway_security::{IdentityProvider, SecuritySchemeWithProviderMetadata}; pub use http::*; use std::sync::Arc; @@ -40,7 +40,7 @@ impl HttpMiddlewares { pub async fn process_middleware_in( &self, - http_request_details: &HttpRequestDetails, + rich_request: &RichRequest, session_store: &GatewaySessionStore, identity_provider: &Arc, ) -> Result { @@ -51,7 +51,7 @@ impl HttpMiddlewares { HttpMiddleware::AddCorsHeaders(_) => {} HttpMiddleware::AuthenticateRequest(auth) => { let result = auth - .apply_http_auth(http_request_details, session_store, identity_provider) + .apply_http_auth(rich_request, session_store, identity_provider) .await?; match result { diff --git a/golem-worker-service-base/src/gateway_request/http_request.rs b/golem-worker-service-base/src/gateway_request/http_request.rs index 3cae96c429..5effd6eca0 100644 --- a/golem-worker-service-base/src/gateway_request/http_request.rs +++ b/golem-worker-service-base/src/gateway_request/http_request.rs @@ -12,29 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::gateway_api_deployment::ApiSiteString; -use http::header::HOST; -use http::uri::Scheme; -use http::StatusCode; -use hyper::http::{HeaderMap, Method}; -use poem::{Body, Response}; -use serde_json::Value; +use poem::Response; use std::collections::HashMap; use std::fmt::Display; -use tracing::error; - -#[derive(Clone, Debug)] -pub struct InputHttpRequest { - pub scheme: Scheme, - pub host: ApiSiteString, - pub api_input_path: ApiInputPath, - pub headers: HeaderMap, - pub req_method: Method, - pub req_body: Value, -} #[derive(Debug)] -pub struct ErrorResponse(Response); +pub struct ErrorResponse(pub Response); impl From for Response { fn from(value: ErrorResponse) -> Self { @@ -42,54 +25,6 @@ impl From for Response { } } -impl InputHttpRequest { - pub async fn from_request(request: poem::Request) -> Result { - let scheme = request.scheme().clone(); - let (req_parts, body) = request.into_parts(); - let headers = req_parts.headers; - let uri = req_parts.uri; - - let host = match headers.get(HOST).and_then(|h| h.to_str().ok()) { - Some(host) => ApiSiteString(host.to_string()), - None => { - return Err(ErrorResponse( - Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from_string("Missing host".to_string())), - )); - } - }; - - let json_request_body: Value = if body.is_empty() { - Value::Null - } else { - match body.into_json().await { - Ok(json_request_body) => json_request_body, - Err(err) => { - error!("API request host: {} - error: {}", host, err); - return Err(ErrorResponse( - Response::builder() - .status(StatusCode::BAD_REQUEST) - .body(Body::from_string("Request body parse error".to_string())), - )); - } - } - }; - - Ok(InputHttpRequest { - scheme: scheme.clone(), - host, - api_input_path: ApiInputPath { - base_path: uri.path().to_string(), - query_path: uri.query().map(|x| x.to_string()), - }, - headers, - req_method: req_parts.method, - req_body: json_request_body, - }) - } -} - #[derive(Debug, Clone)] pub struct ApiInputPath { pub base_path: String, diff --git a/golem-worker-service-base/src/gateway_request/mod.rs b/golem-worker-service-base/src/gateway_request/mod.rs index 4de4fbd444..c61a986966 100644 --- a/golem-worker-service-base/src/gateway_request/mod.rs +++ b/golem-worker-service-base/src/gateway_request/mod.rs @@ -13,4 +13,3 @@ // limitations under the License. pub mod http_request; -pub mod request_details; diff --git a/golem-worker-service-base/src/gateway_request/request_details.rs b/golem-worker-service-base/src/gateway_request/request_details.rs deleted file mode 100644 index 882158e7fc..0000000000 --- a/golem-worker-service-base/src/gateway_request/request_details.rs +++ /dev/null @@ -1,373 +0,0 @@ -// Copyright 2024-2025 Golem Cloud -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::gateway_api_definition::http::{QueryInfo, VarInfo}; - -use crate::gateway_api_deployment::ApiSiteString; -use crate::gateway_execution::gateway_session::{DataKey, GatewaySessionStore, SessionId}; -use crate::gateway_middleware::HttpMiddlewares; -use crate::gateway_request::http_request::ApiInputPath; -use golem_common::SafeDisplay; -use http::uri::Scheme; -use http::{HeaderMap, Method}; -use serde_json::Value; -use std::collections::HashMap; -use url::Url; - -// https://github.com/golemcloud/golem/issues/1069 -#[derive(Clone, Debug)] -pub enum GatewayRequestDetails { - Http(HttpRequestDetails), -} - -// A structure that holds the incoming request details -// along with parameters that are required by the route in API definition -// Any extra query parameter values in the incoming request will not be available -// in query or path values. If we need to retrieve them at any stage, the original -// api_input_path is still available. -#[derive(Debug, Clone)] -pub struct HttpRequestDetails { - pub scheme: Scheme, - pub host: ApiSiteString, - pub request_method: Method, - pub api_input_path: ApiInputPath, - pub request_path_params: RequestPathValues, - pub request_body_value: RequestBody, - pub request_query_params: RequestQueryValues, - pub request_headers: RequestHeaderValues, - pub http_middlewares: Option, - pub request_custom_params: Option>, -} - -impl HttpRequestDetails { - pub async fn inject_auth_details( - &mut self, - session_id: &SessionId, - gateway_session_store: &GatewaySessionStore, - ) -> Result<(), String> { - let claims = gateway_session_store - .get(session_id, &DataKey::claims()) - .await - .map_err(|err| err.to_safe_string())?; - - if let Some(custom_params) = self.request_custom_params.as_mut() { - custom_params.insert("auth".to_string(), claims.0); - } else { - self.request_custom_params = Some(HashMap::from_iter([("auth".to_string(), claims.0)])); - } - - Ok(()) - } - - pub fn as_json(&self) -> Value { - let typed_path_values = self.request_path_params.clone().0; - let typed_query_values = self.request_query_params.clone().0; - - let mut path_values = serde_json::Map::new(); - - for field in typed_path_values.fields.iter() { - path_values.insert(field.name.clone(), field.value.clone()); - } - - for field in typed_query_values.fields.iter() { - path_values.insert(field.name.clone(), field.value.clone()); - } - - let merged_request_path_and_query = Value::Object(path_values); - - let mut header_records = serde_json::Map::new(); - - for field in self.request_headers.0.fields.iter() { - header_records.insert(field.name.clone(), field.value.clone()); - } - - let header_value = Value::Object(header_records); - - let mut basic = serde_json::Map::from_iter(vec![ - ("path".to_string(), merged_request_path_and_query), - ("body".to_string(), self.request_body_value.0.clone()), - ("headers".to_string(), header_value), - ]); - - let custom = self.request_custom_params.clone().unwrap_or_default(); - - for (key, value) in custom.iter() { - basic.insert(key.clone(), value.clone()); - } - - Value::Object(basic) - } - - pub fn url(&self) -> Result { - let url_str = format!( - "{}://{}{}", - &self.scheme, - &self.host, - &self.api_input_path.to_string() - ); - - Url::parse(&url_str).map_err(|err| err.to_string()) - } - - pub fn empty() -> HttpRequestDetails { - HttpRequestDetails { - scheme: Scheme::HTTP, - host: ApiSiteString("".to_string()), - request_method: Method::GET, - api_input_path: ApiInputPath { - base_path: "".to_string(), - query_path: None, - }, - request_path_params: RequestPathValues(JsonKeyValues::default()), - request_body_value: RequestBody(Value::Null), - request_query_params: RequestQueryValues(JsonKeyValues::default()), - request_headers: RequestHeaderValues(JsonKeyValues::default()), - http_middlewares: None, - request_custom_params: None, - } - } - - pub fn get_api_input_path(&self) -> String { - self.api_input_path.to_string() - } - - pub fn get_access_token_from_cookie(&self) -> Option { - self.request_headers - .0 - .fields - .iter() - .find(|field| field.name == "Cookie" || field.name == "cookie") - .and_then(|field| field.value.as_str().map(|x| x.to_string())) - .and_then(|cookie_header| { - let parts: Vec<&str> = cookie_header.split(';').collect(); - let access_token_part = parts.iter().find(|part| part.contains("access_token")); - access_token_part.and_then(|part| { - let token_parts: Vec<&str> = part.split('=').collect(); - if token_parts.len() == 2 { - Some(token_parts[1].to_string()) - } else { - None - } - }) - }) - } - - pub fn get_id_token_from_cookie(&self) -> Option { - self.request_headers - .0 - .fields - .iter() - .find(|field| field.name == "Cookie" || field.name == "cookie") - .and_then(|field| field.value.as_str().map(|x| x.to_string())) - .and_then(|cookie_header| { - let parts: Vec<&str> = cookie_header.split(';').collect(); - let id_token_part = parts.iter().find(|part| part.contains("id_token")); - id_token_part.and_then(|part| { - let token_parts: Vec<&str> = part.split('=').collect(); - if token_parts.len() == 2 { - Some(token_parts[1].to_string()) - } else { - None - } - }) - }) - } - - pub fn get_cookie_values(&self) -> HashMap<&str, &str> { - let mut hash_map = HashMap::new(); - - for json_key_value in &self.request_headers.0.fields { - let field_name = &json_key_value.name; - - if field_name == "cookie" || field_name == "Cookie" { - if let Some(cookie_header) = json_key_value.value.as_str() { - let parts: Vec<&str> = cookie_header.split(';').collect(); - for part in parts { - let key_value: Vec<&str> = part.split('=').collect(); - if let (Some(key), Some(value)) = (key_value.first(), key_value.get(1)) { - hash_map.insert(key.trim(), value.trim()); - } - } - } - } - } - - hash_map - } - - pub fn get_accept_content_type_header(&self) -> Option { - self.request_headers - .0 - .fields - .iter() - .find(|field| field.name == http::header::ACCEPT.to_string()) - .and_then(|field| field.value.as_str().map(|x| x.to_string())) - } - - pub fn from_input_http_request( - scheme: &Scheme, - host: &ApiSiteString, - method: Method, - api_input_path: &ApiInputPath, - path_params: &HashMap, - query_variable_values: &HashMap, - query_variable_names: &[QueryInfo], - request_body: &Value, - all_headers: HeaderMap, - http_middlewares: &Option, - ) -> Result> { - let request_body = RequestBody::from(request_body)?; - let path_params = RequestPathValues::from(path_params); - let query_params = RequestQueryValues::from(query_variable_values, query_variable_names)?; - let header_params = RequestHeaderValues::from(&all_headers)?; - - Ok(Self { - scheme: scheme.clone(), - host: host.clone(), - request_method: method, - api_input_path: api_input_path.clone(), - request_path_params: path_params, - request_body_value: request_body, - request_query_params: query_params, - request_headers: header_params, - http_middlewares: http_middlewares.clone(), - request_custom_params: None, - }) - } -} - -#[derive(Clone, Debug, Default)] -pub struct RequestPathValues(pub JsonKeyValues); - -impl RequestPathValues { - pub fn get(&self, key: &str) -> Option<&Value> { - self.0 - .fields - .iter() - .find(|field| field.name == key) - .map(|field| &field.value) - } - - fn from(path_variables: &HashMap) -> RequestPathValues { - let record_fields: Vec = path_variables - .iter() - .map(|(key, value)| JsonKeyValue { - name: key.key_name.clone(), - value: internal::refine_json_str_value(value), - }) - .collect(); - - RequestPathValues(JsonKeyValues { - fields: record_fields, - }) - } -} - -#[derive(Debug, Clone)] -pub struct RequestQueryValues(pub JsonKeyValues); - -impl RequestQueryValues { - fn from( - query_key_values: &HashMap, - query_keys: &[QueryInfo], - ) -> Result> { - let mut unavailable_query_variables: Vec = vec![]; - let mut query_variable_map: JsonKeyValues = JsonKeyValues::default(); - - for spec_query_variable in query_keys.iter() { - let key = &spec_query_variable.key_name; - if let Some(query_value) = query_key_values.get(key) { - let typed_value = internal::refine_json_str_value(query_value); - query_variable_map.push(key.clone(), typed_value); - } else { - unavailable_query_variables.push(spec_query_variable.to_string()); - } - } - - if unavailable_query_variables.is_empty() { - Ok(RequestQueryValues(query_variable_map)) - } else { - Err(unavailable_query_variables) - } - } -} - -#[derive(Debug, Clone)] -pub struct RequestHeaderValues(pub JsonKeyValues); - -impl RequestHeaderValues { - fn from(headers: &HeaderMap) -> Result> { - let mut headers_map: JsonKeyValues = JsonKeyValues::default(); - - for (header_name, header_value) in headers { - let header_value_str = header_value.to_str().map_err(|err| vec![err.to_string()])?; - - let typed_header_value = internal::refine_json_str_value(header_value_str); - - headers_map.push(header_name.to_string(), typed_header_value); - } - - Ok(RequestHeaderValues(headers_map)) - } -} - -#[derive(Debug, Clone)] -pub struct RequestBody(pub Value); - -impl RequestBody { - fn from(request_body: &Value) -> Result> { - Ok(RequestBody(request_body.clone())) - } -} - -#[derive(Clone, Debug, Default)] -pub struct JsonKeyValues { - pub fields: Vec, -} - -impl JsonKeyValues { - pub fn push(&mut self, key: String, value: Value) { - self.fields.push(JsonKeyValue { name: key, value }); - } -} - -#[derive(Clone, Debug)] -pub struct JsonKeyValue { - pub name: String, - pub value: Value, -} - -mod internal { - use rib::{CoercedNumericValue, LiteralValue}; - use serde_json::Value; - - pub(crate) fn refine_json_str_value(value: impl AsRef) -> Value { - let primitive = LiteralValue::from(value.as_ref().to_string()); - match primitive { - LiteralValue::Num(number) => match number { - CoercedNumericValue::PosInt(value) => { - Value::Number(serde_json::Number::from(value)) - } - CoercedNumericValue::NegInt(value) => { - Value::Number(serde_json::Number::from(value)) - } - CoercedNumericValue::Float(value) => { - Value::Number(serde_json::Number::from_f64(value).unwrap()) - } - }, - LiteralValue::String(value) => Value::String(value), - LiteralValue::Bool(value) => Value::Bool(value), - } - } -} diff --git a/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs b/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs index 5d1fc6805f..607fa75fbf 100644 --- a/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs +++ b/golem-worker-service-base/tests/api_gateway_end_to_end_tests.rs @@ -26,9 +26,6 @@ use crate::security::TestIdentityProvider; use chrono::{DateTime, Utc}; use golem_common::model::IdempotencyKey; use golem_worker_service_base::gateway_execution::auth_call_back_binding_handler::DefaultAuthCallBack; -use golem_worker_service_base::gateway_execution::gateway_binding_resolver::{ - DefaultGatewayBindingResolver, GatewayBindingResolver, -}; use golem_worker_service_base::gateway_execution::gateway_http_input_executor::{ DefaultGatewayInputExecutor, GatewayHttpInputExecutor, }; @@ -36,9 +33,9 @@ use golem_worker_service_base::gateway_execution::gateway_session::{ GatewaySession, GatewaySessionStore, }; use golem_worker_service_base::gateway_middleware::HttpCors; -use golem_worker_service_base::gateway_request::http_request::{ApiInputPath, InputHttpRequest}; +use golem_worker_service_base::gateway_request::http_request::ApiInputPath; use golem_worker_service_base::gateway_security::{ - IdentityProvider, Provider, SecurityScheme, SecuritySchemeIdentifier, + Provider, SecurityScheme, SecuritySchemeIdentifier, }; use golem_worker_service_base::{api, gateway_api_definition}; use http::header::LOCATION; @@ -1152,34 +1149,19 @@ async fn test_api_def_for_valid_input_with_idempotency_key_in_header() { ) .await; - let compiled_api_spec = CompiledHttpApiDefinition::from_http_api_definition( + let session_store = internal::get_session_store(); + + let response = execute( + api_request, &api_specification, - &internal::get_component_metadata(), - &DefaultNamespace::default(), + &session_store, + &TestIdentityProvider::default(), ) - .unwrap(); - - let input_http_request = InputHttpRequest::from_request(api_request).await.unwrap(); - - let identity_provider: Arc = - Arc::new(TestIdentityProvider::default()); + .await; - // Resolve the API definition binding from input - let resolver = DefaultGatewayBindingResolver::new( - input_http_request, - &internal::get_session_store(), - &identity_provider, - ); + let test_response = internal::get_details_from_response(response).await; - let resolved_route = resolver - .resolve_gateway_binding(vec![compiled_api_spec]) - .await - .unwrap(); - - assert_eq!( - resolved_route.get_worker_detail().unwrap().idempotency_key, - idempotency_key - ); + assert_eq!(test_response.idempotency_key, idempotency_key); } test_key(&HeaderMap::new(), None).await; @@ -1578,7 +1560,8 @@ async fn get_api_def_with_with_default_cors_preflight_for_get_endpoint_resource( mod internal { use async_trait::async_trait; - use golem_common::model::ComponentId; + use golem_common::model::{ComponentId, IdempotencyKey}; + use golem_common::virtual_exports::http_incoming_handler::IncomingHttpRequest; use golem_service_base::auth::DefaultNamespace; use golem_service_base::model::VersionedComponentId; use golem_wasm_ast::analysis::analysed_type::{field, record, str, tuple}; @@ -1591,40 +1574,35 @@ mod internal { use golem_worker_service_base::gateway_api_definition::http::{ CompiledHttpApiDefinition, ComponentMetadataDictionary, }; + use golem_worker_service_base::gateway_api_deployment::ApiSiteString; + use golem_worker_service_base::gateway_execution::api_definition_lookup::{ + ApiDefinitionLookupError, HttpApiDefinitionsLookup, + }; use golem_worker_service_base::gateway_execution::file_server_binding_handler::{ FileServerBindingHandler, FileServerBindingResult, }; - use golem_worker_service_base::gateway_execution::gateway_binding_resolver::WorkerDetail; + use golem_worker_service_base::gateway_execution::gateway_session::{ + DataKey, DataValue, GatewaySession, GatewaySessionError, GatewaySessionStore, SessionId, + }; use golem_worker_service_base::gateway_execution::http_handler_binding_handler::{ HttpHandlerBindingHandler, HttpHandlerBindingResult, }; + use golem_worker_service_base::gateway_execution::WorkerDetail; use golem_worker_service_base::gateway_execution::{ GatewayResolvedWorkerRequest, GatewayWorkerRequestExecutor, WorkerRequestExecutorError, WorkerResponse, }; use golem_worker_service_base::gateway_middleware::HttpCors; - - use golem_worker_service_base::gateway_request::request_details::HttpRequestDetails; use golem_worker_service_base::gateway_rib_interpreter::{ DefaultRibInterpreter, EvaluationError, WorkerServiceRibInterpreter, }; - use http::header::{ ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE, }; - use poem::Response; use rib::RibResult; - - use golem_worker_service_base::gateway_execution::api_definition_lookup::{ - ApiDefinitionLookupError, ApiDefinitionsLookup, - }; - use golem_worker_service_base::gateway_execution::gateway_session::{ - DataKey, DataValue, GatewaySession, GatewaySessionError, GatewaySessionStore, SessionId, - }; - use golem_worker_service_base::gateway_request::http_request::InputHttpRequest; use serde_json::Value; use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -1640,13 +1618,12 @@ mod internal { } #[async_trait] - impl ApiDefinitionsLookup for TestApiDefinitionLookup { - type ApiDefinition = CompiledHttpApiDefinition; - + impl HttpApiDefinitionsLookup for TestApiDefinitionLookup { async fn get( &self, - _input: &InputHttpRequest, - ) -> Result, ApiDefinitionLookupError> { + _input: &ApiSiteString, + ) -> Result>, ApiDefinitionLookupError> + { Ok(vec![self.api_definition.clone()]) } } @@ -1687,7 +1664,7 @@ mod internal { &self, _namespace: &Namespace, _worker_detail: &WorkerDetail, - _request_details: &HttpRequestDetails, + _request_details: IncomingHttpRequest, ) -> HttpHandlerBindingResult { unimplemented!() } @@ -1699,7 +1676,8 @@ mod internal { pub function_name: String, pub function_params: Value, pub user_email: Option, - pub cors_middleware_headers: Option, // if binding has cors middleware configured + pub cors_middleware_headers: Option, // if binding has cors middleware configured, + pub idempotency_key: Option, } #[derive(Debug, Clone)] @@ -1783,7 +1761,7 @@ mod internal { if let Some(idempotency_key) = worker_request.clone().idempotency_key { record_elems.push(( - "idempotency-key".to_string(), + "idempotency_key".to_string(), TypeAnnotatedValue::Str(idempotency_key.to_string()), )) }; @@ -1918,12 +1896,19 @@ mod internal { let function_params = body_json.get("function_params").cloned(); + let idempotency_key = body_json + .get("idempotency_key") + .and_then(|v| v.as_str()) + .map(String::from) + .map(IdempotencyKey::new); + DefaultResult { worker_name: worker_name.expect("Worker response expects worker_name"), function_name: function_name.expect("Worker response expects function_name"), function_params: function_params.expect("Worker response expects function_params"), user_email: user_email.clone(), cors_middleware_headers: None, + idempotency_key, } } @@ -1957,6 +1942,12 @@ mod internal { let function_params = body_json.get("function_params").cloned(); + let idempotency_key = body_json + .get("idempotency_key") + .and_then(|v| v.as_str()) + .map(String::from) + .map(IdempotencyKey::new); + DefaultResult { worker_name: worker_name.expect("Worker response expects worker_name"), function_name: function_name.expect("Worker response expects function_name"), @@ -1982,6 +1973,7 @@ mod internal { cors_header_expose_headers, }) }, + idempotency_key, } } diff --git a/golem-worker-service/src/service/mod.rs b/golem-worker-service/src/service/mod.rs index e0eb4f7890..cc491d46a2 100644 --- a/golem-worker-service/src/service/mod.rs +++ b/golem-worker-service/src/service/mod.rs @@ -27,15 +27,13 @@ use golem_worker_service_base::gateway_execution::http_handler_binding_handler:: }; use worker_request_executor::UnauthorisedWorkerRequestExecutor; -use golem_worker_service_base::gateway_api_definition::http::{ - CompiledHttpApiDefinition, HttpApiDefinition, -}; +use golem_worker_service_base::gateway_api_definition::http::HttpApiDefinition; use golem_service_base::auth::{DefaultNamespace, EmptyAuthCtx}; use golem_worker_service_base::app_config::{GatewaySessionStorageConfig, WorkerServiceBaseConfig}; use golem_worker_service_base::gateway_execution::api_definition_lookup::{ - ApiDefinitionsLookup, HttpApiDefinitionLookup, + DefaultHttpApiDefinitionLookup, HttpApiDefinitionsLookup, }; use golem_worker_service_base::gateway_execution::GatewayWorkerRequestExecutor; use golem_worker_service_base::repo::api_definition; @@ -59,7 +57,6 @@ use golem_worker_service_base::gateway_execution::gateway_session::{ GatewaySession, RedisGatewaySession, RedisGatewaySessionExpiration, SqliteGatewaySession, SqliteGatewaySessionExpiration, }; -use golem_worker_service_base::gateway_request::http_request::InputHttpRequest; use golem_worker_service_base::gateway_security::DefaultIdentityProvider; use golem_worker_service_base::repo::security_scheme::{DbSecuritySchemeRepo, SecuritySchemeRepo}; use golem_worker_service_base::service::gateway::api_deployment::{ @@ -81,13 +78,8 @@ pub struct Services { Arc + Sync + Send>, pub deployment_service: Arc + Sync + Send>, - pub http_definition_lookup_service: Arc< - dyn ApiDefinitionsLookup< - InputHttpRequest, - ApiDefinition = CompiledHttpApiDefinition, - > + Sync - + Send, - >, + pub http_definition_lookup_service: + Arc + Sync + Send>, pub worker_to_http_service: Arc + Sync + Send>, pub gateway_session_store: Arc, @@ -292,8 +284,9 @@ impl Services { component_service.clone(), )); - let http_definition_lookup_service = - Arc::new(HttpApiDefinitionLookup::new(deployment_service.clone())); + let http_definition_lookup_service = Arc::new(DefaultHttpApiDefinitionLookup::new( + deployment_service.clone(), + )); Ok(Services { worker_service,