diff --git a/Cargo.lock b/Cargo.lock index 6123e9c..c853de7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -813,7 +813,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1656,7 +1656,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1831,6 +1831,7 @@ name = "pd-edge-abi" version = "0.1.0" dependencies = [ "pd-host-function", + "pd-vm", "syn", ] @@ -1846,7 +1847,7 @@ dependencies = [ [[package]] name = "pd-host-function" version = "0.1.0" -source = "git+https://github.com/rustscript-lang/rustscript.git?rev=b1d6cffede77f49410bf63525f30b9a46b02dc01#b1d6cffede77f49410bf63525f30b9a46b02dc01" +source = "git+https://github.com/rustscript-lang/rustscript.git?rev=2f433edab3f1907e8cb060e901357d7e2af016ce#2f433edab3f1907e8cb060e901357d7e2af016ce" dependencies = [ "pd-host-schema", "proc-macro2", @@ -1857,7 +1858,7 @@ dependencies = [ [[package]] name = "pd-host-schema" version = "0.1.0" -source = "git+https://github.com/rustscript-lang/rustscript.git?rev=b1d6cffede77f49410bf63525f30b9a46b02dc01#b1d6cffede77f49410bf63525f30b9a46b02dc01" +source = "git+https://github.com/rustscript-lang/rustscript.git?rev=2f433edab3f1907e8cb060e901357d7e2af016ce#2f433edab3f1907e8cb060e901357d7e2af016ce" dependencies = [ "proc-macro2", "syn", @@ -1866,7 +1867,7 @@ dependencies = [ [[package]] name = "pd-vm" version = "0.1.0" -source = "git+https://github.com/rustscript-lang/rustscript.git?rev=b1d6cffede77f49410bf63525f30b9a46b02dc01#b1d6cffede77f49410bf63525f30b9a46b02dc01" +source = "git+https://github.com/rustscript-lang/rustscript.git?rev=2f433edab3f1907e8cb060e901357d7e2af016ce#2f433edab3f1907e8cb060e901357d7e2af016ce" dependencies = [ "base64", "cranelift-codegen", diff --git a/Cargo.toml b/Cargo.toml index 1291c24..53fd918 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ name = "edge" # Keep HTTP/3 opt-in in normal builds; release.yml enables it explicitly with --all-features. # Do not enable `vm/edge-abi`: frozen pd-vm's optional edge-abi depends on # crates.io pd-edge-abi 0.1.1 (ABI24). HTTP compiles and runs against the -# in-tree ABI25 catalog, exact compiler overlay, and runtime descriptors. +# in-tree ABI26 catalog, exact compiler overlay, and runtime descriptors. default = ["console", "http", "tls", "websocket"] console = ["http", "tls", "websocket", "edge_abi/console"] native-jit = ["vm/cranelift-jit"] @@ -73,7 +73,7 @@ h3-quinn = { version = "0.0.10", optional = true } futures-util = "0.3" pd-edge-host-function = { path = "./pd-edge-host-function", version = "0.1.0" } linkme = "0.3" -vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "b1d6cffede77f49410bf63525f30b9a46b02dc01", version = "0.1.0", default-features = false, features = ["runtime"] } +vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "2f433edab3f1907e8cb060e901357d7e2af016ce", version = "0.1.0", default-features = false, features = ["runtime"] } edge_abi = { package = "pd-edge-abi", path = "./pd-edge-abi", version = "0.1.0", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/docs/EDGE_HOST_DESCRIPTOR_MIGRATION.md b/docs/EDGE_HOST_DESCRIPTOR_MIGRATION.md index a7267d2..80668a1 100644 --- a/docs/EDGE_HOST_DESCRIPTOR_MIGRATION.md +++ b/docs/EDGE_HOST_DESCRIPTOR_MIGRATION.md @@ -1,7 +1,7 @@ # Edge host descriptor and effect migration This repository is pinned to the frozen RustScript descriptor core -`b1d6cffede77f49410bf63525f30b9a46b02dc01` (a git dependency for `pd-vm` and +`2f433edab3f1907e8cb060e901357d7e2af016ce` (a git dependency for `pd-vm` and `pd-host-function`). This note records how the edge host surface is derived after the migration, and which boundaries are intentionally *not* typed. @@ -55,7 +55,7 @@ Their descriptor schema is the observed parameter list with an untyped return exactly how the guest compiler represents such calls. They must not be moved into the published ABI without a versioned ABI change. -## Named closed records (ABI version 25) +## Named closed records (ABI version 26) Closed fixed-shape returns are overlayed as `HostTypeSchema::Named` on the compiler catalog. Runtime values remain maps. The overlay changes the catalog @@ -63,18 +63,66 @@ fingerprint tag, so it is an explicit ABI-versioned change. | Function | Named schema | Runtime representation | |---|---|---| -| `mqtt::connection::read_event` | `MqttEvent` (`kind` plus optional publish/close/fail fields) | map | +| `mqtt::connection::read_event` | `MqttEvent`: always-present `kind` plus `Option` for every variant-specific member | map with canonical `Option` carriers | Compile options install this catalog so the guest compiler sees the named contract. The coarse `pd-edge-abi` wire type for `read_event` remains `map`. +A member the active variant does not carry is an explicit `None` +carrier, never a missing map entry and never a nullable (`optional`) field: +the frozen compiler rejects a nullable field on a host output and requires the +canonical `Option` carrier for an absent member. Published ABI namespaces (`runtime`, `tcp`, `http`, …) are exact catalog modules. A guest file of the same name is not a host-namespace fallback; local modules still compile when their namespace is not in the catalog. +## Fallible optional-text getters (ABI version 26) + +A getter for a member that may be absent publishes +`Result, string>` instead of returning an empty string: + +| Function | Guest contract | +|---|---| +| `http::request::get_header` | `Ok(None)` absent, `Ok(Some(""))` present-but-empty, `Err` value is not text | +| `http::request::get_query_arg` | same; a repeated key keeps the first value | +| `http::response::get_header` | same | +| `http::response::get_trailer` | same | +| `http::exchange::get_header` | same | + +The wire tag is `result_option_string`; the carrier is the canonical +`Result`/`Option` map pair, so absence is never a bare Null and an undecodable +value is never an empty-string sentinel. An invalid header or trailer name +stays a fatal host error. Fields that always exist (`method`, `path`, `uri`, +`version`, `status`, ...) keep returning `string`/`int`. + +## Core IO readers overridden by the edge runtime (ABI version 26) + +`io::read_all` and `io::read_line` are edge overrides of core builtins: the +runtime keeps its own handles, but the guest contract is the one the frozen +compiler resolves from the core IO module. Both are published as explicit +results: + +| Function | Guest contract | +|---|---| +| `io::read_all` | `Result`: the remaining text, or the guest error | +| `io::read_line` | `Result, string>`: `Ok(None)` at end of stream, `Ok(Some(""))` for a blank line, one trailing `\n` stripped | +| `io::write` | `Result`: bytes written | +| `io::flush` | `Result<(), string>` | +| `io::close` | `Result<(), string>` | + +A handle or transport failure stays a fatal host error. The embedded +`http::upstream::response` wrapper propagates both text contracts (`next_line`, +`read_line`, `read_all`) instead of collapsing them. + +`io::open` stays the one edge override whose value cannot match its core +contract: core publishes `Result`, while the edge +runtime returns a raw virtual-handle `int` (see the raw-handle metadata +family). Minting a core `io.file` resource is not possible from edge scope, so +the open result keeps the raw token and no guest is currently typed against it. + ## Intentional dynamic boundaries -The edge ABI is a published wire contract (ABI version 25, shared with the +The edge ABI is a published wire contract (ABI version 26, shared with the `pd-edge-abi` crate the VM compiler links). The following stay dynamic and are pinned by an allowlist test. WebRTC has no map/any wire types. diff --git a/examples/console/sample_console_http3_client.rss b/examples/console/sample_console_http3_client.rss index 26ee80e..4a2a68e 100644 --- a/examples/console/sample_console_http3_client.rss +++ b/examples/console/sample_console_http3_client.rss @@ -68,7 +68,7 @@ if argc == 0 { console::stdout::write("http-version=" + http::exchange::get_http_version(exchange) + "\n"); console::stdout::write("alpn=" + tls::session::get_alpn(session) + "\n"); - let content_type = http::exchange::get_header(exchange, "content-type"); + let content_type = exchange_header_text(exchange, "content-type"); if content_type != "" { console::stdout::write("content-type=" + content_type + "\n"); } @@ -78,3 +78,17 @@ if argc == 0 { console::stdout::write("\n"); console::stdout::flush(); } + +// `http::exchange::get_header` reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn exchange_header_text(exchange: int, name: string) -> string { + let value: Result, string> = http::exchange::get_header(exchange, name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/http/proxy/sample_anthropic_messages_to_openai_chat_completions_program.rss b/examples/http/proxy/sample_anthropic_messages_to_openai_chat_completions_program.rss index f5c8bb0..d411214 100644 --- a/examples/http/proxy/sample_anthropic_messages_to_openai_chat_completions_program.rss +++ b/examples/http/proxy/sample_anthropic_messages_to_openai_chat_completions_program.rss @@ -62,14 +62,14 @@ struct OpenAiUsage { struct OpenAiAssistantMessage { role: string, content: string, - refusal: null, - annotations: [null], + refusal: (), + annotations: [()], } struct OpenAiChoice { index: int, message: OpenAiAssistantMessage, - logprobs: null, + logprobs: (), finish_reason: string, } @@ -80,7 +80,7 @@ struct OpenAiCompletion { model: string, choices: [OpenAiChoice], usage: OpenAiUsage, - system_fingerprint: null, + system_fingerprint: (), } struct OpenAiRoleDelta { @@ -97,7 +97,7 @@ struct OpenAiEmptyDelta {} struct OpenAiStreamChoice { index: int, delta: TDelta, - logprobs: null, + logprobs: (), finish_reason: TFinish, } @@ -155,7 +155,7 @@ fn openai_stream_chunk( let choice = { index: 0, delta: delta, - logprobs: null, + logprobs: (), finish_reason: finish_reason, }; let chunk: OpenAiStreamChunk = { @@ -191,11 +191,11 @@ fn process_stream_event(event_data: string, state: StreamState) -> StreamState { role: "assistant", content: "", }; - let role_chunk = openai_stream_chunk::( + let role_chunk = openai_stream_chunk::( stream_id.copy(), stream_model.copy(), role_delta, - null + () ); let role_chunk_json = json::encode(role_chunk); write_sse_data(role_chunk_json); @@ -210,11 +210,11 @@ fn process_stream_event(event_data: string, state: StreamState) -> StreamState { let text = delta.text; if text != "" { let text_delta = {content: text}; - let text_chunk = openai_stream_chunk::( + let text_chunk = openai_stream_chunk::( next_stream_id.copy(), next_stream_model.copy(), text_delta, - null + () ); let text_chunk_json = json::encode(text_chunk); write_sse_data(text_chunk_json); @@ -256,14 +256,14 @@ fn process_stream_event(event_data: string, state: StreamState) -> StreamState { let downstream_body = http::request::get_body(); let upstream = http::exchange::default_upstream(); -let requested_upstream_host = http::request::get_header("x-anthropic-host"); +let requested_upstream_host = request_header_text("x-anthropic-host"); let upstream_host = if requested_upstream_host == "" => { "127.0.0.1" } else => { requested_upstream_host }; -let upstream_port_text = http::request::get_header("x-anthropic-port"); +let upstream_port_text = request_header_text("x-anthropic-port"); let mut upstream_port = 18092; if upstream_port_text != "" { let mut parsed_port = 0; @@ -297,14 +297,14 @@ if upstream_port_text != "" { } } -let requested_upstream_scheme = http::request::get_header("x-anthropic-scheme"); +let requested_upstream_scheme = request_header_text("x-anthropic-scheme"); let upstream_scheme = if requested_upstream_scheme == "" => { "http" } else => { requested_upstream_scheme }; -let requested_upstream_path = http::request::get_header("x-anthropic-path"); +let requested_upstream_path = request_header_text("x-anthropic-path"); let upstream_path = if requested_upstream_path == "" => { "/v1/messages" } else => { @@ -316,29 +316,29 @@ http::exchange::set_target(upstream, upstream_host, upstream_port); http::exchange::set_scheme(upstream, upstream_scheme); http::exchange::set_path(upstream, upstream_path); -let api_key = http::request::get_header("x-api-key"); +let api_key = request_header_text("x-api-key"); if api_key != "" { http::exchange::set_header(upstream, "x-api-key", api_key); } -let anthropic_beta = http::request::get_header("anthropic-beta"); +let anthropic_beta = request_header_text("anthropic-beta"); if anthropic_beta != "" { http::exchange::set_header(upstream, "anthropic-beta", anthropic_beta); } -let authorization = http::request::get_header("authorization"); +let authorization = request_header_text("authorization"); if authorization != "" { http::exchange::set_header(upstream, "authorization", authorization); } -let anthropic_version = http::request::get_header("anthropic-version"); +let anthropic_version = request_header_text("anthropic-version"); if anthropic_version == "" { http::exchange::set_header(upstream, "anthropic-version", "2023-06-01"); } else { http::exchange::set_header(upstream, "anthropic-version", anthropic_version); } -let downstream_content_type = http::request::get_header("content-type"); +let downstream_content_type = request_header_text("content-type"); if downstream_content_type == "" { http::exchange::set_header(upstream, "content-type", "application/json"); } else { @@ -348,7 +348,7 @@ if downstream_content_type == "" { http::exchange::set_body(upstream, downstream_body); let upstream_status = http::exchange::get_status(upstream); -let upstream_content_type = http::exchange::get_header(upstream, "content-type"); +let upstream_content_type = exchange_header_text(upstream, "content-type"); http::response::set_status(upstream_status); http::response::set_header("x-compat-upstream", "anthropic-messages"); @@ -375,7 +375,7 @@ if upstream_status != 200 { }; while !http::exchange::body::eof(upstream) { - let line = io::read_line(upstream); + let line = io_line_text(upstream); if line == "" { if event_data != "" { state = process_stream_event(event_data, state); @@ -448,13 +448,13 @@ if upstream_status != 200 { let assistant_message: OpenAiAssistantMessage = { role: "assistant", content: text, - refusal: null, + refusal: (), annotations: [], }; let choice: OpenAiChoice = { index: 0, message: assistant_message, - logprobs: null, + logprobs: (), finish_reason: finish_reason, }; let openai_response: OpenAiCompletion = { @@ -464,9 +464,51 @@ if upstream_status != 200 { model: model, choices: [choice], usage: response_usage, - system_fingerprint: null, + system_fingerprint: (), }; http::response::set_header("content-type", "application/json"); http::response::set_body(json::encode(openai_response)); } + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} + +// `http::exchange::get_header` reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn exchange_header_text(exchange: int, name: string) -> string { + let value: Result, string> = http::exchange::get_header(exchange, name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} + +// `io::read_line` reports end of stream as `None` and a read failure as +// the guest error instead of returning an empty string. The stream loop tests +// `eof`, so an absent line keeps the previous empty-string boundary default. +fn io_line_text(handle: int) -> string { + let value: Result, string> = io::read_line(handle); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/http/proxy/sample_proxy_program.rss b/examples/http/proxy/sample_proxy_program.rss index 340fc12..4fbca60 100644 --- a/examples/http/proxy/sample_proxy_program.rss +++ b/examples/http/proxy/sample_proxy_program.rss @@ -10,10 +10,10 @@ let exchange = http::exchange::default_upstream(); http::exchange::set_target(exchange, upstream_host, upstream_port); http::exchange::set_path(exchange, upstream_path); -if http::request::get_header("Streaming") != "" { +if request_header_text("Streaming") != "" { // Accessing the response metadata/body implicitly executes the outbound exchange. let upstream_status = http::exchange::get_status(exchange); - let content_type = http::exchange::get_header(exchange, "content-type"); + let content_type = exchange_header_text(exchange, "content-type"); if content_type != "" { http::response::set_header("content-type", content_type); } @@ -32,3 +32,29 @@ if http::request::get_header("Streaming") != "" { let proxy_status = proxy::forward_native(downstream, upstream_stream); http::response::set_header("x-proxy-status", proxy_status); } + +// `http::request::get_header` reports absence and undecodable values instead of +// returning an empty string. This sample only needs the value, so an absent +// header and a malformed one both keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} + +// Same collapse for `http::exchange::get_header`. +fn exchange_header_text(exchange: int, name: string) -> string { + let value: Result, string> = http::exchange::get_header(exchange, name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/http/proxy/sample_request_transform_program.rss b/examples/http/proxy/sample_request_transform_program.rss index 9822fd7..0f3d777 100644 --- a/examples/http/proxy/sample_request_transform_program.rss +++ b/examples/http/proxy/sample_request_transform_program.rss @@ -10,7 +10,7 @@ let exchange = http::exchange::default_upstream(); http::exchange::set_target(exchange, upstream_host, upstream_port); http::exchange::set_path(exchange, upstream_path); -if http::request::get_header("Chunk-Transform") != "" { +if request_header_text("Chunk-Transform") != "" { // Consume the request stream incrementally and annotate each chunk before upload. let mut transformed = ""; while !http::request::body::eof() { @@ -29,3 +29,17 @@ let downstream = proxy::stream::downstream(); let upstream_stream = proxy::stream::exchange(exchange); let proxy_status = proxy::forward_native(downstream, upstream_stream); http::response::set_header("x-proxy-status", proxy_status); + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/http/proxy/sample_sse_proxy_program.rss b/examples/http/proxy/sample_sse_proxy_program.rss index abba897..39fe3ae 100644 --- a/examples/http/proxy/sample_sse_proxy_program.rss +++ b/examples/http/proxy/sample_sse_proxy_program.rss @@ -13,7 +13,7 @@ http::exchange::set_path(upstream, upstream_path); let status = http::exchange::get_status(upstream); http::response::set_status(status); -let content_type = http::exchange::get_header(upstream, "content-type"); +let content_type = exchange_header_text(upstream, "content-type"); if content_type != "" { http::response::set_header("content-type", content_type); } @@ -24,7 +24,7 @@ http::response::stream::start(); let mut event = ""; while !http::exchange::body::eof(upstream) { - let line = io::read_line(upstream); + let line = io_line_text(upstream); if line == "" { if event != "" { http::response::stream::write(event + "\n"); @@ -40,3 +40,31 @@ if event != "" { } http::response::stream::finish(); + +// `http::exchange::get_header` reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn exchange_header_text(exchange: int, name: string) -> string { + let value: Result, string> = http::exchange::get_header(exchange, name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} + +// `io::read_line` reports end of stream as `None` and a read failure as +// the guest error instead of returning an empty string. The loop tests `eof`, +// so an absent line keeps the previous empty-string boundary default. +fn io_line_text(handle: int) -> string { + let value: Result, string> = io::read_line(handle); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/http_proxy_perf_framework.rs b/examples/http_proxy_perf_framework.rs index 149a7ad..e98a924 100644 --- a/examples/http_proxy_perf_framework.rs +++ b/examples/http_proxy_perf_framework.rs @@ -135,8 +135,20 @@ use http; let method = http::request::get_method(); let path = http::request::get_path(); -let client_id = http::request::get_header("x-client-id"); -let request_body_mode = http::request::get_header("x-bench-body-mode"); +let client_id = match http::request::get_header("x-client-id") {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", +}}; +let request_body_mode = match http::request::get_header("x-bench-body-mode") {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", +}}; if (acc % 2) == 0 {{ http::response::set_header("x-perf-acc", "even"); diff --git a/examples/mqtt/upstream/sample_mqtt_publish_program.rss b/examples/mqtt/upstream/sample_mqtt_publish_program.rss index 7674652..0858cf7 100644 --- a/examples/mqtt/upstream/sample_mqtt_publish_program.rss +++ b/examples/mqtt/upstream/sample_mqtt_publish_program.rss @@ -51,12 +51,12 @@ fn parse_decimal_or(value, fallback) { if valid => { parsed } else => { fallback } } -let mut host = http::request::get_header("x-mqtt-host"); +let mut host = request_header_text("x-mqtt-host"); if host == "" { host = "127.0.0.1"; } -let mut scheme = http::request::get_header("x-mqtt-scheme"); +let mut scheme = request_header_text("x-mqtt-scheme"); if scheme == "" { scheme = "mqtt"; } @@ -65,36 +65,36 @@ let mut port = if scheme == "mqtts" => { } else => { 1883 }; -port = parse_decimal_or(http::request::get_header("x-mqtt-port"), port); +port = parse_decimal_or(request_header_text("x-mqtt-port"), port); -let requested_handle = http::request::get_header("x-mqtt-handle"); -let mut topic = http::request::get_header("x-mqtt-topic"); +let requested_handle = request_header_text("x-mqtt-handle"); +let mut topic = request_header_text("x-mqtt-topic"); if topic == "" { topic = "pd-edge/sample"; } let request_body = http::request::get_body(); -let header_payload = http::request::get_header("x-mqtt-payload"); -let header_payload_hex = http::request::get_header("x-mqtt-payload-hex"); +let header_payload = request_header_text("x-mqtt-payload"); +let header_payload_hex = request_header_text("x-mqtt-payload-hex"); let payload = if request_body != "" => { request_body } else => { header_payload }; -let subscribe_filter = http::request::get_header("x-mqtt-subscribe"); -let qos_header = http::request::get_header("x-mqtt-qos"); +let subscribe_filter = request_header_text("x-mqtt-subscribe"); +let qos_header = request_header_text("x-mqtt-qos"); let qos = if qos_header == "1" => { 1 } else => { 0 }; -let retain_header = http::request::get_header("x-mqtt-retain"); +let retain_header = request_header_text("x-mqtt-retain"); let retain = retain_header == "true" || retain_header == "1" || retain_header == "on"; -let client_id = http::request::get_header("x-mqtt-client-id"); -let username = http::request::get_header("x-mqtt-username"); -let password = http::request::get_header("x-mqtt-password"); +let client_id = request_header_text("x-mqtt-client-id"); +let username = request_header_text("x-mqtt-username"); +let password = request_header_text("x-mqtt-password"); let mut connection = mqtt::connection::new(); let mut handle_label = "new"; @@ -150,26 +150,22 @@ if header_payload_hex != "" { if subscribe_filter != "" { let event = mqtt::connection::read_event(connection); - let mut kind: string = "unknown"; - if (&event).has("kind") { - kind = (&event)["kind"]; - } + let kind = event.kind; http::response::set_header("x-mqtt-event-kind", kind); - // The event map is dynamic; read each field into a string-typed local - // before handing it to a string-typed host parameter. - if (&event).has("topic") { - let event_topic: string = (&event)["topic"]; - http::response::set_header("x-mqtt-event-topic", event_topic); + // `MqttEvent` is one strict closed record: `kind` is always present and + // every variant-specific member is `Option`, so the guest asks whether + // the member is present instead of probing a dynamic map. + if option_present(event.topic.copy()) { + http::response::set_header("x-mqtt-event-topic", option_text(event.topic)); } - if (&event).has("reason") { - let event_reason: string = (&event)["reason"]; + if option_present(event.reason.copy()) { + let event_reason = option_text(event.reason); http::response::set_header("x-mqtt-event-reason", event_reason); http::response::set_body(event_reason); - } else if (&event).has("payload_text") { - let event_payload_text: string = (&event)["payload_text"]; - http::response::set_body(event_payload_text); + } else if option_present(event.payload_text.copy()) { + http::response::set_body(option_text(event.payload_text)); } else { http::response::set_body(kind); } @@ -181,3 +177,33 @@ if subscribe_filter != "" { mqtt::connection::disconnect(connection, 0, "sample-complete"); http::response::set_header("x-mqtt-phase-after-disconnect", mqtt::connection::get_phase(connection)); + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} + +// Whether the `MqttEvent` member belongs to the active event variant. +fn option_present(value: Option) -> bool { + match value { + Some(text) => true, + None => false, + } +} + +// The member text of an active variant; an absent member renders as "". +fn option_text(value: Option) -> string { + match value { + Some(text) => text, + None => "", + } +} diff --git a/examples/proxy/forward/sample_forward_proxy_program.rss b/examples/proxy/forward/sample_forward_proxy_program.rss index 8468464..ba2378c 100644 --- a/examples/proxy/forward/sample_forward_proxy_program.rss +++ b/examples/proxy/forward/sample_forward_proxy_program.rss @@ -45,7 +45,7 @@ http::exchange::set_path(upstream, upstream_path); http::exchange::set_method(upstream, http::request::get_method()); http::exchange::set_body(upstream, http::request::get_body()); -let request_content_type = http::request::get_header("content-type"); +let request_content_type = request_header_text("content-type"); if request_content_type != "" { http::exchange::set_header(upstream, "content-type", request_content_type); } @@ -53,7 +53,7 @@ if request_content_type != "" { let session = tls::session::from_socket(proxy_socket); http::exchange::attach_tls_plaintext(upstream, session); // Tests can opt out of verification when the upstream uses local certificates. -if http::request::get_header("x-insecure-upstream") != "" { +if request_header_text("x-insecure-upstream") != "" { tls::session::set_verify(session, false); tls::session::set_verify_hostname(session, false); } @@ -81,3 +81,17 @@ let peer_name = tls::session::get_peer_name(session); if peer_name != "" { http::response::set_header("x-upstream-peer", peer_name); } + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/proxy/tunnel/sample_tunnel_proxy_program.rss b/examples/proxy/tunnel/sample_tunnel_proxy_program.rss index 147df12..bd8f506 100644 --- a/examples/proxy/tunnel/sample_tunnel_proxy_program.rss +++ b/examples/proxy/tunnel/sample_tunnel_proxy_program.rss @@ -3,7 +3,7 @@ use proxy; use tcp; use tls; -let upstream_scheme = http::request::get_header("x-upstream-scheme"); +let upstream_scheme = request_header_text("x-upstream-scheme"); let upstream_host = if upstream_scheme == "https" => { "localhost" } else => { "127.0.0.1" }; let upstream_port = if upstream_scheme == "https" => { 18486 } else => { 18086 }; let upstream_path = "/echo"; @@ -43,7 +43,7 @@ if upstream_status != 0 { http::response::set_status(upstream_status); } -let content_type = http::exchange::get_header(exchange, "content-type"); +let content_type = exchange_header_text(exchange, "content-type"); if content_type != "" { http::response::set_header("content-type", content_type); } @@ -59,3 +59,31 @@ if tls::session::is_present(upstream_tls) { http::response::set_header("x-upstream-alpn", alpn); } } + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} + +// `http::exchange::get_header` reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn exchange_header_text(exchange: int, name: string) -> string { + let value: Result, string> = http::exchange::get_header(exchange, name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/transport/io/sample_io_upstream_handle_program.rss b/examples/transport/io/sample_io_upstream_handle_program.rss index 166ce45..b44ba65 100644 --- a/examples/transport/io/sample_io_upstream_handle_program.rss +++ b/examples/transport/io/sample_io_upstream_handle_program.rss @@ -15,7 +15,7 @@ http::exchange::set_path(upstream, upstream_path); http::exchange::set_method(upstream, http::request::get_method()); // `io::read_all(0)` consumes the downstream request body. -let staged = io::read_all(downstream); +let staged = io_read_all_text(downstream); // `io::write(1, ...)` stages bytes into the default upstream request body. io::write(upstream, staged + "|via-io-handle"); @@ -23,5 +23,30 @@ io::write(upstream, staged + "|via-io-handle"); // Reading from the same upstream handle advances the outbound exchange and returns the response. http::response::set_status(http::exchange::get_status(upstream)); http::response::set_header("x-io-upstream-handles", "true"); -http::response::set_header("x-first-line", io::read_line(upstream)); -http::response::set_body(io::read_all(upstream)); +http::response::set_header("x-first-line", io_line_text(upstream)); +http::response::set_body(io_read_all_text(upstream)); + +// `io::read_all` reports a recoverable read failure as the guest error instead +// of a bare string. This sample only needs the text, so a failure keeps the +// previous empty-string default. +fn io_read_all_text(handle: int) -> string { + let value: Result = io::read_all(handle); + match value { + Result::Ok(text) => text, + Result::Err(error) => "", + } +} + +// `io::read_line` reports end of stream as `None` and a read failure as +// the guest error instead of returning an empty string. This sample reads one +// line for a header value, so both keep the previous empty-string default. +fn io_line_text(handle: int) -> string { + let value: Result, string> = io::read_line(handle); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/transport/upstream/sample_upstream_transport_proxy_program.rss b/examples/transport/upstream/sample_upstream_transport_proxy_program.rss index ccf4714..909c2ab 100644 --- a/examples/transport/upstream/sample_upstream_transport_proxy_program.rss +++ b/examples/transport/upstream/sample_upstream_transport_proxy_program.rss @@ -6,7 +6,7 @@ use tls; // HTTP-runtime sample that proxies via transport-style upstream handles. // // This is distinct from: -let upstream_scheme = http::request::get_header("x-upstream-scheme"); +let upstream_scheme = request_header_text("x-upstream-scheme"); let upstream_host = if upstream_scheme == "https" => { "localhost" } else => { "127.0.0.1" }; let upstream_port = if upstream_scheme == "https" => { 18485 } else => { 18085 }; let upstream_path = "/echo"; @@ -45,13 +45,13 @@ if true { } let status = http::exchange::get_status(exchange); - let content_type = http::exchange::get_header(exchange, "content-type"); + let content_type = exchange_header_text(exchange, "content-type"); if content_type != "" { http::response::set_header("content-type", content_type); } http::response::set_status(status); - if http::request::get_header("Streaming") != "" { + if request_header_text("Streaming") != "" { // Stream the upstream response out incrementally after the exchange has started. http::response::stream::start(); while !tcp::stream::eof(upstream) { @@ -71,3 +71,31 @@ if true { http::response::set_body(buffered); } } + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} + +// `http::exchange::get_header` reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn exchange_header_text(exchange: int, name: string) -> string { + let value: Result, string> = http::exchange::get_header(exchange, name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/webrtc/proxy/sample_webrtc_proxy_program.rss b/examples/webrtc/proxy/sample_webrtc_proxy_program.rss index de5707e..2bb7226 100644 --- a/examples/webrtc/proxy/sample_webrtc_proxy_program.rss +++ b/examples/webrtc/proxy/sample_webrtc_proxy_program.rss @@ -8,11 +8,11 @@ use webrtc; // - x-webrtc-handle: "default" to use webrtc::connection::default_upstream(), otherwise webrtc::connection::new() // - x-webrtc-data-channel-label: optional data channel label; defaults to "sample-channel" // - x-webrtc-ice-servers: optional comma-separated ICE server URLs -let text_payload = http::request::get_header("x-webrtc-message"); -let binary_payload_hex = http::request::get_header("x-webrtc-binary-hex"); -let requested_handle = http::request::get_header("x-webrtc-handle"); -let mut data_channel_label = http::request::get_header("x-webrtc-data-channel-label"); -let ice_servers = http::request::get_header("x-webrtc-ice-servers"); +let text_payload = request_header_text("x-webrtc-message"); +let binary_payload_hex = request_header_text("x-webrtc-binary-hex"); +let requested_handle = request_header_text("x-webrtc-handle"); +let mut data_channel_label = request_header_text("x-webrtc-data-channel-label"); +let ice_servers = request_header_text("x-webrtc-ice-servers"); let signal_host = "127.0.0.1"; let signal_port = if binary_payload_hex != "" || requested_handle == "default" => { 18088 } else => { 18087 }; let signal_path = "/offer"; @@ -101,3 +101,17 @@ if true { http::response::set_header("x-webrtc-eof-after-close", "false"); } } + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/websocket/bridge/sample_transport_websocket_sse_bridge_program.rss b/examples/websocket/bridge/sample_transport_websocket_sse_bridge_program.rss index c68221f..f2e73b7 100644 --- a/examples/websocket/bridge/sample_transport_websocket_sse_bridge_program.rss +++ b/examples/websocket/bridge/sample_transport_websocket_sse_bridge_program.rss @@ -21,7 +21,7 @@ http::exchange::set_header(upstream, "accept", "text/event-stream"); let mut event = ""; while !http::exchange::body::eof(upstream) && !websocket::connection::eof(downstream) { - let line = io::read_line(upstream); + let line = io_line_text(upstream); if line == "" { if event != "" { websocket::connection::send_text(downstream, event); @@ -41,3 +41,17 @@ if event != "" && !websocket::connection::eof(downstream) { if !websocket::connection::eof(downstream) { websocket::connection::close(downstream, 1000, "sse-complete"); } + +// `io::read_line` reports end of stream as `None` and a read failure as +// the guest error instead of returning an empty string. The bridge loop tests +// `eof`, so an absent line keeps the previous empty-string boundary default. +fn io_line_text(handle: int) -> string { + let value: Result, string> = io::read_line(handle); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/examples/websocket/proxy/sample_websocket_proxy_program.rss b/examples/websocket/proxy/sample_websocket_proxy_program.rss index 5716289..7f860f9 100644 --- a/examples/websocket/proxy/sample_websocket_proxy_program.rss +++ b/examples/websocket/proxy/sample_websocket_proxy_program.rss @@ -17,12 +17,12 @@ if websocket::connection::is_present(downstream) { } let upstream_host = "127.0.0.1"; let upstream_port = 18091; -let text_payload = http::request::get_header("x-ws-message"); -let binary_payload_hex = http::request::get_header("x-ws-binary-hex"); -let requested_handle = http::request::get_header("x-ws-handle"); -let mut requested_subprotocols = http::request::get_header("x-ws-subprotocols"); -let custom_header_name = http::request::get_header("x-ws-header-name"); -let custom_header_value = http::request::get_header("x-ws-header-value"); +let text_payload = request_header_text("x-ws-message"); +let binary_payload_hex = request_header_text("x-ws-binary-hex"); +let requested_handle = request_header_text("x-ws-handle"); +let mut requested_subprotocols = request_header_text("x-ws-subprotocols"); +let custom_header_name = request_header_text("x-ws-header-name"); +let custom_header_value = request_header_text("x-ws-header-value"); let mut connection = websocket::connection::new(); let mut handle_label = "new"; @@ -98,3 +98,17 @@ if websocket::connection::eof(connection) { } else { http::response::set_header("x-ws-eof-after-close", "false"); } + +// `http::request::get_header` now reports an absent header or an undecodable +// value instead of returning an empty string. This sample only needs the value, +// so absence and a malformed value keep the previous empty-string default. +fn request_header_text(name: string) -> string { + let value: Result, string> = http::request::get_header(name); + match value { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + } +} diff --git a/pd-edge-abi/Cargo.toml b/pd-edge-abi/Cargo.toml index 9ecd4a2..65093e7 100644 --- a/pd-edge-abi/Cargo.toml +++ b/pd-edge-abi/Cargo.toml @@ -22,7 +22,14 @@ websocket = ["http"] webrtc = ["http"] [dependencies] -pd-host-function = { git = "https://github.com/rustscript-lang/rustscript.git", rev = "b1d6cffede77f49410bf63525f30b9a46b02dc01", version = "0.1.0" } +pd-host-function = { git = "https://github.com/rustscript-lang/rustscript.git", rev = "2f433edab3f1907e8cb060e901357d7e2af016ce", version = "0.1.0" } +# The ABI declarations are real Rust signatures of the guest contract, so the +# fallible optional-text return needs the core SDK's `GuestResult`/`GuestOption` +# value types. Both are exported by the core crate root without any feature, so +# this dependency stays feature-free: enabling `runtime` here would leak the VM +# runtime into every consumer's compiler-only graph through feature unification. +# The pin must match the runtime's `pd-vm` pin in the root manifest. +vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "2f433edab3f1907e8cb060e901357d7e2af016ce", version = "0.1.0", default-features = false } [build-dependencies] syn = { version = "2", features = ["full"] } diff --git a/pd-edge-abi/abi.json b/pd-edge-abi/abi.json index 4004076..5a1a53c 100644 --- a/pd-edge-abi/abi.json +++ b/pd-edge-abi/abi.json @@ -1,5 +1,5 @@ { - "abi_version": 25, + "abi_version": 26, "functions": [ { "index": 0, "name": "http::request::get_id", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_id`." }, { "index": 1, "name": "http::request::get_method", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_method`." }, @@ -7,56 +7,56 @@ { "index": 3, "name": "http::request::get_query", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_query`." }, { "index": 4, "name": "http::request::get_scheme", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_scheme`." }, { "index": 5, "name": "http::request::get_host", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_host`." }, - { "index": 6, "name": "http::request::get_header", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "string", "docs": "Host function `http::request::get_header`." }, + { "index": 6, "name": "http::request::get_header", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "result_option_string", "docs": "Returns the first value for a header on the downstream HTTP request.\n`Ok(None)` means the request carries no such header, `Ok(Some(\"\"))` means it\ncarries it with an empty value, and `Err` reports a value that is not valid\ntext. An invalid header name is a fatal host error, not an absent header." }, { "index": 7, "name": "http::request::get_client_ip", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_client_ip`." }, { "index": 8, "name": "http::request::get_headers", "arity": 0, "params": [], "return_type": "map", "docs": "Host function `http::request::get_headers`." }, - { "index": 9, "name": "http::request::get_query_arg", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "string", "docs": "Host function `http::request::get_query_arg`." }, + { "index": 9, "name": "http::request::get_query_arg", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "result_option_string", "docs": "Returns a query parameter from the downstream HTTP request.\n`Ok(None)` means the query string has no such parameter, `Ok(Some(\"\"))`\nmeans it has one with an empty value. A repeated key keeps the first value." }, { "index": 10, "name": "http::request::get_query_args", "arity": 0, "params": [], "return_type": "map", "docs": "Host function `http::request::get_query_args`." }, { "index": 11, "name": "http::request::get_path_with_query", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_path_with_query`." }, { "index": 12, "name": "http::request::get_body", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_body`." }, { "index": 13, "name": "http::request::get_http_version", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::request::get_http_version`." }, { "index": 14, "name": "http::request::get_port", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `http::request::get_port`." }, - { "index": 15, "name": "http::downstream::attach_transport", "arity": 0, "params": [], "return_type": "null", "docs": "Host function `http::downstream::attach_transport`." }, - { "index": 16, "name": "http::response::set_header", "arity": 2, "params": [{"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "null", "docs": "Host function `http::response::set_header`." }, - { "index": 17, "name": "http::response::set_headers", "arity": 1, "params": [{"name": "headers", "type": "any"}], "return_type": "null", "docs": "Host function `http::response::set_headers`." }, - { "index": 18, "name": "http::response::set_body", "arity": 1, "params": [{"name": "body", "type": "string"}], "return_type": "null", "docs": "Host function `http::response::set_body`." }, - { "index": 19, "name": "http::response::stream::start", "arity": 0, "params": [], "return_type": "null", "docs": "Host function `http::response::stream::start`." }, + { "index": 15, "name": "http::downstream::attach_transport", "arity": 0, "params": [], "return_type": "unit", "docs": "Host function `http::downstream::attach_transport`." }, + { "index": 16, "name": "http::response::set_header", "arity": 2, "params": [{"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "unit", "docs": "Host function `http::response::set_header`." }, + { "index": 17, "name": "http::response::set_headers", "arity": 1, "params": [{"name": "headers", "type": "any"}], "return_type": "unit", "docs": "Host function `http::response::set_headers`." }, + { "index": 18, "name": "http::response::set_body", "arity": 1, "params": [{"name": "body", "type": "string"}], "return_type": "unit", "docs": "Host function `http::response::set_body`." }, + { "index": 19, "name": "http::response::stream::start", "arity": 0, "params": [], "return_type": "unit", "docs": "Host function `http::response::stream::start`." }, { "index": 20, "name": "http::response::stream::write", "arity": 1, "params": [{"name": "chunk", "type": "string"}], "return_type": "int", "docs": "Host function `http::response::stream::write`." }, - { "index": 21, "name": "http::response::stream::finish", "arity": 0, "params": [], "return_type": "null", "docs": "Host function `http::response::stream::finish`." }, - { "index": 22, "name": "http::response::set_status", "arity": 1, "params": [{"name": "status", "type": "int"}], "return_type": "null", "docs": "Host function `http::response::set_status`." }, - { "index": 23, "name": "http::response::apply_exchange", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "null", "docs": "Host function `http::response::apply_exchange`." }, - { "index": 24, "name": "http::response::apply_exchange_with_headers", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "headers", "type": "any"}], "return_type": "null", "docs": "Host function `http::response::apply_exchange_with_headers`." }, + { "index": 21, "name": "http::response::stream::finish", "arity": 0, "params": [], "return_type": "unit", "docs": "Host function `http::response::stream::finish`." }, + { "index": 22, "name": "http::response::set_status", "arity": 1, "params": [{"name": "status", "type": "int"}], "return_type": "unit", "docs": "Host function `http::response::set_status`." }, + { "index": 23, "name": "http::response::apply_exchange", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "unit", "docs": "Host function `http::response::apply_exchange`." }, + { "index": 24, "name": "http::response::apply_exchange_with_headers", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "headers", "type": "any"}], "return_type": "unit", "docs": "Host function `http::response::apply_exchange_with_headers`." }, { "index": 25, "name": "http::response::get_status", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `http::response::get_status`." }, { "index": 26, "name": "http::response::get_body", "arity": 0, "params": [], "return_type": "string", "docs": "Host function `http::response::get_body`." }, - { "index": 27, "name": "http::response::get_trailer", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "string", "docs": "Host function `http::response::get_trailer`." }, + { "index": 27, "name": "http::response::get_trailer", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "result_option_string", "docs": "Returns the first trailer value for the downstream HTTP response.\n`Ok(None)` means the response carries no such trailer, `Ok(Some(\"\"))` means\nit carries it with an empty value, and `Err` reports a value that is not\nvalid text. An invalid trailer name is a fatal host error." }, { "index": 28, "name": "http::response::get_trailers", "arity": 0, "params": [], "return_type": "map", "docs": "Host function `http::response::get_trailers`." }, - { "index": 29, "name": "http::response::get_header", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "string", "docs": "Host function `http::response::get_header`." }, + { "index": 29, "name": "http::response::get_header", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "result_option_string", "docs": "Returns the first value for a header on the downstream HTTP response.\n`Ok(None)` means the response carries no such header, `Ok(Some(\"\"))` means\nit carries it with an empty value, and `Err` reports a value that is not\nvalid text. An invalid header name is a fatal host error." }, { "index": 30, "name": "http::response::get_headers", "arity": 0, "params": [], "return_type": "map", "docs": "Host function `http::response::get_headers`." }, - { "index": 31, "name": "http::response::add_header", "arity": 2, "params": [{"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "null", "docs": "Host function `http::response::add_header`." }, - { "index": 32, "name": "http::response::clear_header", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "null", "docs": "Host function `http::response::clear_header`." }, + { "index": 31, "name": "http::response::add_header", "arity": 2, "params": [{"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "unit", "docs": "Host function `http::response::add_header`." }, + { "index": 32, "name": "http::response::clear_header", "arity": 1, "params": [{"name": "name", "type": "string"}], "return_type": "unit", "docs": "Host function `http::response::clear_header`." }, { "index": 33, "name": "http::exchange::new", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `http::exchange::new`." }, { "index": 34, "name": "http::exchange::default_upstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `http::exchange::default_upstream`." }, { "index": 35, "name": "http::exchange::prepare_default_upstream", "arity": 4, "params": [{"name": "host", "type": "string"}, {"name": "port", "type": "int"}, {"name": "version", "type": "string"}, {"name": "headers", "type": "any"}], "return_type": "int", "docs": "Host function `http::exchange::prepare_default_upstream`." }, - { "index": 36, "name": "http::exchange::send", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "null", "docs": "Host function `http::exchange::send`." }, - { "index": 37, "name": "http::exchange::set_header", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_header`." }, - { "index": 38, "name": "http::exchange::set_method", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "method", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_method`." }, - { "index": 39, "name": "http::exchange::set_path", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "path", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_path`." }, - { "index": 40, "name": "http::exchange::set_query", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "query", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_query`." }, - { "index": 41, "name": "http::exchange::set_version", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "version", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_version`." }, + { "index": 36, "name": "http::exchange::send", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "unit", "docs": "Host function `http::exchange::send`." }, + { "index": 37, "name": "http::exchange::set_header", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_header`." }, + { "index": 38, "name": "http::exchange::set_method", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "method", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_method`." }, + { "index": 39, "name": "http::exchange::set_path", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "path", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_path`." }, + { "index": 40, "name": "http::exchange::set_query", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "query", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_query`." }, + { "index": 41, "name": "http::exchange::set_version", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "version", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_version`." }, { "index": 42, "name": "http::exchange::get_version", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "string", "docs": "Host function `http::exchange::get_version`." }, - { "index": 43, "name": "http::exchange::set_target", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "null", "docs": "Host function `http::exchange::set_target`." }, - { "index": 44, "name": "http::exchange::set_scheme", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "scheme", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_scheme`." }, - { "index": 45, "name": "http::exchange::attach_tcp", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "stream", "type": "int"}], "return_type": "null", "docs": "Host function `http::exchange::attach_tcp`." }, - { "index": 46, "name": "http::exchange::attach_tls_plaintext", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "session", "type": "int"}], "return_type": "null", "docs": "Host function `http::exchange::attach_tls_plaintext`." }, - { "index": 47, "name": "http::exchange::set_body", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "body", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_body`." }, - { "index": 48, "name": "http::exchange::add_header", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::add_header`." }, - { "index": 49, "name": "http::exchange::clear_header", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::clear_header`." }, - { "index": 50, "name": "http::exchange::set_query_arg", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "null", "docs": "Host function `http::exchange::set_query_arg`." }, + { "index": 43, "name": "http::exchange::set_target", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "unit", "docs": "Host function `http::exchange::set_target`." }, + { "index": 44, "name": "http::exchange::set_scheme", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "scheme", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_scheme`." }, + { "index": 45, "name": "http::exchange::attach_tcp", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "stream", "type": "int"}], "return_type": "unit", "docs": "Host function `http::exchange::attach_tcp`." }, + { "index": 46, "name": "http::exchange::attach_tls_plaintext", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "session", "type": "int"}], "return_type": "unit", "docs": "Host function `http::exchange::attach_tls_plaintext`." }, + { "index": 47, "name": "http::exchange::set_body", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "body", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_body`." }, + { "index": 48, "name": "http::exchange::add_header", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::add_header`." }, + { "index": 49, "name": "http::exchange::clear_header", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::clear_header`." }, + { "index": 50, "name": "http::exchange::set_query_arg", "arity": 3, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "unit", "docs": "Host function `http::exchange::set_query_arg`." }, { "index": 51, "name": "http::exchange::get_status", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "int", "docs": "Host function `http::exchange::get_status`." }, - { "index": 52, "name": "http::exchange::get_header", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}], "return_type": "string", "docs": "Host function `http::exchange::get_header`." }, + { "index": 52, "name": "http::exchange::get_header", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}], "return_type": "result_option_string", "docs": "Returns the first value for a header on the outbound HTTP exchange.\n`Ok(None)` means the exchange carries no such header, `Ok(Some(\"\"))` means\nit carries it with an empty value, and `Err` reports a value that is not\nvalid text. An invalid header name is a fatal host error." }, { "index": 53, "name": "http::exchange::get_headers", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "map", "docs": "Host function `http::exchange::get_headers`." }, { "index": 54, "name": "http::exchange::get_body", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "string", "docs": "Host function `http::exchange::get_body`." }, - { "index": 55, "name": "http::exchange::get_trailer", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}], "return_type": "string", "docs": "Host function `http::exchange::get_trailer`." }, + { "index": 55, "name": "http::exchange::get_trailer", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "name", "type": "string"}], "return_type": "result_option_string", "docs": "Returns the first trailer value for the outbound HTTP exchange.\n`Ok(None)` means the exchange carries no such trailer, `Ok(Some(\"\"))` means\nit carries it with an empty value, and `Err` reports a value that is not\nvalid text. An invalid trailer name is a fatal host error." }, { "index": 56, "name": "http::exchange::get_trailers", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "map", "docs": "Host function `http::exchange::get_trailers`." }, { "index": 57, "name": "http::exchange::get_http_version", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "string", "docs": "Host function `http::exchange::get_http_version`." }, { "index": 58, "name": "http::exchange::body::next_chunk", "arity": 2, "params": [{"name": "exchange", "type": "int"}, {"name": "max_bytes", "type": "int"}], "return_type": "string", "docs": "Host function `http::exchange::body::next_chunk`." }, @@ -71,13 +71,13 @@ { "index": 67, "name": "console::args::get", "arity": 1, "params": [{"name": "index", "type": "int"}], "return_type": "string", "docs": "Returns the argument at the requested zero-based index, or an empty string when it is missing." }, { "index": 68, "name": "rate_limit::allow", "arity": 3, "params": [{"name": "key", "type": "string"}, {"name": "limit", "type": "int"}, {"name": "window_seconds", "type": "int"}], "return_type": "bool", "docs": "Checks whether a rate-limit bucket allows the current operation." }, { "index": 69, "name": "runtime::sleep", "arity": 1, "params": [{"name": "ms", "type": "int"}], "return_type": "bool", "docs": "Suspends execution for the requested number of milliseconds." }, - { "index": 70, "name": "runtime::exit", "arity": 0, "params": [], "return_type": "null", "docs": "Halts the current VM invocation immediately." }, + { "index": 70, "name": "runtime::exit", "arity": 0, "params": [], "return_type": "unit", "docs": "Halts the current VM invocation immediately." }, { "index": 71, "name": "tcp::stream::downstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `tcp::stream::downstream`." }, { "index": 72, "name": "tcp::stream::default_upstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `tcp::stream::default_upstream`." }, { "index": 73, "name": "tcp::stream::new", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `tcp::stream::new`." }, { "index": 74, "name": "tcp::stream::is_present", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "bool", "docs": "Host function `tcp::stream::is_present`." }, - { "index": 75, "name": "tcp::stream::bind", "arity": 2, "params": [{"name": "stream", "type": "int"}, {"name": "local_addr", "type": "string"}], "return_type": "null", "docs": "Host function `tcp::stream::bind`." }, - { "index": 76, "name": "tcp::stream::set_target", "arity": 3, "params": [{"name": "stream", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "null", "docs": "Host function `tcp::stream::set_target`." }, + { "index": 75, "name": "tcp::stream::bind", "arity": 2, "params": [{"name": "stream", "type": "int"}, {"name": "local_addr", "type": "string"}], "return_type": "unit", "docs": "Host function `tcp::stream::bind`." }, + { "index": 76, "name": "tcp::stream::set_target", "arity": 3, "params": [{"name": "stream", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "unit", "docs": "Host function `tcp::stream::set_target`." }, { "index": 77, "name": "tcp::stream::connect", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "bool", "docs": "Host function `tcp::stream::connect`." }, { "index": 78, "name": "tcp::stream::get_phase", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "string", "docs": "Reports the current lifecycle phase for a TCP stream handle." }, { "index": 79, "name": "tcp::stream::get_local_addr", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "string", "docs": "Host function `tcp::stream::get_local_addr`." }, @@ -90,13 +90,13 @@ { "index": 86, "name": "tcp::stream::write", "arity": 2, "params": [{"name": "stream", "type": "int"}, {"name": "text", "type": "string"}], "return_type": "int", "docs": "Host function `tcp::stream::write`." }, { "index": 87, "name": "tcp::stream::write_binary", "arity": 2, "params": [{"name": "stream", "type": "int"}, {"name": "payload", "type": "bytes"}], "return_type": "int", "docs": "Host function `tcp::stream::write_binary`." }, { "index": 88, "name": "tcp::stream::eof", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "bool", "docs": "Host function `tcp::stream::eof`." }, - { "index": 89, "name": "tcp::stream::close", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "null", "docs": "Host function `tcp::stream::close`." }, + { "index": 89, "name": "tcp::stream::close", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "unit", "docs": "Host function `tcp::stream::close`." }, { "index": 90, "name": "udp::socket::new", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `udp::socket::new`." }, { "index": 91, "name": "udp::socket::downstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `udp::socket::downstream`." }, { "index": 92, "name": "udp::socket::default_upstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `udp::socket::default_upstream`." }, { "index": 93, "name": "udp::socket::is_present", "arity": 1, "params": [{"name": "socket", "type": "int"}], "return_type": "bool", "docs": "Host function `udp::socket::is_present`." }, - { "index": 94, "name": "udp::socket::bind", "arity": 2, "params": [{"name": "socket", "type": "int"}, {"name": "local_addr", "type": "string"}], "return_type": "null", "docs": "Host function `udp::socket::bind`." }, - { "index": 95, "name": "udp::socket::set_target", "arity": 3, "params": [{"name": "socket", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "null", "docs": "Host function `udp::socket::set_target`." }, + { "index": 94, "name": "udp::socket::bind", "arity": 2, "params": [{"name": "socket", "type": "int"}, {"name": "local_addr", "type": "string"}], "return_type": "unit", "docs": "Host function `udp::socket::bind`." }, + { "index": 95, "name": "udp::socket::set_target", "arity": 3, "params": [{"name": "socket", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "unit", "docs": "Host function `udp::socket::set_target`." }, { "index": 96, "name": "udp::socket::connect", "arity": 1, "params": [{"name": "socket", "type": "int"}], "return_type": "bool", "docs": "Host function `udp::socket::connect`." }, { "index": 97, "name": "udp::socket::get_phase", "arity": 1, "params": [{"name": "socket", "type": "int"}], "return_type": "string", "docs": "Host function `udp::socket::get_phase`." }, { "index": 98, "name": "udp::socket::get_local_addr", "arity": 1, "params": [{"name": "socket", "type": "int"}], "return_type": "string", "docs": "Host function `udp::socket::get_local_addr`." }, @@ -107,22 +107,22 @@ { "index": 103, "name": "udp::socket::recv_binary", "arity": 2, "params": [{"name": "socket", "type": "int"}, {"name": "max_bytes", "type": "int"}], "return_type": "bytes", "docs": "Host function `udp::socket::recv_binary`." }, { "index": 104, "name": "udp::socket::send_binary_base64", "arity": 2, "params": [{"name": "socket", "type": "int"}, {"name": "payload", "type": "string"}], "return_type": "int", "docs": "Host function `udp::socket::send_binary_base64`." }, { "index": 105, "name": "udp::socket::recv_binary_base64", "arity": 2, "params": [{"name": "socket", "type": "int"}, {"name": "max_bytes", "type": "int"}], "return_type": "string", "docs": "Host function `udp::socket::recv_binary_base64`." }, - { "index": 106, "name": "udp::socket::close", "arity": 1, "params": [{"name": "socket", "type": "int"}], "return_type": "null", "docs": "Host function `udp::socket::close`." }, + { "index": 106, "name": "udp::socket::close", "arity": 1, "params": [{"name": "socket", "type": "int"}], "return_type": "unit", "docs": "Host function `udp::socket::close`." }, { "index": 107, "name": "tls::session::from_socket", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "int", "docs": "Host function `tls::session::from_socket`." }, { "index": 108, "name": "tls::session::is_present", "arity": 1, "params": [{"name": "session", "type": "int"}], "return_type": "bool", "docs": "Host function `tls::session::is_present`." }, { "index": 109, "name": "tls::session::needs_configuration", "arity": 1, "params": [{"name": "session", "type": "int"}], "return_type": "bool", "docs": "Host function `tls::session::needs_configuration`." }, { "index": 110, "name": "tls::session::handshake", "arity": 1, "params": [{"name": "session", "type": "int"}], "return_type": "bool", "docs": "Host function `tls::session::handshake`." }, - { "index": 111, "name": "tls::session::set_alpn", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "protocols", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_alpn`." }, - { "index": 112, "name": "tls::session::set_verify", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "verify", "type": "bool"}], "return_type": "null", "docs": "Host function `tls::session::set_verify`." }, - { "index": 113, "name": "tls::session::set_verify_hostname", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "verify", "type": "bool"}], "return_type": "null", "docs": "Host function `tls::session::set_verify_hostname`." }, - { "index": 114, "name": "tls::session::set_trusted_certificate", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "certificate_pem", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_trusted_certificate`." }, - { "index": 115, "name": "tls::session::set_client_certificate", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "certificate_pem", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_client_certificate`." }, - { "index": 116, "name": "tls::session::set_client_private_key", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "private_key_pem", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_client_private_key`." }, - { "index": 117, "name": "tls::session::set_server_certificate", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "certificate_pem", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_server_certificate`." }, - { "index": 118, "name": "tls::session::set_server_private_key", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "private_key_pem", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_server_private_key`." }, - { "index": 119, "name": "tls::session::set_sni", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "enabled", "type": "bool"}], "return_type": "null", "docs": "Host function `tls::session::set_sni`." }, - { "index": 120, "name": "tls::session::set_min_version", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "version", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_min_version`." }, - { "index": 121, "name": "tls::session::set_max_version", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "version", "type": "string"}], "return_type": "null", "docs": "Host function `tls::session::set_max_version`." }, + { "index": 111, "name": "tls::session::set_alpn", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "protocols", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_alpn`." }, + { "index": 112, "name": "tls::session::set_verify", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "verify", "type": "bool"}], "return_type": "unit", "docs": "Host function `tls::session::set_verify`." }, + { "index": 113, "name": "tls::session::set_verify_hostname", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "verify", "type": "bool"}], "return_type": "unit", "docs": "Host function `tls::session::set_verify_hostname`." }, + { "index": 114, "name": "tls::session::set_trusted_certificate", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "certificate_pem", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_trusted_certificate`." }, + { "index": 115, "name": "tls::session::set_client_certificate", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "certificate_pem", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_client_certificate`." }, + { "index": 116, "name": "tls::session::set_client_private_key", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "private_key_pem", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_client_private_key`." }, + { "index": 117, "name": "tls::session::set_server_certificate", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "certificate_pem", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_server_certificate`." }, + { "index": 118, "name": "tls::session::set_server_private_key", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "private_key_pem", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_server_private_key`." }, + { "index": 119, "name": "tls::session::set_sni", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "enabled", "type": "bool"}], "return_type": "unit", "docs": "Host function `tls::session::set_sni`." }, + { "index": 120, "name": "tls::session::set_min_version", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "version", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_min_version`." }, + { "index": 121, "name": "tls::session::set_max_version", "arity": 2, "params": [{"name": "session", "type": "int"}, {"name": "version", "type": "string"}], "return_type": "unit", "docs": "Host function `tls::session::set_max_version`." }, { "index": 122, "name": "tls::session::get_peer_name", "arity": 1, "params": [{"name": "session", "type": "int"}], "return_type": "string", "docs": "Host function `tls::session::get_peer_name`." }, { "index": 123, "name": "tls::session::get_server_name", "arity": 1, "params": [{"name": "session", "type": "int"}], "return_type": "string", "docs": "Host function `tls::session::get_server_name`." }, { "index": 124, "name": "tls::session::get_alpn", "arity": 1, "params": [{"name": "session", "type": "int"}], "return_type": "string", "docs": "Host function `tls::session::get_alpn`." }, @@ -132,16 +132,16 @@ { "index": 128, "name": "mqtt::connection::new", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `mqtt::connection::new`." }, { "index": 129, "name": "mqtt::connection::default_upstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `mqtt::connection::default_upstream`." }, { "index": 130, "name": "mqtt::connection::is_present", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `mqtt::connection::is_present`." }, - { "index": 131, "name": "mqtt::connection::set_scheme", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "scheme", "type": "string"}], "return_type": "null", "docs": "Host function `mqtt::connection::set_scheme`." }, - { "index": 132, "name": "mqtt::connection::set_target", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "null", "docs": "Host function `mqtt::connection::set_target`." }, - { "index": 133, "name": "mqtt::connection::set_client_id", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "client_id", "type": "string"}], "return_type": "null", "docs": "Host function `mqtt::connection::set_client_id`." }, - { "index": 134, "name": "mqtt::connection::set_username", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "username", "type": "string"}], "return_type": "null", "docs": "Host function `mqtt::connection::set_username`." }, - { "index": 135, "name": "mqtt::connection::set_password", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "password", "type": "string"}], "return_type": "null", "docs": "Host function `mqtt::connection::set_password`." }, - { "index": 136, "name": "mqtt::connection::set_keep_alive_secs", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "keep_alive_secs", "type": "int"}], "return_type": "null", "docs": "Host function `mqtt::connection::set_keep_alive_secs`." }, - { "index": 137, "name": "mqtt::connection::set_clean_start", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "enabled", "type": "bool"}], "return_type": "null", "docs": "Host function `mqtt::connection::set_clean_start`." }, + { "index": 131, "name": "mqtt::connection::set_scheme", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "scheme", "type": "string"}], "return_type": "unit", "docs": "Host function `mqtt::connection::set_scheme`." }, + { "index": 132, "name": "mqtt::connection::set_target", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "unit", "docs": "Host function `mqtt::connection::set_target`." }, + { "index": 133, "name": "mqtt::connection::set_client_id", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "client_id", "type": "string"}], "return_type": "unit", "docs": "Host function `mqtt::connection::set_client_id`." }, + { "index": 134, "name": "mqtt::connection::set_username", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "username", "type": "string"}], "return_type": "unit", "docs": "Host function `mqtt::connection::set_username`." }, + { "index": 135, "name": "mqtt::connection::set_password", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "password", "type": "string"}], "return_type": "unit", "docs": "Host function `mqtt::connection::set_password`." }, + { "index": 136, "name": "mqtt::connection::set_keep_alive_secs", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "keep_alive_secs", "type": "int"}], "return_type": "unit", "docs": "Host function `mqtt::connection::set_keep_alive_secs`." }, + { "index": 137, "name": "mqtt::connection::set_clean_start", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "enabled", "type": "bool"}], "return_type": "unit", "docs": "Host function `mqtt::connection::set_clean_start`." }, { "index": 138, "name": "mqtt::connection::connect", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `mqtt::connection::connect`." }, { "index": 139, "name": "mqtt::connection::get_phase", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "string", "docs": "Host function `mqtt::connection::get_phase`." }, - { "index": 140, "name": "mqtt::connection::disconnect", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "reason_code", "type": "int"}, {"name": "reason_text", "type": "string"}], "return_type": "null", "docs": "Host function `mqtt::connection::disconnect`." }, + { "index": 140, "name": "mqtt::connection::disconnect", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "reason_code", "type": "int"}, {"name": "reason_text", "type": "string"}], "return_type": "unit", "docs": "Host function `mqtt::connection::disconnect`." }, { "index": 141, "name": "mqtt::connection::publish_text", "arity": 5, "params": [{"name": "connection", "type": "int"}, {"name": "topic", "type": "string"}, {"name": "payload", "type": "string"}, {"name": "qos", "type": "int"}, {"name": "retain", "type": "bool"}], "return_type": "bool", "docs": "Host function `mqtt::connection::publish_text`." }, { "index": 142, "name": "mqtt::connection::publish_binary_base64", "arity": 5, "params": [{"name": "connection", "type": "int"}, {"name": "topic", "type": "string"}, {"name": "payload", "type": "string"}, {"name": "qos", "type": "int"}, {"name": "retain", "type": "bool"}], "return_type": "bool", "docs": "Host function `mqtt::connection::publish_binary_base64`." }, { "index": 143, "name": "mqtt::connection::publish_binary", "arity": 5, "params": [{"name": "connection", "type": "int"}, {"name": "topic", "type": "string"}, {"name": "payload", "type": "bytes"}, {"name": "qos", "type": "int"}, {"name": "retain", "type": "bool"}], "return_type": "bool", "docs": "Host function `mqtt::connection::publish_binary`." }, @@ -152,12 +152,12 @@ { "index": 148, "name": "websocket::connection::downstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `websocket::connection::downstream`." }, { "index": 149, "name": "websocket::connection::default_upstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `websocket::connection::default_upstream`." }, { "index": 150, "name": "websocket::connection::is_present", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `websocket::connection::is_present`." }, - { "index": 151, "name": "websocket::connection::set_target", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "null", "docs": "Host function `websocket::connection::set_target`." }, - { "index": 152, "name": "websocket::connection::set_scheme", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "scheme", "type": "string"}], "return_type": "null", "docs": "Host function `websocket::connection::set_scheme`." }, - { "index": 153, "name": "websocket::connection::set_path", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "path", "type": "string"}], "return_type": "null", "docs": "Host function `websocket::connection::set_path`." }, - { "index": 154, "name": "websocket::connection::set_query", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "query", "type": "string"}], "return_type": "null", "docs": "Host function `websocket::connection::set_query`." }, - { "index": 155, "name": "websocket::connection::set_header", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "null", "docs": "Host function `websocket::connection::set_header`." }, - { "index": 156, "name": "websocket::connection::set_subprotocols", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "protocols", "type": "string"}], "return_type": "null", "docs": "Host function `websocket::connection::set_subprotocols`." }, + { "index": 151, "name": "websocket::connection::set_target", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "host", "type": "string"}, {"name": "port", "type": "int"}], "return_type": "unit", "docs": "Host function `websocket::connection::set_target`." }, + { "index": 152, "name": "websocket::connection::set_scheme", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "scheme", "type": "string"}], "return_type": "unit", "docs": "Host function `websocket::connection::set_scheme`." }, + { "index": 153, "name": "websocket::connection::set_path", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "path", "type": "string"}], "return_type": "unit", "docs": "Host function `websocket::connection::set_path`." }, + { "index": 154, "name": "websocket::connection::set_query", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "query", "type": "string"}], "return_type": "unit", "docs": "Host function `websocket::connection::set_query`." }, + { "index": 155, "name": "websocket::connection::set_header", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "name", "type": "string"}, {"name": "value", "type": "string"}], "return_type": "unit", "docs": "Host function `websocket::connection::set_header`." }, + { "index": 156, "name": "websocket::connection::set_subprotocols", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "protocols", "type": "string"}], "return_type": "unit", "docs": "Host function `websocket::connection::set_subprotocols`." }, { "index": 157, "name": "websocket::connection::connect", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `websocket::connection::connect`." }, { "index": 158, "name": "websocket::connection::get_phase", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "string", "docs": "Host function `websocket::connection::get_phase`." }, { "index": 159, "name": "websocket::connection::get_subprotocol", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "string", "docs": "Host function `websocket::connection::get_subprotocol`." }, @@ -168,14 +168,14 @@ { "index": 164, "name": "websocket::connection::read_binary_base64", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "string", "docs": "Host function `websocket::connection::read_binary_base64`." }, { "index": 165, "name": "websocket::connection::read_binary", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bytes", "docs": "Host function `websocket::connection::read_binary`." }, { "index": 166, "name": "websocket::connection::eof", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `websocket::connection::eof`." }, - { "index": 167, "name": "websocket::connection::close", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "code", "type": "int"}, {"name": "reason", "type": "string"}], "return_type": "null", "docs": "Host function `websocket::connection::close`." }, + { "index": 167, "name": "websocket::connection::close", "arity": 3, "params": [{"name": "connection", "type": "int"}, {"name": "code", "type": "int"}, {"name": "reason", "type": "string"}], "return_type": "unit", "docs": "Host function `websocket::connection::close`." }, { "index": 168, "name": "webrtc::connection::new", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `webrtc::connection::new`." }, { "index": 169, "name": "webrtc::connection::downstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `webrtc::connection::downstream`." }, { "index": 170, "name": "webrtc::connection::default_upstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `webrtc::connection::default_upstream`." }, { "index": 171, "name": "webrtc::connection::is_present", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `webrtc::connection::is_present`." }, - { "index": 172, "name": "webrtc::connection::set_ice_servers", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "urls", "type": "string"}], "return_type": "null", "docs": "Host function `webrtc::connection::set_ice_servers`." }, - { "index": 173, "name": "webrtc::connection::set_data_channel_label", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "label", "type": "string"}], "return_type": "null", "docs": "Host function `webrtc::connection::set_data_channel_label`." }, - { "index": 174, "name": "webrtc::connection::set_remote_description", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "description_json", "type": "string"}], "return_type": "null", "docs": "Host function `webrtc::connection::set_remote_description`." }, + { "index": 172, "name": "webrtc::connection::set_ice_servers", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "urls", "type": "string"}], "return_type": "unit", "docs": "Host function `webrtc::connection::set_ice_servers`." }, + { "index": 173, "name": "webrtc::connection::set_data_channel_label", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "label", "type": "string"}], "return_type": "unit", "docs": "Host function `webrtc::connection::set_data_channel_label`." }, + { "index": 174, "name": "webrtc::connection::set_remote_description", "arity": 2, "params": [{"name": "connection", "type": "int"}, {"name": "description_json", "type": "string"}], "return_type": "unit", "docs": "Host function `webrtc::connection::set_remote_description`." }, { "index": 175, "name": "webrtc::connection::create_offer", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "string", "docs": "Host function `webrtc::connection::create_offer`." }, { "index": 176, "name": "webrtc::connection::create_answer", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "string", "docs": "Host function `webrtc::connection::create_answer`." }, { "index": 177, "name": "webrtc::connection::connect", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `webrtc::connection::connect`." }, @@ -187,7 +187,7 @@ { "index": 183, "name": "webrtc::connection::read_binary_base64", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "string", "docs": "Host function `webrtc::connection::read_binary_base64`." }, { "index": 184, "name": "webrtc::connection::read_binary", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bytes", "docs": "Host function `webrtc::connection::read_binary`." }, { "index": 185, "name": "webrtc::connection::eof", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "bool", "docs": "Host function `webrtc::connection::eof`." }, - { "index": 186, "name": "webrtc::connection::close", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "null", "docs": "Host function `webrtc::connection::close`." }, + { "index": 186, "name": "webrtc::connection::close", "arity": 1, "params": [{"name": "connection", "type": "int"}], "return_type": "unit", "docs": "Host function `webrtc::connection::close`." }, { "index": 187, "name": "proxy::stream::downstream", "arity": 0, "params": [], "return_type": "int", "docs": "Host function `proxy::stream::downstream`." }, { "index": 188, "name": "proxy::stream::exchange", "arity": 1, "params": [{"name": "exchange", "type": "int"}], "return_type": "int", "docs": "Host function `proxy::stream::exchange`." }, { "index": 189, "name": "proxy::stream::from_tcp", "arity": 1, "params": [{"name": "stream", "type": "int"}], "return_type": "int", "docs": "Host function `proxy::stream::from_tcp`." }, diff --git a/pd-edge-abi/build.rs b/pd-edge-abi/build.rs index b0fde6f..61d2ce8 100644 --- a/pd-edge-abi/build.rs +++ b/pd-edge-abi/build.rs @@ -162,7 +162,7 @@ fn parse_function_decl( param_names, param_types, return_type: match &function.sig.output { - ReturnType::Default => "Null".to_string(), + ReturnType::Default => "Unit".to_string(), ReturnType::Type(_, ty) => type_label(ty), }, docs, @@ -405,7 +405,7 @@ fn type_label(ty: &Type) -> String { Type::Group(group) => type_label(&group.elem), Type::Paren(paren) => type_label(&paren.elem), Type::Reference(reference) => type_label(&reference.elem), - Type::Tuple(tuple) if tuple.elems.is_empty() => "Null".to_string(), + Type::Tuple(tuple) if tuple.elems.is_empty() => "Unit".to_string(), Type::Path(path) => { let Some(segment) = path.path.segments.last() else { panic!("unsupported callable type"); @@ -423,6 +423,10 @@ fn type_label(ty: &Type) -> String { "Map" | "VmMap" => "Map".to_string(), "Number" => "Number".to_string(), "Unknown" => "Unknown".to_string(), + "GuestResult" => { + guest_result_option_string(segment); + "ResultOptionString".to_string() + } "Option" => { let syn::PathArguments::AngleBracketed(args) = &segment.arguments else { panic!("Option requires one generic argument"); @@ -448,6 +452,43 @@ fn type_label(ty: &Type) -> String { } } +/// Requires the exact `GuestResult, String>` return shape. +/// +/// The edge ABI publishes exactly one fallible optional-text return: absence is +/// a guest `Option::None`, an empty value is `Option::Some("")`, and a member +/// that is not valid text is the guest error. Any other `GuestResult` shape is +/// rejected here so the published manifest can never mislabel a wider contract. +fn guest_result_option_string(segment: &syn::PathSegment) { + let syn::PathArguments::AngleBracketed(args) = &segment.arguments else { + panic!("GuestResult requires two generic arguments"); + }; + let mut arguments = args.args.iter(); + let (Some(syn::GenericArgument::Type(ok)), Some(syn::GenericArgument::Type(err)), None) = + (arguments.next(), arguments.next(), arguments.next()) + else { + panic!("GuestResult requires exactly two type arguments"); + }; + let Type::Path(ok_path) = ok else { + panic!("GuestResult Ok type must be GuestOption"); + }; + let Some(ok_segment) = ok_path.path.segments.last() else { + panic!("GuestResult Ok type must be GuestOption"); + }; + if ok_segment.ident != "GuestOption" { + panic!("GuestResult Ok type must be GuestOption"); + } + let syn::PathArguments::AngleBracketed(ok_args) = &ok_segment.arguments else { + panic!("GuestOption requires one generic argument"); + }; + match (&ok_args.args.len(), ok_args.args.first()) { + (1, Some(syn::GenericArgument::Type(inner))) if type_label(inner) == "String" => {} + _ => panic!("GuestResult Ok type must be GuestOption"), + } + if type_label(err) != "String" { + panic!("GuestResult error type must be String"); + } +} + fn parse_namespace_file(path: &Path, enabled_features: &BTreeSet) -> Vec { let source = fs::read_to_string(path) .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display())); @@ -753,10 +794,30 @@ fn render_abi_rust(functions: &[AbiFunctionDecl], namespaces: &[NamespaceDecl]) out } +/// Renders a Rust type label as the manifest's lowercase wire tag. +/// +/// Single-word labels are unchanged (`Int` → `int`, `Map` → `map`), while a +/// multi-word label keeps its word boundary so the published tag stays exact +/// (`ResultOptionString` → `result_option_string`). +fn manifest_type_tag(label: &str) -> String { + let mut out = String::new(); + for (index, ch) in label.chars().enumerate() { + if ch.is_ascii_uppercase() { + if index > 0 { + out.push('_'); + } + out.push(ch.to_ascii_lowercase()); + } else { + out.push(ch); + } + } + out +} + fn render_abi_json(functions: &[AbiFunctionDecl]) -> String { let mut out = String::new(); out.push_str("{\n"); - out.push_str(" \"abi_version\": 25,\n"); + out.push_str(" \"abi_version\": 26,\n"); out.push_str(" \"functions\": [\n"); for (index, function) in functions.iter().enumerate() { let suffix = if index + 1 == functions.len() { @@ -771,7 +832,7 @@ fn render_abi_json(functions: &[AbiFunctionDecl]) -> String { .map(|(name, ty)| { format!( "{{\"name\": {name:?}, \"type\": {:?}}}", - ty.to_ascii_lowercase() + manifest_type_tag(ty) ) }) .collect::>() @@ -782,7 +843,7 @@ fn render_abi_json(functions: &[AbiFunctionDecl]) -> String { function.name, function.param_names.len(), params, - function.return_type.to_ascii_lowercase(), + manifest_type_tag(&function.return_type), function.docs ) .unwrap(); diff --git a/pd-edge-abi/src/abi_spec/http.exchange.rs b/pd-edge-abi/src/abi_spec/http.exchange.rs index 981f392..9ce9acc 100644 --- a/pd-edge-abi/src/abi_spec/http.exchange.rs +++ b/pd-edge-abi/src/abi_spec/http.exchange.rs @@ -118,9 +118,13 @@ fn http_exchange_get_status(exchange: i64) -> i64 { unreachable!("abi declaration only") } -/// Host function `http::exchange::get_header`. +/// Returns the first value for a header on the outbound HTTP exchange. +/// +/// `Ok(None)` means the exchange carries no such header, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid header name is a fatal host error. #[pd_host_function(name = "http::exchange::get_header")] -fn http_exchange_get_header(exchange: i64, name: &str) -> String { +fn http_exchange_get_header(exchange: i64, name: &str) -> GuestResult, String> { unreachable!("abi declaration only") } @@ -136,9 +140,16 @@ fn http_exchange_get_body(exchange: i64) -> String { unreachable!("abi declaration only") } -/// Host function `http::exchange::get_trailer`. +/// Returns the first trailer value for the outbound HTTP exchange. +/// +/// `Ok(None)` means the exchange carries no such trailer, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid trailer name is a fatal host error. #[pd_host_function(name = "http::exchange::get_trailer")] -fn http_exchange_get_trailer(exchange: i64, name: &str) -> String { +fn http_exchange_get_trailer( + exchange: i64, + name: &str, +) -> GuestResult, String> { unreachable!("abi declaration only") } diff --git a/pd-edge-abi/src/abi_spec/http.request.rs b/pd-edge-abi/src/abi_spec/http.request.rs index bca8171..c81284e 100644 --- a/pd-edge-abi/src/abi_spec/http.request.rs +++ b/pd-edge-abi/src/abi_spec/http.request.rs @@ -34,9 +34,13 @@ fn http_request_get_host() -> String { unreachable!("abi declaration only") } -/// Host function `http::request::get_header`. +/// Returns the first value for a header on the downstream HTTP request. +/// +/// `Ok(None)` means the request carries no such header, `Ok(Some(""))` means it +/// carries it with an empty value, and `Err` reports a value that is not valid +/// text. An invalid header name is a fatal host error, not an absent header. #[pd_host_function(name = "http::request::get_header")] -fn http_request_get_header(name: &str) -> String { +fn http_request_get_header(name: &str) -> GuestResult, String> { unreachable!("abi declaration only") } @@ -52,9 +56,12 @@ fn http_request_get_headers() -> Map { unreachable!("abi declaration only") } -/// Host function `http::request::get_query_arg`. +/// Returns a query parameter from the downstream HTTP request. +/// +/// `Ok(None)` means the query string has no such parameter, `Ok(Some(""))` +/// means it has one with an empty value. A repeated key keeps the first value. #[pd_host_function(name = "http::request::get_query_arg")] -fn http_request_get_query_arg(name: &str) -> String { +fn http_request_get_query_arg(name: &str) -> GuestResult, String> { unreachable!("abi declaration only") } diff --git a/pd-edge-abi/src/abi_spec/http.response.rs b/pd-edge-abi/src/abi_spec/http.response.rs index 43dac86..bb9ff2d 100644 --- a/pd-edge-abi/src/abi_spec/http.response.rs +++ b/pd-edge-abi/src/abi_spec/http.response.rs @@ -64,9 +64,13 @@ fn http_response_get_body() -> String { unreachable!("abi declaration only") } -/// Host function `http::response::get_trailer`. +/// Returns the first trailer value for the downstream HTTP response. +/// +/// `Ok(None)` means the response carries no such trailer, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid trailer name is a fatal host error. #[pd_host_function(name = "http::response::get_trailer")] -fn http_response_get_trailer(name: &str) -> String { +fn http_response_get_trailer(name: &str) -> GuestResult, String> { unreachable!("abi declaration only") } @@ -76,9 +80,13 @@ fn http_response_get_trailers() -> Map { unreachable!("abi declaration only") } -/// Host function `http::response::get_header`. +/// Returns the first value for a header on the downstream HTTP response. +/// +/// `Ok(None)` means the response carries no such header, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid header name is a fatal host error. #[pd_host_function(name = "http::response::get_header")] -fn http_response_get_header(name: &str) -> String { +fn http_response_get_header(name: &str) -> GuestResult, String> { unreachable!("abi declaration only") } diff --git a/pd-edge-abi/src/lib.rs b/pd-edge-abi/src/lib.rs index f560bba..1a562bf 100644 --- a/pd-edge-abi/src/lib.rs +++ b/pd-edge-abi/src/lib.rs @@ -1,7 +1,9 @@ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AbiValueType { Unknown, - Null, + /// Guest `()`: the function returns no value. Its physical carrier is the + /// VM's internal Null, but the guest schema is Unit, never a nullable value. + Unit, Int, Float, Bool, @@ -9,13 +11,20 @@ pub enum AbiValueType { Bytes, Array, Map, + /// Guest `Result, string>`. + /// + /// `Ok(None)` means the member is absent, `Ok(Some(""))` means it is + /// present with an empty value, and `Err(message)` carries the text of a + /// member whose value is not valid text. Fatal failures stay fatal VM + /// errors and are never encoded here. + ResultOptionString, } impl AbiValueType { pub const fn as_str(self) -> &'static str { match self { Self::Unknown => "unknown", - Self::Null => "null", + Self::Unit => "unit", Self::Int => "int", Self::Float => "float", Self::Bool => "bool", @@ -23,6 +32,7 @@ impl AbiValueType { Self::Bytes => "bytes", Self::Array => "array", Self::Map => "map", + Self::ResultOptionString => "result_option_string", } } } @@ -75,7 +85,7 @@ pub struct HostNamespaceSpec { pub docs: &'static str, } -pub const ABI_VERSION: u16 = 25; +pub const ABI_VERSION: u16 = 26; #[allow(dead_code, unused_variables)] mod callable_specs { @@ -99,6 +109,7 @@ mod callable_specs { #[allow(unused_imports)] use self::marker::{Any, Array, Bytes, Map, Value}; use pd_host_function::pd_host_function; + use vm::{GuestOption, GuestResult}; include!("abi_spec/functions.rs"); } @@ -170,7 +181,7 @@ mod tests { #[test] fn abi_json_contains_declared_functions() { let manifest = abi_json(); - assert!(manifest.contains("\"abi_version\": 25")); + assert!(manifest.contains("\"abi_version\": 26")); for function in FUNCTIONS { assert!(manifest.contains(function.name)); assert!(manifest.contains(function.return_type.as_str())); diff --git a/pd-edge-host-function/src/edge.rs b/pd-edge-host-function/src/edge.rs index e4cab63..c480594 100644 --- a/pd-edge-host-function/src/edge.rs +++ b/pd-edge-host-function/src/edge.rs @@ -121,7 +121,7 @@ fn parse_edge_host_attr(args: &Punctuated) -> Result { let idents = list.parse_args_with(Punctuated::::parse_terminated)?; - bind_params.extend(idents.into_iter()); + bind_params.extend(idents); } other => { return Err(Error::new_spanned( diff --git a/src/abi_impl/descriptor.rs b/src/abi_impl/descriptor.rs index 28f9839..b9a6b87 100644 --- a/src/abi_impl/descriptor.rs +++ b/src/abi_impl/descriptor.rs @@ -21,7 +21,7 @@ //! //! Closed records are overlayed as [`HostTypeSchema::Named`] on the compiler //! catalog. Runtime values remain maps. That overlay changes the catalog -//! fingerprint tag, so it is an explicit ABI-versioned change (version 25). +//! fingerprint tag, so it is an explicit ABI-versioned change (version 26). //! //! ## Intentional dynamic boundaries (allowlisted) //! @@ -87,7 +87,7 @@ pub(crate) fn edge_param_type_schema(param: AbiParamType) -> HostTypeSchema { pub(crate) fn edge_return_type_schema(value: AbiValueType) -> HostTypeSchema { match value { AbiValueType::Unknown => HostTypeSchema::Unknown, - AbiValueType::Null => HostTypeSchema::Null, + AbiValueType::Unit => HostTypeSchema::Unit, AbiValueType::Int => HostTypeSchema::Int, AbiValueType::Float => HostTypeSchema::Float, AbiValueType::Bool => HostTypeSchema::Bool, @@ -95,13 +95,20 @@ pub(crate) fn edge_return_type_schema(value: AbiValueType) -> HostTypeSchema { AbiValueType::Bytes => HostTypeSchema::Bytes, AbiValueType::Array => HostTypeSchema::Array(Box::new(HostTypeSchema::Unknown)), AbiValueType::Map => HostTypeSchema::Map(Box::new(HostTypeSchema::Unknown)), + AbiValueType::ResultOptionString => HostTypeSchema::Result { + ok: Box::new(HostTypeSchema::Option(Box::new(HostTypeSchema::String))), + err: Box::new(HostTypeSchema::String), + }, } } /// Closed MQTT connection event: `publish` | `closed` | `failed`. /// /// Runtime values remain maps; the compiler catalog types the shape as a -/// named struct so field access and `.has` stay exact. +/// named struct so field access stays exact. Only `kind` exists on every +/// variant, so every other member is `Option`: a member that the active +/// variant does not carry is the guest `Option::None`, never a member that is +/// absent from the map and never an empty-string sentinel. pub(crate) fn mqtt_event_schema() -> HostTypeSchema { HostTypeSchema::named_struct( "MqttEvent", @@ -109,31 +116,28 @@ pub(crate) fn mqtt_event_schema() -> HostTypeSchema { HostStructField::new("kind", HostTypeSchema::String), HostStructField::new( "topic", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), HostStructField::new( "payload_text", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), HostStructField::new( "payload_base64", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), - ), - HostStructField::new( - "qos", - HostTypeSchema::Optional(Box::new(HostTypeSchema::Int)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), + HostStructField::new("qos", HostTypeSchema::Option(Box::new(HostTypeSchema::Int))), HostStructField::new( "retain", - HostTypeSchema::Optional(Box::new(HostTypeSchema::Bool)), + HostTypeSchema::Option(Box::new(HostTypeSchema::Bool)), ), HostStructField::new( "dup", - HostTypeSchema::Optional(Box::new(HostTypeSchema::Bool)), + HostTypeSchema::Option(Box::new(HostTypeSchema::Bool)), ), HostStructField::new( "reason", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), ], ) @@ -309,8 +313,14 @@ fn resolve_edge_schema( /// /// - `io::*`: the runtime overrides the core IO builtins with edge-scoped /// implementations (`EdgeHostScope::Io`), including helpers the standard -/// catalog does not publish in every build (`io::exists`, `io::read_line`, -/// `io::popen`, ...). +/// catalog does not publish in every build (`io::exists`, `io::popen`, ...). +/// An override must still encode the core contract the guest compiler +/// resolves for that name: `io::read_all` is `Result`, +/// `io::read_line` is `Result, string>` (EOF is `Ok(None)`, +/// a blank line is `Ok(Some(""))`), `io::write` is `Result`, and +/// `io::flush`/`io::close` are `Result<(), string>`. `io::open` is the one +/// exception: core publishes `Result` and the edge +/// runtime can only return a raw virtual-handle `int`. /// - `http::request::body::*`: downstream request-body streaming helpers used /// by the checked-in request-transform example, resolved dynamically by the /// guest compiler (`arity`/`Unknown` imports). diff --git a/src/abi_impl/http/exchange.rs b/src/abi_impl/http/exchange.rs index ef6ea7b..7a6a743 100644 --- a/src/abi_impl/http/exchange.rs +++ b/src/abi_impl/http/exchange.rs @@ -2,8 +2,9 @@ use super::state::attach_outbound_exchange_tls_transport; use super::{ helpers::{ - headers_to_value_map, is_valid_request_path, parse_header, parse_header_name, - parse_string_header_batch, serialize_query_pairs, + headers_to_value_map, is_valid_request_path, optional_header_text, optional_text_outcome, + optional_text_result, parse_header, parse_header_name, parse_string_header_batch, + serialize_query_pairs, }, state::{ HttpUpstreamScheme, SharedProxyVmContext, allocate_outbound_exchange_handle, @@ -15,7 +16,7 @@ use super::{ version::HttpVersionPreference, }; use crate::abi_impl::schedule_current_future_call; -use axum::http::Method; +use axum::http::{HeaderMap, Method}; use edge_abi::symbols::http::exchange as http_exchange; use pd_edge_host_function::pd_edge_host_function; use vm::{CallOutcome, CallReturn, Value, Vm, VmError}; @@ -516,6 +517,10 @@ fn get_exchange_status( } /// Returns the first value for a header on the outbound HTTP exchange. +/// +/// `Ok(None)` means the exchange carries no such header, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid header name is a fatal host error. #[pd_edge_host_function(name = http_exchange::GET_HEADER.name, scope = http)] fn get_exchange_header( vm: &mut Vm, @@ -526,12 +531,9 @@ fn get_exchange_header( let header_name = axum::http::HeaderName::from_bytes(name.as_bytes()) .map_err(|_| VmError::HostError(format!("invalid header name '{name}'")))?; exchange_response_values_outcome(vm, context, exchange, move |snapshot| { - let value = snapshot - .headers - .get(&header_name) - .and_then(|value| value.to_str().ok()) - .unwrap_or(""); - Ok(vm::CallReturn::one(Value::string(value))) + Ok(vm::CallReturn::one(optional_text_result( + optional_header_text(snapshot.headers.get(&header_name)), + ))) }) } @@ -560,7 +562,25 @@ async fn get_exchange_body( )))) } +/// Selects one trailer value from an outbound exchange trailer map. +/// +/// An absent trailer is `Ok(None)`, a present trailer decodes to `Ok(Some(text))` +/// even when the text is empty, a trailer that is not valid text is `Err`, and +/// an invalid trailer name is a fatal host error rather than an absent trailer. +fn exchange_trailer_value( + trailers: &HeaderMap, + name: &str, +) -> Result, String>, VmError> { + let header_name = axum::http::HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| VmError::HostError(format!("invalid trailer name '{name}'")))?; + Ok(optional_header_text(trailers.get(&header_name))) +} + /// Returns the first trailer value for the outbound HTTP exchange. +/// +/// `Ok(None)` means the exchange carries no such trailer, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid trailer name is a fatal host error. #[pd_edge_host_function(name = "http::exchange::get_trailer", scope = http)] async fn get_exchange_trailer( _vm: &mut Vm, @@ -568,17 +588,10 @@ async fn get_exchange_trailer( exchange: i64, name: String, ) -> Result { - let header_name = axum::http::HeaderName::from_bytes(name.as_bytes()) - .map_err(|_| VmError::HostError(format!("invalid trailer name '{name}'")))?; let trailers = read_outbound_exchange_response_trailers(&context, exchange).await?; - let value = trailers - .get(&header_name) - .and_then(|value| value.to_str().ok()) - .unwrap_or("") - .to_string(); - Ok(CallOutcome::Return(vm::CallReturn::one(Value::string( - value, - )))) + Ok(optional_text_outcome(exchange_trailer_value( + &trailers, &name, + )?)) } /// Returns all trailers on the outbound HTTP exchange as a map. @@ -639,3 +652,72 @@ async fn get_exchange_body_eof( let eof = outbound_exchange_response_eof(&context, exchange).await?; Ok(CallOutcome::Return(vm::CallReturn::one(Value::Bool(eof)))) } + +#[cfg(test)] +mod tests { + use axum::http::{HeaderMap, HeaderValue}; + + use super::*; + use crate::abi_impl::http::helpers::{decode_optional_text_result, optional_text_outcome}; + + fn trailer_value(bytes: &[u8]) -> HeaderValue { + HeaderValue::from_bytes(bytes).expect("trailer value bytes should be admissible") + } + + /// Runs the real trailer selection through the real guest encoding. + fn exchange_trailer_return(trailers: &HeaderMap, name: &str) -> Result, String> { + let selected = exchange_trailer_value(trailers, name) + .expect("an admissible trailer name is not a fatal host error"); + decode_optional_text_result(&optional_text_outcome(selected)) + } + + #[test] + fn exchange_get_trailer_absent_is_ok_none() { + let trailers = HeaderMap::new(); + assert_eq!( + exchange_trailer_return(&trailers, "x-absent"), + Ok(None), + "an absent exchange trailer must be Ok(None), not an empty string" + ); + } + + #[test] + fn exchange_get_trailer_present_empty_is_ok_some_empty() { + let mut trailers = HeaderMap::new(); + trailers.insert("x-empty", trailer_value(b"")); + assert_eq!( + exchange_trailer_return(&trailers, "x-empty"), + Ok(Some(String::new())), + "a present empty exchange trailer must stay distinguishable from an absent one" + ); + } + + #[test] + fn exchange_get_trailer_invalid_text_is_err() { + let mut trailers = HeaderMap::new(); + trailers.insert("x-binary", trailer_value(&[0x80, 0xff])); + match exchange_trailer_return(&trailers, "x-binary") { + Err(message) => assert!( + message.contains("not valid text"), + "the guest error must describe the decode failure: {message}" + ), + other => panic!( + "an exchange trailer value that is not text must be a guest error, got {other:?}" + ), + } + } + + #[test] + fn exchange_get_trailer_invalid_name_is_fatal() { + let trailers = HeaderMap::new(); + let error = exchange_trailer_value(&trailers, "not a trailer name") + .expect_err("an invalid trailer name must stay a fatal host error"); + match error { + VmError::HostError(message) => assert!( + message.contains("invalid trailer name"), + "the host error must name the rejection: {message}" + ), + other => panic!("an invalid trailer name must be a host error, got {other:?}"), + } + } +} diff --git a/src/abi_impl/http/helpers.rs b/src/abi_impl/http/helpers.rs index 0050b8f..df3cbac 100644 --- a/src/abi_impl/http/helpers.rs +++ b/src/abi_impl/http/helpers.rs @@ -8,7 +8,125 @@ use std::{ use axum::http::{HeaderMap, HeaderName, HeaderValue}; use parking_lot::Mutex; use vm::bytecode::VmMap; -use vm::{Value, VmError}; +use vm::{CallOutcome, CallReturn, Value, VmError}; + +/// Strictly decodes one optional header or trailer value as guest text. +/// +/// `Ok(None)` is an absent member, a present value decodes to `Ok(Some(text))` +/// even when the text is empty, and a value that is not valid text is an error +/// instead of a silent empty string. +pub(crate) fn optional_header_text(value: Option<&HeaderValue>) -> Result, String> { + match value { + None => Ok(None), + Some(value) => match value.to_str() { + Ok(text) => Ok(Some(text.to_string())), + Err(error) => Err(format!("header value is not valid text: {error}")), + }, + } +} + +/// Builds the guest value of a `Result, string>` edge getter. +/// +/// The carrier is the core canonical union, never a bare Null and never an +/// empty-string sentinel: an absent member is `Option::None`, a present member +/// is `Option::Some(text)`, and a malformed member is the guest error. +pub(crate) fn optional_text_result(value: Result, String>) -> Value { + match value { + Ok(Some(text)) => vm::result::carrier(true, vm::option::some_carrier(Value::string(text))), + Ok(None) => vm::result::carrier(true, vm::option::none_carrier()), + Err(message) => vm::result::carrier(false, Value::string(message)), + } +} + +/// Wraps [`optional_text_result`] into the single-value host return. +pub(crate) fn optional_text_outcome(value: Result, String>) -> CallOutcome { + CallOutcome::Return(CallReturn::one(optional_text_result(value))) +} + +/// Builds the guest value of a `Result` edge reader. +/// +/// The core `io::read_all` contract reports a recoverable read failure as the +/// guest error, so the value is the canonical `Result` carrier rather than a +/// bare string. +pub(crate) fn text_result(value: Result) -> Value { + match value { + Ok(text) => vm::result::carrier(true, Value::string(text)), + Err(message) => vm::result::carrier(false, Value::string(message)), + } +} + +/// Wraps [`text_result`] into the single-value host return. +pub(crate) fn text_result_outcome(value: Result) -> CallOutcome { + CallOutcome::Return(CallReturn::one(text_result(value))) +} + +/// Builds the guest value of a `Result` edge writer. +/// +/// The core `io::write` contract reports the byte count as the success value, +/// so the handle-level writer must publish the canonical `Result` carrier. +pub(crate) fn int_result_outcome(written: i64) -> CallOutcome { + CallOutcome::Return(CallReturn::one(vm::result::carrier( + true, + Value::Int(written), + ))) +} + +/// Builds the guest value of a `Result<(), string>` edge call. +/// +/// The core `io::flush` / `io::close` contracts publish a unit success value, +/// whose physical carrier is the VM's internal Null. +pub(crate) fn unit_result_outcome() -> CallOutcome { + CallOutcome::Return(CallReturn::one(vm::result::carrier(true, Value::Null))) +} + +/// Reads the Boolean `tag` and active `payload` of one canonical carrier map. +#[cfg(test)] +fn carrier_fields(value: &Value) -> (bool, Option) { + let Value::Map(entries) = value else { + panic!("carrier must be a map, got {value:?}"); + }; + let tag = match entries.get(&Value::string("tag")) { + Some(Value::Bool(tag)) => *tag, + other => panic!("carrier must carry a Boolean tag, got {other:?}"), + }; + (tag, entries.get(&Value::string("payload")).cloned()) +} + +/// Decodes a `Result, string>` edge getter return for assertions. +/// +/// This is the test-side contract check: a return that is not the canonical +/// two-level carrier fails here instead of being coerced. +#[cfg(test)] +pub(crate) fn decode_optional_text_result(outcome: &CallOutcome) -> Result, String> { + let values = match outcome { + CallOutcome::Return(values) => values.as_slice(), + other => panic!("edge getter must return a value, got {other:?}"), + }; + assert_eq!(values.len(), 1, "edge getter returns exactly one value"); + let (is_ok, payload) = carrier_fields(&values[0]); + if !is_ok { + return match payload { + Some(Value::String(message)) => Err(message.to_string()), + other => panic!("guest error payload must be text, got {other:?}"), + }; + } + let (is_some, payload) = carrier_fields( + payload + .as_ref() + .unwrap_or_else(|| panic!("GuestResult::Ok must carry an Option payload")), + ); + if !is_some { + assert!( + payload.is_none(), + "Option::None must not carry an active payload" + ); + return Ok(None); + } + match payload { + Some(Value::String(text)) => Ok(Some(text.to_string())), + other => panic!("Option::Some payload must be text, got {other:?}"), + } +} const HEADER_BATCH_CACHE_CAPACITY: usize = 256; diff --git a/src/abi_impl/http/mod.rs b/src/abi_impl/http/mod.rs index 47f0645..3d8e0e5 100644 --- a/src/abi_impl/http/mod.rs +++ b/src/abi_impl/http/mod.rs @@ -1,7 +1,7 @@ #[cfg(feature = "http")] pub(crate) mod exchange; pub(crate) mod fast_path; -mod helpers; +pub(crate) mod helpers; pub(crate) mod outbound_http1; #[cfg(feature = "http")] mod request; diff --git a/src/abi_impl/http/request.rs b/src/abi_impl/http/request.rs index 98a9ef2..c78f01f 100644 --- a/src/abi_impl/http/request.rs +++ b/src/abi_impl/http/request.rs @@ -1,10 +1,13 @@ use super::{ - helpers::{headers_to_value_map, query_to_value_map, request_path_with_query}, + helpers::{ + headers_to_value_map, optional_text_outcome, query_to_value_map, request_path_with_query, + }, state::{ SharedProxyVmContext, read_request_body_all, read_request_body_next_chunk, request_body_eof, schedule_downstream_http_handoff, }, }; +use axum::http::HeaderName; use edge_abi::symbols::http::request as http_request; use pd_edge_host_function::pd_edge_host_function; use vm::{CallOutcome, CallReturn, Value, Vm, VmError}; @@ -157,14 +160,21 @@ fn get_request_http_version(context: SharedProxyVmContext) -> Result Result { - let value = context - .with_request_head(|request_head| request_head.lazy_headers().get_str(name)) - .unwrap_or_default(); - Ok(CallOutcome::Return(vm::CallReturn::one(Value::string( - value, - )))) +fn get_request_header_impl( + context: SharedProxyVmContext, + name: &str, +) -> Result { + let header_name = HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| VmError::HostError(format!("invalid header name '{name}'")))?; + let value = context.with_request_head(|request_head| { + request_head.lazy_headers().get_text(header_name.as_str()) + }); + Ok(optional_text_outcome(value)) } /// Returns all headers on the downstream HTTP request as a map. @@ -176,6 +186,9 @@ fn get_request_headers(context: SharedProxyVmContext) -> Result Result { let value = context.with_request_head(|request_head| { url::form_urlencoded::parse(request_head.query().as_bytes()) - .find_map(|(key, value)| { - if key == name { - Some(value.into_owned()) - } else { - None - } - }) - .unwrap_or_default() + .find(|(key, _)| key == name) + .map(|(_, value)| value.into_owned()) }); - Ok(CallOutcome::Return(vm::CallReturn::one(Value::string( - value, - )))) + Ok(optional_text_outcome(Ok(value))) } /// Returns all query parameters from the downstream HTTP request as a map. @@ -212,3 +217,124 @@ fn get_request_port(context: SharedProxyVmContext) -> Result SharedProxyVmContext { + Arc::new(ProxyVmContext::from_http_request( + HttpRequestContext { + request_id: LazyRequestId::from_string("test-request".to_string()), + method: Method::GET, + path: RequestStringField::Static("/getters".to_string()), + query: RequestStringField::Static(query.to_string()), + http_version: RequestStringField::Static("1.1".to_string()), + port: RequestPortField::Static(80), + scheme: RequestStringField::Static("http".to_string()), + host: RequestStringField::Static("localhost".to_string()), + client_ip: RequestStringField::Static("127.0.0.1".to_string()), + body: Body::empty(), + headers: headers.into(), + }, + Arc::new(RateLimiterStore::new()), + )) + } + + fn header_value(bytes: &[u8]) -> HeaderValue { + HeaderValue::from_bytes(bytes).expect("header value bytes should be admissible") + } + + #[test] + fn request_get_header_absent_is_ok_none() { + let context = test_context("", HeaderMap::new()); + let outcome = + get_request_header_impl(context, "x-absent").expect("absent header is not fatal"); + assert_eq!( + decode_optional_text_result(&outcome), + Ok(None), + "an absent request header must be Ok(None), not an empty string" + ); + } + + #[test] + fn request_get_header_present_empty_is_ok_some_empty() { + let mut headers = HeaderMap::new(); + headers.insert("x-empty", header_value(b"")); + let context = test_context("", headers); + let outcome = + get_request_header_impl(context, "x-empty").expect("empty header is not fatal"); + assert_eq!( + decode_optional_text_result(&outcome), + Ok(Some(String::new())), + "a present empty request header must stay distinguishable from an absent one" + ); + } + + #[test] + fn request_get_header_invalid_text_is_err() { + let mut headers = HeaderMap::new(); + headers.insert("x-binary", header_value(&[0x80, 0xff])); + let context = test_context("", headers); + let outcome = + get_request_header_impl(context, "x-binary").expect("decode error is a guest error"); + match decode_optional_text_result(&outcome) { + Err(message) => assert!( + message.contains("not valid text"), + "the guest error must describe the decode failure: {message}" + ), + other => panic!("a header value that is not text must be a guest error, got {other:?}"), + } + } + + #[test] + fn request_get_header_invalid_name_is_fatal() { + let context = test_context("", HeaderMap::new()); + let error = get_request_header_impl(context, "not a header name") + .expect_err("an invalid header name must stay a fatal host error"); + assert!( + format!("{error}").contains("invalid header name"), + "the fatal error must name the invalid header: {error}" + ); + } + + #[test] + fn request_get_query_arg_repeated_key_keeps_the_first_value() { + let context = test_context("a=1&a=2&flag=", HeaderMap::new()); + + let repeated = + get_request_query_arg_impl(context.clone(), "a").expect("query arg is not fatal"); + assert_eq!( + decode_optional_text_result(&repeated), + Ok(Some("1".to_string())), + "a repeated query key must keep the first value" + ); + + let empty = + get_request_query_arg_impl(context.clone(), "flag").expect("query arg is not fatal"); + assert_eq!( + decode_optional_text_result(&empty), + Ok(Some(String::new())), + "a parameter with an empty value must be Ok(Some(\"\"))" + ); + + let absent = + get_request_query_arg_impl(context, "missing").expect("query arg is not fatal"); + assert_eq!( + decode_optional_text_result(&absent), + Ok(None), + "an absent query parameter must be Ok(None)" + ); + } +} diff --git a/src/abi_impl/http/response.rs b/src/abi_impl/http/response.rs index cd97776..2165d6e 100644 --- a/src/abi_impl/http/response.rs +++ b/src/abi_impl/http/response.rs @@ -1,5 +1,8 @@ use super::{ - helpers::{headers_to_value_map, parse_header, parse_header_name, parse_string_header_batch}, + helpers::{ + headers_to_value_map, optional_header_text, optional_text_outcome, parse_header, + parse_header_name, parse_string_header_batch, + }, state::{ DownstreamResponseStreamWriteMode, SharedProxyVmContext, ensure_outbound_exchange_response_started, finish_downstream_response_stream, @@ -65,6 +68,10 @@ async fn get_response_body( } /// Returns the first trailer value for the downstream HTTP response. +/// +/// `Ok(None)` means the response carries no such trailer, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid trailer name is a fatal host error. #[pd_edge_host_function(name = "http::response::get_trailer", scope = http)] async fn get_response_trailer( _vm: &mut Vm, @@ -74,14 +81,9 @@ async fn get_response_trailer( let header_name = HeaderName::from_bytes(name.as_bytes()) .map_err(|_| VmError::HostError(format!("invalid trailer name '{name}'")))?; let trailers = read_downstream_response_trailers(&context).await?; - let value = trailers - .get(&header_name) - .and_then(|value| value.to_str().ok()) - .unwrap_or("") - .to_string(); - Ok(CallOutcome::Return(vm::CallReturn::one(Value::string( - value, - )))) + Ok(optional_text_outcome(optional_header_text( + trailers.get(&header_name), + ))) } /// Returns all trailers on the downstream HTTP response as a map. @@ -97,21 +99,18 @@ async fn get_response_trailers( } /// Returns the first value for a header on the downstream HTTP response. +/// +/// `Ok(None)` means the response carries no such header, `Ok(Some(""))` means +/// it carries it with an empty value, and `Err` reports a value that is not +/// valid text. An invalid header name is a fatal host error. #[pd_edge_host_function(name = http_response::GET_HEADER.name, scope = http)] fn get_response_header(context: SharedProxyVmContext, name: &str) -> Result { let header_name = HeaderName::from_bytes(name.as_bytes()) .map_err(|_| VmError::HostError(format!("invalid header name '{name}'")))?; let value = context.with_downstream_response(|response| { - response - .headers - .get(&header_name) - .and_then(|value| value.to_str().ok()) - .unwrap_or("") - .to_string() + optional_header_text(response.headers.get(&header_name)) }); - Ok(CallOutcome::Return(vm::CallReturn::one(Value::string( - value, - )))) + Ok(optional_text_outcome(value)) } /// Returns all headers on the downstream HTTP response as a map. @@ -304,3 +303,128 @@ fn clear_response_header( })?; Ok(CallOutcome::Return(vm::CallReturn::none())) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use axum::http::{HeaderMap, HeaderName, HeaderValue}; + + use super::*; + use crate::abi_impl::RateLimiterStore; + use crate::abi_impl::http::ProxyVmContext; + use crate::abi_impl::http::helpers::decode_optional_text_result; + + fn test_context(headers: HeaderMap) -> SharedProxyVmContext { + let context = Arc::new(ProxyVmContext::from_request_headers( + HeaderMap::new(), + Arc::new(RateLimiterStore::new()), + )); + context + .insert_downstream_response_headers(headers) + .expect("downstream response headers should be writable"); + context + } + + fn header_value(bytes: &[u8]) -> HeaderValue { + HeaderValue::from_bytes(bytes).expect("header value bytes should be admissible") + } + + #[test] + fn response_get_header_absent_is_ok_none() { + let context = test_context(HeaderMap::new()); + let outcome = + get_response_header_impl(context, "x-absent").expect("absent header is not fatal"); + assert_eq!( + decode_optional_text_result(&outcome), + Ok(None), + "an absent response header must be Ok(None), not an empty string" + ); + } + + #[test] + fn response_get_header_present_empty_is_ok_some_empty() { + let mut headers = HeaderMap::new(); + headers.insert("x-empty", header_value(b"")); + let context = test_context(headers); + let outcome = + get_response_header_impl(context, "x-empty").expect("empty header is not fatal"); + assert_eq!( + decode_optional_text_result(&outcome), + Ok(Some(String::new())), + "a present empty response header must stay distinguishable from an absent one" + ); + } + + #[test] + fn response_get_header_invalid_text_is_err() { + let mut headers = HeaderMap::new(); + headers.insert("x-binary", header_value(&[0x80, 0xff])); + let context = test_context(headers); + let outcome = + get_response_header_impl(context, "x-binary").expect("decode error is a guest error"); + match decode_optional_text_result(&outcome) { + Err(message) => assert!( + message.contains("not valid text"), + "the guest error must describe the decode failure: {message}" + ), + other => panic!("a header value that is not text must be a guest error, got {other:?}"), + } + } + + #[test] + fn response_get_header_invalid_name_is_fatal() { + let context = test_context(HeaderMap::new()); + let error = get_response_header_impl(context, "not a header name") + .expect_err("an invalid header name must stay a fatal host error"); + assert!( + format!("{error}").contains("invalid header name"), + "the fatal error must name the invalid header: {error}" + ); + } + + /// The trailer getter reuses the same absent/decode contract as headers; the + /// async host wrapper needs a live store, so this pins the value contract the + /// wrapper feeds into `optional_text_outcome`. + #[test] + fn response_get_trailer_uses_the_same_absent_and_decode_contract() { + let mut trailers = HeaderMap::new(); + trailers.insert( + HeaderName::from_bytes(b"x-trailer").expect("valid trailer name"), + header_value(b"done"), + ); + trailers.insert( + HeaderName::from_bytes(b"x-empty-trailer").expect("valid trailer name"), + header_value(b""), + ); + trailers.insert( + HeaderName::from_bytes(b"x-binary-trailer").expect("valid trailer name"), + header_value(&[0x80, 0xff]), + ); + + assert_eq!( + decode_optional_text_result(&optional_text_outcome(optional_header_text( + trailers.get("x-trailer") + ))), + Ok(Some("done".to_string())) + ); + assert_eq!( + decode_optional_text_result(&optional_text_outcome(optional_header_text( + trailers.get("x-empty-trailer") + ))), + Ok(Some(String::new())) + ); + assert_eq!( + decode_optional_text_result(&optional_text_outcome(optional_header_text( + trailers.get("x-absent-trailer") + ))), + Ok(None) + ); + assert!(matches!( + decode_optional_text_result(&optional_text_outcome(optional_header_text( + trailers.get("x-binary-trailer") + ))), + Err(message) if message.contains("not valid text") + )); + } +} diff --git a/src/abi_impl/http/state.rs b/src/abi_impl/http/state.rs index ef2c1d3..0e8c6ad 100644 --- a/src/abi_impl/http/state.rs +++ b/src/abi_impl/http/state.rs @@ -2806,7 +2806,8 @@ mod tests { let line = read_request_body_next_line(&context) .await - .expect("line read should succeed"); + .expect("line read should succeed") + .expect("the last line is present, not end of stream"); assert_eq!(line.as_slice(), b"tail-without-newline"); diff --git a/src/abi_impl/http/state/body_io.rs b/src/abi_impl/http/state/body_io.rs index 146b86b..cf51d5d 100644 --- a/src/abi_impl/http/state/body_io.rs +++ b/src/abi_impl/http/state/body_io.rs @@ -63,10 +63,15 @@ impl BufferedByteStream { Ok(chunk) } + /// Reads the next `\n`-delimited line, excluding the delimiter. + /// + /// `Ok(None)` is end of stream. `Ok(Some(line))` is a present line, which + /// may be empty when the stream carries a blank line; the delimiter itself + /// is never part of the returned bytes. pub(super) async fn read_next_line( &mut self, source: &mut S, - ) -> Result, VmError> { + ) -> Result>, VmError> { loop { let start = self.read_offset.min(self.buffered.len()); if start < self.buffered.len() { @@ -77,15 +82,15 @@ impl BufferedByteStream { let end = start + rel_end; let line = self.buffered[start..end].to_vec(); self.read_offset = end.saturating_add(1); - return Ok(line); + return Ok(Some(line)); } if self.eof { let line = self.buffered[start..].to_vec(); self.read_offset = self.buffered.len(); - return Ok(line); + return Ok(Some(line)); } } else if self.eof { - return Ok(Vec::new()); + return Ok(None); } self.apply_pull(source.pull_next().await?); @@ -190,7 +195,7 @@ impl InboundRequestBodyState { .await } - pub(super) async fn read_next_line(&mut self) -> Result, VmError> { + pub(super) async fn read_next_line(&mut self) -> Result>, VmError> { self.stream.read_next_line(&mut self.source).await } @@ -274,6 +279,31 @@ fn finalize_downstream_body_eof_result( } } +/// Finalizes one downstream line read. +/// +/// `Ok(None)` is end of stream and closes the downstream transport; a present +/// line does not, because an empty line is a real line rather than EOF. +fn finalize_downstream_body_line_result( + context: &SharedProxyVmContext, + inbound: &InboundRequestBodyState, + result: Result>, VmError>, +) -> Result>, VmError> { + context.note_downstream_request_body_read(); + match result { + Ok(line) => { + if line.is_none() || inbound.is_drained() { + mark_downstream_transport_closed(context); + } + Ok(line) + } + Err(err) => { + let message = err.to_string(); + mark_downstream_transport_failed(context, &message); + Err(err) + } + } +} + pub(crate) async fn read_request_body_all( context: &SharedProxyVmContext, ) -> Result, VmError> { @@ -299,13 +329,90 @@ pub(crate) async fn read_request_body_next_chunk( pub(crate) async fn read_request_body_next_line( context: &SharedProxyVmContext, -) -> Result, VmError> { +) -> Result>, VmError> { let mut inbound = context.inbound_request_body.lock().await; let result = inbound.read_next_line().await; - finalize_downstream_body_read_result(context, &inbound, result) + finalize_downstream_body_line_result(context, &inbound, result) } pub(crate) async fn request_body_eof(context: &SharedProxyVmContext) -> Result { let mut inbound = context.inbound_request_body.lock().await; finalize_downstream_body_eof_result(context, inbound.eof().await) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A source that yields one fixed chunk and then reports end of stream. + struct OneChunkSource { + chunk: Option, + } + + impl BufferedByteSource for OneChunkSource { + fn pull_next<'a>(&'a mut self) -> BufferedByteSourceFuture<'a> { + Box::pin(async move { + Ok(match self.chunk.take() { + Some(chunk) => BufferedByteStreamPull::Chunk(chunk), + None => BufferedByteStreamPull::Eof, + }) + }) + } + } + + async fn read_lines(payload: &'static str) -> Vec> { + let mut stream = BufferedByteStream::default(); + let mut source = OneChunkSource { + chunk: Some(Bytes::from_static(payload.as_bytes())), + }; + let mut lines = Vec::new(); + loop { + let line = stream + .read_next_line(&mut source) + .await + .expect("line read should succeed"); + let done = line.is_none(); + lines.push(line.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())); + if done { + return lines; + } + } + } + + #[tokio::test(flavor = "current_thread")] + async fn read_next_line_distinguishes_blank_lines_from_end_of_stream() { + let lines = read_lines("alpha\n\nbeta").await; + assert_eq!( + lines, + vec![ + Some("alpha".to_string()), + Some(String::new()), + Some("beta".to_string()), + None + ], + "a blank line is a present empty line and end of stream is None" + ); + } + + #[tokio::test(flavor = "current_thread")] + async fn read_next_line_strips_one_trailing_delimiter() { + let lines = read_lines("alpha\n").await; + assert_eq!(lines, vec![Some("alpha".to_string()), None]); + } + + #[tokio::test(flavor = "current_thread")] + async fn read_next_line_keeps_the_carriage_return_of_a_crlf_terminator() { + let lines = read_lines("a\r\nb").await; + assert_eq!( + lines, + vec![Some("a\r".to_string()), Some("b".to_string()), None], + "only the `\\n` delimiter is stripped; the `\\r` of a `\\r\\n` terminator stays in the line, matching the core reader" + ); + } + + #[tokio::test(flavor = "current_thread")] + async fn read_next_line_reports_only_end_of_stream_for_an_empty_body() { + let lines = read_lines("").await; + assert_eq!(lines, vec![None]); + } +} diff --git a/src/abi_impl/http/state/request_context.rs b/src/abi_impl/http/state/request_context.rs index fa77a38..b6fbf3b 100644 --- a/src/abi_impl/http/state/request_context.rs +++ b/src/abi_impl/http/state/request_context.rs @@ -360,6 +360,30 @@ impl LazyHttpHeaders { }) } + /// Strictly decodes one request header value as guest text. + /// + /// `Ok(None)` is an absent header, a header present with an empty value is + /// `Ok(Some(String::new()))`, and a value that is not valid UTF-8 is an + /// error instead of an empty-string sentinel. + pub(crate) fn get_text(&self, name: &str) -> Result, String> { + if let Some(parsed) = self.inner.parsed.get() { + return crate::abi_impl::http::helpers::optional_header_text(parsed.get(name)); + } + let Some(raw) = self.inner.raw.as_ref() else { + return Ok(None); + }; + let Some(header) = raw + .iter() + .find(|header| header.name.as_ref().eq_ignore_ascii_case(name.as_bytes())) + else { + return Ok(None); + }; + match std::str::from_utf8(&header.value) { + Ok(text) => Ok(Some(text.to_string())), + Err(error) => Err(format!("header value is not valid text: {error}")), + } + } + pub(crate) fn contains_name(&self, name: &str) -> bool { if let Some(parsed) = self.inner.parsed.get() { return parsed.contains_key(name); diff --git a/src/abi_impl/http/state/upstream.rs b/src/abi_impl/http/state/upstream.rs index 4eb5207..a74f466 100644 --- a/src/abi_impl/http/state/upstream.rs +++ b/src/abi_impl/http/state/upstream.rs @@ -2866,7 +2866,7 @@ pub(crate) async fn read_outbound_exchange_response_next_chunk( pub(crate) async fn read_upstream_response_next_line( context: &SharedProxyVmContext, -) -> Result, VmError> { +) -> Result>, VmError> { context.note_exchange_response_body_read(DEFAULT_UPSTREAM_EXCHANGE_HANDLE); let snapshot = ensure_upstream_response_started(context).await?; let body = snapshot.body; @@ -2878,7 +2878,7 @@ pub(crate) async fn read_upstream_response_next_line( pub(crate) async fn read_outbound_exchange_response_next_line( context: &SharedProxyVmContext, handle: i64, -) -> Result, VmError> { +) -> Result>, VmError> { context.note_exchange_response_body_read(handle); if handle == DEFAULT_UPSTREAM_EXCHANGE_HANDLE { return read_upstream_response_next_line(context).await; diff --git a/src/abi_impl/http/state/upstream_body.rs b/src/abi_impl/http/state/upstream_body.rs index edd5d3a..a9a9073 100644 --- a/src/abi_impl/http/state/upstream_body.rs +++ b/src/abi_impl/http/state/upstream_body.rs @@ -313,7 +313,7 @@ impl UpstreamResponseBodyState { .await } - pub(super) async fn read_next_line(&mut self) -> Result, VmError> { + pub(super) async fn read_next_line(&mut self) -> Result>, VmError> { self.stream.read_next_line(&mut self.source).await } diff --git a/src/abi_impl/io.rs b/src/abi_impl/io.rs index 29ea7cd..810c309 100644 --- a/src/abi_impl/io.rs +++ b/src/abi_impl/io.rs @@ -99,12 +99,15 @@ fn read_edge_virtual_handle_all(context: &ProxyVmContext, handle: i64) -> Result } } -fn read_edge_virtual_handle_line(context: &ProxyVmContext, handle: i64) -> Result { +fn read_edge_virtual_handle_line( + context: &ProxyVmContext, + handle: i64, +) -> Result, VmError> { match context.lock_edge_io().handles.get_mut(&handle) { Some(EdgeVirtualIoHandle::BufferedRead { text, offset }) => { let start = (*offset).min(text.len()); if start >= text.len() { - return Ok(String::new()); + return Ok(None); } let bytes = text.as_bytes(); let mut end = start; @@ -116,7 +119,7 @@ fn read_edge_virtual_handle_line(context: &ProxyVmContext, handle: i64) -> Resul end += 1; } *offset = end; - Ok(line) + Ok(Some(line)) } Some(EdgeVirtualIoHandle::FileWrite { .. }) => Err(VmError::HostError(format!( "edge io handle {handle} is write-only", @@ -200,28 +203,26 @@ async fn read_io_target_all( } } +/// Reads one line from a protocol-backed handle. +/// +/// `Ok(None)` is end of stream, `Ok(Some(""))` is a present blank line, and +/// the trailing `\n` is stripped by the underlying line reader. async fn read_io_target_line( context: &SharedProxyVmContext, target: EdgeProtocolIoHandle, -) -> Result { - match target { - EdgeProtocolIoHandle::Downstream => { - let line = read_request_body_next_line(context).await?; - Ok(String::from_utf8_lossy(&line).into_owned()) - } +) -> Result, VmError> { + let line = match target { + EdgeProtocolIoHandle::Downstream => read_request_body_next_line(context).await?, EdgeProtocolIoHandle::OutboundExchange(handle) if handle == default_upstream_exchange_handle() => { - Ok( - String::from_utf8_lossy(&read_upstream_response_next_line(context).await?) - .into_owned(), - ) + read_upstream_response_next_line(context).await? } - EdgeProtocolIoHandle::OutboundExchange(handle) => Ok(String::from_utf8_lossy( - &read_outbound_exchange_response_next_line(context, handle).await?, - ) - .into_owned()), - } + EdgeProtocolIoHandle::OutboundExchange(handle) => { + read_outbound_exchange_response_next_line(context, handle).await? + } + }; + Ok(line.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())) } fn write_io_target( @@ -286,6 +287,9 @@ async fn io_popen(_vm: &mut Vm, _command: String, _mode: String) -> Result read_io_target_all(&context, target).await?, EdgeIoReadSource::VirtualHandle(handle) => read_edge_virtual_handle_all(&context, handle)?, }; - Ok(CallOutcome::Return(vm::CallReturn::one(Value::string( - text, - )))) + Ok(super::http::helpers::text_result_outcome(Ok(text))) } /// Reads a single line of text from an I/O handle. +/// +/// Publishes the core `io::read_line` contract: `Ok(None)` is end of stream, +/// `Ok(Some(""))` is a present blank line, and `Ok(Some(text))` is a line with +/// the trailing `\n` stripped (a preceding `\r` is kept, exactly as the core +/// reader keeps it). A handle or transport failure is not a line value: it +/// stays a fatal host error, so the guest never sees an `Err` here. +/// `io::read_line` overrides the core builtin, so it must encode exactly the +/// contract the guest compiler resolves for that name. #[pd_edge_host_function(name = "io::read_line", scope = io)] async fn io_read_line( _vm: &mut Vm, @@ -314,9 +324,9 @@ async fn io_read_line( EdgeIoReadSource::Protocol(target) => read_io_target_line(&context, target).await?, EdgeIoReadSource::VirtualHandle(handle) => read_edge_virtual_handle_line(&context, handle)?, }; - Ok(CallOutcome::Return(vm::CallReturn::one(Value::string( - text, - )))) + // The read itself succeeded, so the guest sees the optional line value; + // a handle or transport failure above stays a fatal host error. + Ok(super::http::helpers::optional_text_outcome(Ok(text))) } /// Writes text to an I/O handle. @@ -334,12 +344,13 @@ async fn io_write( write_edge_file_path(&path, append, &text).await?; } } - Ok(CallOutcome::Return(vm::CallReturn::one(Value::Int( - text.len() as i64, - )))) + Ok(super::http::helpers::int_result_outcome(text.len() as i64)) } /// Flushes buffered output for an I/O handle. +/// +/// Publishes the core `io::flush` contract: a unit success value, and an +/// invalid handle stays a fatal host error. #[pd_edge_host_function(name = "io::flush", scope = io)] async fn io_flush( _vm: &mut Vm, @@ -358,10 +369,13 @@ async fn io_flush( Value::String(_) => return Err(requires_io_handle_error("io::flush")), _ => return Err(VmError::TypeMismatch("int")), } - Ok(CallOutcome::Return(vm::CallReturn::one(Value::Bool(true)))) + Ok(super::http::helpers::unit_result_outcome()) } /// Closes an I/O handle. +/// +/// Publishes the core `io::close` contract: a unit success value, and an +/// invalid handle stays a fatal host error. #[pd_edge_host_function(name = "io::close", scope = io)] async fn io_close( _vm: &mut Vm, @@ -371,7 +385,7 @@ async fn io_close( match target { Value::Int(handle) => { if decode_protocol_io_handle(&context, handle).is_some() { - return Ok(CallOutcome::Return(vm::CallReturn::one(Value::Bool(true)))); + return Ok(super::http::helpers::unit_result_outcome()); } if context.lock_edge_io().handles.remove(&handle).is_none() { return Err(invalid_io_handle_error(handle)); @@ -380,7 +394,7 @@ async fn io_close( Value::String(_) => return Err(requires_io_handle_error("io::close")), _ => return Err(VmError::TypeMismatch("int")), } - Ok(CallOutcome::Return(vm::CallReturn::one(Value::Bool(true)))) + Ok(super::http::helpers::unit_result_outcome()) } /// Returns whether a file system path exists. diff --git a/src/abi_impl/mod.rs b/src/abi_impl/mod.rs index 0934768..f63600d 100644 --- a/src/abi_impl/mod.rs +++ b/src/abi_impl/mod.rs @@ -11,7 +11,8 @@ use std::{ use edge_abi::FUNCTIONS as EDGE_ABI_FUNCTIONS; use tokio::sync::oneshot; use vm::{ - CallOutcome, CallReturn, HostAsyncBridge, HostOpId, HostStackFunction, Value, Vm, VmError, + CallOutcome, CallReturn, HostAsyncBridge, HostAsyncOpTerminal, HostFutureOutput, HostOpId, + HostStackFunction, Value, Vm, VmError, }; use crate::lock_metrics::{self, LockMetricKey, ProfiledMutexGuard}; @@ -231,6 +232,13 @@ impl VmAsyncOps { } } } + + /// Drops the bridge state of one operation after the VM reported a + /// terminal outcome. Dropping the pending future is the cancellation: the + /// executor never resumes it, so no work survives the operation. + fn cleanup_op(&mut self, op_id: HostOpId) { + self.pending.remove(&op_id); + } } #[derive(Default)] @@ -264,6 +272,29 @@ impl HostAsyncBridge for VmAsyncOpBridge { let mut guard = self.ops.lock_ops(); guard.poll_op(op_id, cx) } + + /// Every edge host operation is scheduled through [`VmAsyncOps`] and + /// polled by [`poll_op`](Self::poll_op); the bridge never accepts a + /// VM-submitted future, so there is nothing to poll here. + fn poll_submitted_op( + &mut self, + op_id: HostOpId, + _cx: &mut Context<'_>, + ) -> Poll> { + Poll::Ready(Err(VmError::HostError(format!( + "edge async host bridge owns no submitted future for op {op_id}", + )))) + } + + fn cleanup_op( + &mut self, + op_id: HostOpId, + _terminal: HostAsyncOpTerminal, + ) -> Result<(), VmError> { + let mut guard = self.ops.lock_ops(); + guard.cleanup_op(op_id); + Ok(()) + } } pub fn new_shared_vm_async_ops() -> SharedVmAsyncOps { @@ -884,7 +915,10 @@ mod tests { #[cfg(feature = "http")] struct TestNoopWake; + // The store drives this test waker through an `Arc`, so it cannot be + // replaced by `Waker::noop()` without changing the helper's ownership. #[cfg(feature = "http")] + #[allow(clippy::manual_noop_waker)] impl Wake for TestNoopWake { fn wake(self: Arc) {} } diff --git a/src/abi_impl/mqtt/model.rs b/src/abi_impl/mqtt/model.rs index 3985eb3..c4a1705 100644 --- a/src/abi_impl/mqtt/model.rs +++ b/src/abi_impl/mqtt/model.rs @@ -110,7 +110,19 @@ pub(crate) enum MqttEvent { } impl MqttEvent { + /// Encodes the event as the closed `MqttEvent` record. + /// + /// Every published member is always present. A member the active variant + /// does not carry is the canonical guest `Option::None` carrier, so a + /// guest distinguishes "this variant has no topic" from "the topic is the + /// empty string" without relying on a missing map entry. pub(crate) fn into_value(self) -> Value { + fn some(value: Value) -> Value { + vm::option::some_carrier(value) + } + fn none() -> Value { + vm::option::none_carrier() + } match self { Self::Publish { topic, @@ -120,31 +132,45 @@ impl MqttEvent { dup, } => Value::map(vec![ (Value::string("kind"), Value::string("publish")), - (Value::string("topic"), Value::string(topic)), + (Value::string("topic"), some(Value::string(topic))), ( Value::string("payload_text"), - Value::string(String::from_utf8_lossy(&payload).into_owned()), + some(Value::string( + String::from_utf8_lossy(&payload).into_owned(), + )), ), ( Value::string("payload_base64"), - Value::string(STANDARD.encode(payload)), + some(Value::string(STANDARD.encode(payload))), ), - (Value::string("qos"), Value::Int(i64::from(qos))), - (Value::string("retain"), Value::Bool(retain)), - (Value::string("dup"), Value::Bool(dup)), - ]), - Self::Closed { reason } => Value::map(vec![ - (Value::string("kind"), Value::string("closed")), - (Value::string("reason"), Value::string(reason)), - ]), - Self::Failed { reason } => Value::map(vec![ - (Value::string("kind"), Value::string("failed")), - (Value::string("reason"), Value::string(reason)), + (Value::string("qos"), some(Value::Int(i64::from(qos)))), + (Value::string("retain"), some(Value::Bool(retain))), + (Value::string("dup"), some(Value::Bool(dup))), + (Value::string("reason"), none()), ]), + Self::Closed { reason } => closed_event_value("closed", reason), + Self::Failed { reason } => closed_event_value("failed", reason), } } } +/// Encodes one reason-only event (`closed` | `failed`) as the closed record. +fn closed_event_value(kind: &str, reason: String) -> Value { + Value::map(vec![ + (Value::string("kind"), Value::string(kind)), + (Value::string("topic"), vm::option::none_carrier()), + (Value::string("payload_text"), vm::option::none_carrier()), + (Value::string("payload_base64"), vm::option::none_carrier()), + (Value::string("qos"), vm::option::none_carrier()), + (Value::string("retain"), vm::option::none_carrier()), + (Value::string("dup"), vm::option::none_carrier()), + ( + Value::string("reason"), + vm::option::some_carrier(Value::string(reason)), + ), + ]) +} + #[derive(Clone, Debug)] pub(crate) struct MqttConnectConfig { pub(crate) scheme: MqttScheme, @@ -393,3 +419,101 @@ impl MqttConnectionState { self.ping_response_pending = false; } } + +#[cfg(test)] +mod tests { + use super::*; + + fn field<'a>(value: &'a Value, name: &str) -> &'a Value { + let Value::Map(entries) = value else { + panic!("MqttEvent must be a map, got {value:?}"); + }; + entries + .get(&Value::string(name)) + .unwrap_or_else(|| panic!("MqttEvent must always carry '{name}'")) + } + + fn optional_text(value: &Value) -> Option { + let (some, payload) = vm::option::payload(value) + .unwrap_or_else(|error| panic!("'{value:?}' must be a canonical Option: {error}")); + if !some { + return None; + } + match payload { + Some(Value::String(text)) => Some(text.to_string()), + other => panic!("Option::Some payload must be text, got {other:?}"), + } + } + + #[test] + fn publish_event_carries_publish_members_and_no_reason() { + let value = MqttEvent::Publish { + topic: "pd-edge/topic".to_string(), + payload: b"hello".to_vec(), + qos: 1, + retain: true, + dup: false, + } + .into_value(); + + assert_eq!( + field(&value, "kind"), + &Value::string("publish"), + "the discriminator is always present" + ); + assert_eq!( + optional_text(field(&value, "topic")), + Some("pd-edge/topic".to_string()) + ); + assert_eq!( + optional_text(field(&value, "payload_text")), + Some("hello".to_string()) + ); + assert!(optional_text(field(&value, "payload_base64")).is_some()); + assert_eq!( + field(&value, "qos"), + &vm::option::some_carrier(Value::Int(1)) + ); + assert_eq!( + field(&value, "retain"), + &vm::option::some_carrier(Value::Bool(true)) + ); + assert_eq!( + field(&value, "dup"), + &vm::option::some_carrier(Value::Bool(false)) + ); + assert_eq!( + field(&value, "reason"), + &vm::option::none_carrier(), + "a publish event carries no reason member" + ); + } + + #[test] + fn closed_event_carries_only_its_reason_member() { + let value = MqttEvent::Closed { + reason: "broker closed".to_string(), + } + .into_value(); + + assert_eq!(field(&value, "kind"), &Value::string("closed")); + for absent in [ + "topic", + "payload_text", + "payload_base64", + "qos", + "retain", + "dup", + ] { + assert_eq!( + field(&value, absent), + &vm::option::none_carrier(), + "'{absent}' is absent on a closed event" + ); + } + assert_eq!( + optional_text(field(&value, "reason")), + Some("broker closed".to_string()) + ); + } +} diff --git a/src/compile.rs b/src/compile.rs index bdc8a27..cc3558f 100644 --- a/src/compile.rs +++ b/src/compile.rs @@ -22,7 +22,7 @@ fn with_edge_stdlib_overrides(mut options: CompileSourceFileOptions) -> CompileS options } -/// Compile options used by [`compile_edge_source_file`]: the in-tree ABI25 +/// Compile options used by [`compile_edge_source_file`]: the in-tree ABI26 /// catalog plus the embedded edge stdlib overlays. pub fn edge_compile_options() -> CompileSourceFileOptions { with_edge_stdlib_overrides(CompileSourceFileOptions::new()) diff --git a/src/runtime/http_plane/proxy_path.rs b/src/runtime/http_plane/proxy_path.rs index c45bf64..2fb8b36 100644 --- a/src/runtime/http_plane/proxy_path.rs +++ b/src/runtime/http_plane/proxy_path.rs @@ -1283,6 +1283,9 @@ fn data_plane_vm_execution_error_response( } } +// The HTTP response error variant is the caller-visible value; boxing it would +// change every call site for a lint that this boundary cannot satisfy. +#[allow(clippy::result_large_err)] pub(super) async fn run_prepared_data_plane_http_request_context( state: SharedState, program: Arc, diff --git a/stdlib/rss/http/upstream/response.rss b/stdlib/rss/http/upstream/response.rss index fcc1578..8d68496 100644 --- a/stdlib/rss/http/upstream/response.rss +++ b/stdlib/rss/http/upstream/response.rss @@ -10,13 +10,14 @@ pub fn get_status() -> int { http::exchange::get_status(upstream_response_default_exchange()) } -pub fn get_header(name: string) -> string { +pub fn get_header(name: string) -> Result, string> { http::exchange::get_header(upstream_response_default_exchange(), name) } -pub fn get_headers() -> map { - http::exchange::get_headers(upstream_response_default_exchange()) -} +// The open header map (`http::exchange::get_headers`) stays a deliberate +// dynamic boundary in ABI 26, and the frozen compiler does not admit a dynamic +// host output as a guest value, so this wrapper publishes no header-map getter. +// Guests that need one header use the typed `get_header` contract above. pub fn get_body() -> string { http::exchange::get_body(upstream_response_default_exchange()) @@ -30,7 +31,11 @@ pub fn next_chunk(max_bytes: int) -> string { http::exchange::body::next_chunk(upstream_response_default_exchange(), max_bytes) } -pub fn next_line() -> string { +/// Reads the next line of the default exchange response. +/// +/// `Ok(None)` is end of stream, `Ok(Some(""))` is a present blank line (the +/// SSE event boundary), and the trailing `\n` is not part of the value. +pub fn next_line() -> Result, string> { io::read_line(upstream_response_default_exchange()) } @@ -38,10 +43,14 @@ pub fn eof() -> bool { http::exchange::body::eof(upstream_response_default_exchange()) } -pub fn read_all() -> string { +/// Reads the whole default exchange response body. +/// +/// The text is the guest success value; a read failure is the guest error. +pub fn read_all() -> Result { io::read_all(upstream_response_default_exchange()) } -pub fn read_line() -> string { +/// Reads the next line of the default exchange response (alias of `next_line`). +pub fn read_line() -> Result, string> { io::read_line(upstream_response_default_exchange()) } diff --git a/tests/compile_tests.rs b/tests/compile_tests.rs index e695cfb..7e1e75c 100644 --- a/tests/compile_tests.rs +++ b/tests/compile_tests.rs @@ -434,8 +434,8 @@ fn assert_unresolved_protocol_imports_are_not_catalog_backed( ); } -fn assert_every_import_is_abi25_catalog_backed(compiled: &CompiledProgram, label: &str) { - assert_eq!(ABI_VERSION, 25, "{label}: published ABI must stay at 25"); +fn assert_every_import_is_abi26_catalog_backed(compiled: &CompiledProgram, label: &str) { + assert_eq!(ABI_VERSION, 26, "{label}: published ABI must stay at 26"); let imports = &compiled.program.imports; let schemas = compiled.program.host_import_schemas(); assert!( @@ -451,21 +451,21 @@ fn assert_every_import_is_abi25_catalog_backed(compiled: &CompiledProgram, label for (import, schema) in imports.iter().zip(schemas) { let schema = schema.as_ref().unwrap_or_else(|| { panic!( - "{label}: {} must have Some(schema) from the ABI25 catalog", + "{label}: {} must have Some(schema) from the ABI26 catalog", import.name ) }); assert_eq!(schema.name, import.name, "{label}"); assert!( function_by_name(&import.name).is_some(), - "{label}: {} must resolve through exact ABI25 catalog lookup", + "{label}: {} must resolve through exact ABI26 catalog lookup", import.name ); match fingerprint { None => fingerprint = Some(schema.fingerprint), Some(expected) => assert_eq!( schema.fingerprint, expected, - "{label}: {} fingerprint drifted from the ABI25 catalog", + "{label}: {} fingerprint drifted from the ABI26 catalog", import.name ), } @@ -485,12 +485,12 @@ fn schema_for_import<'a>(compiled: &'a CompiledProgram, name: &str) -> &'a vm::H .host_import_schemas() .get(index) .and_then(Option::as_ref) - .unwrap_or_else(|| panic!("{name} must carry Some(schema) from the ABI25 catalog")) + .unwrap_or_else(|| panic!("{name} must carry Some(schema) from the ABI26 catalog")) } #[test] -fn published_edge_abi_is_version_25() { - assert_eq!(ABI_VERSION, 25); +fn published_edge_abi_is_version_26() { + assert_eq!(ABI_VERSION, 26); } #[cfg(all(feature = "http", not(feature = "mqtt"), not(feature = "webrtc")))] @@ -547,7 +547,7 @@ fn mqtt_feature_publishes_named_mqtt_event_and_runtime_module() { assert_eq!(function.name, "mqtt::connection::read_event"); let compiled = compile_example("examples/mqtt/upstream/sample_mqtt_publish_program.rss"); - assert_every_import_is_abi25_catalog_backed(&compiled, "mqtt sample"); + assert_every_import_is_abi26_catalog_backed(&compiled, "mqtt sample"); let schema = schema_for_import(&compiled, "mqtt::connection::read_event"); match &schema.return_type { @@ -582,7 +582,7 @@ fn webrtc_imports_are_not_catalog_backed_without_webrtc_feature() { #[cfg(all(feature = "http", feature = "tls", feature = "websocket"))] #[test] -fn representative_sources_carry_abi25_catalog_schemas() { +fn representative_sources_carry_abi26_catalog_schemas() { let cases = [ "examples/http/proxy/sample_proxy_program.rss", "examples/transport/tls/sample_transport_tls_handshake_program.rss", @@ -592,7 +592,7 @@ fn representative_sources_carry_abi25_catalog_schemas() { ]; for relative in cases { let compiled = compile_example(relative); - assert_every_import_is_abi25_catalog_backed(&compiled, relative); + assert_every_import_is_abi26_catalog_backed(&compiled, relative); } let udp = compile_inline( @@ -602,7 +602,7 @@ fn representative_sources_carry_abi25_catalog_schemas() { udp::socket::new(); "#, ); - assert_every_import_is_abi25_catalog_backed(&udp, "udp inline"); + assert_every_import_is_abi26_catalog_backed(&udp, "udp inline"); assert!( udp.program .imports diff --git a/tests/dependency_pin_tests.rs b/tests/dependency_pin_tests.rs index e580a6e..b89372d 100644 --- a/tests/dependency_pin_tests.rs +++ b/tests/dependency_pin_tests.rs @@ -16,7 +16,7 @@ use std::process::Command; use serde::Deserialize; /// The frozen core candidate this workspace migrates against. -const FROZEN_CORE_REV: &str = "b1d6cffede77f49410bf63525f30b9a46b02dc01"; +const FROZEN_CORE_REV: &str = "2f433edab3f1907e8cb060e901357d7e2af016ce"; const FROZEN_CORE_URL: &str = "https://github.com/rustscript-lang/rustscript.git"; fn manifest_dir() -> PathBuf { @@ -290,6 +290,10 @@ fn family_registry_offenders(metadata: &CargoMetadata) -> Vec { .collect() } +/// Features the workspace runtime build resolves for its own `pd-vm` pin. +/// +/// The pin tests above require every core git dependency to carry the frozen +/// revision, so exactly one `pd-vm` copy can appear in the resolved graph. fn pd_vm_enabled_features(metadata: &CargoMetadata) -> BTreeSet { let package = metadata .packages @@ -308,7 +312,7 @@ fn pd_vm_enabled_features(metadata: &CargoMetadata) -> BTreeSet { .collect() } -fn in_tree_abi25_present(metadata: &CargoMetadata) -> bool { +fn in_tree_abi26_present(metadata: &CargoMetadata) -> bool { metadata.packages.iter().any(|package| { package.name == "pd-edge-abi" && package.version == "0.1.0" @@ -353,7 +357,7 @@ fn pd_edge_features_never_enable_vm_edge_abi() { .expect("the http feature must remain declared"); assert!( http.iter().any(|item| item == "edge_abi/http"), - "http must keep enabling the in-tree ABI25 http surface: {http:?}" + "http must keep enabling the in-tree ABI26 http surface: {http:?}" ); assert!( !http.iter().any(|item| enables_vm_edge_abi(item)), @@ -362,7 +366,7 @@ fn pd_edge_features_never_enable_vm_edge_abi() { } #[test] -fn feature_matrix_metadata_keeps_git_abi25_and_drops_registry_family() { +fn feature_matrix_metadata_keeps_git_abi26_and_drops_registry_family() { for (label, extra) in feature_matrices() { let metadata = cargo_metadata(extra); let offenders = family_registry_offenders(&metadata); @@ -380,8 +384,120 @@ fn feature_matrix_metadata_keeps_git_abi25_and_drops_registry_family() { "{label} cargo metadata enabled pd-vm edge-abi: {features:?}" ); assert!( - in_tree_abi25_present(&metadata), - "{label} cargo metadata must keep the in-tree ABI25 pd-edge-abi crate" + in_tree_abi26_present(&metadata), + "{label} cargo metadata must keep the in-tree ABI26 pd-edge-abi crate" ); } } + +/// Features the native compiler must never see on `pd-vm`; they are the same +/// ones IronRust's `scripts/check-native-compiler.ps1` rejects. +const FORBIDDEN_VM_FEATURES: &[&str] = &[ + "runtime", + "async", + "http-client", + "sqlite", + "cli", + "cranelift-jit", + "edge-abi", +]; + +/// Crates whose presence means the compiler-only graph picked up the edge +/// runtime or its HTTP/TLS stack. +fn is_runtime_package(name: &str) -> bool { + matches!( + name, + "pd-edge" + | "pd-edge-host-function" + | "tokio" + | "hyper" + | "hyper-util" + | "axum" + | "rustls" + | "tokio-rustls" + | "rusqlite" + | "libsqlite3-sys" + | "reqwest" + | "mimalloc" + | "aws-lc-rs" + ) || name.starts_with("cranelift-") +} + +/// The ABI surface is what a compiler-only consumer links. It must stay +/// runtime-free: let `pd-vm` come in through feature unification and the +/// compiler-only graph silently gains the whole runtime, which is exactly how +/// IronRust's `Check compiler-only dependencies` step went red. +#[test] +fn compiler_only_surface_never_enables_pd_vm_runtime() { + let abi_manifest = manifest_dir().join("pd-edge-abi/Cargo.toml"); + let manifest = read(&abi_manifest); + let line = dependency_line(&manifest, "vm"); + assert!( + line.contains("default-features = false"), + "the pd-edge-abi `vm` dependency must stay feature-minimal: {line}" + ); + let requested_features = line + .split_once("features = [") + .map(|(_, rest)| rest.split(']').next().unwrap_or_default()) + .unwrap_or_default(); + assert!( + requested_features.trim().is_empty(), + "the pd-edge-abi `vm` dependency must not request any pd-vm feature: {line}" + ); + + let output = Command::new(env!("CARGO")) + .arg("tree") + .arg("--offline") + .arg("--locked") + .arg("--manifest-path") + .arg(&abi_manifest) + .args([ + "--edges", + "normal,build", + "--no-default-features", + "--features", + "console,http,tls,websocket", + "--prefix", + "none", + "--format", + "{p} features={f}", + ]) + .current_dir(manifest_dir()) + .output() + .unwrap_or_else(|error| panic!("failed to run cargo tree: {error}")); + assert!( + output.status.success(), + "cargo tree for the compiler-only ABI surface failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + + let tree = String::from_utf8(output.stdout).expect("cargo tree output must be utf-8"); + let mut vm_lines = 0; + for line in tree.lines() { + let Some(name) = line.split_whitespace().next() else { + continue; + }; + if name == "pd-vm" { + vm_lines += 1; + let features = line + .split_once("features=") + .map(|(_, features)| features.trim_end_matches(" (*)")) + .unwrap_or_default(); + for feature in features.split(',') { + assert!( + !FORBIDDEN_VM_FEATURES.contains(&feature), + "the compiler-only ABI surface enables pd-vm/{feature}: {line}" + ); + } + } else { + assert!( + !is_runtime_package(name), + "runtime dependency in the compiler-only ABI surface: {line}" + ); + } + } + assert!( + vm_lines > 0, + "cargo tree must resolve pd-vm for the compiler-only ABI surface" + ); +} diff --git a/tests/proxy_tests/debug.rs b/tests/proxy_tests/debug.rs index 5e8d4de..e704b78 100644 --- a/tests/proxy_tests/debug.rs +++ b/tests/proxy_tests/debug.rs @@ -91,7 +91,7 @@ async fn debug_attached_request_does_not_block_non_debug_requests() { } } - timeout(Duration::from_secs(10), async { + timeout(Duration::from_secs(60), async { let (data_addr, admin_addr, data_handle, admin_handle) = spawn_proxy(1024 * 1024).await; let _abort_proxy = AbortProxyOnDrop { data: data_handle, @@ -131,7 +131,7 @@ async fn debug_attached_request_does_not_block_non_debug_requests() { tokio::time::sleep(Duration::from_millis(150)).await; let non_debug = timeout( - Duration::from_secs(2), + Duration::from_secs(15), client.get(format!("http://{data_addr}/normal")).send(), ) .await @@ -142,7 +142,7 @@ async fn debug_attached_request_does_not_block_non_debug_requests() { send_pdb_continue(debug_addr).await; - let (status, body) = timeout(Duration::from_secs(2), debug_request.join()) + let (status, body) = timeout(Duration::from_secs(15), debug_request.join()) .await .expect("debug request timed out") .expect("debug task should join"); @@ -156,7 +156,7 @@ async fn debug_attached_request_does_not_block_non_debug_requests() { #[tokio::test] async fn debug_session_is_removed_after_debugger_disconnects() { - timeout(Duration::from_secs(10), async { + timeout(Duration::from_secs(60), async { let (data_addr, admin_addr, data_handle, admin_handle) = spawn_proxy(1024 * 1024).await; let client = reqwest::Client::new(); @@ -198,7 +198,7 @@ async fn debug_session_is_removed_after_debugger_disconnects() { .await .expect("debugger helper should not panic"); - let (status, body) = timeout(Duration::from_secs(2), debug_request) + let (status, body) = timeout(Duration::from_secs(15), debug_request) .await .expect("debug request timed out") .expect("debug task should join"); diff --git a/tests/proxy_tests/http.rs b/tests/proxy_tests/http.rs index 7bf724e..a23e431 100644 --- a/tests/proxy_tests/http.rs +++ b/tests/proxy_tests/http.rs @@ -582,7 +582,14 @@ async fn tiny_language_can_enforce_simple_rate_limit() { use http; use rate_limit; - if rate_limit::allow(http::request::get_header("x-client-id"), 2, 60) { + let client_id = match http::request::get_header("x-client-id") { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", + }; + if rate_limit::allow(client_id, 2, 60) { http::response::set_header("x-vm", "allowed"); http::response::set_body("ok"); } else { @@ -673,7 +680,13 @@ async fn http_prefixed_host_abi_can_rewrite_request_and_short_circuit() { use http; use rate_limit; - let client_id = http::request::get_header("x-client-id"); + let client_id = match http::request::get_header("x-client-id") {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", + }}; if rate_limit::allow(client_id, 1, 60) {{ let upstream = http::exchange::default_upstream(); http::exchange::set_path(upstream, "/rewritten"); @@ -2594,13 +2607,27 @@ async fn direct_vm_can_read_upstream_response_line_by_line_via_io_handle_api() { let downstream = tcp::stream::downstream(); while !http::exchange::body::eof(upstream) {{ - let line = io::read_line(upstream); + let line = io_line_text(upstream); if line == "" {{ tcp::stream::write(downstream, "\n"); }} else {{ tcp::stream::write(downstream, line + "\n"); }} }} + + // `io::read_line` is the core fallible optional-text contract: EOF is + // `None`, a blank line is `Some("")`, and a failure is the + // guest error. The loop tests `eof`, so both keep "" here. + fn io_line_text(handle: int) -> string {{ + let value: Result, string> = io::read_line(handle); + match value {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", + }} + }} "#, upstream_port = upstream_addr.port() ); @@ -4595,3 +4622,226 @@ async fn http_proxy_https_listener_explicit_handoff_exposes_downstream_mtls_and_ https_handle.abort(); admin_handle.abort(); } + +/// End-to-end coverage for `http::exchange::get_header` as the published +/// `Result, string>` contract: a header the upstream response +/// carries is `Ok(Some(text))` and a header it does not carry is `Ok(None)`. +#[tokio::test] +async fn exchange_get_header_reports_present_and_absent_members() { + let upstream_app = Router::new().fallback(any(|request: Request| async move { + let mut response = Response::new(Body::from("exchange-header-body")); + if request.uri().path() == "/present" { + response + .headers_mut() + .insert("x-present", HeaderValue::from_static("v1")); + response + .headers_mut() + .insert("x-empty", HeaderValue::from_static("")); + } + response + })); + let (upstream_addr, upstream_handle) = spawn_server(upstream_app).await; + let (data_addr, admin_addr, data_handle, admin_handle) = spawn_proxy(1024 * 1024).await; + let client = reqwest::Client::new(); + let source = format!( + r#" + use http; + + let upstream = http::exchange::default_upstream(); + http::exchange::set_target(upstream, "127.0.0.1", {upstream_port}); + http::exchange::set_path(upstream, http::request::get_path()); + http::response::set_status(http::exchange::get_status(upstream)); + + let present = match http::exchange::get_header(upstream, "x-present") {{ + Result::Ok(member) => match member {{ + Some(text) => "some:" + text, + None => "none", + }}, + Result::Err(error) => "error:" + error, + }}; + let empty = match http::exchange::get_header(upstream, "x-empty") {{ + Result::Ok(member) => match member {{ + Some(text) => "some:" + text, + None => "none", + }}, + Result::Err(error) => "error:" + error, + }}; + let absent = match http::exchange::get_header(upstream, "x-absent") {{ + Result::Ok(member) => match member {{ + Some(text) => "some:" + text, + None => "none", + }}, + Result::Err(error) => "error:" + error, + }}; + + http::response::set_header("x-exchange-present", present); + http::response::set_header("x-exchange-empty", empty); + http::response::set_header("x-exchange-absent", absent); + http::response::set_body(http::exchange::get_body(upstream)); + "#, + upstream_port = upstream_addr.port() + ); + let compiled = compile_source(&source).expect("exchange header source should compile"); + let upload = upload_program(&client, admin_addr, &compiled.program).await; + assert_eq!(upload.status(), StatusCode::NO_CONTENT); + + let present = client + .get(format!("http://{data_addr}/present")) + .send() + .await + .expect("present request should complete"); + assert_eq!(present.status(), StatusCode::OK); + let present_headers = present.headers().clone(); + let present_body = present.text().await.expect("present body should read"); + + let absent = client + .get(format!("http://{data_addr}/absent")) + .send() + .await + .expect("absent request should complete"); + assert_eq!(absent.status(), StatusCode::OK); + let absent_headers = absent.headers().clone(); + let absent_body = absent.text().await.expect("absent body should read"); + + assert_eq!( + present_headers + .get("x-exchange-present") + .and_then(|value| value.to_str().ok()), + Some("some:v1") + ); + assert_eq!( + present_headers + .get("x-exchange-empty") + .and_then(|value| value.to_str().ok()), + Some("some:") + ); + assert_eq!( + present_headers + .get("x-exchange-absent") + .and_then(|value| value.to_str().ok()), + Some("none") + ); + assert_eq!(present_body, "exchange-header-body"); + + assert_eq!( + absent_headers + .get("x-exchange-present") + .and_then(|value| value.to_str().ok()), + Some("none") + ); + assert_eq!( + absent_headers + .get("x-exchange-absent") + .and_then(|value| value.to_str().ok()), + Some("none") + ); + assert_eq!(absent_body, "exchange-header-body"); + + upstream_handle.abort(); + data_handle.abort(); + admin_handle.abort(); +} + +/// Serves one chunked response whose trailer block carries `x-checksum`. +async fn spawn_trailer_upstream() -> (SocketAddr, JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind(loopback_addr(0)) + .await + .expect("trailer listener should bind"); + let addr = listener.local_addr().expect("trailer listener addr"); + let handle = tokio::spawn(async move { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + loop { + let (mut stream, _) = listener.accept().await.expect("trailer accept"); + tokio::spawn(async move { + let mut buffer = [0u8; 4096]; + let _ = stream.read(&mut buffer).await; + stream + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n", + ) + .await + .expect("trailer response head should write"); + // 13 bytes of data ("trailer-body!") then the terminating + // chunk followed by the trailing header block. + stream + .write_all(b"D\r\ntrailer-body!\r\n0\r\nX-Checksum: abc123\r\n\r\n") + .await + .expect("trailer body should write"); + let _ = stream.shutdown().await; + }); + } + }); + (addr, handle) +} + +/// End-to-end coverage for `http::response::get_trailer` when the upstream +/// response ends with a trailer: the present value is `Ok(Some(text))`. +#[tokio::test] +async fn response_get_trailer_reports_a_present_upstream_trailer() { + let (upstream_addr, upstream_handle) = spawn_trailer_upstream().await; + let (data_addr, admin_addr, data_handle, admin_handle) = spawn_proxy(1024 * 1024).await; + let client = reqwest::Client::new(); + let source = format!( + r#" + use http; + + let upstream = http::exchange::default_upstream(); + http::exchange::set_target(upstream, "127.0.0.1", {upstream_port}); + http::exchange::set_path(upstream, "/trailers"); + let status = http::exchange::get_status(upstream); + + let checksum = match http::response::get_trailer("x-checksum") {{ + Result::Ok(member) => match member {{ + Some(text) => text, + None => "none", + }}, + Result::Err(error) => "error:" + error, + }}; + let absent_trailer = match http::response::get_trailer("x-not-sent") {{ + Result::Ok(member) => match member {{ + Some(text) => text, + None => "none", + }}, + Result::Err(error) => "error:" + error, + }}; + + http::response::set_status(status); + http::response::set_header("x-trailer-checksum", checksum); + http::response::set_header("x-trailer-absent", absent_trailer); + http::response::set_body(http::exchange::get_body(upstream)); + "#, + upstream_port = upstream_addr.port() + ); + let compiled = compile_source(&source).expect("trailer source should compile"); + let upload = upload_program(&client, admin_addr, &compiled.program).await; + assert_eq!(upload.status(), StatusCode::NO_CONTENT); + + let response = client + .get(format!("http://{data_addr}/trailers")) + .send() + .await + .expect("trailer request should complete"); + let status = response.status(); + let headers = response.headers().clone(); + let body = response.text().await.expect("trailer body should read"); + + assert_eq!(status, StatusCode::OK); + assert_eq!( + headers + .get("x-trailer-checksum") + .and_then(|value| value.to_str().ok()), + Some("abc123") + ); + assert_eq!( + headers + .get("x-trailer-absent") + .and_then(|value| value.to_str().ok()), + Some("none") + ); + assert_eq!(body, "trailer-body!"); + + upstream_handle.abort(); + data_handle.abort(); + admin_handle.abort(); +} diff --git a/tests/proxy_tests/io.rs b/tests/proxy_tests/io.rs index 213010b..0e9d31f 100644 --- a/tests/proxy_tests/io.rs +++ b/tests/proxy_tests/io.rs @@ -85,8 +85,32 @@ async fn io_protocol_handles_accept_direct_integer_arguments() { http::exchange::set_method(upstream, "POST"); io::write(1, "direct-int-body"); http::response::set_status(http::exchange::get_status(upstream)); - http::response::set_header("x-first-line", io::read_line(1)); - http::response::set_body(io::read_all(1)); + http::response::set_header("x-first-line", io_line_text(1)); + http::response::set_body(io_read_all_text(1)); + + // `io::read_all` reports a read failure as the guest error, so the test + // collapses it to "" exactly as the previous bare string did. + fn io_read_all_text(handle: int) -> string {{ + let value: Result = io::read_all(handle); + match value {{ + Result::Ok(text) => text, + Result::Err(error) => "", + }} + }} + + // `io::read_line` is the core fallible optional-text contract: EOF is + // `None`, a blank line is `Some("")`, and a failure is the + // guest error. This test needs the header text, so both keep "". + fn io_line_text(handle: int) -> string {{ + let value: Result, string> = io::read_line(handle); + match value {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", + }} + }} "#, upstream_host = upstream_addr.ip(), upstream_port = upstream_addr.port() @@ -140,8 +164,29 @@ async fn io_protocol_handles_accept_tls_session_handles_for_https_exchange() { io::write(session, "tls-direct-body"); http::response::set_status(http::exchange::get_status(upstream)); - http::response::set_header("x-first-line", io::read_line(session)); - http::response::set_body(io::read_all(session)); + http::response::set_header("x-first-line", io_line_text(session)); + http::response::set_body(io_read_all_text(session)); + + // `io::read_all` reports a read failure as the guest error. + fn io_read_all_text(handle: int) -> string {{ + let value: Result = io::read_all(handle); + match value {{ + Result::Ok(text) => text, + Result::Err(error) => "", + }} + }} + + // `io::read_line` is the core fallible optional-text contract. + fn io_line_text(handle: int) -> string {{ + let value: Result, string> = io::read_line(handle); + match value {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", + }} + }} "#, upstream_addr.port() ); @@ -193,8 +238,29 @@ async fn direct_vm_io_protocol_handles_accept_direct_integer_arguments() { http::exchange::set_path(upstream, "/literal"); http::exchange::set_method(upstream, "POST"); io::write(1, "direct-int-body"); - http::response::set_header("x-first-line", io::read_line(1)); - http::response::set_body(io::read_all(1)); + http::response::set_header("x-first-line", io_line_text(1)); + http::response::set_body(io_read_all_text(1)); + + // `io::read_all` reports a read failure as the guest error. + fn io_read_all_text(handle: int) -> string {{ + let value: Result = io::read_all(handle); + match value {{ + Result::Ok(text) => text, + Result::Err(error) => "", + }} + }} + + // `io::read_line` is the core fallible optional-text contract. + fn io_line_text(handle: int) -> string {{ + let value: Result, string> = io::read_line(handle); + match value {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", + }} + }} "#, upstream_host = upstream_addr.ip(), upstream_port = upstream_addr.port() diff --git a/tests/proxy_tests/transport.rs b/tests/proxy_tests/transport.rs index 502d580..d005252 100644 --- a/tests/proxy_tests/transport.rs +++ b/tests/proxy_tests/transport.rs @@ -948,7 +948,13 @@ async fn proxy_pipe_forwards_dynamic_exchange_response_via_proxy_stream_handle() http::response::set_header("x-proxy-status", status); http::response::set_status(http::exchange::get_status(exchange)); - let content_type = http::exchange::get_header(exchange, "content-type"); + let content_type = match http::exchange::get_header(exchange, "content-type") {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", + }}; if content_type != "" {{ http::response::set_header("content-type", content_type); }} diff --git a/tests/proxy_tests/websocket.rs b/tests/proxy_tests/websocket.rs index 549a7d6..9f22bd2 100644 --- a/tests/proxy_tests/websocket.rs +++ b/tests/proxy_tests/websocket.rs @@ -358,7 +358,13 @@ async fn downstream_websocket_binary_tunnel_upgrades_and_relays_frames() { let upstream = websocket::connection::new(); websocket::connection::set_target(upstream, "{upstream_host}", {upstream_port}); websocket::connection::set_path(upstream, "/binary"); - let protocols = http::request::get_header("sec-websocket-protocol"); + let protocols = match http::request::get_header("sec-websocket-protocol") {{ + Result::Ok(present) => match present {{ + Some(text) => text, + None => "", + }}, + Result::Err(error) => "", + }}; if protocols != "" {{ websocket::connection::set_subprotocols(upstream, protocols); }} diff --git a/tests/rss_fixture_compile_tests.rs b/tests/rss_fixture_compile_tests.rs index 8d090eb..c4d12c5 100644 --- a/tests/rss_fixture_compile_tests.rs +++ b/tests/rss_fixture_compile_tests.rs @@ -141,11 +141,11 @@ fn every_supported_flavor_example_compiles() { let flavors = [ ( "examples/http/proxy/sample_proxy_program.js", - SourceFlavor::JavaScript, + SourceFlavor::Plugin(vm::FrontendId::new("javascript")), ), ( "examples/http/proxy/sample_proxy_program.lua", - SourceFlavor::Lua, + SourceFlavor::Plugin(vm::FrontendId::new("lua")), ), ]; let mut skipped = Vec::new();