diff --git a/README.md b/README.md index c0b40e678b..f2b2bc701c 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ npx skills add iii-hq/iii --all | [`worktree`](worktree/) | Rust | Git worktree lifecycle for parallel agents — `worktree::*` mint, claim, and track isolated worktrees per repo, emit six lifecycle trigger types, and land branches back through a per-repo FIFO queue (rebase, test gate, ff-only merge). | | [`github`](github/) | Rust | GitHub CLI (`gh`) as an iii worker — typed `github::pr/issue/repo/run/workflow/release/search::*` functions plus `github::exec` argv passthrough and `github::api` for any GitHub REST endpoint. | | [`sandbox-code-runner`](sandbox-code-runner/) | Rust | Run Node.js and Python in iii-sandbox microVMs — run code, register bus functions from working source, and tear down runtimes on demand. | +| [`code-runner`](code-runner/) | Rust | Run untrusted Node.js and Python in-process — V8 isolates and CPython-on-WebAssembly behind one run/register_function/teardown API, with no microVM and no /dev/kvm. Code gets a global `iii` and a private scratch directory. | | [`openwiki`](openwiki/) | Node | Source-grounded markdown wiki for any git repository — a lead agent plans the index and writer sub-agents store cited pages via `openwiki::write-page`, with router and heuristic fallback tiers, incremental refresh from git diffs on a per-wiki cron schedule, and a browser UI + JSON API under `/openwiki`. | | [`pdf`](pdf/) | Rust | Read PDFs locally — `pdf::classify` routes text-based versus scanned in tens of milliseconds and names the pages that still need OCR, `pdf::to-markdown` converts with headings, lists and tables intact, and `pdf::extract-items` / `::extract-regions` expose positions and the text inside a box. Ships a console page. | diff --git a/code-runner/Cargo.lock b/code-runner/Cargo.lock new file mode 100644 index 0000000000..1dc7e747bb --- /dev/null +++ b/code-runner/Cargo.lock @@ -0,0 +1,4805 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59317f77929f0e679d39364702289274de2f0f0b22cbf50b2b8cff2169a0b27a" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.0", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" + +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "az" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be5eb007b7cacc6c660343e96f650fedf4b5a77512399eb952ca6642cf8d13f7" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "boxed_error" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17d4f95e880cfd28c4ca5a006cf7f6af52b4bcb7b5866f573b2faa126fb7affb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +dependencies = [ + "allocator-api2", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + +[[package]] +name = "cap-fs-ext" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78e5a3368ae89b7cb68186411452b4b9fac8b41be9c19bf3f47c2d2c8e36e6b" +dependencies = [ + "cap-primitives", + "cap-std", + "io-lifetimes 3.0.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "cap-primitives" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdadbd7c002d3a484b35243669abdae85a0ebaded5a61117169dc3400f9a7ff0" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix 1.1.4", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + +[[package]] +name = "cap-std" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7281235d6e96d3544ca18bba9049be92f4190f8d923e3caef1b5f66cfa752608" +dependencies = [ + "cap-primitives", + "io-extras", + "io-lifetimes 3.0.1", + "rustix 1.1.4", +] + +[[package]] +name = "capacity_builder" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f2d24a6dcf0cd402a21b65d35340f3a49ff3475dc5fdac91d22d2733e6641c6" +dependencies = [ + "capacity_builder_macros", + "itoa", +] + +[[package]] +name = "capacity_builder_macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b4a6cae9efc04cc6cbb8faf338d2c497c165c83e74509cf4dbedea948bbf6e5" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "cc" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.20", +] + +[[package]] +name = "code-runner" +version = "0.1.0" +dependencies = [ + "anyhow", + "arc-swap", + "clap", + "futures", + "iii-console-ui", + "iii-helpers", + "iii-node-core", + "iii-python-core", + "iii-sdk", + "schemars", + "serde", + "serde_json", + "serde_yaml", + "tokio", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "cooked-waker" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147be55d677052dabc6b22252d5dd0fd4c29c8c27aa4f2fbef0f94aa003b406f" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cpp_demangle" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "cranelift-assembler-x64" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d552bd33b7a56dc70aeb1e1c960e51a218fa0db50f23873b500a310379450b2d" +dependencies = [ + "cranelift-assembler-x64-meta", +] + +[[package]] +name = "cranelift-assembler-x64-meta" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078e80e4c222279e3330f6aa1a256ca77ddf156d4453166a9f09defedc4594dd" +dependencies = [ + "cranelift-srcgen", +] + +[[package]] +name = "cranelift-bforest" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820ce15d4ad3562d613c31a67b6d0434d403e7091a68d1349903842f7d31737e" +dependencies = [ + "cranelift-entity", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-bitset" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61bca563d4b86d285928d9e27f97f27039bb33a0fc524fa130d7d0c106bf8ab3" +dependencies = [ + "serde", + "serde_derive", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709f4b7c0fb57d952658d5b5c07fbdc4149acd7b7f0de9678ae754b9c981949a" +dependencies = [ + "bumpalo", + "cranelift-assembler-x64", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-codegen-meta", + "cranelift-codegen-shared", + "cranelift-control", + "cranelift-entity", + "cranelift-isle", + "gimli", + "hashbrown 0.17.1", + "libm", + "log", + "postcard", + "pulley-interpreter", + "regalloc2", + "rustc-hash", + "serde", + "serde_derive", + "sha2 0.10.9", + "smallvec", + "target-lexicon", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen-meta" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "903dc8915af62aad1d9d0f39a5968d33fa80b9aa899ed6f56e47f40ca4512e1e" +dependencies = [ + "cranelift-assembler-x64-meta", + "cranelift-codegen-shared", + "cranelift-srcgen", + "heck", + "pulley-interpreter", +] + +[[package]] +name = "cranelift-codegen-shared" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0522d74c227e49f3fd49ab055311486ae4f09083262b66705bed676952491469" + +[[package]] +name = "cranelift-control" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66560ea1c5cef72e170b18e46d263dba2d3169c9d39e8cafdab2173c6362cc1a" +dependencies = [ + "arbitrary", +] + +[[package]] +name = "cranelift-entity" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62ef5b17cc814d27e96b66a5b46da0e4ce2b8ac55a6d478048bb99d04b05526" +dependencies = [ + "cranelift-bitset", + "serde", + "serde_derive", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-frontend" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a87e0aaa39dbf70693b348a221e45904111704ee8f9fef140498471005f9842d" +dependencies = [ + "cranelift-codegen", + "hashbrown 0.17.1", + "log", + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cranelift-isle" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf79003ebfa1eed5e87f3b84446ad5236f540268289960e14f387dc9b28e40b7" + +[[package]] +name = "cranelift-native" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05bf4f235743c81e67ee4db617c5a4a0b65d58d3f0cfc575ee0f1a4e0cd58273" +dependencies = [ + "cranelift-codegen", + "libc", + "target-lexicon", +] + +[[package]] +name = "cranelift-srcgen" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6977c2a71ab1e0d1e62f966b411a498aa04c4dce47d93d52f8a360a06058922" + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "serde", + "uuid", +] + +[[package]] +name = "deflate64" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" + +[[package]] +name = "deno_core" +version = "0.409.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b44f6f84139c39ec2f8d1b838412eb84ecaa9837103f7b12169896fd8778b4" +dependencies = [ + "anyhow", + "az", + "base64", + "bincode", + "bit-set", + "bit-vec", + "boxed_error", + "bytes", + "capacity_builder", + "cooked-waker", + "deno_error", + "deno_ops", + "deno_path_util", + "deno_unsync", + "futures", + "indexmap", + "inventory", + "libc", + "num-bigint", + "parking_lot", + "percent-encoding", + "pin-project", + "serde", + "serde_json", + "serde_v8", + "smallvec", + "sourcemap", + "static_assertions", + "sys_traits", + "thiserror 2.0.20", + "tokio", + "url", + "uuid", + "v8", + "wasm_dep_analyzer", + "windows-sys 0.59.0", +] + +[[package]] +name = "deno_error" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfafd2219b29886a71aecbb3449e462deed1b2c474dc5b12f855f0e58c478931" +dependencies = [ + "deno_error_macro", + "libc", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "deno_error_macro" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c28ede88783f14cd8aae46ca89f230c226b40e4a81ab06fa52ed72af84beb2f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "deno_ops" +version = "0.285.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c02fede673301e8b47d19368e0f3146d020e5dfcc5ee31d020cbbe542b2a50" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "stringcase", + "strum", + "strum_macros", + "syn 2.0.119", + "syn-match", + "thiserror 2.0.20", +] + +[[package]] +name = "deno_path_util" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c7e98943f0d068928906db0c7bde89de684fa32c6a8018caacc4cee2cdd72b" +dependencies = [ + "deno_error", + "percent-encoding", + "sys_traits", + "thiserror 2.0.20", + "url", +] + +[[package]] +name = "deno_unsync" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6742a724e8becb372a74c650a1aefb8924a5b8107f7d75b3848763ea24b27a87" +dependencies = [ + "futures-util", + "parking_lot", + "tokio", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", + "zeroize", +] + +[[package]] +name = "diplomat" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26fdfa02eb9a2e1ff82a375524be1ce9fd50ae63787f5737da6951b25d21e857" +dependencies = [ + "diplomat_core", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "diplomat-runtime" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae517853d9f82b2d144393b1c32c34c46c2e361de2b6c44a8fdfce23beb211cd" + +[[package]] +name = "diplomat_core" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4ede23809e2fcc555d8b2e10ffa7a1c31331ebca8e5477f4f2b48ab8a0a9a6b" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "smallvec", + "strck", + "syn 3.0.3", +] + +[[package]] +name = "directories-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339ee130d97a610ea5a5872d2bbb130fdf68884ff09d3028b81bec8a1ac23bbc" +dependencies = [ + "cfg-if", + "dirs-sys-next", +] + +[[package]] +name = "dirs-sys-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "either" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix 1.1.4", + "windows-sys 0.59.0", +] + +[[package]] +name = "fslock" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" + +[[package]] +name = "futures-executor" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a" + +[[package]] +name = "futures-macro" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "futures-sink" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307" + +[[package]] +name = "futures-task" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" + +[[package]] +name = "futures-util" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fxprof-processed-profile" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25234f20a3ec0a962a61770cfe39ecf03cb529a6e474ad8cff025ed497eda557" +dependencies = [ + "bitflags", + "debugid", + "rustc-hash", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gimli" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" +dependencies = [ + "fnv", + "hashbrown 0.16.1", + "indexmap", + "stable_deref_trait", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "gzip-header" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86848f4fd157d91041a62c78046fb7b248bcc2dce78376d436a1756e9a038577" +dependencies = [ + "crc32fast", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", + "serde", + "serde_core", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_calendar" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b2acc6263f494f1df50685b53ff8e57869e47d5c6fe39c23d518ae9a4f3e45" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar_data", + "icu_locale", + "icu_locale_core", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_calendar_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "118577bcf3a0fa7c6ac0a7d6e951814da84ee56b9b1f68fb4d8d10b08cefaf4d" + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a396343c7208121dc86e35623d3dfe19814a7613cfd14964994cdc9c9a2e26" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5fdcc9ac77c6d74ff5cf6e65ef3181d6af32003b16fce3a77fb451d2f695993" + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "if_chain" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb" + +[[package]] +name = "iii-console-ui" +version = "0.1.0" +dependencies = [ + "iii-sdk", + "schemars", + "serde", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "iii-helpers" +version = "0.21.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0d84d5c149ae4404365a79feca28aa66f6a7dbed56423b4b8c4e2421e0b5add" +dependencies = [ + "futures-util", + "opentelemetry", + "opentelemetry-http", + "opentelemetry_sdk", + "reqwest", + "schemars", + "serde", + "serde_json", + "sysinfo", + "tokio", + "tokio-tungstenite", + "tracing", + "uuid", +] + +[[package]] +name = "iii-node-core" +version = "0.1.0" +dependencies = [ + "deno_core", + "deno_error", + "futures", + "libc", + "once_cell", + "schemars", + "serde", + "serde_json", + "tempfile", + "tokio", + "tracing", + "uuid", +] + +[[package]] +name = "iii-python-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "bytes", + "futures", + "schemars", + "serde", + "serde_json", + "sha2 0.11.0", + "tempfile", + "tokio", + "tracing", + "uuid", + "wasmtime", + "wasmtime-wasi", + "zip", +] + +[[package]] +name = "iii-sdk" +version = "0.21.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07dd060fddcc9153b0dd07c038a14cf172ce15ce1d4edb98155563ed55b2caba" +dependencies = [ + "async-trait", + "futures-util", + "hostname", + "iii-helpers", + "reqwest", + "schemars", + "serde", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tokio-tungstenite", + "tracing", + "uuid", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "inventory" +version = "0.3.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.59.0", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "ittapi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b996fe614c41395cdaedf3cf408a9534851090959d90d54a535f675550b64b1" +dependencies = [ + "anyhow", + "ittapi-sys", + "log", +] + +[[package]] +name = "ittapi-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5385394064fa2c886205dba02598013ce83d3e92d33dbdc0c52fe0e7bf4fc" +dependencies = [ + "cc", +] + +[[package]] +name = "ixdtf" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ceaf4c6c48465bead8cb6a0b7c4ee0c86ecbb31239032b9c66ab9a08d2f3ee1" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libbz2-rs-sys" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2026a5056764a10b2bf5d56488cba40da507f5493a6a429340e2004d9ed085fa" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "lzma-rust2" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca93e534d1142d1d0dcca6d25fe302508a5dfb40b302802904577725ea0b695b" +dependencies = [ + "sha2 0.11.0", +] + +[[package]] +name = "mach2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memfd" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad38eb12aea514a0466ea40a80fd8cc83637065948eb4a426e4aa46261175227" +dependencies = [ + "rustix 1.1.4", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", + "rand 0.8.7", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "crc32fast", + "hashbrown 0.17.1", + "indexmap", + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "opentelemetry" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b84bcd6ae87133e903af7ef497404dda70c60d0ea14895fc8a5e6722754fc2a0" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror 2.0.20", + "tracing", +] + +[[package]] +name = "opentelemetry-http" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7a6d09a73194e6b66df7c8f1b680f156d916a1a942abf2de06823dd02b7855d" +dependencies = [ + "async-trait", + "bytes", + "http", + "opentelemetry", + "reqwest", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14ae4f5991976fd48df6d843de219ca6d31b01daaab2dad5af2badeded372bd" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "rand 0.9.5", + "thiserror 2.0.20", + "tokio", + "tokio-stream", +] + +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppmd-rust" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efca4c95a19a79d1c98f791f10aebd5c1363b473244630bb7dbde1dc98455a24" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pulley-interpreter" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc5c8c21ea032e4efbdf2d067dc45171779dbe0c8ecf20ef4a57efa7474f2b0a" +dependencies = [ + "cranelift-bitset", + "log", + "pulley-macros", + "wasmtime-internal-core", +] + +[[package]] +name = "pulley-macros" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f10925455d5dde962e3604eade797ba5488644c8ee14a44191e2f2b58980574" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.20", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.20", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "regalloc2" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85" +dependencies = [ + "allocator-api2", + "bumpalo", + "hashbrown 0.17.1", + "log", + "rustc-hash", + "serde", + "smallvec", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "resb" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22d392791f3c6802a1905a509e9d1a6039cbbcb5e9e00e5a6d3661f7c874f390" +dependencies = [ + "potential_utf", + "serde_core", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix 1.1.4", +] + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_v8" +version = "0.318.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb994c8fd6bc9746ac605f1c38219fc5eaa99ca4509db1b6519eefa0219b04a0" +dependencies = [ + "deno_error", + "num-bigint", + "serde", + "smallvec", + "thiserror 2.0.20", + "v8", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sourcemap" +version = "9.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "314d62a489431668f719ada776ca1d49b924db951b7450f8974c9ae51ab05ad7" +dependencies = [ + "base64-simd", + "bitvec", + "data-encoding", + "debugid", + "if_chain", + "rustc-hash", + "serde", + "serde_json", + "unicode-id-start", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strck" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42316e70da376f3d113a68d138a60d8a9883c604fe97942721ec2068dab13a9f" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "stringcase" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72abeda133c49d7bddece6c154728f83eec8172380c80ab7096da9487e20d27c" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn-match" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b8f0a9004d6aafa6a588602a1119e6cdaacec9921aa1605383e6e7d6258fd6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sys_traits" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88826d6169418c98e8bc52a43f79d50907dfa3e87ba5161930d42c6f980b35ee" +dependencies = [ + "sys_traits_macros", +] + +[[package]] +name = "sys_traits_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "181f22127402abcf8ee5c83ccd5b408933fec36a6095cf82cda545634692657e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sysinfo" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "temporal_capi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f48eb9ca4ca22caaa48d1e7a534ad3fd598a23d1a71945e8ad5ac0be501fa5f2" +dependencies = [ + "diplomat", + "diplomat-runtime", + "icu_calendar", + "icu_locale_core", + "num-traits", + "temporal_rs", + "timezone_provider", + "writeable", + "zoneinfo64", +] + +[[package]] +name = "temporal_rs" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a978fef907a27736827d336c0bfaab14fb8a7509dd6dc2b43c44e51d59aca5b" +dependencies = [ + "calendrical_calculations", + "core_maths", + "icu_calendar", + "icu_locale_core", + "ixdtf", + "num-traits", + "timezone_provider", + "tinystr", + "writeable", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "js-sys", + "num-conv", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "timezone_provider" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52" +dependencies = [ + "tinystr", + "zerotrie", + "zerovec", + "zoneinfo64", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "rustls", + "rustls-pki-types", + "sha1 0.10.7", + "thiserror 2.0.20", + "utf-8", +] + +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-id-start" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81b79ad29b5e19de4260020f8919b443b2ef0277d242ce532ec7b7a2cc8b6007" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "v8" +version = "150.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42a978ff11f15b24e5c05a7123cf2b68f41e763546699781a924ef4e2cf43a49" +dependencies = [ + "bindgen", + "bitflags", + "fslock", + "gzip-header", + "home", + "miniz_oxide", + "paste", + "temporal_capi", + "which", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-compose" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59b710751a35d54732a63851cdfacbfb2266b7160ce174faf269d3f4e84e31b" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "log", + "petgraph", + "smallvec", + "wasm-encoder 0.252.0", + "wasmparser 0.252.0", + "wat", +] + +[[package]] +name = "wasm-encoder" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8185ae345fa5687c054626ff9a50e7089797a343d9904d1dc9820eb4c4d3196f" +dependencies = [ + "leb128fmt", + "wasmparser 0.252.0", +] + +[[package]] +name = "wasm-encoder" +version = "0.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b524283fb5df62eec102ed0574838961bdd7ba5ac9c50d38e2756c51c971a42" +dependencies = [ + "leb128fmt", + "wasmparser 0.255.0", +] + +[[package]] +name = "wasm_dep_analyzer" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a10e6b67c951a84de7029487e0e0a496860dae49f6699edd279d5ff35b8fbf54" +dependencies = [ + "deno_error", + "thiserror 2.0.20", +] + +[[package]] +name = "wasmparser" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3eb099dcadcde5be9eef55e3a337128efd4e44b4c93122487e4d2e4e1c6627c" +dependencies = [ + "bitflags", + "hashbrown 0.17.1", + "indexmap", + "semver", + "serde", +] + +[[package]] +name = "wasmparser" +version = "0.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e329ef4b5d46e73b91d3ac6924417cad55a8cbbf869c199283383427c3320b" +dependencies = [ + "bitflags", + "indexmap", + "semver", +] + +[[package]] +name = "wasmprinter" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7142797de29b35ab8dbf15c00f55fda75d409da4c423a8ab8bd6b667a785824b" +dependencies = [ + "anyhow", + "termcolor", + "wasmparser 0.252.0", +] + +[[package]] +name = "wasmtime" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c80ca6098e0d4d06886d91d7f2cc3cb6623eb583c4c0ab3c89cbfb6098c8586c" +dependencies = [ + "addr2line", + "async-trait", + "bitflags", + "bumpalo", + "cc", + "cfg-if", + "encoding_rs", + "futures", + "fxprof-processed-profile", + "gimli", + "ittapi", + "libc", + "log", + "mach2", + "memfd", + "object", + "once_cell", + "postcard", + "pulley-interpreter", + "rayon", + "rustix 1.1.4", + "semver", + "serde", + "serde_derive", + "serde_json", + "smallvec", + "target-lexicon", + "tempfile", + "wasm-compose", + "wasm-encoder 0.252.0", + "wasmparser 0.252.0", + "wasmtime-environ", + "wasmtime-internal-cache", + "wasmtime-internal-component-macro", + "wasmtime-internal-component-util", + "wasmtime-internal-core", + "wasmtime-internal-cranelift", + "wasmtime-internal-fiber", + "wasmtime-internal-jit-debug", + "wasmtime-internal-jit-icache-coherence", + "wasmtime-internal-unwinder", + "wasmtime-internal-versioned-export-macros", + "wat", + "windows-sys 0.61.2", + "wit-parser", +] + +[[package]] +name = "wasmtime-environ" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "134f9d136d29c76f6c1b4c9b468e97a2efc38c7d49fd188e39b64870b2fea701" +dependencies = [ + "anyhow", + "cpp_demangle", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-entity", + "gimli", + "hashbrown 0.17.1", + "indexmap", + "log", + "object", + "postcard", + "rustc-demangle", + "semver", + "serde", + "serde_derive", + "sha2 0.10.9", + "smallvec", + "target-lexicon", + "wasm-encoder 0.252.0", + "wasmparser 0.252.0", + "wasmprinter", + "wasmtime-internal-component-util", + "wasmtime-internal-core", +] + +[[package]] +name = "wasmtime-internal-cache" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65db2eb1bfc5371a3b4107dbf539d0b93d05016fc29625b1648146b47db02071" +dependencies = [ + "base64", + "directories-next", + "log", + "postcard", + "rustix 1.1.4", + "serde", + "serde_derive", + "sha2 0.10.9", + "toml", + "wasmtime-environ", + "windows-sys 0.61.2", + "zstd", +] + +[[package]] +name = "wasmtime-internal-component-macro" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf7b91fed3fc34781d57f9c6654ea2513bf0a99f7b0b0523c00de1e6efebe1c" +dependencies = [ + "anyhow", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasmtime-internal-component-util", + "wasmtime-internal-wit-bindgen", + "wit-parser", +] + +[[package]] +name = "wasmtime-internal-component-util" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc8a678149885cae00289f806fbe74c7863084cf74cace0b8dc73602279400e1" + +[[package]] +name = "wasmtime-internal-core" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a0092c4b9d070ac5e278b6d0db10f5e71214190f0347ca57502b4692f796321" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "libm", + "serde", +] + +[[package]] +name = "wasmtime-internal-cranelift" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6851ebc9e03cab23d9821d2b2505d380bdfe38f35ccec945247b05274d85c98b" +dependencies = [ + "cfg-if", + "cranelift-codegen", + "cranelift-control", + "cranelift-entity", + "cranelift-frontend", + "cranelift-native", + "gimli", + "itertools 0.14.0", + "log", + "object", + "pulley-interpreter", + "smallvec", + "target-lexicon", + "thiserror 2.0.20", + "wasmparser 0.252.0", + "wasmtime-environ", + "wasmtime-internal-core", + "wasmtime-internal-unwinder", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-fiber" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b26da6d5f60d4c438da70bba3553fe810a840533a64156be287dca2081c6991" +dependencies = [ + "cc", + "cfg-if", + "libc", + "rustix 1.1.4", + "wasmtime-environ", + "wasmtime-internal-versioned-export-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmtime-internal-jit-debug" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed621ba25d7bf78b7edd7b4749abbb27c2e5cdba836c9504a424ee74b6c23149" +dependencies = [ + "cc", + "object", + "rustix 1.1.4", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-jit-icache-coherence" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5684ba160951baad06a725696f3c590e2fb0e8067c2aebee27bf7f9259058e85" +dependencies = [ + "cfg-if", + "libc", + "wasmtime-internal-core", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmtime-internal-unwinder" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112eead527bffa8ff0646a11fb4339a9d52ddd1da2b9a6fce4aff84c815dd94f" +dependencies = [ + "cfg-if", + "cranelift-codegen", + "log", + "object", + "wasmtime-environ", +] + +[[package]] +name = "wasmtime-internal-versioned-export-macros" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "153592e0bed824fc13c6696203fa1bd7bd20eb355316475e39a55f081ef80eca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "wasmtime-internal-wit-bindgen" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c456ad6e81e0f46abfeca43687d18ea15e289c395b262ea6e0023e2682e088be" +dependencies = [ + "anyhow", + "bitflags", + "heck", + "indexmap", + "wit-parser", +] + +[[package]] +name = "wasmtime-wasi" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c1cf60cd6a565213af7074b4aad7bb5e110e3c6c6aae54425aa0500a0e15e86" +dependencies = [ + "async-trait", + "bitflags", + "bytes", + "cap-fs-ext", + "cap-std", + "cfg-if", + "futures", + "io-lifetimes 3.0.1", + "rand 0.10.2", + "rustix 1.1.4", + "thiserror 2.0.20", + "tokio", + "tracing", + "url", + "wasmtime", + "wasmtime-wasi-io", + "wiggle", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmtime-wasi-io" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fb08e1d7755aaa467ce14080b7b01e33c914a920f6000696f1e42e40ea6387e" +dependencies = [ + "async-trait", + "bytes", + "futures", + "tracing", + "wasmtime", +] + +[[package]] +name = "wast" +version = "35.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef140f1b49946586078353a453a1d28ba90adfc54dde75710bc1931de204d68" +dependencies = [ + "leb128", +] + +[[package]] +name = "wast" +version = "255.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ffec530f199bd3d553ac442c13dd108353cad533cad8514bc41e1f1f0fe686" +dependencies = [ + "bumpalo", + "leb128fmt", + "memchr", + "unicode-width", + "wasm-encoder 0.255.0", +] + +[[package]] +name = "wat" +version = "1.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dda82c82e1486c7eed42a0465e544d80fff37abc3b39482e0d34dbaabe2fe5b1" +dependencies = [ + "wast 255.0.0", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" +dependencies = [ + "either", + "home", + "rustix 0.38.44", + "winsafe", +] + +[[package]] +name = "wiggle" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89091642df051b84a7e00bdff75e985e507f2298384e477cc9310b0ddd79f004" +dependencies = [ + "bitflags", + "thiserror 2.0.20", + "tracing", + "wasmtime", + "wasmtime-environ", + "wiggle-macro", +] + +[[package]] +name = "wiggle-generate" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12247f46f31bb5e7593947f9bba07317d0c1978e0d02250b979dd08f56f46e9f" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasmtime-environ", + "witx", +] + +[[package]] +name = "wiggle-macro" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e556a0880c9506fdcc662b1e226c7ced692f4977fed5b1ed40a3f3f0a48356f2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "wiggle-generate", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags", + "windows-sys 0.59.0", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-parser" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4266bea110371c620ccf3201c5023676046bc4556e5c7cfb5d500bda5ebc162d" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser 0.252.0", +] + +[[package]] +name = "witx" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e366f27a5cabcddb2706a78296a40b8fcc451e1a6aba2fc1d94b4a01bdaaef4b" +dependencies = [ + "anyhow", + "log", + "thiserror 1.0.69", + "wast 35.0.2", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "aes", + "bzip2", + "constant_time_eq", + "crc32fast", + "deflate64", + "flate2", + "getrandom 0.4.3", + "hmac", + "indexmap", + "lzma-rust2", + "memchr", + "pbkdf2", + "ppmd-rust", + "sha1 0.11.0", + "time", + "typed-path", + "zeroize", + "zopfli", + "zstd", +] + +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zoneinfo64" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed6eb2607e906160c457fd573e9297e65029669906b9ac8fb1b5cd5e055f0705" +dependencies = [ + "calendrical_calculations", + "icu_locale_core", + "potential_utf", + "resb", + "serde", +] + +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/code-runner/Cargo.toml b/code-runner/Cargo.toml new file mode 100644 index 0000000000..7236fdb96b --- /dev/null +++ b/code-runner/Cargo.toml @@ -0,0 +1,41 @@ +[workspace] + +[package] +name = "code-runner" +version = "0.1.0" +edition = "2021" +publish = false + +[[bin]] +name = "code-runner" +path = "src/main.rs" + +[lib] +path = "src/lib.rs" + +[dependencies] +iii-sdk = "=0.21.6" +iii-helpers = "=0.21.6" +# The two engines, as libraries. Both are bus-free: this worker owns the only +# connection and implements `iii_node_core::engine::Engine` against it. +iii-node-core = { path = "../crates/node-core" } +iii-python-core = { path = "../crates/python-core" } +# The injected console UI: registration machinery for the two assets +# `src/ui.rs` embeds (see crates/console-ui). +iii-console-ui = { path = "../crates/console-ui" } +tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros", "sync", "signal", "time"] } +# Lock-free hot-reload snapshot for the configuration-worker integration, +# same pattern as browser. +arc-swap = "1" +futures = "0.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +serde_yaml = "0.9" +# Must stay on the same schemars major as iii-sdk so derived schemas match +# what RegisterFunction emits at registration time. +schemars = "0.8" +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] } +clap = { version = "4", features = ["derive", "env"] } +uuid = { version = "1", features = ["v4"] } diff --git a/code-runner/README.md b/code-runner/README.md new file mode 100644 index 0000000000..9e78b7745a --- /dev/null +++ b/code-runner/README.md @@ -0,0 +1,317 @@ +# code-runner + +Run untrusted Node.js and Python **in-process**: iterate with +`code-runner::run`, publish working functions to the bus with +`code-runner::register_function`, clean up with `code-runner::teardown`. + +Same wire contract as +[sandbox-code-runner](../sandbox-code-runner/), so a caller written against +that worker needs no changes — but no microVM, no daemon, and **no +`/dev/kvm`**. JavaScript runs in a V8 isolate; Python runs as CPython compiled +to WebAssembly inside wasmtime. + +```bash +iii worker add code-runner +``` + +## Quickstart + +```bash +iii trigger code-runner::run lang=node code='console.log("hi"); return 2 + 2' +``` + +```json +{ "stdout": "hi\n", "stderr": "", "exit_code": 0, "success": true, + "duration_ms": 12, "result": 4 } +``` + +`run` is **one-shot by default**: it creates a runtime, runs your code, +returns, and destroys it. Nothing persists, and the response carries no +`runtime_id` because there is nothing left to address. + +Pass `keep: true` to leave it running. The response's `runtime_id` then +addresses it on later calls — same globals, same scratch directory — and is +the capability `teardown` needs. + +**A failing script is a response, not an error.** `stdout`, `stderr` and +`exit_code` come back verbatim; a thrown exception is `exit_code: 1` with the +message on `stderr`, not a failed bus call. Errors are reserved for +infrastructure: timeouts, resource kills, unknown runtimes. + +`result` is this worker's one addition to sandbox-code-runner's response: the +value your code returned, so a caller does not have to print JSON and parse +`stdout`. + +## Output caps + +`result`, `stdout` and `stderr` are each capped before the response leaves +this worker, so one runaway script cannot flood your context window with its +own output. Both caps are on by default and apply the same way to node and +python, and to a thrown/raised response exactly as to a successful one — +`exit_code`, `success`, `duration_ms` and `runtime_id` are never touched: a +capped response is still `success: true` when the run itself succeeded, only +the echo is bounded. + +**`result`** — capped at `max_result_bytes` (default `32768` bytes, **`0` +disables it**). An oversized value is not truncated or reshaped, it is +*replaced whole* by a string marker naming what was dropped: + +```text + +``` + +For example, `for (i=0;i<100000;i++) result.push(i); return result` returns +`result` as `` +instead of the 100,000-element array. This is deliberate: `result` is often +consumed by code (an `fp::pipe` step, another `iii.trigger` call), so a step +that receives a string where it expected an array fails loudly with the +marker text in the error — the teaching failure you want, not data quietly +gone missing. + +**`stdout` / `stderr`** — each capped independently at `max_stream_bytes` +(default `16384` bytes, **`0` disables it**). An oversized stream keeps its +first 60% and its last 40% — so both the first failure and the final summary +line survive — with a marker spliced into the middle: + +```text +[head: ~60% of the budget] +[…stdout truncated: was ~{KB} KB; middle omitted] +[tail: ~40% of the budget] +``` + +(`stderr`'s marker names itself the same way.) + +**If you hit a cap:** the full value is gone at this layer, not stored +anywhere for a later look — re-running is the only way to get it back. Print +a slice instead of the whole value, aggregate in code (counts, sums, +first/last N) instead of returning or logging everything, or write the full +data to `iii.files` and return a short summary. + +## The `iii` global + +Code you run gets a global `iii`: + +- `await iii.trigger({ function_id, payload })` — invoke any bus function. +- `iii.registerFunction(id, handler, opts?)` — publish one for the life of + this runtime. For one that outlives it, use `code-runner::register_function`. + `opts` takes `description`, and `request_format` / `response_format` — JSON + Schema objects `engine::functions::info` shows callers in place of "any". +- `iii.files` — a **private scratch directory** that lives exactly as long as + the runtime: `write(name, contents)`, `read(name)`, `readText(name)`, + `list()`, `remove(name)`. Names are one file each — no paths, no + subdirectories — and the directory is bounded by `scratch_mb`/`scratch_files`. +- `iii.namespace` — the prefix this runtime may register under. + +Python's `iii` is narrower: `iii.trigger({...})` and `iii.namespace`, and it +is **synchronous** — the call blocks until the answer comes back. Registration +from inside guest Python is not available; use `code-runner::register_function` +(node) or trigger a worker that registers for you. A guest timeout is clamped +to what is left of the run's own budget, so `iii.trigger` inside a 5s run +cannot ask for 30s and take the whole run down with it. + +```python +answer = iii.trigger({"function_id": "state::get", "payload": {"key": "k"}}) +result = answer["value"] +``` + +## What this cannot do + +Read this before choosing between the two workers. + +| | `code-runner` | `sandbox-code-runner` | +|---|---|---| +| Isolation | V8 isolate / wasm sandbox, in-process | microVM per runtime | +| Requires `/dev/kvm` or Apple Silicon | **no** | yes | +| Outbound network | **no** | yes | +| `npm install` / `pip install` | **no** | yes | +| Real filesystem | no — only `iii.files` | yes, a whole OS | +| Guest `iii` | host-implemented surface | the real iii-sdk client | +| Per-call cost | milliseconds | VM boot | + +**There is no network, so package installation cannot work at all** — not +slowly, not with a flag. If your code needs a third-party package, use +`sandbox-code-runner`. What you can do here is write your own modules into +`iii.files` and load them from there. + +## Configuration + +Served by the **`configuration` worker** (entry id `code-runner`) — edit it in +the console's Workers tab (the worker ships its own form there) or via +`configuration::set`; the fs adapter persists it under +`./data/configuration/code-runner.yaml`. There is no committed config file; +`--config ` seeds the initial value on first boot only. Reload tier 1: +**`max_result_bytes`, `max_stream_bytes`, `default_timeout_ms`, +`max_timeout_ms`, and `inject_guidance` hot-apply on save**; the remaining fields are captured when +the engines boot and cannot be rebound under live guest runtimes — a change to +them is saved immediately and applies at the next worker restart (the reload +log says so). + +| key | default | meaning | +|---|---|---| +| `max_runtimes` | 32 | live runtimes across both engines | +| `default_timeout_ms` | 5000 | per run when unspecified | +| `max_timeout_ms` | 30000 | ceiling a request's `timeout_ms` is clamped to | +| `idle_ttl_secs` | 900 | reap runtimes idle this long | +| `heap_mb` | 128 | V8 object-heap cap per node runtime | +| `external_mb` | 64 | off-heap cap per node runtime; `heap_mb` does not cover it | +| `scratch_mb` | 8 | `iii.files` quota per **node** runtime; **0 disables it entirely**. Python's `/work` budget is fixed by its engine (256 MiB, 20k files) | +| `scratch_files` | 64 | max files per node runtime | +| `scratch_root` | unset | where node scratch directories live | +| `inject_guidance` | true | append the code-runner usage guidance to agent system prompts (the `pre_generate` hook); off answers the hook with a no-op | +| `max_result_bytes` | 32768 | ceiling on the serialized `result`; over it becomes an omission marker (see [Output caps](#output-caps)). **0 disables it** | +| `max_stream_bytes` | 16384 | ceiling on each of `stdout`/`stderr`; over it keeps head+tail around a truncation marker. **0 disables it** | + +**Worst-case host footprint is `max_runtimes * scratch_mb`** — 256 MiB at the +defaults — and the system temp directory is tmpfs, i.e. host RAM, on most +Linux hosts. Set `scratch_root` to real disk if that matters. + +## Errors + +| code | meaning | +|---|---| +| `code-runner::invalid_request` | malformed request, or a `lang` that contradicts the runtime | +| `code-runner::runtime_not_found` | unknown `runtime_id`, or a namespace with nothing behind it | +| `code-runner::expired` | the runtime was reaped or killed; get a fresh one | +| `code-runner::capacity` | all runtime slots in use — retry later | +| `code-runner::timeout` | the run blew its deadline | +| `code-runner::resource_exhausted` | a cap was hit mid-run (memory, scratch quota). Unlike `capacity`, retrying will not help — shrink the workload | +| `code-runner::handler_error` | a registered handler threw | +| `code-runner::engine` | infrastructure failure | + +## Console UI + +The worker ships an injected console UI (the injectable-UI protocol, +`iii/tech-specs/2026-07-17-injectable-ui`) — two assets, built from `ui/` by +esbuild and embedded in the binary, so there is nothing to install and nothing +to serve separately: + +| Asset | Slot | What it does | +|---|---|---| +| `code-runner/page.js` | `console:script` | how `run` / `register_function` / `teardown` render in chat and the traces span view | +| `code-runner/styles.css` | `console:style` | the stylesheet, every rule scoped under `[data-iii-ui="code-runner"]` | + +One renderer per op, under `ui/src/function-trigger-message/`, sharing the card +frame in `ui/src/lib/shared.tsx`. They replace the console's raw-JSON card, +which turns `code` into one escaped line and buries the verdict. + +What the cards are for: + +- **`run`** leads with the verdict (`exit`, duration), then the **completion + value**, then the source highlighted as the language it runs as, then + stdout/stderr as terminal output. A **non-zero exit renders as a warning, not + an alert** — errors are for infrastructure, and a script that throws is an + ordinary response. +- A **null `result`** is shown explicitly, with the engine's return convention + beside it: node code is a function body (`return 2 + 2`), python code is a + module (assign `result`). That mismatch is the usual reason a call "worked" + and returned nothing. +- **`register_function`** puts the namespace the id claims on its own line, and + advises when the source defines no `handler` — on python that fails the + registration outright, not the first call. +- **`teardown`** answers the one question the payload does not: which function + ids stopped resolving. + +**`runtime_id` is never rendered in full.** It is a capability — whoever holds +one can run into or tear down that runtime — so it appears only as a truncated +chip whose full value is handed over on an explicit click-to-copy. Every other +string on a card is filtered first: stdout, stderr, error messages (which quote +the id by design — see `src/error.rs`), the submitted source, the completion +value, and the `raw json` tab the console mounts regardless of what a card does. + +### Developing it + +```sh +cd ui && pnpm install && pnpm build # cargo build does this for you +pnpm test # vitest, renders the cards server-side +``` + +`build.rs` runs `pnpm install && pnpm build` when `ui/dist/` is missing or +stale, so a plain `cargo build` is enough. `SKIP_UI_BUILD=1` uses the existing +`ui/dist/` as-is. For a hot-reload loop, run `pnpm watch` and start the worker +with `III_CODE_RUNNER_UI_WATCH=1` — every open console tab swaps the changed +asset. + +## Status + +| | node | python | +|---|---|---| +| one-shot `run` | yes | yes | +| `keep` / `runtime_id` | yes | **yes** | +| what a kept runtime persists | globals **and** files | globals **and** files | +| `register_function` | yes | **yes** | +| `iii.trigger` from guest code | yes | **yes** | +| `iii.registerFunction` from guest code | yes | no | +| `iii.files` | yes | use `/work` | + +**A kept python runtime persists its working directory *and* its +interpreter.** `python.wasm` is a WASI *command* module — the artifact exports +`memory` and `_start` and nothing else — so the interpreter cannot be re-entered +once `_start` returns. Instead it never returns: the wrapper parks on stdin +between calls and the host hands it one turn at a time. Globals stay bound, +modules stay imported, and files under `/work` stay put. + +That is a **superset** of what `sandbox-code-runner` promises for its own +`keep`, which is *"same filesystem, fresh interpreter process each time"*. Code +written against that worker still behaves correctly here; code written against +this one may not port back. + +Two consequences worth knowing before you rely on it: + +- **A call that overruns its `timeout_ms` takes the interpreter with it.** The + only kill that reaches a guest parked in a host call unwinds `_start`, so + there is nothing left to resume. The working directory survives, and the next + call on that `runtime_id` boots a fresh interpreter on the same files. +- **`memory_mb` is fixed when the runtime is created.** Wasm linear memory only + ever grows, so a per-call ceiling would be a promise the sandbox cannot keep — + a later caller would inherit whatever an earlier one grew to. Sending + `memory_mb` alongside a `runtime_id` is refused rather than ignored. + +Only `result` is cleared between turns. It is the output slot, not state: a +turn that assigns no `result` returns `null`, never the previous turn's value. + +### `register_function` with `lang: "python"` + +Your `source` must define `handler(payload)`; anything else it defines stays +available to every later invocation, because the namespace runs on one pinned +interpreter. + +```python +# code-runner::register_function, lang=python, function_id="my-app::greet" +import json + +_greetings = {"en": "hello", "pt": "olá"} + +def handler(payload): + return _greetings.get(payload.get("lang", "en"), "hello") +``` + +Four things worth knowing: + +- **Source that leaves no callable `handler` fails the registration**, not the + first call. The id never reaches the catalog, so a corrected redeploy of the + same id works. +- **Re-registering an id replaces it.** The previous registration is retired + before the new one is published. +- **The interpreter is exempt from the idle sweep.** A registration's lifetime + is the registration's, not its traffic's; `teardown` with `namespace` is the + only way to remove one. +- **The namespace is shared with node.** Function ids are claimed in one + registry, so `my-app::greet` cannot exist in both languages, and the same + charset rule applies to the namespace in both. +- **Schemas are optional but shown.** `request_format` / `response_format` + (JSON Schema objects, max 16 KiB, must actually constrain something) ride + the registration in either language, and `engine::functions::info` shows + them in place of "any". + +Unlike node, guest Python cannot register a function *from inside* a run — +`python.wasm` exports `_start` and nothing else, so there is no +`iii.registerFunction` to call. The host publishes on the guest's behalf and +dispatches each invocation as one turn on the namespace interpreter. + +```python +# lang=python, keep=true — then reuse the runtime_id +open("/work/state.json", "w").write('{"n": 1}') +result = "saved" +``` diff --git a/code-runner/build.rs b/code-runner/build.rs new file mode 100644 index 0000000000..2299b719fe --- /dev/null +++ b/code-runner/build.rs @@ -0,0 +1,185 @@ +//! Build script for the `code-runner` worker. +//! +//! 1. Forwards the build-time target triple to the binary as `env!("TARGET")` +//! (used by `manifest.rs` for the registry `supported_targets` field). +//! 2. Ensures the injected console UI assets exist: `src/ui.rs` embeds +//! `ui/dist/page.js` and `ui/dist/styles.css` via `include_str!`, so if +//! either is missing or stale we run `pnpm install && pnpm build` inside +//! `ui/` first (the `state` worker's precedent). Set `SKIP_UI_BUILD=1` to +//! use the existing `ui/dist/` outputs as-is. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::SystemTime; + +fn main() { + println!( + "cargo:rustc-env=TARGET={}", + std::env::var("TARGET").unwrap() + ); + + // `dist/` itself is not listed: include_str! reads it directly, and + // listing it would rebuild-loop on our own output. + println!("cargo:rerun-if-changed=ui/page.tsx"); + println!("cargo:rerun-if-changed=ui/styles.css"); + println!("cargo:rerun-if-changed=ui/src"); + println!("cargo:rerun-if-changed=ui/build.mjs"); + println!("cargo:rerun-if-changed=ui/package.json"); + // The lockfile lives at the workers-repo root (pnpm workspace: the ui + // project links @iii-dev/console-ui from packages/console-ui — watched + // too, or an edit there leaves a stale page.js embedded in the worker). + println!("cargo:rerun-if-changed=../pnpm-lock.yaml"); + println!("cargo:rerun-if-changed=../packages/console-ui"); + println!("cargo:rerun-if-changed=ui/tsconfig.json"); + + let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let ui_dir = manifest_dir.join("ui"); + // Only the two console assets: unlike sandbox-code-runner, this worker + // plants no `iii-sdk` bundle into a guest — its Node guest gets a + // host-implemented op surface and its Python guest a framed stdio bridge, + // so there is nothing to bundle for them. + let dist_assets = [ + ui_dir.join("dist").join("page.js"), + ui_dir.join("dist").join("styles.css"), + ]; + + if dist_assets + .iter() + .all(|a| a.exists() && dist_is_fresh(a, &ui_dir)) + { + return; + } + + if std::env::var_os("SKIP_UI_BUILD").is_some() { + for asset in &dist_assets { + if !asset.exists() { + panic!( + "SKIP_UI_BUILD set but {} is missing — build the UI manually \ + (cd ui && pnpm install && pnpm build) or unset the env var", + asset.display() + ); + } + } + return; + } + + let pnpm = locate_pnpm(); + + let status = Command::new(&pnpm) + .args(["install"]) + .current_dir(&ui_dir) + .status() + .unwrap_or_else(|e| { + panic!( + "failed to spawn `pnpm install` in {}: {e}", + ui_dir.display() + ) + }); + if !status.success() { + panic!("`pnpm install` exited with {status} — see logs above"); + } + + let status = Command::new(&pnpm) + .args(["build"]) + .current_dir(&ui_dir) + .status() + .unwrap_or_else(|e| panic!("failed to spawn `pnpm build` in {}: {e}", ui_dir.display())); + if !status.success() { + panic!("`pnpm build` exited with {status} — see logs above"); + } + + for asset in &dist_assets { + if !asset.exists() { + panic!( + "`pnpm build` finished but {} is still missing — check the esbuild \ + output above", + asset.display() + ); + } + } +} + +/// `true` when the built asset is at least as new as every source that +/// contributes to it. Conservative: any I/O failure forces a rebuild. +fn dist_is_fresh(dist_asset: &Path, ui_dir: &Path) -> bool { + let Ok(dist_mtime) = dist_asset.metadata().and_then(|m| m.modified()) else { + return false; + }; + + let watched_files = [ + ui_dir.join("page.tsx"), + ui_dir.join("styles.css"), + ui_dir.join("build.mjs"), + ui_dir.join("package.json"), + ui_dir.join("../../pnpm-lock.yaml"), + ui_dir.join("tsconfig.json"), + ]; + for f in watched_files.iter() { + if !f.exists() { + continue; + } + let Ok(m) = f.metadata().and_then(|m| m.modified()) else { + return false; + }; + if m > dist_mtime { + return false; + } + } + + for dir in [ui_dir.join("src"), ui_dir.join("../../packages/console-ui")] { + if dir.exists() && !subtree_older_than(&dir, dist_mtime) { + return false; + } + } + + true +} + +fn subtree_older_than(root: &Path, ceiling: SystemTime) -> bool { + let Ok(read) = std::fs::read_dir(root) else { + return false; + }; + for entry in read.flatten() { + let path = entry.path(); + let Ok(meta) = entry.metadata() else { + return false; + }; + if meta.is_dir() { + if !subtree_older_than(&path, ceiling) { + return false; + } + } else { + let Ok(m) = meta.modified() else { + return false; + }; + if m > ceiling { + return false; + } + } + } + true +} + +fn locate_pnpm() -> PathBuf { + if let Ok(explicit) = std::env::var("PNPM") { + return PathBuf::from(explicit); + } + let candidates = if cfg!(windows) { + ["pnpm.cmd", "pnpm.exe", "pnpm"].as_slice() + } else { + ["pnpm"].as_slice() + }; + let path = std::env::var_os("PATH").unwrap_or_default(); + for dir in std::env::split_paths(&path) { + for name in candidates { + let candidate = dir.join(name); + if candidate.is_file() { + return candidate; + } + } + } + panic!( + "pnpm not found on PATH — install Node + pnpm, or set SKIP_UI_BUILD=1 \ + after building the UI manually with `cd ui && pnpm install && pnpm build`" + ); +} diff --git a/code-runner/iii.worker.yaml b/code-runner/iii.worker.yaml new file mode 100644 index 0000000000..44da1c4444 --- /dev/null +++ b/code-runner/iii.worker.yaml @@ -0,0 +1,28 @@ +iii: v1 +name: code-runner +language: rust +deploy: binary +manifest: Cargo.toml +bin: code-runner +tags: [javascript, python, run, sandbox, v8, wasm] +description: Run untrusted Node.js and Python in-process — V8 isolates and CPython-on-WebAssembly behind one run/register_function/teardown API, with no microVM and no /dev/kvm. Code gets a global `iii` and a private scratch directory. +dependencies: + configuration: "^0.21.6" + +# Restricted for TWO independent reasons, both of which must hold before this +# list can be widened — do not conclude it is liftable by dropping one +# dependency: +# 1. rusty_v8 150.4.0 (via deno_core) publishes no prebuilt for +# i686-pc-windows-msvc or armv7-unknown-linux-gnueabihf. +# 2. Cranelift (wasmtime's compiler) has no backend for those same two. +# With no `targets:` the release matrix fans out to all 9 default triples, +# those two shards fail, and `publish` is gated `if: !failure()` — so a +# code-runner/v* tag would build red and never reach the registry. +targets: + - x86_64-apple-darwin + - aarch64-apple-darwin + - x86_64-pc-windows-msvc + - aarch64-pc-windows-msvc + - x86_64-unknown-linux-gnu + - x86_64-unknown-linux-musl + - aarch64-unknown-linux-gnu diff --git a/code-runner/src/config.rs b/code-runner/src/config.rs new file mode 100644 index 0000000000..92b335502e --- /dev/null +++ b/code-runner/src/config.rs @@ -0,0 +1,286 @@ +//! Operator config, served by the `configuration` worker (docs/sops/configuration.md). +//! +//! One flat struct rather than nested `node:`/`python:` sections: the three +//! shared knobs would otherwise need duplicating or hoisting, and flat is what +//! both engines already ship. +//! +//! `deny_unknown_fields` is deliberate, following python-engine rather than +//! node-engine: this is operator config, not a wire request, so a typo like +//! `max_runtimez: 3` should fail loudly rather than silently no-op. +//! +//! Reload semantics (Tier 1, hot snapshot via [`SharedConfig`]): the output +//! caps (`max_result_bytes`/`max_stream_bytes`) and the timeout knobs are read +//! per call and hot-reload on `configuration:updated`. The engine-structural +//! fields — `max_runtimes`, `heap_mb`, `external_mb`, `idle_ttl_secs`, and the +//! scratch knobs — are captured when the V8/CPython engines are built at boot +//! and CANNOT be rebound under live guest runtimes; a change is persisted +//! immediately but applies at the next worker restart (the reload handler says +//! so in the log). This is the documented exception the SOP's hot-reload rule +//! allows. + +use std::sync::Arc; + +use anyhow::Result; +use arc_swap::ArcSwap; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Hot-swappable config snapshot: handlers `load()` per call (lock-free), +/// the configuration trigger `store()`s a whole new value. +pub type SharedConfig = Arc>; + +fn default_true() -> bool { + true +} + +fn default_max_result_bytes() -> usize { + 32_768 +} + +fn default_max_stream_bytes() -> usize { + 16_384 +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(default, deny_unknown_fields)] +pub struct CodeRunnerConfig { + /// Live runtimes across both engines. Applied at worker start. + pub max_runtimes: usize, + /// Timeout used when a run omits `timeout_ms`. + pub default_timeout_ms: u64, + /// Hard ceiling a run's `timeout_ms` is clamped to. + pub max_timeout_ms: u64, + /// Reap runtimes idle longer than this. Applied at worker start. + pub idle_ttl_secs: u64, + /// V8 object-heap cap per node runtime (MiB). Applied at worker start. + pub heap_mb: usize, + /// Off-heap cap per node runtime (ArrayBuffer/TypedArray, MiB); `heap_mb` + /// does not cover it. Applied at worker start. + pub external_mb: usize, + /// Per-runtime scratch directory (`iii.files`), MiB — NODE runtimes + /// only; python's `/work` budget is fixed by its engine (256 MiB, + /// 20k files). 0 disables it and removes the guest surface. Applied at + /// worker start. + /// + /// WORST-CASE HOST FOOTPRINT IS `max_runtimes * scratch_mb`, and the + /// system temp directory is tmpfs — host RAM — on most Linux hosts. + pub scratch_mb: usize, + /// Maximum files per scratch directory (node runtimes only). Applied at + /// worker start. + pub scratch_files: usize, + /// Where scratch directories live (node runtimes only); unset uses the + /// system temp directory. Applied at worker start. + pub scratch_root: Option, + /// Append the code-runner usage guidance to agent system prompts (the + /// `pre_generate` hook). Off silences the hook without unbinding it. + #[serde(default = "default_true")] + pub inject_guidance: bool, + /// Byte ceiling for the serialized `result` echoed in a RunResponse; + /// larger values are replaced by an omission marker string. 0 disables. + #[serde(default = "default_max_result_bytes")] + pub max_result_bytes: usize, + /// Byte ceiling for each of stdout/stderr; larger streams keep + /// head+tail around a truncation marker. 0 disables. + #[serde(default = "default_max_stream_bytes")] + pub max_stream_bytes: usize, +} + +impl Default for CodeRunnerConfig { + fn default() -> Self { + Self { + max_runtimes: 32, + default_timeout_ms: 5_000, + max_timeout_ms: 30_000, + idle_ttl_secs: 900, + heap_mb: 128, + external_mb: 64, + scratch_mb: 8, + scratch_files: 64, + scratch_root: None, + inject_guidance: true, + max_result_bytes: default_max_result_bytes(), + max_stream_bytes: default_max_stream_bytes(), + } + } +} + +impl CodeRunnerConfig { + pub fn json_schema() -> serde_json::Value { + serde_json::to_value(schemars::schema_for!(CodeRunnerConfig)) + .expect("CodeRunnerConfig schema serializes") + } + + /// Parse a value already env-expanded by the configuration worker. + pub fn from_json(v: &serde_json::Value) -> Result { + serde_json::from_value(v.clone()).map_err(|e| format!("invalid code-runner config: {e}")) + } + + pub fn to_json(&self) -> serde_json::Value { + serde_json::to_value(self).expect("CodeRunnerConfig serializes") + } + + pub fn into_shared(self) -> SharedConfig { + Arc::new(ArcSwap::from_pointee(self)) + } + + /// True when `self` → `next` changes a field the engines captured at + /// boot — everything except the per-call knobs (output caps + timeouts). + /// The reload handler uses this to say "applies at next restart". + pub fn restart_required(&self, next: &CodeRunnerConfig) -> bool { + let per_call = |c: &CodeRunnerConfig| CodeRunnerConfig { + max_result_bytes: 0, + max_stream_bytes: 0, + default_timeout_ms: 0, + max_timeout_ms: 0, + inject_guidance: false, + ..c.clone() + }; + per_call(self) != per_call(next) + } + + /// The node engine's own config, derived from this one. + pub fn node(&self) -> iii_node_core::config::NodeEngineConfig { + iii_node_core::config::NodeEngineConfig { + max_runtimes: self.max_runtimes, + default_timeout_ms: self.default_timeout_ms, + max_timeout_ms: self.max_timeout_ms, + heap_mb: self.heap_mb, + external_mb: self.external_mb, + idle_ttl_secs: self.idle_ttl_secs, + scratch_mb: self.scratch_mb, + scratch_files: self.scratch_files, + scratch_root: self.scratch_root.clone(), + } + } + + /// The python half of the same operator config. + /// + /// Every key this worker documents and both engines understand is passed + /// through. Without this the python engine silently ran on its own + /// defaults — an operator lowering `idle_ttl_secs` or `max_timeout_ms` + /// changed node's behaviour and nothing else, with no error to say so. + /// + /// Three key groups are NOT taken from the shared config, on purpose: + /// `max_concurrent_runs` bounds how many CPython instances execute at + /// once and is a memory ceiling of a different shape to node's isolate + /// count; the memory knobs are python's own — `heap_mb`/`external_mb` + /// are V8 concepts with no wasm equivalent; and the scratch knobs are + /// node's — python's `/work` is a fixed engine budget + /// (`MAX_WORK_DIR_BYTES`), not configurable here. + pub fn python(&self) -> iii_python_core::config::PythonEngineConfig { + let d = iii_python_core::config::PythonEngineConfig::default(); + iii_python_core::config::PythonEngineConfig { + max_runtimes: self.max_runtimes, + idle_ttl_secs: self.idle_ttl_secs, + default_timeout_ms: self.default_timeout_ms, + max_timeout_ms: self.max_timeout_ms, + ..d + } + } +} + +/// Parse an optional `--config` seed file. Used ONLY as a one-time +/// `initial_value` on first registration with the configuration worker — +/// after that, the configuration worker's stored value is authoritative and +/// nothing on disk is read at runtime. +pub fn load_config(path: &str) -> Result { + let raw = std::fs::read_to_string(path)?; + Ok(serde_yaml::from_str(&raw)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unknown_config_keys_are_rejected() { + let err = serde_yaml::from_str::("max_runtimez: 3").unwrap_err(); + assert!(err.to_string().contains("max_runtimez")); + } + + /// Every shared knob must reach the engine that enforces it. Mutation: + /// drop any line from `node()` and the corresponding assertion fails. + #[test] + fn the_node_config_carries_every_shared_knob() { + let cfg = CodeRunnerConfig { + max_runtimes: 3, + default_timeout_ms: 11, + max_timeout_ms: 22, + idle_ttl_secs: 33, + heap_mb: 44, + external_mb: 55, + scratch_mb: 66, + scratch_files: 77, + scratch_root: Some("/tmp/x".into()), + ..Default::default() + }; + let n = cfg.node(); + assert_eq!(n.max_runtimes, 3); + assert_eq!(n.default_timeout_ms, 11); + assert_eq!(n.max_timeout_ms, 22); + assert_eq!(n.idle_ttl_secs, 33); + assert_eq!(n.heap_mb, 44); + assert_eq!(n.external_mb, 55); + assert_eq!(n.scratch_mb, 66); + assert_eq!(n.scratch_files, 77); + assert_eq!(n.scratch_root.as_deref(), Some("/tmp/x")); + } + + #[test] + fn output_caps_default_on() { + let c = CodeRunnerConfig::default(); + assert_eq!(c.max_result_bytes, 32_768); + assert_eq!(c.max_stream_bytes, 16_384); + } + + /// What `configuration::register` publishes and `configuration::set` + /// validates against must round-trip the defaults exactly. + #[test] + fn json_round_trips_the_defaults() { + let d = CodeRunnerConfig::default(); + assert_eq!(CodeRunnerConfig::from_json(&d.to_json()).unwrap(), d); + } + + #[test] + fn schema_names_every_field() { + let schema = CodeRunnerConfig::json_schema(); + let props = schema["properties"].as_object().unwrap(); + for field in [ + "max_runtimes", + "default_timeout_ms", + "max_timeout_ms", + "idle_ttl_secs", + "heap_mb", + "external_mb", + "scratch_mb", + "scratch_files", + "scratch_root", + "inject_guidance", + "max_result_bytes", + "max_stream_bytes", + ] { + assert!(props.contains_key(field), "schema lost `{field}`"); + } + } + + /// The reload handler's restart warning must fire for boot-captured + /// fields ONLY — a caps or timeout change is fully hot. + #[test] + fn restart_required_splits_hot_from_boot_fields() { + let base = CodeRunnerConfig::default(); + let hot = CodeRunnerConfig { + max_result_bytes: 1, + max_stream_bytes: 2, + default_timeout_ms: 3, + max_timeout_ms: 4, + inject_guidance: false, + ..base.clone() + }; + assert!(!base.restart_required(&hot)); + let boot = CodeRunnerConfig { + max_runtimes: base.max_runtimes + 1, + ..base.clone() + }; + assert!(base.restart_required(&boot)); + } +} diff --git a/code-runner/src/configuration.rs b/code-runner/src/configuration.rs new file mode 100644 index 0000000000..1e1ff95e92 --- /dev/null +++ b/code-runner/src/configuration.rs @@ -0,0 +1,202 @@ +//! Integration with the `configuration` worker (docs/sops/configuration.md, +//! Tier 1) — register the JSON Schema + optional seed at boot, read the +//! authoritative (env-expanded) value, and bind a `configuration` trigger so +//! `configuration:updated` re-fetches and swaps the snapshot. Mirrors +//! [`browser`](../../browser/src/configuration.rs). +//! +//! The output caps and timeout knobs are read per call and hot-apply on the +//! swap; the engine-structural fields are boot-captured, so the reload +//! handler warns when a change to them will only apply at the next restart +//! (see `CodeRunnerConfig::restart_required`). + +use std::sync::Arc; +use std::time::Duration; + +use iii_sdk::errors::Error; +use iii_sdk::protocol::{RegisterTriggerInput, TriggerRequest}; +use iii_sdk::{IIIClient, RegisterFunction}; +use serde_json::{json, Value}; + +use crate::config::{CodeRunnerConfig, SharedConfig}; + +pub const CONFIG_ID: &str = "code-runner"; +/// Internal hot-reload hook; denied to agents in iii-permissions.yaml and +/// seeded into the runtime-id registry (functions::seeded_ids) so a guest +/// `register_function` cannot claim it. +pub const CONFIG_FN_ID: &str = "code-runner::on-config-change"; +const CONFIG_TIMEOUT_MS: u64 = 5_000; +const CONFIG_RETRIES: u32 = 3; + +pub async fn register_config( + iii: &IIIClient, + seed: Option<&CodeRunnerConfig>, +) -> Result<(), String> { + let mut payload = json!({ + "id": CONFIG_ID, + "name": "code-runner", + "description": "Runtime limits for in-process Node.js/Python: output caps and timeouts \ + (hot-reload), plus runtime-count, memory, and scratch limits (applied \ + at worker restart).", + "schema": CodeRunnerConfig::json_schema(), + }); + if let Some(seed) = seed { + payload["initial_value"] = seed.to_json(); + } else if should_seed_default(iii).await? { + payload["initial_value"] = CodeRunnerConfig::default().to_json(); + } + trigger_with_retry(iii, "configuration::register", payload).await?; + Ok(()) +} + +pub async fn fetch_config(iii: &IIIClient) -> Result { + match try_get_value(iii).await? { + Some(v) if !v.is_null() => CodeRunnerConfig::from_json(&v), + _ => { + tracing::info!("no configuration value found; using built-in defaults"); + Ok(CodeRunnerConfig::default()) + } + } +} + +async fn should_seed_default(iii: &IIIClient) -> Result { + match try_get_value(iii).await? { + None => Ok(true), + Some(v) if v.is_null() => Ok(true), + Some(_) => Ok(false), + } +} + +/// `Ok(None)` when the entry does not exist yet. The engine's missing-entry +/// codes vary in case, so match case-insensitively. +async fn try_get_value(iii: &IIIClient) -> Result, String> { + match trigger_with_retry(iii, "configuration::get", json!({ "id": CONFIG_ID })).await { + Ok(resp) => Ok(resp.get("value").cloned()), + Err(e) if e.to_ascii_uppercase().contains("NOT_FOUND") => Ok(None), + Err(e) => Err(e), + } +} + +#[derive(Debug, Default, serde::Deserialize, schemars::JsonSchema)] +struct OnConfigChangeRequest {} + +#[derive(Debug, serde::Serialize, schemars::JsonSchema)] +struct OnConfigChangeResponse { + ok: bool, +} + +/// Register the internal reload hook and bind the `configuration` trigger. +/// Call LAST in boot, after every function and the console UI exist. +pub fn register_config_trigger(iii: &IIIClient, config: SharedConfig) -> Result<(), Error> { + let cfg = config.clone(); + let engine = iii.clone(); + iii.register_function( + CONFIG_FN_ID, + RegisterFunction::new_async(move |_req: OnConfigChangeRequest| { + let cfg = cfg.clone(); + let engine = engine.clone(); + async move { + refresh(&engine, &cfg).await; + Ok::(OnConfigChangeResponse { ok: true }) + } + }) + .description( + "Internal: reload code-runner settings from the authoritative configuration on \ + change. Output caps and timeouts hot-apply; runtime/memory/scratch limits apply \ + at the next worker restart.", + ) + .metadata(json!({ "internal": true })), + ); + + iii.register_trigger(RegisterTriggerInput { + trigger_type: "configuration".to_string(), + function_id: CONFIG_FN_ID.to_string(), + config: json!({ "configuration_id": CONFIG_ID, "event_types": ["configuration:updated"] }), + metadata: None, + })?; + Ok(()) +} + +/// Serializes every refresh's fetch→store. The fetch happens INSIDE the +/// lock, so whichever refresh stores later also fetched later — a slow, older +/// `configuration::get` response can never overwrite a newer snapshot. +static REFRESH_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// Re-fetch the AUTHORITATIVE value and swap the snapshot. The trigger +/// payload is deliberately ignored: `on-config-change` is a discoverable bus +/// function, and trusting a caller-supplied value would let anyone inject +/// config without updating persisted state. +/// +/// Called by the `configuration` trigger, and once more at the end of boot: +/// an update landing between the boot fetch and the trigger registration +/// fires into nothing, and without the boot refresh it would stay invisible +/// until the NEXT update or a restart. +pub async fn refresh(iii: &IIIClient, config: &SharedConfig) { + let _serialized = REFRESH_LOCK.lock().await; + match fetch_config(iii).await { + Ok(next) => { + if config.load().restart_required(&next) { + tracing::warn!( + "configuration changed a boot-captured field (runtimes/memory/scratch); \ + the change is saved but applies at the next worker restart" + ); + } + config.store(Arc::new(next)); + tracing::info!("code-runner configuration reloaded"); + } + Err(e) => tracing::error!(error = %e, "config-change: keeping previous config"), + } +} + +async fn trigger_with_retry( + iii: &IIIClient, + function_id: &str, + payload: Value, +) -> Result { + let mut last_err = String::new(); + for attempt in 1..=CONFIG_RETRIES { + match iii + .trigger(TriggerRequest { + function_id: function_id.to_string(), + payload: payload.clone(), + action: None, + timeout_ms: Some(CONFIG_TIMEOUT_MS), + }) + .await + { + Ok(v) => return Ok(v), + Err(e) => { + last_err = e.to_string(); + if attempt < CONFIG_RETRIES { + tracing::warn!( + function_id, + attempt, + error = %last_err, + "configuration RPC failed; retrying" + ); + tokio::time::sleep(Duration::from_millis(250 * u64::from(attempt))).await; + } + } + } + } + Err(format!( + "{function_id} failed after {CONFIG_RETRIES} attempts: {last_err}" + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The store()/load() path the reload handler uses: a swap must be + /// visible to the next per-call read. + #[test] + fn snapshot_swap_is_visible_to_readers() { + let shared = CodeRunnerConfig::default().into_shared(); + assert_eq!(shared.load().max_result_bytes, 32_768); + shared.store(Arc::new(CodeRunnerConfig { + max_result_bytes: 7, + ..CodeRunnerConfig::default() + })); + assert_eq!(shared.load().max_result_bytes, 7); + } +} diff --git a/code-runner/src/error.rs b/code-runner/src/error.rs new file mode 100644 index 0000000000..e2d2da54ba --- /dev/null +++ b/code-runner/src/error.rs @@ -0,0 +1,167 @@ +//! The worker's error taxonomy. Every variant maps to a stable +//! `code-runner::` wire code, matching sandbox-code-runner's +//! shape so a caller written against that worker needs no changes. +//! +//! One code is new: `resource_exhausted`. See its variant. + +use iii_sdk::errors::Error; + +/// Deliberate exception to the redaction convention: this type `Display`s +/// runtime ids to the holder — the caller who already supplied them. Every +/// other surface treats a `runtime_id` as a capability. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CodeRunnerError { + InvalidRequest(String), + RuntimeNotFound(String), + /// `teardown namespace=…` naming a namespace with no runtime behind it. + /// Same wire code as `RuntimeNotFound` (both mean "nothing addressable by + /// this"), a distinct variant only because the wording differs. + NamespaceNotFound(String), + /// The runtime is gone — reaped for idleness, or killed mid-call. + /// Re-create it. + Expired(String), + /// No runtime slot available. Admission failure: retrying later may work. + Capacity(String), + Timeout, + /// A registered handler threw, or returned something JSON cannot carry. + HandlerError(String), + /// A cap was hit mid-run — memory, or the scratch quota. + /// + /// NOT `capacity`, which is documented as an admission failure and means + /// "retry later, it may succeed". A mid-run resource kill fails identically + /// on every retry, so folding the two together would tell a caller the + /// opposite of the truth. One code for all such caps rather than three, + /// because the caller's action is the same in every case — shrink the + /// workload — and the message names which cap was hit. + ResourceExhausted(String), + Engine(String), +} + +impl CodeRunnerError { + pub fn code(&self) -> &'static str { + match self { + Self::InvalidRequest(_) => "code-runner::invalid_request", + Self::RuntimeNotFound(_) | Self::NamespaceNotFound(_) => { + "code-runner::runtime_not_found" + } + Self::Expired(_) => "code-runner::expired", + Self::Capacity(_) => "code-runner::capacity", + Self::Timeout => "code-runner::timeout", + Self::HandlerError(_) => "code-runner::handler_error", + Self::ResourceExhausted(_) => "code-runner::resource_exhausted", + Self::Engine(_) => "code-runner::engine", + } + } + + fn message(&self) -> String { + match self { + Self::InvalidRequest(m) => m.clone(), + Self::RuntimeNotFound(id) => format!("unknown runtime_id {id}"), + Self::NamespaceNotFound(ns) => format!( + "no runtime is registered for namespace {ns:?}; register a function in it \ + first, or pass a runtime_id instead" + ), + Self::Expired(id) => format!( + "runtime {id} expired: it was reaped or killed and its functions \ + unregistered — call run again without this runtime_id to get a fresh one \ + (its scratch directory starts empty)" + ), + Self::Capacity(m) => m.clone(), + Self::Timeout => "execution exceeded its deadline".into(), + Self::HandlerError(m) => m.clone(), + Self::ResourceExhausted(m) => m.clone(), + Self::Engine(m) => m.clone(), + } + } +} + +impl std::fmt::Display for CodeRunnerError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.code(), self.message()) + } +} + +impl std::error::Error for CodeRunnerError {} + +impl From for Error { + fn from(e: CodeRunnerError) -> Self { + Error::Handler(e.to_string()) + } +} + +/// Rewrite an error that would disclose a `runtime_id` the receiving caller +/// never held. +/// +/// `RuntimeNotFound`/`Expired` name their id deliberately — to the holder. +/// A caller who ran one-shot, or whose call was routed through a namespace +/// runtime they never addressed, is not that holder. +pub fn redact_unheld(e: CodeRunnerError) -> CodeRunnerError { + match e { + CodeRunnerError::RuntimeNotFound(_) | CodeRunnerError::Expired(_) => { + CodeRunnerError::Engine("the run's runtime was reaped or lost mid-run; retry".into()) + } + other => other, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_stable_wire_strings() { + for (e, code) in [ + ( + CodeRunnerError::InvalidRequest("x".into()), + "code-runner::invalid_request", + ), + ( + CodeRunnerError::RuntimeNotFound("r".into()), + "code-runner::runtime_not_found", + ), + ( + CodeRunnerError::NamespaceNotFound("n".into()), + "code-runner::runtime_not_found", + ), + (CodeRunnerError::Expired("r".into()), "code-runner::expired"), + ( + CodeRunnerError::Capacity("x".into()), + "code-runner::capacity", + ), + (CodeRunnerError::Timeout, "code-runner::timeout"), + ( + CodeRunnerError::HandlerError("x".into()), + "code-runner::handler_error", + ), + ( + CodeRunnerError::ResourceExhausted("x".into()), + "code-runner::resource_exhausted", + ), + (CodeRunnerError::Engine("x".into()), "code-runner::engine"), + ] { + assert_eq!(e.code(), code, "wrong code for {e:?}"); + } + } + + #[test] + fn display_is_code_colon_message() { + assert_eq!( + CodeRunnerError::RuntimeNotFound("rt-7".into()).to_string(), + "code-runner::runtime_not_found: unknown runtime_id rt-7" + ); + } + + /// A caller who never supplied a runtime_id must not learn one. Mutation: + /// make `redact_unheld` the identity function. + #[test] + fn an_unheld_runtime_id_is_never_disclosed() { + let redacted = redact_unheld(CodeRunnerError::Expired("rt-secret".into())); + assert!(!redacted.to_string().contains("rt-secret")); + assert_eq!(redacted.code(), "code-runner::engine"); + // Everything else passes through untouched. + assert_eq!( + redact_unheld(CodeRunnerError::Timeout).code(), + "code-runner::timeout" + ); + } +} diff --git a/code-runner/src/functions/inject_guidance.rs b/code-runner/src/functions/inject_guidance.rs new file mode 100644 index 0000000000..687b6a850c --- /dev/null +++ b/code-runner/src/functions/inject_guidance.rs @@ -0,0 +1,235 @@ +//! `code-runner::inject-guidance` — a `pre_generate` hook that contributes the +//! `code-runner::*` usage guidance to the agent's system prompt, ONLY while this +//! worker is connected. The binding dies with the worker, so the guidance is +//! presence-gated for free: a deployment without code-runner never pays for it, +//! and the text is never hand-duplicated into a static harness prompt. +//! +//! Mirrors `web/src/functions/inject_guidance.rs`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +pub const GUIDANCE_HOOK_ID: &str = "code-runner::inject-guidance"; +pub const GUIDANCE_HOOK_DESC: &str = + "Internal pre_generate hook: appends code-runner usage guidance to the agent system \ + prompt. Bound to harness::hook::pre-generate at worker startup; not called directly. \ + Silenced by inject_guidance: false in the code-runner configuration."; + +/// The single canonical copy of the code-runner usage guidance. Pure USAGE +/// guidance: the hook only fires while this worker is present, so it carries no +/// "look for it / install it" discovery text. +const NODE_ENGINE_GUIDANCE: &str = "To run JavaScript or Python — computing something, reshaping data, or exposing a piece of logic other workers can call — use `code-runner::*` rather than a throwaway script through `shell::exec`. `code-runner::run` evaluates code in a V8 isolate: your code is wrapped in an async IIFE, so `return` sets the result and top-level `await` works. Pass `lang: \"python\"` to run Python instead — python code is a MODULE, not a function body: assign `result = x` to yield a value (a top-level `return` is a SyntaxError), its `iii` is synchronous (`iii.trigger({...})`, no await), and it gets a persistent `/work` directory in place of `iii.files`. By default `run` is ONE-SHOT — it creates a runtime, evaluates the code, and disposes the runtime before responding, so the response carries no `runtime_id`. Pass `keep: true` to leave the runtime running instead: the response's `runtime_id` then addresses it, and is the capability `code-runner::teardown` needs to stop it later — treat `runtime_id` as a secret. Pass `runtime_id` on a later call to reuse that same isolate, sharing its globals and registrations; a runtime you supplied `runtime_id` for is never disposed by that call, you own it until you tear it down. Inside evaluated code the only host surface is the `iii` global: `await iii.trigger({function_id, payload, action?, timeout?})` calls any engine function; `iii.registerFunction(functionId, handler, options?)` publishes a live function for the life of this runtime and returns `{unregister()}`; `iii.registerTrigger(input)`, `iii.registerTriggerType(triggerType, handler)` and `iii.unregisterTriggerType(triggerType)` are also available; `iii.namespace` is the prefix this runtime may register under; `iii.shutdown()` throws by design, pointing you at `code-runner::teardown` instead — the connection belongs to the worker, shared by every runtime on it; `console` output comes back in `logs`. To publish a JS function on the bus without hand-authoring a run payload, use `code-runner::register_function`: one function per call, `{function_id: \"my-app::greet\", source: \"export function handler(p) { return p.n * 2 }\", description: \"what it does\"}`. `source` must DEFINE `handler(payload)` — `export function handler(p) {...}` and `const handler = ...` both work (`export` is only recognised as the very FIRST token of `source`); a bare expression like `\"(p) => p.n * 2\"` is refused, since nothing is bound to that name. The segment before the first `::` in `function_id` is the namespace: code-runner keeps one persistent runtime per namespace and language, created by the first registration and reused by every later one of that lang, as an implementation detail you never see or manage — there is no `runtime_id` for it to hand back. Always write a `description`: it is what `engine::functions::info` shows the next caller — and pass `request_format`/`response_format` (JSON Schema objects) when callers must know the payload shape; `engine::functions::info` then shows the real schemas instead of \"any\" — catalog metadata, not call-time validation: the handler still receives whatever payload arrives, so validate inside the handler. An id another runtime already holds is refused as `code-runner::invalid_request`, its message saying the id is already registered. Registrations live exactly as long as their runtime: call `code-runner::teardown` with `runtime_id` or `namespace` (exactly one) when the work is done — everything that runtime registered stops resolving the moment it is torn down or swept for being idle, so do not register a function and walk away expecting it to answer later. This is plain V8, NOT Node: there is no npm, no `require`, no `fs`, no `fetch`, and no Node builtins — not even `global`; state that must survive later calls on a kept runtime goes on `globalThis`. Fetch exact request shapes via `engine::functions::info` before the first call."; + +/// The slice of the `pre_generate` hook envelope we read (lenient: ignores every +/// other field the harness sends). The harness nests the live generation context +/// under `generate`. +#[derive(Debug, Default, Deserialize, JsonSchema)] +pub struct PreGenerateEvent { + #[serde(default)] + pub generate: GenerateContext, +} + +#[derive(Debug, Default, Deserialize, JsonSchema)] +pub struct GenerateContext { + /// The system prompt assembled so far (base + any prior hook's mutation). + #[serde(default)] + pub system_prompt: String, +} + +/// Hook envelope returned to the harness: the mutations to apply to the +/// generation. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PreGenerateResponse { + pub mutations: PreGenerateMutations, +} + +/// The harness applies `system_prompt` only when the key is present, so `None` +/// serializes to an empty object: the safe no-op that preserves the harness's +/// assembled prompt. +#[derive(Debug, Default, Serialize, JsonSchema)] +pub struct PreGenerateMutations { + /// Full replacement system prompt (base + appended guidance). The harness + /// overwrites, it does not merge. + #[serde(skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, +} + +/// Build the `pre_generate` mutations for a given base prompt. Pure, so it is +/// unit-testable. +/// +/// Returns NO `system_prompt` when disabled (`inject_guidance: false` in the +/// live configuration) or when `base` is empty. A missing or renamed +/// `generate.system_prompt` deserializes to `""` (schema drift), and a fail-open +/// hook must PRESERVE the harness's assembled prompt, never replace it with the +/// guidance alone. +fn mutations_for(base: &str, enabled: bool) -> PreGenerateMutations { + if !enabled || base.is_empty() { + PreGenerateMutations::default() + } else { + PreGenerateMutations { + system_prompt: Some(format!("{base}\n\n{NODE_ENGINE_GUIDANCE}")), + } + } +} + +/// `pre_generate` hook entrypoint. Bound `fail_open`, so an error here never +/// blocks a turn. +/// +/// `enabled` is the live `inject_guidance` config knob, read per call by the +/// registration closure so a configuration save applies to the very next +/// turn. +// ponytail: the hook stays bound while disabled — one no-op roundtrip per +// generation; re-bind the trigger on config change if that ever matters. +pub async fn handle( + event: PreGenerateEvent, + enabled: bool, +) -> Result { + Ok(PreGenerateResponse { + mutations: mutations_for(&event.generate.system_prompt, enabled), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn appends_guidance_after_a_real_base() { + let m = mutations_for("BASE PROMPT", true); + let sp = m + .system_prompt + .expect("a non-empty base yields a system_prompt mutation"); + assert!( + sp.starts_with("BASE PROMPT\n\n"), + "the base prompt must be preserved, guidance appended after it" + ); + assert!(sp.contains("code-runner::run"), "guidance content present"); + } + + #[test] + fn empty_base_emits_no_system_prompt_mutation() { + // A missing/malformed hook payload (system_prompt absent → "") must + // PRESERVE the harness prompt: emit no system_prompt key, rather than + // replacing the whole prompt with the guidance alone. The wire shape + // must stay `{"mutations": {}}`. + let wire = serde_json::to_value(PreGenerateResponse { + mutations: mutations_for("", true), + }) + .expect("response serializes"); + assert_eq!(wire, serde_json::json!({ "mutations": {} })); + } + + #[test] + fn disabled_emits_the_no_op_mutation() { + // `inject_guidance: false` must be indistinguishable on the wire from + // the fail-safe no-op: `{"mutations": {}}`, never a prompt rewrite. + let wire = serde_json::to_value(PreGenerateResponse { + mutations: mutations_for("BASE PROMPT", false), + }) + .expect("response serializes"); + assert_eq!(wire, serde_json::json!({ "mutations": {} })); + } + + /// Mirrors the registry publish gate: the derived response schema must + /// carry a schema-defining keyword, not the permissive AnyValue schema. + #[test] + fn response_schema_passes_the_publish_typed_gate() { + let schema = schemars::r#gen::SchemaSettings::draft07() + .into_generator() + .into_root_schema_for::(); + let value = serde_json::to_value(schema).expect("schema serializes"); + let obj = value.as_object().expect("schema is an object"); + assert!( + ["type", "properties", "$ref"] + .iter() + .any(|k| obj.contains_key(*k)), + "PreGenerateResponse schema is untyped: {value}" + ); + } + + #[test] + fn guidance_covers_this_worker_s_surface() { + // Each needle is a fact an agent gets wrong without the guidance: the + // three function ids, that it is NOT Node, that the description field + // exists, and that runtime_id is a capability. + for needle in [ + "code-runner::run", + "code-runner::register_function", + "code-runner::teardown", + "NOT Node", + "no npm", + "engine::functions::info", + "treat `runtime_id` as a secret", + "keep: true", + "iii.namespace", + "stops resolving the moment it is torn down", + // The two an agent gets wrong without being told, each one + // observed rather than imagined: `source` must bind a name + // (not just evaluate to a function), and `shutdown` throwing + // rather than silently no-op-ing. + "must DEFINE `handler(payload)`", + "iii.shutdown()", + "throws by design", + // Observed: an agent wrote Node-idiom `global.counter` and got + // `ReferenceError: global is not defined` — the `lang: "node"` + // name primes the Node mental model, so the guidance must name + // the standard alias. + "goes on `globalThis`", + // The id-clash sentence must quote the REAL wire code: this + // worker's taxonomy has no `id_taken` (error.rs), and guidance + // inventing one taught agents to match a phantom code. + "code-runner::invalid_request", + // Without this an agent has no way to know the catalog can show + // real schemas — the register card and functions::info both said + // "any" for every dynamic registration until these fields. + "request_format", + // Observed in dogfooding: an agent read the schema in + // functions::info and assumed the boundary enforces it. It does + // not — nothing on this bus does — and guidance that shows a + // schema without saying so invites handlers with no input checks. + "not call-time validation", + // The other dogfooding finding: agents mix the two return + // conventions and learn only from the first silent null. The + // guidance was a JavaScript-only document until this clause. + "assign `result = x`", + ] { + assert!( + NODE_ENGINE_GUIDANCE.contains(needle), + "guidance is missing: {needle}" + ); + } + } + + /// Guidance is the first thing an agent reads about this worker. Text + /// describing a removed function is worse than no text: it produces calls + /// that cannot succeed. + #[test] + fn guidance_describes_only_functions_that_exist() { + for gone in [ + "register_worker", + "eject", + "code-runner::eval", + "callFunction", + // Not a wire code (error.rs) — an id clash is re-coded to + // `code-runner::invalid_request`, and guidance quoting `id_taken` + // taught agents to match a code that never arrives. + "id_taken", + ] { + assert!( + !NODE_ENGINE_GUIDANCE.contains(gone), + "guidance still mentions {gone}" + ); + } + for present in [ + "code-runner::run", + "code-runner::register_function", + "iii.trigger", + "keep", + ] { + assert!( + NODE_ENGINE_GUIDANCE.contains(present), + "guidance never mentions {present}" + ); + } + } +} diff --git a/code-runner/src/functions/mod.rs b/code-runner/src/functions/mod.rs new file mode 100644 index 0000000000..718b2f172f --- /dev/null +++ b/code-runner/src/functions/mod.rs @@ -0,0 +1,198 @@ +//! The statically registered `code-runner::*` functions. +//! +//! Each `.rs` holds its typed request/response structs; the handler +//! bodies are thin wrappers over `Manager`, which is what the tests drive +//! directly. + +pub mod inject_guidance; +pub mod register; +pub mod run; +pub mod teardown; + +use std::sync::Arc; + +use iii_sdk::{IIIClient, RegisterFunction}; + +use crate::manager::Manager; + +pub const RUN_ID: &str = "code-runner::run"; +/// Contract essentials only — the injected harness guidance +/// (`inject_guidance`) teaches the full surface, and every extra byte here +/// is paid on each catalog read. +pub const RUN_DESC: &str = + "Run code in an in-process sandbox — lang \"node\" or \"python\"; no network, no host \ + filesystem, no package installs. One-shot by default; keep: true returns a runtime_id, \ + and passing runtime_id later reuses that runtime (same globals and scratch) until \ + code-runner::teardown or the idle TTL reaps it (then: code-runner::expired — retry \ + without runtime_id). Code gets an `iii` global for bus calls. stdout/stderr/exit_code \ + come back verbatim — a failing script is a response, not an error — and `result` \ + carries the returned value: node code is a FUNCTION BODY (`return x`), python a MODULE \ + (assign `result = x`)."; + +pub const TEARDOWN_ID: &str = "code-runner::teardown"; +pub const TEARDOWN_DESC: &str = "Destroy a runtime: unregister every bus function it registered, \ + kill it, and free its slot. Pass exactly one of runtime_id (a kept run's runtime, from \ + code-runner::run keep=true) or namespace (a register_function namespace, e.g. \"app\" for \ + ids like app::greet) — never both, never neither."; + +pub const REGISTER_ID: &str = "code-runner::register_function"; +pub const REGISTER_DESC: &str = "Publish a bus function whose handler runs in a sandbox. \ + `source` must DEFINE handler(payload) in `lang`; one persistent runtime per namespace \ + (function_id before `::`) AND lang is booted by the first registration and shared by \ + later ones. Write a `description` for callers. Optional `request_format` / \ + `response_format` (JSON Schema objects, max 16 KiB) are shown by engine::functions::info \ + but NOT enforced at call time — validate inside the handler. Registrations stop \ + resolving when the namespace is torn down or its runtime reaped for idleness."; + +/// Every id this worker registers on its own client, in registration order. +/// +/// The order is `run, teardown, register_function, inject-guidance`, matching +/// sandbox-code-runner's own — including the odd teardown-before-register +/// placement. `catalog()` and the golden schema snapshots agree with it, so +/// do not "fix" the ordering. +pub const STATIC_IDS: &[&str] = &[ + RUN_ID, + TEARDOWN_ID, + REGISTER_ID, + inject_guidance::GUIDANCE_HOOK_ID, +]; + +/// Every id this worker owns, for seeding the runtime manager's id registry. +/// +/// STRICTLY LARGER than `STATIC_IDS`, which is only what `register_all` +/// registers: the console UI's content function is published later, by +/// `crate::ui::register`, and it must be seeded all the same. +/// +/// Why it matters. The registry is what stops a caller claiming an id the +/// worker already holds. `register_function` lets a caller pick ANY namespace, +/// including `code-runner::`, so an unseeded worker id can be claimed — and the +/// claim then reaches `iii_sdk`'s `register_function` on an id that is already +/// registered, whose duplicate-id panic ABORTS THE PROCESS. Verified +/// reachable: before `ui-content` was seeded, +/// `register_function("code-runner::ui-content", …)` returned +/// `registered: true`. +pub fn seeded_ids() -> Vec<&'static str> { + let mut ids = STATIC_IDS.to_vec(); + ids.push(crate::ui::CONTENT_FUNCTION_ID); + // Registered by `configuration::register_config_trigger`, after this seed + // exists — same reasoning as `ui-content` above. + ids.push(crate::configuration::CONFIG_FN_ID); + ids +} + +pub fn register_all(iii: &Arc, manager: &Arc) { + let mut registered: Vec<&str> = Vec::new(); + + let m = manager.clone(); + registered.push(RUN_ID); + iii.register_function( + RUN_ID, + RegisterFunction::new_async(move |req: run::RunRequest| { + let m = m.clone(); + async move { m.run(req).await.map_err(iii_sdk::errors::Error::from) } + }) + .description(RUN_DESC), + ); + + let m = manager.clone(); + registered.push(TEARDOWN_ID); + iii.register_function( + TEARDOWN_ID, + RegisterFunction::new_async(move |req: teardown::TeardownRequest| { + let m = m.clone(); + async move { m.teardown(req).await.map_err(iii_sdk::errors::Error::from) } + }) + .description(TEARDOWN_DESC), + ); + + let m = manager.clone(); + registered.push(REGISTER_ID); + iii.register_function( + REGISTER_ID, + RegisterFunction::new_async(move |req: register::RegisterRequest| { + let m = m.clone(); + async move { m.register(req).await.map_err(iii_sdk::errors::Error::from) } + }) + .description(REGISTER_DESC), + ); + + let cfg = manager.shared_config(); + registered.push(inject_guidance::GUIDANCE_HOOK_ID); + iii.register_function( + inject_guidance::GUIDANCE_HOOK_ID, + RegisterFunction::new_async(move |event: inject_guidance::PreGenerateEvent| { + let enabled = cfg.load().inject_guidance; + async move { inject_guidance::handle(event, enabled).await } + }) + .description(inject_guidance::GUIDANCE_HOOK_DESC) + // The harness calls this, never an agent; it must not show up as a + // callable option alongside run/register_function/teardown. + .metadata(serde_json::json!({ "internal": true })), + ); + + assert_eq!( + registered, STATIC_IDS, + "register_all must register exactly STATIC_IDS, in order: the id registry is seeded \ + from that list, and an unseeded registration lets a runtime claim a worker id" + ); + + tracing::info!("code-runner functions registered"); +} + +/// Bind the `pre_generate` hook so the guidance reaches the agent's system +/// prompt while this worker is connected. +/// +/// `on_error: fail_open` is MANDATORY. `pre_generate` defaults to +/// fail-CLOSED, so an error or timeout here would abort the agent's turn; a +/// missing guidance line must never do that. +pub fn setup_harness_hooks(iii: &Arc) { + match iii.register_trigger(iii_sdk::protocol::RegisterTriggerInput { + trigger_type: "harness::hook::pre-generate".to_string(), + function_id: inject_guidance::GUIDANCE_HOOK_ID.to_string(), + config: serde_json::json!({ "on_error": "fail_open" }), + metadata: None, + }) { + Ok(_) => tracing::info!("code-runner pre-generate hook bound"), + Err(e) => tracing::warn!(error = %e, "guidance hook binding failed; continuing without it"), + } +} + +pub struct FunctionSpec { + pub function_id: &'static str, + pub description: &'static str, + pub request_schema: schemars::schema::RootSchema, + pub response_schema: schemars::schema::RootSchema, +} + +/// MUST mirror iii-sdk's internal `json_schema_for` (draft07) so a catalog +/// snapshot pins exactly what registration emits. +fn schema_of() -> schemars::schema::RootSchema { + schemars::r#gen::SchemaSettings::draft07() + .into_generator() + .into_root_schema_for::() +} + +fn spec(function_id: &'static str, description: &'static str) -> FunctionSpec +where + Req: schemars::JsonSchema, + Resp: schemars::JsonSchema, +{ + FunctionSpec { + function_id, + description, + request_schema: schema_of::(), + response_schema: schema_of::(), + } +} + +pub fn catalog() -> Vec { + vec![ + spec::(RUN_ID, RUN_DESC), + spec::(TEARDOWN_ID, TEARDOWN_DESC), + spec::(REGISTER_ID, REGISTER_DESC), + spec::( + inject_guidance::GUIDANCE_HOOK_ID, + inject_guidance::GUIDANCE_HOOK_DESC, + ), + ] +} diff --git a/code-runner/src/functions/register.rs b/code-runner/src/functions/register.rs new file mode 100644 index 0000000000..332367debd --- /dev/null +++ b/code-runner/src/functions/register.rs @@ -0,0 +1,56 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::lang::Lang; + +#[derive(Deserialize, JsonSchema)] +pub struct RegisterRequest { + /// e.g. `my-app::greet`. The segment before the first `::` is the + /// namespace. Each language keeps its own persistent runtime per + /// namespace, created by its first registration — a namespace can hold + /// node and python ids side by side. + pub function_id: String, + /// Source that DEFINES `handler(payload)` in `lang`. + /// + /// Node publishes itself, by calling `iii.registerFunction`. Python's + /// source just defines the name — the host publishes it — and anything + /// else the source defines stays available to every later invocation, + /// because the namespace runs on one pinned interpreter. + pub source: String, + /// What `engine::functions::info` shows a caller — write one. + #[serde(default)] + pub description: Option, + /// Optional JSON Schema for the payload the registered function expects — + /// `engine::functions::info` then shows it in place of "any". Must be a + /// JSON object that actually constrains something (`type`, `properties`, + /// `$ref`, …); at most 16 KiB serialized. + #[serde(default)] + pub request_format: Option, + /// Optional JSON Schema for the value the handler returns; same rules as + /// `request_format`. + #[serde(default)] + pub response_format: Option, + /// Which engine backs this namespace. Required here, unlike on `run`: a + /// registration has no runtime to infer it from. + pub lang: Lang, +} + +// `source` is the tenant's own program. +impl std::fmt::Debug for RegisterRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RegisterRequest") + .field("function_id", &self.function_id) + .field("source", &"") + .field("description", &self.description) + .field("request_format", &self.request_format) + .field("response_format", &self.response_format) + .field("lang", &self.lang) + .finish() + } +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct RegisterResponse { + pub function_id: String, + pub registered: bool, +} diff --git a/code-runner/src/functions/run.rs b/code-runner/src/functions/run.rs new file mode 100644 index 0000000000..70bef9e9b9 --- /dev/null +++ b/code-runner/src/functions/run.rs @@ -0,0 +1,138 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::lang::Lang; + +#[derive(Deserialize, JsonSchema)] +pub struct RunRequest { + /// Node: the body of an async function — `return x` yields the result, + /// top-level `await` works. Python: a module — assign `result = x`. Both + /// get a global `iii` that can trigger any bus function; node's can also + /// register functions for the life of the runtime and reach its private + /// scratch directory via `iii.files`, python's is synchronous and gets + /// `/work` instead. + pub code: String, + /// Run in a SPECIFIC runtime, sharing its scratch directory and its + /// globals: the run lands in that runtime and it is NOT destroyed + /// afterwards — you own it. Omit this to run one-shot (see `keep`). + #[serde(default)] + pub runtime_id: Option, + /// Required when `runtime_id` is omitted — picks the engine ("node" or + /// "python"). On an existing runtime: omit it, or pass the runtime's own + /// language; languages cannot be mixed in one runtime. + #[serde(default)] + pub lang: Option, + /// Only meaningful when `runtime_id` is omitted. `false` (the default): + /// one-shot — create a runtime, run `code`, return the result, destroy + /// it. Nothing persists. `true`: leave it running; the response's + /// `runtime_id` addresses it for later runs and is the capability + /// `code-runner::teardown` needs to stop it. + #[serde(default)] + pub keep: bool, + /// Wall-clock budget in milliseconds, clamped to the configured maximum. + #[serde(default)] + pub timeout_ms: Option, +} + +// `code` is the tenant's own program and `runtime_id` is a capability; +// neither may reach a log line through a stray `{:?}`. Hand-rolled rather +// than derived for exactly that reason — the sibling engines learned this the +// hard way, four separate times in one branch. +impl std::fmt::Debug for RunRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunRequest") + .field("code", &"") + .field( + "runtime_id", + &self.runtime_id.as_ref().map(|_| ""), + ) + .field("lang", &self.lang) + .field("keep", &self.keep) + .field("timeout_ms", &self.timeout_ms) + .finish() + } +} + +#[derive(Serialize, JsonSchema)] +pub struct RunResponse { + /// Present when this run addresses a runtime that outlives the call — a + /// `keep: true` run that SUCCEEDED, or a `runtime_id` echoed back. + /// Absent, not null, otherwise: there is nothing to address. Treat a + /// present value as a secret. + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_id: Option, + pub stdout: String, + pub stderr: String, + pub exit_code: i64, + pub success: bool, + pub duration_ms: u64, + /// The completion value: what the code returned (node) or assigned to + /// `result` (python). Null when it returned nothing, when it returned + /// something JSON cannot represent, or when the run failed. + /// + /// Always present, never skipped — unlike `runtime_id`, a null result is + /// information ("the code returned nothing") rather than an absence. + pub result: serde_json::Value, +} + +impl std::fmt::Debug for RunResponse { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunResponse") + .field( + "runtime_id", + &self.runtime_id.as_ref().map(|_| ""), + ) + .field("stdout", &"") + .field("stderr", &"") + .field("exit_code", &self.exit_code) + .field("success", &self.success) + .field("duration_ms", &self.duration_ms) + .field("result", &"") + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `runtime_id` is a capability, so its absence must be an ABSENT key, + /// not `null` — a caller checking `'runtime_id' in response` has to get + /// the right answer. Mutation: drop `skip_serializing_if`. + #[test] + fn the_response_omits_runtime_id_entirely_when_absent() { + let r = RunResponse { + runtime_id: None, + stdout: String::new(), + stderr: String::new(), + exit_code: 0, + success: true, + duration_ms: 1, + result: serde_json::Value::Null, + }; + let v = serde_json::to_value(&r).unwrap(); + assert!(v.get("runtime_id").is_none(), "key must be absent: {v}"); + // `result` is the opposite case and must survive as an explicit null. + assert_eq!(v.get("result"), Some(&serde_json::Value::Null)); + } + + /// Mutation: derive `Debug` on either struct. Both would then print the + /// tenant's program and the capability. + #[test] + fn debug_redacts_the_code_and_the_capability() { + let req = RunRequest { + code: "SECRET_SOURCE".into(), + runtime_id: Some("rt-secret".into()), + lang: Some(Lang::Node), + keep: true, + timeout_ms: Some(5), + }; + let s = format!("{req:?}"); + assert!(!s.contains("SECRET_SOURCE"), "{s}"); + assert!(!s.contains("rt-secret"), "{s}"); + assert!( + s.contains("Node") && s.contains("keep"), + "diagnostics survive: {s}" + ); + } +} diff --git a/code-runner/src/functions/teardown.rs b/code-runner/src/functions/teardown.rs new file mode 100644 index 0000000000..55c347b4ab --- /dev/null +++ b/code-runner/src/functions/teardown.rs @@ -0,0 +1,40 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Exactly one of `runtime_id` (a kept run's runtime) or `namespace` (a +/// `register_function` namespace) must be set — never both, never neither. +#[derive(Deserialize, JsonSchema)] +pub struct TeardownRequest { + #[serde(default)] + pub runtime_id: Option, + #[serde(default)] + pub namespace: Option, +} + +impl std::fmt::Debug for TeardownRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TeardownRequest") + .field( + "runtime_id", + &self.runtime_id.as_ref().map(|_| ""), + ) + .field("namespace", &self.namespace) + .finish() + } +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct TeardownResponse { + /// Set when this teardown was addressed by `runtime_id`. + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_id: Option, + /// Set when addressed by `namespace` — echoed in its canonical `app::` + /// form, since more than one runtime (one per language) can back it and + /// there is no single `runtime_id` to report. + #[serde(skip_serializing_if = "Option::is_none")] + pub namespace: Option, + pub torn_down: bool, + /// Bus function ids this teardown unregistered, across every runtime it + /// destroyed. + pub unregistered: Vec, +} diff --git a/code-runner/src/lang.rs b/code-runner/src/lang.rs new file mode 100644 index 0000000000..d252d7d728 --- /dev/null +++ b/code-runner/src/lang.rs @@ -0,0 +1,43 @@ +use serde::{Deserialize, Serialize}; + +/// Which engine backs a runtime. +/// +/// Only `node` and `python` are accepted; anything else fails deserialization +/// before a handler runs, so the schema itself is the validation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum Lang { + Node, + Python, +} + +impl std::fmt::Display for Lang { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Node => "node", + Self::Python => "python", + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_two_known_languages_deserialize() { + assert_eq!( + serde_json::from_str::("\"node\"").unwrap(), + Lang::Node + ); + assert_eq!( + serde_json::from_str::("\"python\"").unwrap(), + Lang::Python + ); + assert!(serde_json::from_str::("\"ruby\"").is_err()); + // The wire spelling is lowercase; `Display` must agree with it, since + // error messages name the language back to the caller. + assert_eq!(Lang::Node.to_string(), "node"); + assert_eq!(Lang::Python.to_string(), "python"); + } +} diff --git a/code-runner/src/lib.rs b/code-runner/src/lib.rs new file mode 100644 index 0000000000..69ae1221a7 --- /dev/null +++ b/code-runner/src/lib.rs @@ -0,0 +1,20 @@ +//! code-runner: run untrusted Node.js and Python in-process. +//! +//! One worker over two sandboxes — `iii-node-core` (V8 isolates) and, from +//! phase 5, `iii-python-core` (CPython on WebAssembly) — behind +//! sandbox-code-runner's wire contract, so a caller written against that +//! worker needs no changes. What differs is documented in the README: no +//! network, therefore no npm/pip, and no `/dev/kvm` requirement. + +pub mod config; +pub mod configuration; +pub mod error; +pub mod functions; +pub mod lang; +pub mod manager; +pub mod manifest; +pub mod node_bus; +pub mod python_bus; +pub mod translate; +pub mod truncate; +pub mod ui; diff --git a/code-runner/src/main.rs b/code-runner/src/main.rs new file mode 100644 index 0000000000..7fa568c2a5 --- /dev/null +++ b/code-runner/src/main.rs @@ -0,0 +1,185 @@ +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::Parser; +use code_runner::manager::Manager; +use code_runner::node_bus::IIIEngine; +use code_runner::{config, configuration, functions, manifest}; +use iii_helpers::observability::OtelConfig; +use iii_node_core::manager::RuntimeManager; +use iii_node_core::runtime; +use iii_sdk::runtime::WorkerMetadata; +use iii_sdk::{register_worker, InitOptions}; + +#[derive(Parser, Debug)] +#[command( + name = "code-runner", + version, + about = "Run untrusted Node.js and Python in-process, no microVM required" +)] +struct Cli { + /// Optional one-time seed for the `configuration` worker: installed as + /// the initial value on first registration, never overwrites a stored + /// value. The configuration worker is the authoritative runtime config. + #[arg(long)] + config: Option, + + /// WebSocket URL of the iii engine. + #[arg(long, env = "III_URL", default_value = "ws://127.0.0.1:49134")] + url: String, + + /// Print the registry manifest as JSON and exit without connecting. + #[arg(long)] + manifest: bool, +} + +fn worker_metadata() -> WorkerMetadata { + WorkerMetadata { + runtime: "rust".to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + name: "code-runner".to_string(), + os: std::env::consts::OS.to_string(), + pid: Some(std::process::id()), + telemetry: None, + ..WorkerMetadata::default() + } +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .init(); + + let cli = Cli::parse(); + + if cli.manifest { + println!( + "{}", + serde_json::to_string_pretty(&manifest::build_manifest()).unwrap() + ); + return Ok(()); + } + + let iii = Arc::new(register_worker( + &cli.url, + InitOptions { + otel: Some(OtelConfig::default()), + metadata: Some(worker_metadata()), + ..InitOptions::default() + }, + )); + + // The configuration worker is a REQUIRED boot dependency + // (docs/sops/configuration.md): register the schema (+ optional one-time + // seed), then read the authoritative value. A seed that fails to parse + // warns and falls through — the stored value or built-in default applies. + let seed = cli + .config + .as_deref() + .and_then(|p| match config::load_config(p) { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, path = %p, "failed to parse --config seed; ignoring it"); + None + } + }); + configuration::register_config(&iii, seed.as_ref()) + .await + .map_err(anyhow::Error::msg) + .context("registering code-runner configuration schema")?; + let cfg = configuration::fetch_config(&iii) + .await + .map_err(anyhow::Error::msg) + .context("loading code-runner configuration")?; + + // Once per process, before any isolate exists. + runtime::init_v8_platform(); + + // One `Engine` shared by both halves: node-core registers through it from + // its ops, and the router registers python handlers through it directly. + let engine = Arc::new(IIIEngine::new(iii.clone())); + // `seeded_ids`, not `STATIC_IDS`: the console UI's content function is + // registered after this, and an unseeded worker id is claimable through + // `register_function` — which ends in the SDK's duplicate-id abort. + let node = RuntimeManager::new( + Arc::new(cfg.node()), + engine.clone(), + &functions::seeded_ids(), + ); + // Booting the python engine extracts and compiles the embedded CPython + // artifact, which can fail on a host with no writable cache. Degrade to + // node-only and say so loudly rather than refusing to start: a node-only + // deployment losing its whole worker to a python problem is the wrong + // trade, and every python call reports the reason. + let python = match iii_python_core::runner::Runner::boot() { + Ok(runner) => Some(iii_python_core::manager::Manager::with_bridge( + Arc::new(cfg.python()), + runner, + Arc::new(code_runner::python_bus::IIIBridge::new(iii.clone())), + )), + Err(e) => { + tracing::error!( + error = %e, + "python engine failed to start; code-runner will serve node only and refuse \ + lang=\"python\"" + ); + None + } + }; + + tracing::info!( + max_runtimes = cfg.max_runtimes, + heap_mb = cfg.heap_mb, + scratch_mb = cfg.scratch_mb, + "code-runner ready" + ); + + // The engines above captured the structural fields; the shared snapshot + // serves the per-call knobs and is what the configuration trigger swaps. + let shared = cfg.into_shared(); + let manager = Manager::new(shared.clone(), node, engine, python); + functions::register_all(&iii, &manager); + // After the functions: the UI's renderers key off function ids, so there + // is nothing for a console to render until those exist. + code_runner::ui::register(&iii); + functions::setup_harness_hooks(&iii); + // LAST, so the reload handler closes over fully-built state. + configuration::register_config_trigger(&iii, shared.clone()) + .context("registering the configuration change trigger")?; + // An update between the boot fetch and the trigger registration above + // fired into nothing; one refresh now closes that window (serialized + // with trigger-driven refreshes inside `refresh` itself). + configuration::refresh(&iii, &shared).await; + + // Backstop for callers that never call teardown. + let sweeper = manager.clone(); + let ttl = manager.idle_ttl_secs(); + tokio::spawn(async move { + let mut ticker = tokio::time::interval(std::time::Duration::from_secs(ttl.clamp(1, 60))); + loop { + ticker.tick().await; + // An unguarded panic here would kill the task silently — `main` is + // parked on ctrl_c and would never notice — and idle runtimes would + // accumulate until `max_runtimes` is exhausted. + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| sweeper.sweep_idle())) { + Ok(reaped) if !reaped.is_empty() => { + tracing::info!(count = reaped.len(), "reaped idle runtimes"); + } + Ok(_) => {} + Err(_) => tracing::error!( + "idle-runtime sweep panicked; runtimes whose callers never call \ + code-runner::teardown will accumulate until max_runtimes is exhausted" + ), + } + } + }); + + tokio::signal::ctrl_c().await?; + tracing::info!("code-runner shutting down"); + iii.shutdown_async().await; + Ok(()) +} diff --git a/code-runner/src/manager.rs b/code-runner/src/manager.rs new file mode 100644 index 0000000000..c630f55833 --- /dev/null +++ b/code-runner/src/manager.rs @@ -0,0 +1,1791 @@ +//! The router: one public runtime id space over two engines. +//! +//! Ids are minted by whichever engine owns the runtime and passed through +//! unchanged; this map records only WHICH engine owns each, so `teardown` and +//! a `runtime_id`-addressed `run` route without parsing the id. Encoding the +//! language into the id was rejected: a `runtime_id` is documented as a +//! capability-secret, and routing must not depend on reading it. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use futures::future::BoxFuture; +use iii_node_core::engine::{CallResult, Engine, ProxyHandler, UnregisterFn}; +use iii_node_core::manager::RuntimeManager; +use iii_python_core::manager::Manager as PythonManager; + +use crate::config::SharedConfig; +use crate::error::{redact_unheld, CodeRunnerError}; +use crate::functions::register::{RegisterRequest, RegisterResponse}; +use crate::functions::run::{RunRequest, RunResponse}; +use crate::functions::teardown::{TeardownRequest, TeardownResponse}; +use crate::lang::Lang; + +use crate::translate; +use crate::truncate; +/// node-core's own caps, reused so the two languages refuse the same inputs. +use iii_node_core::ops::{MAX_DESCRIPTION_BYTES, MAX_FUNCTION_ID_BYTES}; + +/// A python `register_function` namespace: one pinned interpreter, plus the +/// closure that removes each of its functions from the bus. +struct PyNamespace { + runtime_id: String, + /// Registrations past `py_namespace_runtime` but not yet inserted into + /// `functions` (their define is still executing). A failing sibling's + /// cleanup must not read `functions.is_empty()` as "namespace unused" + /// and destroy the interpreter these are defining on. + in_flight: usize, + functions: HashMap, +} + +pub struct Manager { + /// Live config snapshot, swapped by `configuration::register_config_trigger` + /// on `configuration:updated`. Per-call knobs (output caps, timeouts) are + /// `load()`ed at each use so they hot-reload; the engine-structural fields + /// were captured when the engines were built and a change to them applies + /// at the next restart. + cfg: SharedConfig, + node: Arc, + /// The bus. Node reaches it through `RuntimeManager`, which owns its own + /// handle; python registrations are published from HERE, because the + /// python guest has no `iii.registerFunction` to publish them from — its + /// `iii` is `trigger` and `namespace` only. + engine: Arc, + /// Canonical namespace (`"app::"`) → its interpreter and registrations. + py_ns: Mutex>, + /// `None` when the CPython artifact could not be prepared at boot. The + /// worker still serves node rather than refusing to start, and every + /// python call says why — a node-only deployment losing its whole worker + /// to a python problem would be the wrong trade. + python: Option>, + /// Public runtime id → the engine that owns it. + owners: Mutex>, +} + +impl Manager { + pub fn new( + cfg: SharedConfig, + node: Arc, + engine: Arc, + python: Option>, + ) -> Arc { + Arc::new(Self { + cfg, + node, + engine, + py_ns: Mutex::new(HashMap::new()), + python, + owners: Mutex::new(HashMap::new()), + }) + } + + fn owner_of(&self, runtime_id: &str) -> Option { + self.owners.lock().unwrap().get(runtime_id).copied() + } + + /// Which engine a request addresses, and the refusal when it does not say. + /// + /// Messages are sandbox-code-runner's, so a caller written against that + /// worker reads the same words. + fn resolve_lang(&self, req: &RunRequest) -> Result { + match (&req.runtime_id, req.lang) { + (Some(id), asked) => { + let owner = self + .owner_of(id) + .ok_or_else(|| CodeRunnerError::RuntimeNotFound(id.clone()))?; + if let Some(asked) = asked { + if asked != owner { + return Err(CodeRunnerError::InvalidRequest(format!( + "this runtime runs {owner}; omit `lang` or pass the matching one \ + — languages cannot be mixed in one runtime" + ))); + } + } + Ok(owner) + } + (None, Some(lang)) => Ok(lang), + (None, None) => Err(CodeRunnerError::InvalidRequest( + "`lang` is required when there is no `runtime_id`: \"node\" or \"python\"".into(), + )), + } + } + + pub async fn run(&self, req: RunRequest) -> Result { + let lang = self.resolve_lang(&req)?; + let held_id = req.runtime_id.clone(); + let resp = match lang { + Lang::Node => self.run_node(req, held_id).await, + Lang::Python => self.run_python(req, held_id).await, + }?; + Ok(self.cap_response(resp)) + } + + /// The one seam every payload-carrying response passes through before + /// reaching the bus: both engines' four `translate::{node_ok,node_err, + /// python_ok,python_err}` builders return through `run_node`/`run_python` + /// into here, so capping once HERE covers all four. A transport error + /// (`Err` from either) carries no payload and never reaches this — it + /// returns through the `?` above instead. + /// + /// `exit_code`/`success`/`duration_ms`/`runtime_id` are untouched: a + /// capped response is still `success: true` when the run was — only the + /// echo is bounded. + fn cap_response(&self, resp: RunResponse) -> RunResponse { + let cfg = self.cfg.load(); + RunResponse { + result: truncate::cap_result(resp.result, cfg.max_result_bytes), + stdout: truncate::cap_stream("stdout", resp.stdout, cfg.max_stream_bytes), + stderr: truncate::cap_stream("stderr", resp.stderr, cfg.max_stream_bytes), + ..resp + } + } + + /// A python runtime persists its working directory **and** its + /// interpreter. `python.wasm` is a WASI command module and cannot be + /// re-entered once `_start` returns, so the wrapper never lets it return: + /// it parks on stdin between calls and takes one turn at a time. + /// + /// A superset of what sandbox-code-runner promises for its own `keep` + /// ("same filesystem, fresh interpreter process each time"), so code + /// written against that worker ports here but not necessarily back. + async fn run_python( + &self, + req: RunRequest, + held_id: Option, + ) -> Result { + let Some(python) = &self.python else { + return Err(CodeRunnerError::Engine( + "the python engine failed to start on this worker; check its boot logs".into(), + )); + }; + let core_req = iii_python_core::manager::RunRequest { + code: req.code, + payload: None, + timeout_ms: req.timeout_ms, + memory_mb: None, + }; + let started = Instant::now(); + + // A `keep` that fails must NOT leave a runtime behind — the caller + // gets no id back, so one would be unreachable and would sit there + // until the sweep. sandbox-code-runner makes the same choice. + let (result, id) = match (&held_id, req.keep) { + (Some(id), _) => (python.run_in(id, core_req).await, Some(id.clone())), + (None, true) => { + // `None` = the config default. `memory_mb` binds for the + // runtime's whole life because wasm linear memory only grows, + // and this worker's wire has no per-runtime memory knob to + // pass through — a request that carries one against an + // existing id is refused by the core. + let id = python.create_runtime(None).map_err(|e| { + translate::python_err(e, 0) + .err() + .unwrap_or_else(|| CodeRunnerError::Engine("create failed".into())) + })?; + let out = python.run_in(&id, core_req).await; + match &out { + Ok(_) => { + self.owners.lock().unwrap().insert(id.clone(), Lang::Python); + (out, Some(id)) + } + Err(_) => { + let _ = python.destroy_runtime(&id); + (out, None) + } + } + } + (None, false) => (python.run(core_req).await, None), + }; + let duration_ms = started.elapsed().as_millis() as u64; + match result { + Ok(out) => { + let mut resp = translate::python_ok(out, duration_ms); + resp.runtime_id = id; + Ok(resp) + } + Err(e) => { + let mapped = translate::python_err(e, duration_ms); + match mapped { + Ok(mut r) => { + r.runtime_id = id; + Ok(r) + } + Err(err) if held_id.is_none() => Err(redact_unheld(err)), + Err(err) => Err(err), + } + } + } + } + + async fn run_node( + &self, + req: RunRequest, + held_id: Option, + ) -> Result { + let started = Instant::now(); + let core_req = iii_node_core::wire::run::RunRequest { + code: req.code, + runtime_id: req.runtime_id, + // Namespaces come only from `register_function`'s `function_id`, + // exactly as sandbox-code-runner does — `run` has no namespace + // field on this worker's wire. + namespace: None, + keep: req.keep, + timeout_ms: req.timeout_ms, + }; + let result = self.node.run(core_req).await; + let duration_ms = started.elapsed().as_millis() as u64; + + // The id a kept run minted, recorded before it can be addressed. + match result { + Ok(out) => { + let id = out.runtime_id.clone(); + if let Some(id) = &id { + self.owners.lock().unwrap().insert(id.clone(), Lang::Node); + } + let eval = iii_node_core::runtime::EvalOutcome { + result: out.result, + logs: out.logs, + registered: out.registered, + }; + Ok(translate::node_ok(eval, id, duration_ms)) + } + Err(e) => { + let resp = translate::node_err(e, held_id.clone(), duration_ms); + match resp { + Ok(r) => Ok(r), + // A caller who never supplied an id must not learn one. + Err(err) if held_id.is_none() => Err(redact_unheld(err)), + Err(err) => Err(err), + } + } + } + } + + pub async fn register( + &self, + req: RegisterRequest, + ) -> Result { + // One rule for both engines, checked before anything is claimed or + // booted: node re-validates in `op_iii_register` either way (that op + // is also the guest surface), but failing HERE gives the caller the + // error without a runtime having been created for a doomed request. + for (field, format) in [ + ("request_format", &req.request_format), + ("response_format", &req.response_format), + ] { + if let Some(value) = format { + iii_node_core::wire::register::validate_format(field, value) + .map_err(CodeRunnerError::InvalidRequest)?; + } + } + match req.lang { + Lang::Python => return self.register_python(req).await, + Lang::Node => {} + } + let core_req = iii_node_core::wire::register::RegisterRequest { + function_id: req.function_id.clone(), + source: req.source, + description: req.description, + request_format: req.request_format, + response_format: req.response_format, + }; + match self.node.register(core_req).await { + // node-core reports the namespace it claimed; this wire reports + // only that the registration landed, matching + // sandbox-code-runner's two-field response. + Ok(out) => Ok(RegisterResponse { + function_id: out.function_id, + registered: true, + }), + // A register caller never holds the namespace runtime's id. + Err(e) => Err(redact_unheld( + translate::node_err(e, None, 0) + .err() + .unwrap_or_else(|| CodeRunnerError::Engine("registration failed".into())), + )), + } + } + + /// Publish a python `handler(payload)` on the bus. + /// + /// Structurally different from the node path, and deliberately so. Node's + /// guest publishes itself: the evaluated source calls + /// `iii.registerFunction`, which reaches the bus through an op. Python's + /// guest cannot — `python.wasm` imports one module and exports `_start`, + /// so its `iii` is `trigger` and `namespace` only. The host publishes on + /// its behalf and dispatches each invocation back in as one turn on the + /// namespace's pinned interpreter. + async fn register_python( + &self, + req: RegisterRequest, + ) -> Result { + let python = self + .python + .as_ref() + .ok_or_else(|| { + CodeRunnerError::Engine( + "the python engine failed to start on this worker; check its boot logs".into(), + ) + })? + .clone(); + let invalid = CodeRunnerError::InvalidRequest; + + if req.function_id.len() > MAX_FUNCTION_ID_BYTES { + return Err(invalid(format!( + "function id {:?}… is {} bytes; the limit is {MAX_FUNCTION_ID_BYTES}", + req.function_id.chars().take(40).collect::(), + req.function_id.len() + ))); + } + if let Some(d) = &req.description { + if d.len() > MAX_DESCRIPTION_BYTES { + return Err(invalid(format!( + "description is {} bytes; the limit is {MAX_DESCRIPTION_BYTES}", + d.len() + ))); + } + } + + // The namespace IS the first segment; an id with no `::` cannot name + // one and is refused rather than silently placed in a default. + let ns = match req.function_id.split_once("::") { + Some((head, _)) if !head.is_empty() => format!("{head}::"), + _ => { + return Err(invalid(format!( + "function id {:?} has no namespace; pass something like \"my-app::greet\"", + req.function_id + ))) + } + }; + // node-core's validator, shared rather than copied: the two languages + // have to agree byte-for-byte on what a legal namespace is. + let namespace = iii_node_core::manager::normalize_namespace( + &ns, + std::slice::from_ref(&req.function_id), + ) + .map_err(invalid)?; + + // Claim BEFORE creating anything, in the SAME registry node claims + // into — including the guest-driven op. Two registries would each + // believe they owned this id, both would reach the SDK's + // `register_function`, and the second would hit its duplicate-id + // panic in a non-unwinding V8 callback, which aborts the process. + // + // The OWNER must not be the bare namespace: that is exactly the + // placeholder node's `register` claims under before it has a runtime + // id, so a python id claimed that way looks to node like its own + // earlier claim and is silently reclaimed — after which node evals the + // source and `op_iii_register` takes the process down. Observed, as an + // abort, by the e2e suite. `python:` cannot collide: a node owner is + // either a minted runtime id or `::`, and a stem is + // `[a-z0-9._-]` only, so it can never contain a colon. + let owner = format!("python:{namespace}"); + let one_id = std::slice::from_ref(&req.function_id); + self.node.ids().claim_all(one_id, &owner).map_err(|_| { + invalid(format!( + "function id {:?} is already taken", + req.function_id + )) + })?; + + let runtime_id = match self.py_namespace_runtime(&python, &namespace) { + Ok(id) => id, + Err(e) => { + self.node.ids().release_ids(one_id, &owner); + return Err(e); + } + }; + + if let Err(e) = self + .py_define_handler(&python, &runtime_id, &req.source) + .await + { + // Nothing reached the bus, so the id is free to release. Unlike + // node's path there is no guest-driven registration that could + // have landed one behind our back: this function is the only way + // a python id reaches the bus at all. + self.node.ids().release_ids(one_id, &owner); + // And if this call is what created the namespace, take its + // interpreter with it. A pinned runtime is exempt from the idle + // sweep, so an orphan left here is one nothing will ever reclaim, + // and it counts against `max_runtimes` forever. Only when the + // namespace has no OTHER registrations — inserted (`functions`) + // or still defining (`in_flight`): an existing namespace owns its + // interpreter and a failed addition must not kill it. The + // incarnation check covers a concurrent teardown+recreate: a + // fresh entry under the same name is not ours to decrement. + let mut map = self.py_ns.lock().unwrap(); + if let Some(entry) = map + .get_mut(&namespace) + .filter(|e| e.runtime_id == runtime_id) + { + entry.in_flight -= 1; + if entry.functions.is_empty() && entry.in_flight == 0 { + map.remove(&namespace); + drop(map); + let _ = python.destroy_runtime(&runtime_id); + } + } + return Err(e); + } + + // A redeploy replaces. Retire the previous registration FIRST: + // `unregister` is keyed by function id, so calling the old closure + // after publishing the new one removes the NEW registration and leaves + // the id advertised by nothing. Dropping the closure instead of calling + // it is the other way to get this wrong — `UnregisterFn` is an explicit + // call, not a `Drop` — and leaves two handlers on one id. + let previous = self + .py_ns + .lock() + .unwrap() + .get_mut(&namespace) + .and_then(|e| e.functions.remove(&req.function_id)); + if let Some(old) = previous { + old(); + } + + let handler = self.py_handler(&python, &runtime_id); + let unregister = self.engine.register( + req.function_id.clone(), + req.description.clone(), + req.request_format.clone(), + req.response_format.clone(), + handler, + ); + let stale = { + let mut map = self.py_ns.lock().unwrap(); + match map + .get_mut(&namespace) + .filter(|e| e.runtime_id == runtime_id) + { + Some(entry) => { + entry.in_flight -= 1; + entry.functions.insert(req.function_id.clone(), unregister); + None + } + // A concurrent teardown removed the namespace (and destroyed + // its interpreter) while our define was executing. The handler + // just published points at a dead runtime: retract it and + // report the collision instead of panicking on the map. + None => Some(unregister), + } + }; + if let Some(unregister) = stale { + unregister(); + self.node.ids().release_ids(one_id, &owner); + return Err(CodeRunnerError::Engine(format!( + "namespace {namespace:?} was torn down while this registration was in flight" + ))); + } + + Ok(RegisterResponse { + function_id: req.function_id, + registered: true, + }) + } + + /// The namespace's interpreter, created and pinned on first use. + fn py_namespace_runtime( + &self, + python: &Arc, + namespace: &str, + ) -> Result { + // Held across the create so two first-registrations on one namespace + // cannot each mint an interpreter and leave one orphaned. Every + // return also counts this registration in `in_flight`, matched by + // the decrement on both exits of `register_python`. + let mut map = self.py_ns.lock().unwrap(); + if let Some(ns) = map.get_mut(namespace) { + ns.in_flight += 1; + return Ok(ns.runtime_id.clone()); + } + let to_err = |e| { + translate::python_err(e, 0) + .err() + .unwrap_or_else(|| CodeRunnerError::Engine("creating the runtime failed".into())) + }; + let runtime_id = python.create_runtime(None).map_err(to_err)?; + // A registration's lifetime is the registration's, not its traffic's: + // without this an unpopular function is reaped by the idle sweep and + // its next caller gets a runtime error for a function the catalog + // still advertises. + if let Err(e) = python.pin_runtime(&runtime_id) { + let _ = python.destroy_runtime(&runtime_id); + return Err(to_err(e)); + } + map.insert( + namespace.to_string(), + PyNamespace { + runtime_id: runtime_id.clone(), + in_flight: 1, + functions: HashMap::new(), + }, + ); + Ok(runtime_id) + } + + /// Run the caller's source in the namespace interpreter and prove it left + /// a callable `handler` behind. + async fn py_define_handler( + &self, + python: &Arc, + runtime_id: &str, + source: &str, + ) -> Result<(), CodeRunnerError> { + // The check runs in the same turn as the source, in the same + // namespace, so it sees exactly what the source defined. A separate + // turn would also work — the interpreter persists — but would report a + // missing handler as a second, unrelated-looking failure. + let code = format!("{source}\n\n{HANDLER_CHECK}"); + let req = iii_python_core::manager::RunRequest { + code, + payload: None, + timeout_ms: Some(self.cfg.load().default_timeout_ms), + memory_mb: None, + }; + python + .run_in(runtime_id, req) + .await + .map(|_| ()) + .map_err(|e| { + use iii_python_core::error::ErrorKind; + match e.kind { + // On `run` these three are a RESPONSE — a failing script is + // not an infrastructure failure. On `register_function` there + // is no response to carry them: the caller asked to publish a + // handler and no handler exists, so the registration itself + // failed. Same three kinds, opposite verdict, because the + // request means something different. + ErrorKind::SyntaxError + | ErrorKind::PythonException + | ErrorKind::ResultTooLarge => { + let mut m = e.message; + if let Some(tb) = e.traceback { + m.push('\n'); + m.push_str(&tb); + } + CodeRunnerError::InvalidRequest(m) + } + _ => translate::python_err(e, 0).err().unwrap_or_else(|| { + CodeRunnerError::Engine("defining the handler failed".into()) + }), + } + }) + } + + /// What the bus calls. One turn on the namespace interpreter per + /// invocation, so a handler sees every global its registration left + /// behind — and every global a previous invocation left behind. + fn py_handler(&self, python: &Arc, runtime_id: &str) -> ProxyHandler { + let python = python.clone(); + let runtime_id = runtime_id.to_string(); + // The snapshot handle, not a value: `default_timeout_ms` is a + // per-call knob (struct doc above), so a registered handler must see + // a configuration save on its next invocation, not its next redeploy. + let cfg = self.cfg.clone(); + Arc::new(move |payload: serde_json::Value| { + let python = python.clone(); + let runtime_id = runtime_id.clone(); + let timeout_ms = cfg.load().default_timeout_ms; + Box::pin(async move { + let req = iii_python_core::manager::RunRequest { + code: "result = handler(payload)".into(), + payload: Some(payload), + timeout_ms: Some(timeout_ms), + memory_mb: None, + }; + match python.run_in(&runtime_id, req).await { + Ok(out) => Ok(out.result), + // The bus wants a message, not a taxonomy. `stderr` is + // already folded into it by the core for a tenant + // exception, which is the case a caller actually debugs. + Err(e) => Err(e.message), + } + }) as BoxFuture<'static, CallResult> + }) + } + + /// Tear down a python namespace: unregister its functions, release their + /// ids, and destroy the interpreter. Returns the ids removed. + fn teardown_py_namespace(&self, namespace: &str) -> Option> { + let entry = self.py_ns.lock().unwrap().remove(namespace)?; + let mut removed: Vec = Vec::new(); + for (id, unregister) in entry.functions { + unregister(); + removed.push(id); + } + // Released under the same owner that claimed them (see + // `register_python`), so a later registration can take the same ids. + self.node + .ids() + .release_ids(&removed, &format!("python:{namespace}")); + removed.sort(); + if let Some(python) = &self.python { + let _ = python.destroy_runtime(&entry.runtime_id); + } + Some(removed) + } + + pub async fn teardown( + &self, + req: TeardownRequest, + ) -> Result { + match (&req.runtime_id, &req.namespace) { + (Some(id), None) => { + let owner = self + .owner_of(id) + .ok_or_else(|| CodeRunnerError::RuntimeNotFound(id.clone()))?; + match owner { + Lang::Node => { + let out = self + .node + .teardown_runtime(id) + .await + .map_err(|e| self.core_err(e))?; + self.owners.lock().unwrap().remove(id); + Ok(TeardownResponse { + runtime_id: Some(id.clone()), + namespace: None, + torn_down: true, + unregistered: out.unregistered, + }) + } + Lang::Python => { + let python = self.python.as_ref().ok_or_else(|| { + CodeRunnerError::Engine("the python engine is not running".into()) + })?; + python.destroy_runtime(id).map_err(|e| { + translate::python_err(e, 0).err().unwrap_or_else(|| { + CodeRunnerError::Engine("teardown failed".into()) + }) + })?; + self.owners.lock().unwrap().remove(id); + Ok(TeardownResponse { + runtime_id: Some(id.clone()), + namespace: None, + torn_down: true, + // A python runtime registers nothing: handlers + // need an interpreter that outlives the call. + unregistered: Vec::new(), + }) + } + } + } + (None, Some(ns)) => { + let canonical = normalize_namespace(ns); + // Both halves are tried. A namespace is not owned by a + // language — ids are claimed one at a time — so `app::a` in + // node and `app::b` in python can coexist, and tearing down + // "app" has to mean both. Python first because it cannot fail: + // it is a map removal, so a node failure afterwards cannot + // leave python half-torn-down with nothing recorded. + let py = self.teardown_py_namespace(&canonical); + + let core_req = iii_node_core::wire::teardown::TeardownRequest { + runtime_id: None, + namespace: Some(ns.clone()), + }; + let node = match self.node.teardown(core_req).await { + Ok(out) => Some(out.unregistered), + // Not found in node is only fatal when python had nothing + // either — otherwise this namespace WAS torn down, just + // not on the side that answered. + Err(iii_node_core::error::NodeEngineError::RuntimeNotFound(n)) => { + if py.is_none() { + return Err(CodeRunnerError::NamespaceNotFound(n)); + } + None + } + Err(other) => return Err(self.core_err(other)), + }; + + // Any id these runtimes held is now dead; ownership entries + // naming them are pruned on the next sweep. The namespace path + // never returns a runtime id, so nothing more precise is + // available here. + let mut unregistered = node.unwrap_or_default(); + unregistered.extend(py.unwrap_or_default()); + unregistered.sort(); + unregistered.dedup(); + Ok(TeardownResponse { + runtime_id: None, + // Canonical form, even when the caller passed the bare one. + namespace: Some(canonical), + torn_down: true, + unregistered, + }) + } + (Some(_), Some(_)) => Err(CodeRunnerError::InvalidRequest( + "pass exactly one of runtime_id or namespace, not both: runtime_id tears down a \ + single kept run's runtime, namespace tears down every runtime backing a \ + register_function namespace" + .into(), + )), + (None, None) => Err(CodeRunnerError::InvalidRequest( + "pass exactly one of runtime_id (a kept run's runtime) or namespace (a \ + register_function namespace, e.g. \"app\" for ids like app::greet)" + .into(), + )), + } + } + + fn core_err(&self, e: iii_node_core::error::NodeEngineError) -> CodeRunnerError { + translate::node_err(e, None, 0) + .err() + .unwrap_or_else(|| CodeRunnerError::Engine("unexpected engine outcome".into())) + } + + /// Reap runtimes idle past `idle_ttl_secs`, forgetting their ownership + /// entries so a stale id cannot route anywhere. + pub fn sweep_idle(&self) -> Vec { + let mut reaped = self.node.sweep_idle(); + if let Some(python) = &self.python { + reaped.extend(python.sweep_idle()); + } + if !reaped.is_empty() { + let mut owners = self.owners.lock().unwrap(); + for id in &reaped { + owners.remove(id); + } + } + reaped + } + + pub fn idle_ttl_secs(&self) -> u64 { + self.cfg.load().idle_ttl_secs + } + + /// The live config handle, for handlers registered outside this struct + /// (the guidance hook reads `inject_guidance` per call). + pub fn shared_config(&self) -> SharedConfig { + self.cfg.clone() + } +} + +/// `app` and `app::` both mean `app::`, and that canonical form is what a +/// teardown response echoes. +/// Proves the caller's source left a callable `handler` behind, in words that +/// say what to write rather than what went wrong. A bare `NameError: handler` +/// from a failed registration reads like a bug in this worker. +const HANDLER_CHECK: &str = r#"if not callable(globals().get("handler")): + raise TypeError( + "register_function: your source must define handler(payload) — a callable " + "taking one argument. Found: " + repr(globals().get("handler")) + )"#; + +fn normalize_namespace(ns: &str) -> String { + let trimmed = ns.trim_end_matches(':'); + format!("{trimmed}::") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_namespace_echoes_back_canonical() { + assert_eq!(normalize_namespace("app"), "app::"); + assert_eq!(normalize_namespace("app::"), "app::"); + assert_eq!(normalize_namespace("app:"), "app::"); + } +} + +#[cfg(test)] +mod router_tests { + use super::*; + use crate::config::CodeRunnerConfig; + + fn manager() -> Arc { + manager_and_bus().0 + } + + fn manager_and_bus() -> (Arc, Arc) { + manager_with(CodeRunnerConfig { + // Small enough to reach the cap in a test without spawning 32 + // isolates. + max_runtimes: 4, + ..CodeRunnerConfig::default() + }) + } + + fn manager_with(cfg: CodeRunnerConfig) -> (Arc, Arc) { + let (m, bus, _shared) = manager_with_shared(cfg); + (m, bus) + } + + /// Also returns the live config handle, for tests that hot-swap it the + /// way the configuration trigger does. + fn manager_with_shared( + cfg: CodeRunnerConfig, + ) -> (Arc, Arc, crate::config::SharedConfig) { + iii_node_core::runtime::init_v8_platform(); + let bus = Arc::new(TestBus::default()); + let node = RuntimeManager::new( + Arc::new(cfg.node()), + bus.clone(), + // The SAME seed as production (`main.rs`): seeding only + // `STATIC_IDS` here would leave the console UI's content function + // claimable in tests and make the regression test below pass for + // the wrong reason. + &crate::functions::seeded_ids(), + ); + let python = iii_python_core::runner::Runner::boot() + .ok() + .map(|r| iii_python_core::manager::Manager::new(Arc::new(cfg.python()), r)); + let shared = cfg.into_shared(); + ( + Manager::new(shared.clone(), node, bus.clone(), python), + bus, + shared, + ) + } + + /// A bus-free `Engine` that REMEMBERS what was published. This crate's + /// tests never need a live engine, and the core's own `FakeEngine` is + /// `cfg(test)`-gated to that crate — but a registration whose handler is + /// dropped on the floor cannot be told from one that never happened, so + /// this one keeps them callable. + #[derive(Default)] + struct TestBus { + published: Arc>>, + /// `(request_format, response_format)` per live id, so a test can + /// prove the wire fields survived the trip to `Engine::register`. + formats: Arc>>, + /// Every id whose `UnregisterFn` was actually CALLED. A closure that + /// is dropped instead of called leaves a registration live on a real + /// bus, and nothing else here would notice. + retired: Arc>>, + } + + /// One registration's `(request_format, response_format)`. + type FormatPair = (Option, Option); + + impl TestBus { + fn formats_of(&self, fn_id: &str) -> Option { + self.formats.lock().unwrap().get(fn_id).cloned() + } + fn ids(&self) -> Vec { + let mut v: Vec = self.published.lock().unwrap().keys().cloned().collect(); + v.sort(); + v + } + fn retired(&self) -> Vec { + self.retired.lock().unwrap().clone() + } + async fn invoke(&self, fn_id: &str, payload: serde_json::Value) -> CallResult { + let h = self + .published + .lock() + .unwrap() + .get(fn_id) + .cloned() + .unwrap_or_else(|| panic!("{fn_id} was never published")); + h(payload).await + } + } + + impl iii_node_core::engine::Engine for TestBus { + fn call( + &self, + _: String, + _: serde_json::Value, + _: u64, + _: Option, + ) -> futures::future::BoxFuture<'static, iii_node_core::engine::CallResult> { + Box::pin(async { Err("no bus in tests".to_string()) }) + } + fn register( + &self, + fn_id: String, + _: Option, + request_format: Option, + response_format: Option, + handler: iii_node_core::engine::ProxyHandler, + ) -> iii_node_core::engine::UnregisterFn { + self.formats + .lock() + .unwrap() + .insert(fn_id.clone(), (request_format, response_format)); + self.published + .lock() + .unwrap() + .insert(fn_id.clone(), handler); + // Keyed by id, exactly like the SDK's `function_ref`: calling a + // stale one after the id was re-registered removes whatever holds + // the id NOW. + let published = self.published.clone(); + let retired = self.retired.clone(); + Box::new(move || { + published.lock().unwrap().remove(&fn_id); + retired.lock().unwrap().push(fn_id.clone()); + }) + } + fn register_trigger( + &self, + _: serde_json::Value, + ) -> futures::future::BoxFuture<'static, Result> { + Box::pin(async { Ok("trig-test".to_string()) }) + } + fn unregister_trigger( + &self, + _: String, + ) -> futures::future::BoxFuture<'static, Result<(), String>> { + Box::pin(async { Ok(()) }) + } + fn register_trigger_type( + &self, + _: String, + _: Option, + _: iii_node_core::engine::ProxyHandler, + ) -> iii_node_core::engine::UnregisterFn { + Box::new(|| {}) + } + } + + fn run(code: &str) -> RunRequest { + RunRequest { + code: code.into(), + runtime_id: None, + lang: Some(Lang::Node), + keep: false, + timeout_ms: Some(5_000), + } + } + + #[tokio::test] + async fn a_one_shot_run_returns_a_process_shaped_response_and_no_id() { + let m = manager(); + let r = m.run(run("console.log('hi'); return 2 + 2")).await.unwrap(); + assert_eq!(r.stdout, "hi\n"); + assert_eq!(r.exit_code, 0); + assert!(r.success); + assert_eq!(r.result, serde_json::json!(4)); + assert!( + r.runtime_id.is_none(), + "a one-shot run has nothing to address" + ); + } + + /// The output caps apply through the real seam, on the crate's actual + /// default config — not just in `truncate`'s own unit tests. Mutation: + /// drop the `cap_response` call in `run` and this fails on the ~575KB + /// array `Array.from({length: 100000}, ...)` produces. + #[tokio::test] + async fn a_runaway_result_is_capped_at_the_default() { + let m = manager(); + let r = m + .run(run("return Array.from({length: 100000}, (_, i) => i)")) + .await + .unwrap(); + assert!(r.success); + let marker = r + .result + .as_str() + .expect("an oversized result becomes a marker string"); + assert!( + marker.starts_with(" RunRequest { + RunRequest { + code: code.into(), + runtime_id: None, + lang: Some(Lang::Python), + keep: false, + timeout_ms: Some(10_000), + } + } + + /// The point of wiring python at all: one API, two languages, the same + /// process-shaped response. + #[tokio::test] + async fn a_python_run_returns_the_same_shape_a_node_run_does() { + let m = manager(); + let r = m + .run(py("print('hi')\nresult = 2 + 2")) + .await + .expect("python must run"); + assert_eq!(r.stdout, "hi\n"); + assert_eq!(r.exit_code, 0); + assert!(r.success); + assert_eq!(r.result, serde_json::json!(4)); + assert!(r.runtime_id.is_none()); + } + + /// Identical rule to the node side. Mutation: move `PythonException` + /// into `python_err`'s error arm and the two languages stop agreeing. + #[tokio::test] + async fn a_throwing_python_script_is_also_a_response() { + let m = manager(); + let r = m + .run(py("raise ValueError('boom')")) + .await + .expect("a tenant exception must not be a bus error"); + assert_eq!(r.exit_code, 1); + assert!(!r.success); + assert!(r.stderr.contains("boom"), "stderr was {:?}", r.stderr); + } + + /// The python half of `keep`: the files AND the interpreter persist. + /// + /// Both halves asserted, because they used to differ — python's `keep` + /// persisted only files until park-and-loop landed, and node's persists + /// only files still. A caller reading `keep` on this worker's wire has to + /// be able to trust that "the runtime persists" means the same thing here + /// as `a_kept_node_runtime_*` says it means there. + #[tokio::test] + async fn a_kept_python_runtime_persists_files_and_globals() { + let m = manager(); + let first = m + .run(RunRequest { + keep: true, + ..py("leaked = 1\nopen('/work/f', 'w').write('kept')\nresult = None") + }) + .await + .expect("python keep must work"); + let id = first.runtime_id.clone().expect("keep must mint an id"); + + let second = m + .run(RunRequest { + runtime_id: Some(id.clone()), + lang: None, + ..py("result = ['leaked' in globals(), open('/work/f').read()]") + }) + .await + .unwrap(); + assert_eq!(second.result, serde_json::json!([true, "kept"])); + + let torn = m + .teardown(TeardownRequest { + runtime_id: Some(id.clone()), + namespace: None, + }) + .await + .unwrap(); + assert!(torn.torn_down); + + let after = m + .run(RunRequest { + runtime_id: Some(id), + lang: None, + ..py("result = 1") + }) + .await + .expect_err("a torn-down python id must not resolve"); + assert_eq!(after.code(), "code-runner::runtime_not_found"); + } + + /// A `keep` that fails must leave nothing behind: the caller gets no id, + /// so any runtime created for it would be unreachable until the sweep. + /// Mutation: drop the `destroy_runtime` in the failure arm. + #[tokio::test] + async fn a_failed_python_keep_does_not_strand_a_runtime() { + let m = manager(); + let before = m.python.as_ref().unwrap().live_runtime_count(); + let r = m + .run(RunRequest { + keep: true, + timeout_ms: Some(200), + ..py("while True:\n pass") + }) + .await; + assert!(r.is_err(), "a runaway must fail"); + assert_eq!( + m.python.as_ref().unwrap().live_runtime_count(), + before, + "a failed keep must not strand a runtime" + ); + } + + /// Two concurrent registrations share one interpreter. If one fails while + /// the other is still inside its define (looked the runtime up, inserted + /// nothing yet), the failure's cleanup used to see `functions` empty, + /// remove the namespace, and destroy the interpreter under the survivor. + /// The sibling is simulated deterministically: a bare + /// `py_namespace_runtime` call IS a registration parked mid-define. + /// Mutation: drop the `in_flight` guard from the failure arm. + #[tokio::test] + async fn a_failed_registration_spares_a_sibling_still_defining() { + let m = manager(); + let python = m.python.clone().unwrap(); + let sibling_runtime = m.py_namespace_runtime(&python, "app::").unwrap(); + + m.register(reg("app::boom", "this is not python")) + .await + .expect_err("a bad source must fail"); + + // The namespace entry — and the interpreter it pins — must survive: + // rejoining the namespace lands on the SAME runtime, not a fresh one + // minted over the sibling's grave. + let rejoined = m.py_namespace_runtime(&python, "app::").unwrap(); + assert_eq!( + sibling_runtime, rejoined, + "the failing registration destroyed the interpreter a sibling was defining on" + ); + } + + /// A one-line `def` body is still a definition. This spelling used to be + /// the fixture for "python handlers are refused"; it is now the smallest + /// registration that works, and it stays as a regression test that the + /// wrapper does not require a multi-line body. + #[tokio::test] + async fn a_single_line_def_registers() { + let (m, bus) = manager_and_bus(); + m.register(RegisterRequest { + function_id: "app::greet".into(), + source: "def handler(payload): return 'hi'".into(), + description: None, + request_format: None, + response_format: None, + lang: Lang::Python, + }) + .await + .expect("a single-line def defines a handler"); + assert_eq!( + bus.invoke("app::greet", serde_json::json!(null)) + .await + .unwrap(), + serde_json::json!("hi") + ); + } + + #[tokio::test] + async fn teardown_refuses_both_and_neither() { + let m = manager(); + for (rt, ns) in [ + (Some("rt-1".to_string()), Some("app".to_string())), + (None, None), + ] { + let err = m + .teardown(TeardownRequest { + runtime_id: rt, + namespace: ns, + }) + .await + .expect_err("exactly one must be required"); + assert_eq!(err.code(), "code-runner::invalid_request"); + } + } + + /// A caller who ran one-shot never held an id, so a mid-run runtime death + /// must not disclose one. Mutation: drop the `redact_unheld` call in + /// `run_node`'s error arm. + #[tokio::test] + async fn a_one_shot_caller_never_learns_a_runtime_id() { + let m = manager(); + let err = m + .run(RunRequest { + timeout_ms: Some(50), + ..run("while (true) {}") + }) + .await + .expect_err("a runaway must fail"); + assert!( + !err.to_string().contains("rt-"), + "a one-shot caller must not learn an id: {err}" + ); + } + fn reg(function_id: &str, source: &str) -> RegisterRequest { + RegisterRequest { + function_id: function_id.into(), + source: source.into(), + description: Some("a test handler".into()), + request_format: None, + response_format: None, + lang: Lang::Python, + } + } + + /// Both languages must deliver the wire's formats to the bus + /// registration — that is what `engine::functions::info` reads in place + /// of "any". Node rides the whole guest chain; python is a direct host + /// publish. Mutation: either arm dropping the fields (the `core_req` + /// literal, `register_python`'s engine call). + #[tokio::test] + async fn register_formats_reach_the_bus_in_both_languages() { + let (m, bus) = manager_and_bus(); + let request = + serde_json::json!({"type": "object", "properties": {"n": {"type": "number"}}}); + let response = serde_json::json!({"type": "number"}); + for (id, lang, source) in [ + ( + "fmt-node::double", + Lang::Node, + "export function handler(p) { return p.n * 2 }", + ), + ( + "fmt-py::double", + Lang::Python, + "def handler(payload):\n return payload[\"n\"] * 2", + ), + ] { + m.register(RegisterRequest { + function_id: id.into(), + source: source.into(), + description: Some("doubles n".into()), + request_format: Some(request.clone()), + response_format: Some(response.clone()), + lang, + }) + .await + .unwrap_or_else(|e| panic!("{id}: {e}")); + assert_eq!( + bus.formats_of(id), + Some((Some(request.clone()), Some(response.clone()))), + "{id}" + ); + } + } + + /// A bad format is refused at the wire — code `invalid_request`, message + /// saying what to write — before any claim or runtime exists, for BOTH + /// languages (the check sits above the lang dispatch). Mutation: the + /// validation loop removed, or moved into one arm. + #[tokio::test] + async fn register_refuses_bad_formats_before_creating_anything() { + let (m, bus) = manager_and_bus(); + for (lang, source) in [ + (Lang::Node, "export function handler(p) { return p }"), + (Lang::Python, "def handler(payload):\n return payload"), + ] { + for (format, expected) in [ + (serde_json::json!("nope"), "OBJECT"), + (serde_json::json!({}), "constrains nothing"), + ] { + let err = m + .register(RegisterRequest { + function_id: "fmt-bad::fn".into(), + source: source.into(), + description: None, + request_format: Some(format.clone()), + response_format: None, + lang, + }) + .await + .expect_err("a bad format must be refused"); + assert_eq!( + err.code(), + "code-runner::invalid_request", + "{format}: {err}" + ); + assert!(err.to_string().contains(expected), "{format}: {err}"); + } + } + assert!( + bus.published.lock().unwrap().is_empty(), + "a refused registration must not reach the bus" + ); + } + + /// The end-to-end shape: source defines `handler`, the id reaches the bus, + /// and invoking it there runs the handler. + #[tokio::test] + async fn a_python_registration_publishes_a_callable_handler() { + let (m, bus) = manager_and_bus(); + let out = m + .register(reg( + "pyapp::double", + "def handler(payload):\n return payload['n'] * 2", + )) + .await + .expect("python register_function must work"); + assert_eq!(out.function_id, "pyapp::double"); + assert!(out.registered); + assert_eq!(bus.ids(), vec!["pyapp::double".to_string()]); + + let answer = bus + .invoke("pyapp::double", serde_json::json!({"n": 21})) + .await + .expect("the handler must answer"); + assert_eq!(answer, serde_json::json!(42)); + } + + /// The interpreter behind a registration persists, so a handler keeps + /// whatever its registration set up — the reason python `register_function` + /// could not exist before park-and-loop landed. + #[tokio::test] + async fn a_handler_keeps_the_state_its_registration_built() { + let (m, bus) = manager_and_bus(); + m.register(reg( + "pyapp::counter", + "import itertools\n_seq = itertools.count(1)\n\ + def handler(payload):\n return next(_seq)", + )) + .await + .unwrap(); + + for expected in 1..=3 { + let got = bus + .invoke("pyapp::counter", serde_json::json!(null)) + .await + .unwrap(); + assert_eq!(got, serde_json::json!(expected), "state did not persist"); + } + } + + /// Source that never defines `handler` must fail the REGISTRATION, not + /// publish an id that fails on first call. + /// + /// Mutation: drop `HANDLER_CHECK` from `py_define_handler`. The register + /// then succeeds, the catalog advertises `pyapp::nope`, and the caller + /// finds out at invocation time instead. + #[tokio::test] + async fn source_without_a_handler_is_refused_at_registration() { + let (m, bus) = manager_and_bus(); + let err = m + .register(reg("pyapp::nope", "x = 1 # no handler here")) + .await + .unwrap_err(); + assert!( + err.to_string().contains("handler(payload)"), + "message must say what to write: {err}" + ); + assert!( + bus.ids().is_empty(), + "a failed registration reached the bus" + ); + + // And the id is free, so a corrected redeploy works. + m.register(reg( + "pyapp::nope", + "def handler(payload):\n return 'fixed'", + )) + .await + .expect("the id must have been released"); + } + + /// A registration that fails to define its handler leaves nothing behind. + /// + /// Mutation: drop the namespace cleanup on the define-failure path. The + /// interpreter it booted is PINNED, so the idle sweep will never reclaim + /// it — a typo in a redeploy would permanently consume a `max_runtimes` + /// slot, and `teardown` would report success for a namespace that holds + /// no functions. + #[tokio::test] + async fn a_failed_registration_leaves_no_runtime_behind() { + let (m, _bus) = manager_and_bus(); + let before = m.python.as_ref().unwrap().live_runtime_count(); + + m.register(reg("pyorphan::x", "x = 1 # no handler")) + .await + .unwrap_err(); + + assert_eq!( + m.python.as_ref().unwrap().live_runtime_count(), + before, + "a failed registration left a pinned interpreter behind" + ); + // And the namespace does not exist, so teardown says so. + assert!(m + .teardown(TeardownRequest { + runtime_id: None, + namespace: Some("pyorphan".into()), + }) + .await + .is_err()); + } + + /// A non-callable `handler` is the same failure as a missing one — binding + /// the NAME is not the contract, being callable is. + #[tokio::test] + async fn a_non_callable_handler_is_refused() { + let (m, _bus) = manager_and_bus(); + let err = m + .register(reg("pyapp::notfn", "handler = 42")) + .await + .unwrap_err(); + assert!(err.to_string().contains("handler(payload)"), "{err}"); + } + + /// A python id is claimed in the SAME registry node claims into. + /// + /// Two registries would each believe they owned the id, both would reach + /// the SDK's `register_function`, and the second would hit its duplicate-id + /// panic — which aborts the process, so there is no recovering from it at + /// runtime. Asserted against the registry directly rather than by racing a + /// node registration through its guest-eval path, because the claim IS the + /// mechanism and a colliding registration is only one thing it stops. + /// + /// Mutation: give the python path its own `IdRegistry`, or claim under the + /// bare `namespace`. Either way this claim succeeds — and the second is + /// worse than it looks: the bare namespace is the placeholder node claims + /// under before it has a runtime id, so node reads a python id claimed + /// that way as its own earlier claim, reclaims it, evals the source, and + /// `op_iii_register` aborts the process from a non-unwinding V8 callback. + #[tokio::test] + async fn a_python_id_is_claimed_in_the_registry_node_shares() { + let (m, _bus) = manager_and_bus(); + m.register(reg( + "shared::fn", + "def handler(payload):\n return payload", + )) + .await + .unwrap(); + + assert!( + m.node + .ids() + .claim_all(&["shared::fn".to_string()], "some-other-owner") + .is_err(), + "node's registry does not know about the python registration" + ); + // And specifically NOT reclaimable under the bare namespace, which is + // the owner node's own `register` uses before it has a runtime id. + assert!( + m.node + .ids() + .claim_all(&["shared::fn".to_string()], "shared::") + .is_err(), + "node would reclaim this id as its own and then abort on register" + ); + + // And teardown releases it in that same registry. + m.teardown(TeardownRequest { + runtime_id: None, + namespace: Some("shared".into()), + }) + .await + .unwrap(); + assert!(m + .node + .ids() + .claim_all(&["shared::fn".to_string()], "some-other-owner") + .is_ok()); + } + + /// A registered function's runtime is exempt from the idle sweep: its + /// lifetime is the registration's, not its traffic's. + /// + /// Mutation: drop the `pin_runtime` call in `py_namespace_runtime`. The + /// sweep then reaps the interpreter behind a merely unpopular function, + /// and its next caller gets a runtime error for something the catalog + /// still advertises. + #[tokio::test] + async fn a_registered_functions_runtime_survives_the_idle_sweep() { + // Everything idle is stale at a zero TTL, which is what makes the + // exemption the only thing keeping this runtime alive. + let (m, bus) = manager_with(CodeRunnerConfig { + idle_ttl_secs: 0, + ..CodeRunnerConfig::default() + }); + m.register(reg( + "pyapp::rare", + "def handler(payload):\n return 'still here'", + )) + .await + .unwrap(); + + m.sweep_idle(); + + assert_eq!( + bus.invoke("pyapp::rare", serde_json::json!(null)) + .await + .unwrap(), + serde_json::json!("still here"), + "the sweep reaped a registered function's interpreter" + ); + } + + /// A redeploy replaces rather than doubling up. `UnregisterFn` is an + /// explicit call, not a `Drop`, so dropping the old closure would leave the + /// first handler live alongside the second. + #[tokio::test] + async fn re_registering_an_id_replaces_its_handler() { + let (m, bus) = manager_and_bus(); + m.register(reg("pyapp::v", "def handler(payload):\n return 'v1'")) + .await + .unwrap(); + m.register(reg("pyapp::v", "def handler(payload):\n return 'v2'")) + .await + .expect("a redeploy of the same id must be allowed"); + + // Both halves matter. `retired` catches never retiring the old + // registration, which on a real bus leaves two handlers on one id; + // `ids` catches retiring it too late, which removes the id entirely. + assert_eq!(bus.retired(), vec!["pyapp::v".to_string()]); + assert_eq!(bus.ids(), vec!["pyapp::v".to_string()]); + assert_eq!( + bus.invoke("pyapp::v", serde_json::json!(null)) + .await + .unwrap(), + serde_json::json!("v2") + ); + } + + /// An id with no `::` names no namespace and is refused rather than + /// silently placed in a default — the same rule node applies. + #[tokio::test] + async fn a_python_id_without_a_namespace_is_refused() { + let (m, _bus) = manager_and_bus(); + let err = m + .register(reg("bare", "def handler(payload):\n return 1")) + .await + .unwrap_err(); + assert!(err.to_string().contains("namespace"), "{err}"); + } + + /// `teardown namespace=` removes python registrations too, and frees their + /// ids for a later registration. + #[tokio::test] + async fn tearing_down_a_namespace_unregisters_its_python_functions() { + let (m, _bus) = manager_and_bus(); + m.register(reg("pyapp::a", "def handler(payload):\n return 'a'")) + .await + .unwrap(); + m.register(reg("pyapp::b", "def handler(payload):\n return 'b'")) + .await + .unwrap(); + + let torn = m + .teardown(TeardownRequest { + runtime_id: None, + namespace: Some("pyapp".into()), + }) + .await + .unwrap(); + assert!(torn.torn_down); + assert_eq!(torn.namespace.as_deref(), Some("pyapp::")); + assert_eq!(torn.unregistered, vec!["pyapp::a", "pyapp::b"]); + + // The ids are free again. + m.register(reg("pyapp::a", "def handler(payload):\n return 'again'")) + .await + .expect("teardown must release the ids it unregistered"); + } + + /// A namespace nothing registered under is still not found — teardown must + /// not report success for a namespace that never existed. + #[tokio::test] + async fn tearing_down_an_unknown_namespace_is_not_found() { + let (m, _bus) = manager_and_bus(); + let err = m + .teardown(TeardownRequest { + runtime_id: None, + namespace: Some("ghost".into()), + }) + .await + .unwrap_err(); + // `NamespaceNotFound` shares `runtime_not_found` on the wire — one + // code for "the thing you addressed is not here", which is what + // sandbox-code-runner returns too. + assert_eq!(err.code(), "code-runner::runtime_not_found", "{err}"); + } + + /// A handler that raises comes back as an error to the bus, carrying the + /// tenant's own message — not a generic engine failure. + #[tokio::test] + async fn a_raising_handler_answers_the_bus_with_its_own_message() { + let (m, bus) = manager_and_bus(); + m.register(reg( + "pyapp::boom", + "def handler(payload):\n raise ValueError('handler said no')", + )) + .await + .unwrap(); + let err = bus + .invoke("pyapp::boom", serde_json::json!(null)) + .await + .unwrap_err(); + assert!(err.contains("handler said no"), "{err}"); + } + /// Every id this worker owns is claimed in the registry, so no caller can + /// register one — including the console UI's content function, which is + /// published by `ui::register` rather than by `register_all`. + /// + /// This is not hygiene. `register_function` lets a caller choose ANY + /// namespace, `code-runner::` included, and an unseeded worker id is + /// claimable — the claim then reaches `iii_sdk`'s `register_function` on an + /// already-registered id, and its duplicate-id panic ABORTS THE PROCESS. + /// + /// Mutation: seed `STATIC_IDS` instead of `seeded_ids()`. The `ui-content` + /// case then returns `registered: true` — exactly what it did before this + /// was fixed, and a live worker dies on that call. + #[tokio::test] + async fn no_caller_can_claim_an_id_this_worker_owns() { + let (m, _bus) = manager_and_bus(); + for owned in [ + "code-runner::run", + "code-runner::teardown", + "code-runner::register_function", + "code-runner::inject-guidance", + crate::ui::CONTENT_FUNCTION_ID, + ] { + let err = m + .register(reg(owned, "def handler(payload):\n return 1")) + .await + .err() + .unwrap_or_else(|| panic!("{owned} was claimable — a live worker aborts on this")); + assert!(err.to_string().contains("already taken"), "{owned}: {err}"); + } + } +} diff --git a/code-runner/src/manifest.rs b/code-runner/src/manifest.rs new file mode 100644 index 0000000000..73fbe08759 --- /dev/null +++ b/code-runner/src/manifest.rs @@ -0,0 +1,83 @@ +use serde::Serialize; + +use crate::config::CodeRunnerConfig; + +#[derive(Serialize)] +pub struct ModuleManifest { + pub name: String, + pub version: String, + pub description: String, + pub default_config: serde_json::Value, + pub supported_targets: Vec, +} + +pub fn build_manifest() -> ModuleManifest { + let d = CodeRunnerConfig::default(); + ModuleManifest { + name: env!("CARGO_PKG_NAME").to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + description: "Run untrusted Node.js and Python in-process — V8 isolates and \ + CPython-on-WebAssembly behind one run/register_function/teardown API, with no \ + microVM and no /dev/kvm. Code gets a global `iii` and a private scratch directory." + .to_string(), + // Every operator-facing key, so an operator reading the registry + // sees the same surface the configuration entry holds. Serialized + // from the struct rather than hand-listed: node-engine's manifest + // drifted by omitting `external_mb`, and the hand-listed version of + // THIS one drifted by four keys within one branch. + default_config: serde_json::to_value(&d).expect("CodeRunnerConfig serializes"), + supported_targets: vec![env!("TARGET").to_string()], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_roundtrip_has_required_fields() { + let json = serde_json::to_string_pretty(&build_manifest()).unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(parsed["name"], env!("CARGO_PKG_NAME")); + assert_eq!(parsed["version"], env!("CARGO_PKG_VERSION")); + assert!(!parsed["description"].as_str().unwrap().is_empty()); + assert!(parsed["default_config"].is_object()); + assert!(!parsed["supported_targets"].as_array().unwrap().is_empty()); + } + + /// Every operator-facing key must be advertised: the manifest's keys and + /// the configuration schema's properties are the same surface. Compared + /// as key SETS so neither side can drift — the hand-listed predecessor + /// of this test blessed a four-key omission. + #[test] + fn default_config_advertises_every_operator_key() { + let m = build_manifest(); + let advertised: std::collections::BTreeSet = m + .default_config + .as_object() + .expect("default_config is an object") + .keys() + .cloned() + .collect(); + let schema = CodeRunnerConfig::json_schema(); + let configurable: std::collections::BTreeSet = schema["properties"] + .as_object() + .expect("schema has properties") + .keys() + .cloned() + .collect(); + assert_eq!(advertised, configurable); + } + + /// A registry entry that describes the wrong worker is worse than none. + #[test] + fn the_description_names_what_this_worker_actually_is() { + let m = build_manifest(); + assert!(m.description.contains("Python"), "{}", m.description); + assert!( + !m.description.contains("Evaluate JavaScript in V8 isolates"), + "node-engine's description leaked through: {}", + m.description + ); + } +} diff --git a/code-runner/src/node_bus.rs b/code-runner/src/node_bus.rs new file mode 100644 index 0000000000..734412032b --- /dev/null +++ b/code-runner/src/node_bus.rs @@ -0,0 +1,341 @@ +//! The production [`Engine`] implementation for the node engine: the single +//! seam between this worker and the iii bus. +//! +//! The trait itself, its `Value`-shaped types and the `FakeEngine` test double +//! live in `iii-node-core`, which carries no SDK dependency. This file is the +//! half that owns an `IIIClient`. + +use std::sync::Arc; + +use futures::future::BoxFuture; +use iii_sdk::errors::Error; +use iii_sdk::protocol::{RegisterTriggerInput, TriggerAction, TriggerRequest}; +use iii_sdk::trigger::{Trigger, TriggerConfig, TriggerHandler}; +use iii_sdk::{IIIClient, RegisterFunction, RegisterTriggerType}; +use serde_json::Value; + +use iii_node_core::engine::{ + parse_guest_trigger, trigger_callback_payload, CallResult, Engine, ProxyHandler, + TriggerCallback, UnregisterFn, +}; + +/// Stands in when a caller registers without a description, on this worker's +/// own connection. Shadows the core's constant, which names node-engine — +/// the description a caller reads should name the worker they called. +const DYNAMIC_DESC: &str = "Registered at runtime by code-runner; implemented in JavaScript."; + +/// Adapt the SDK's `TriggerConfig` onto the core's SDK-free mirror, so the +/// live path and the fake keep sharing one payload builder. +fn callback_of(config: TriggerConfig) -> TriggerCallback { + TriggerCallback { + id: config.id, + function_id: config.function_id, + config: config.config, + metadata: config.metadata, + } +} + +pub struct IIIEngine { + iii: Arc, + /// Trigger handles keyed by an id THIS engine mints, not the SDK's own. + /// `IIIClient::register_trigger` generates its trigger id internally + /// (see `RegisterTriggerInput`'s doc: "The `id` is auto-generated + /// internally") and never hands it back — only an opaque `Trigger` with + /// an `unregister()` method. `unregister_trigger` takes just an id + /// string, decoupled from that handle, so this map is what lets a later + /// call find the handle again. + triggers: Arc>>, +} + +impl IIIEngine { + pub fn new(iii: Arc) -> Self { + Self { + iii, + triggers: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())), + } + } + + fn description_or_default<'a>(&self, description: &'a Option) -> &'a str { + description.as_deref().unwrap_or(DYNAMIC_DESC) + } +} + +/// Translate the guest's node-shaped registration into the Rust sdk's. +/// +/// The parse and its validation live in `iii-node-core` +/// ([`parse_guest_trigger`]) so `FakeEngine` runs the exact same one — that +/// shared parse is what closed a real defect: `iii.registerTrigger` failed +/// for EVERY documented call with ``missing field `trigger_type` `` while the +/// unit tests stayed green, because the fake took a bare `Value` and never +/// deserialized at all. Only the field rename onto the SDK struct belongs +/// here, because only that names an SDK type. +fn guest_trigger_input(input: Value) -> Result { + let guest = parse_guest_trigger(input)?; + Ok(RegisterTriggerInput { + trigger_type: guest.r#type, + function_id: guest.function_id, + config: guest.config, + metadata: guest.metadata, + }) +} + +/// Best-effort mapping of the guest's `action` string onto the SDK's typed +/// [`TriggerAction`]. `"void"` is the bare keyword the wire contract commits +/// to first, mirroring the enum's own `rename_all = "lowercase"` tag; +/// anything else is tried as a JSON-encoded `TriggerAction` so a future +/// queued action (`{"type":"enqueue","queue":"..."}`) round-trips without +/// touching this again. `iii.trigger`'s `action` field is what supplies the +/// `Some(_)` this now decodes; see the `parse_trigger_action_*` tests below. +fn parse_trigger_action(raw: &str) -> Result { + if raw == "void" { + return Ok(TriggerAction::Void); + } + serde_json::from_str(raw).map_err(|e| format!("invalid action {raw:?}: {e}")) +} + +impl Engine for IIIEngine { + fn call( + &self, + fn_id: String, + payload: Value, + timeout_ms: u64, + action: Option, + ) -> BoxFuture<'static, CallResult> { + let iii = self.iii.clone(); + Box::pin(async move { + let action = action.map(|raw| parse_trigger_action(&raw)).transpose()?; + iii.trigger(TriggerRequest { + function_id: fn_id, + payload, + action, + timeout_ms: Some(timeout_ms), + }) + .await + .map_err(|e| e.to_string()) + }) + } + + fn register( + &self, + fn_id: String, + description: Option, + request_format: Option, + response_format: Option, + handler: ProxyHandler, + ) -> UnregisterFn { + let desc = self.description_or_default(&description).to_string(); + // Without an explicit format the SDK auto-extracts the schema from + // the handler's types — `Value → Value` here, i.e. "any", which is + // exactly what `engine::functions::info` showed before these fields + // existed. The builder calls below are the whole feature. + let mut registration = RegisterFunction::new_async(move |req: Value| { + let handler = handler.clone(); + async move { handler(req).await.map_err(Error::Handler) } + }) + .description(desc); + if let Some(schema) = request_format { + registration = registration.request_format(schema); + } + if let Some(schema) = response_format { + registration = registration.response_format(schema); + } + let function_ref = self.iii.register_function(&fn_id, registration); + Box::new(move || function_ref.unregister()) + } + + fn register_trigger(&self, input: Value) -> BoxFuture<'static, Result> { + let iii = self.iii.clone(); + let triggers = self.triggers.clone(); + Box::pin(async move { + let trigger = iii + .register_trigger(guest_trigger_input(input)?) + .map_err(|e| e.to_string())?; + let id = uuid::Uuid::new_v4().to_string(); + triggers.lock().unwrap().insert(id.clone(), trigger); + Ok(id) + }) + } + + fn unregister_trigger(&self, trigger_id: String) -> BoxFuture<'static, Result<(), String>> { + let triggers = self.triggers.clone(); + Box::pin(async move { + let trigger = triggers + .lock() + .unwrap() + .remove(&trigger_id) + .ok_or_else(|| format!("no such trigger: {trigger_id}"))?; + trigger.unregister(); + Ok(()) + }) + } + + fn register_trigger_type( + &self, + type_id: String, + description: Option, + handler: ProxyHandler, + ) -> UnregisterFn { + let desc = self.description_or_default(&description).to_string(); + let _ = self.iii.register_trigger_type(RegisterTriggerType::new( + type_id.clone(), + desc, + TriggerHandlerAdapter { handler }, + )); + let iii = self.iii.clone(); + Box::new(move || iii.unregister_trigger_type(type_id.clone())) + } +} +/// Adapts a Value-in/Value-out [`ProxyHandler`] to the SDK's [`TriggerHandler`] +/// trait — two typed, `async_trait`-shaped methods each returning +/// `Result<(), Error>`, rather than our one Value-to-Value shape shared with +/// `register`. The `method` field on the payload is what tells the +/// registered JS handler which of the two happened; the guest's return value +/// is otherwise discarded, since `TriggerHandler` has nowhere to put it. +/// +/// Implements the trait by hand at the exact signature `#[async_trait]` +/// desugars to (a `Pin + Send>>`-returning method, which +/// is exactly what `BoxFuture` already is) rather than depending on the +/// `async-trait` macro crate itself, which `iii-sdk` does not re-export and +/// which this worker does not otherwise depend on. +struct TriggerHandlerAdapter { + handler: ProxyHandler, +} + +impl TriggerHandler for TriggerHandlerAdapter { + fn register_trigger<'life0, 'async_trait>( + &'life0 self, + config: TriggerConfig, + ) -> BoxFuture<'async_trait, Result<(), Error>> + where + 'life0: 'async_trait, + Self: 'async_trait, + { + let handler = self.handler.clone(); + Box::pin(async move { + let payload = trigger_callback_payload(callback_of(config), "registerTrigger"); + handler(payload).await.map(|_| ()).map_err(Error::Handler) + }) + } + + fn unregister_trigger<'life0, 'async_trait>( + &'life0 self, + config: TriggerConfig, + ) -> BoxFuture<'async_trait, Result<(), Error>> + where + 'life0: 'async_trait, + Self: 'async_trait, + { + let handler = self.handler.clone(); + Box::pin(async move { + let payload = trigger_callback_payload(callback_of(config), "unregisterTrigger"); + handler(payload).await.map(|_| ()).map_err(Error::Handler) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// Neither constructor touches the network — `IIIClient::new` only builds + /// local state; `connect()` (not called here) is what spawns the + /// background thread. Same trick the real-factory shutdown test below + /// uses for the same reason. + #[test] + fn new_keeps_node_engines_own_fallback_description() { + let iii = Arc::new(IIIClient::new("ws://127.0.0.1:1")); + let engine = IIIEngine::new(iii); + assert_eq!(engine.description_or_default(&None), DYNAMIC_DESC); + assert!( + DYNAMIC_DESC.contains("code-runner"), + "the fallback must name this worker" + ); + } + + /// An explicit description always wins over the fallback. + #[test] + fn an_explicit_description_overrides_the_fallback() { + let iii = Arc::new(IIIClient::new("ws://127.0.0.1:1")); + let engine = IIIEngine::new(iii); + let explicit = Some("what this actually does".to_string()); + assert_eq!( + engine.description_or_default(&explicit), + "what this actually does" + ); + } + + /// The one field rename the guest seam exists for. Caught live by the e2e + /// suite: `iii.registerTrigger` failed for EVERY documented call because + /// the node-shaped object a guest writes was deserialized against the Rust + /// sdk's `RegisterTriggerInput`, whose field is `trigger_type`. + #[test] + fn a_guest_registration_translates_node_type_onto_the_rust_trigger_type() { + let input = guest_trigger_input(json!({ + "type": "app::mytype", + "function_id": "app::react", + "config": { "key": "k" }, + "metadata": { "note": "n" }, + })) + .unwrap(); + assert_eq!(input.trigger_type, "app::mytype"); + assert_eq!(input.function_id, "app::react"); + assert_eq!(input.config, json!({ "key": "k" })); + assert_eq!(input.metadata, Some(json!({ "note": "n" }))); + } + + /// `metadata` is the only optional field; everything else is required, and + /// a missing one is reported in the GUEST's vocabulary. Naming `type` here + /// is the whole point — the message a caller used to get named + /// `trigger_type`, a field their sdk does not have. + #[test] + fn a_guest_registration_reports_a_missing_field_by_its_guest_name() { + let err = + guest_trigger_input(json!({ "function_id": "app::react", "config": {} })).unwrap_err(); + assert!( + err.contains("invalid trigger registration") && err.contains("`type`"), + "a missing type must be named as `type`, got: {err}" + ); + assert!( + !err.contains("trigger_type"), + "the refusal must not name a field the guest sdk does not have: {err}" + ); + } + + /// The Rust spelling is NOT a second way in: one field, one name. Without + /// `type` this is a missing field, whatever else it carries. + #[test] + fn a_guest_registration_does_not_accept_the_rust_spelling() { + assert!(guest_trigger_input(json!({ + "trigger_type": "app::mytype", + "function_id": "app::react", + "config": {}, + })) + .is_err()); + } + + /// `parse_trigger_action` had zero coverage before Task 10 — nothing ever + /// called `Engine::call` with `Some(_)` for `action` until `iii.trigger` + /// did. These three cover its whole contract: the bare keyword, the + /// JSON-decoded fallback, and the clean-error case. + #[test] + fn parse_trigger_action_maps_the_bare_void_keyword() { + let action = parse_trigger_action("void").unwrap(); + assert!(matches!(action, TriggerAction::Void)); + } + + #[test] + fn parse_trigger_action_json_decodes_anything_else() { + let action = parse_trigger_action(r#"{"type":"enqueue","queue":"payments"}"#).unwrap(); + assert!(matches!(action, TriggerAction::Enqueue { queue } if queue == "payments")); + } + + #[test] + fn parse_trigger_action_reports_malformed_input_cleanly() { + let err = parse_trigger_action("not json").unwrap_err(); + assert!( + err.contains("invalid action"), + "unhelpful error, got: {err}" + ); + } +} diff --git a/code-runner/src/python_bus.rs b/code-runner/src/python_bus.rs new file mode 100644 index 0000000000..1b3fad1429 --- /dev/null +++ b/code-runner/src/python_bus.rs @@ -0,0 +1,54 @@ +//! The production [`GuestBridge`]: what guest Python's `iii` global can reach. +//! +//! The mirror of [`crate::node_bus`] for the other engine. `iii-python-core` +//! is bus-free, so this is the only thing in the program that turns a guest +//! request into a real engine call. +//! +//! Deliberately one method. The guest gets `trigger` and nothing else — no +//! `register_function`, no triggers, no shutdown. Registration is a WORKER +//! function taking `source` (`code-runner::register_function`), so a +//! guest-callable version would duplicate a capability the API already +//! exposes while dragging in the whole id-ownership apparatus; and `shutdown` +//! is a guest-callable self-DoS that a `return` already covers. + +use std::sync::Arc; + +use futures::future::BoxFuture; +use iii_python_core::runner::GuestBridge; +use iii_sdk::protocol::TriggerRequest; +use iii_sdk::IIIClient; +use serde_json::Value; + +pub struct IIIBridge { + iii: Arc, +} + +impl IIIBridge { + pub fn new(iii: Arc) -> Self { + Self { iii } + } +} + +impl GuestBridge for IIIBridge { + fn call( + &self, + fn_id: String, + payload: Value, + timeout_ms: u64, + ) -> BoxFuture<'static, Result> { + let iii = self.iii.clone(); + Box::pin(async move { + iii.trigger(TriggerRequest { + function_id: fn_id, + payload, + action: None, + timeout_ms: Some(timeout_ms), + }) + .await + // The guest sees the engine's own message. It is already the + // caller-facing text a bus error carries, and reshaping it here + // would only make a tenant's error less like every other worker's. + .map_err(|e| e.to_string()) + }) + } +} diff --git a/code-runner/src/translate.rs b/code-runner/src/translate.rs new file mode 100644 index 0000000000..371a06678b --- /dev/null +++ b/code-runner/src/translate.rs @@ -0,0 +1,341 @@ +//! Core outcome → wire response. +//! +//! The one semantic this file exists for: **a failing script is a RESPONSE, +//! not an error.** Both engines return a structured error when tenant code +//! throws; sandbox-code-runner's contract — which this worker reproduces — +//! reports that as a successful call with a non-zero `exit_code` and the +//! diagnostics on `stderr`. Errors stay reserved for infrastructure. +//! +//! Getting this backwards is how hostile input pages an operator: a tenant +//! that can reach an `internal`-shaped error at will has a way to make the +//! worker look broken. + +use iii_node_core::error::NodeEngineError; +use iii_node_core::runtime::{EvalOutcome, LogLine}; + +use crate::error::CodeRunnerError; +use crate::functions::run::RunResponse; + +/// Split level-tagged log lines into the two streams a process has. +/// +/// `console.error` and `console.warn` are what Node itself routes to stderr, +/// so that is the faithful split. Rejected: everything to stdout (discards +/// the distinction the levels exist to carry), and a `[warn] ` text prefix +/// (nothing on the wire says these were ever level-tagged — that would be +/// invented data). +fn split_streams(logs: &[LogLine]) -> (String, String) { + let mut out = String::new(); + let mut err = String::new(); + for line in logs { + let sink = if line.level == "error" || line.level == "warn" { + &mut err + } else { + &mut out + }; + sink.push_str(&line.message); + sink.push('\n'); + } + (out, err) +} + +/// A successful eval. +pub fn node_ok(outcome: EvalOutcome, runtime_id: Option, duration_ms: u64) -> RunResponse { + let (stdout, stderr) = split_streams(&outcome.logs); + RunResponse { + runtime_id, + stdout, + stderr, + exit_code: 0, + success: true, + duration_ms, + result: outcome.result, + } +} + +/// A failed eval: either a response (the tenant's own fault) or an error +/// (ours). +/// +/// `runtime_id` is threaded in rather than read off the error, because the +/// caller who ran one-shot never held one and must not learn it. +pub fn node_err( + err: NodeEngineError, + runtime_id: Option, + duration_ms: u64, +) -> Result { + match err { + // The tenant's script threw. Its stdout still stands, and its message + // goes where a process would put it. + NodeEngineError::EvalFailed { message, logs } => { + let (stdout, mut stderr) = split_streams(&logs); + if !stderr.is_empty() && !stderr.ends_with('\n') { + stderr.push('\n'); + } + stderr.push_str(&message); + stderr.push('\n'); + Ok(RunResponse { + runtime_id, + stdout, + stderr, + exit_code: 1, + success: false, + duration_ms, + result: serde_json::Value::Null, + }) + } + // Everything below is infrastructure, and stays an error. + NodeEngineError::Timeout => Err(CodeRunnerError::Timeout), + NodeEngineError::Oom => Err(CodeRunnerError::ResourceExhausted( + "the runtime exceeded its memory cap and was killed".into(), + )), + NodeEngineError::RuntimeNotFound(id) => Err(CodeRunnerError::RuntimeNotFound(id)), + NodeEngineError::RuntimeGone(id) => Err(CodeRunnerError::Expired(id)), + NodeEngineError::Capacity(max) => Err(CodeRunnerError::Capacity(format!( + "all {max} runtime slots are in use" + ))), + NodeEngineError::NamespaceDenied { .. } + | NodeEngineError::IdTaken(_) + | NodeEngineError::InvalidRequest(_) => { + // `message()`, not `to_string()`: Display prefixes the core's own + // `node-engine::`, and this error is about to be surfaced + // under the REAL wire code — the engine shows `code: message`, so + // the core's prefix would read as a second, phantom code. + Err(CodeRunnerError::InvalidRequest(err.message())) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn log(level: &str, message: &str) -> LogLine { + LogLine { + level: level.to_string(), + message: message.to_string(), + } + } + + #[test] + fn console_error_and_warn_go_to_stderr_the_rest_to_stdout() { + let (out, err) = split_streams(&[ + log("log", "one"), + log("error", "bad"), + log("info", "two"), + log("warn", "careful"), + ]); + assert_eq!(out, "one\ntwo\n"); + assert_eq!(err, "bad\ncareful\n"); + } + + /// The whole point of this module. Mutation: return + /// `Err(CodeRunnerError::HandlerError(message))` instead — the call then + /// fails where sandbox-code-runner's contract says it succeeds, and the + /// tenant's stdout is lost. + #[test] + fn a_thrown_script_is_a_response_with_its_stdout_intact() { + let resp = node_err( + NodeEngineError::EvalFailed { + message: "Error: boom".into(), + logs: vec![log("log", "printed first")], + }, + None, + 7, + ) + .expect("a tenant throw must be a response, not an error"); + assert_eq!(resp.stdout, "printed first\n"); + assert!(resp.stderr.contains("Error: boom")); + assert_eq!(resp.exit_code, 1); + assert!(!resp.success); + assert_eq!(resp.result, serde_json::Value::Null); + assert_eq!(resp.duration_ms, 7); + } + + /// The other half of the same rule: infrastructure stays an error, so a + /// timeout is never reported as a successful run. Mutation: map `Timeout` + /// into the response arm with `exit_code: 124`. + #[test] + fn infrastructure_failures_stay_errors() { + for (err, code) in [ + (NodeEngineError::Timeout, "code-runner::timeout"), + (NodeEngineError::Oom, "code-runner::resource_exhausted"), + (NodeEngineError::Capacity(4), "code-runner::capacity"), + ( + NodeEngineError::RuntimeGone("rt-1".into()), + "code-runner::expired", + ), + ] { + let got = node_err(err, None, 0).expect_err("must stay an error"); + assert_eq!(got.code(), code); + } + } + + /// The caller-facing message must not smuggle the core's retired + /// `node-engine::` prefix past the re-coding above. Mutation: build + /// the message with `err.to_string()` again. + #[test] + fn re_coded_errors_do_not_leak_the_core_s_own_code() { + let got = node_err(NodeEngineError::IdTaken("app::x".into()), None, 0) + .expect_err("an id clash stays an error"); + let msg = got.to_string(); + assert!( + msg.contains("id app::x is already registered"), + "lost the actual explanation: {msg}" + ); + assert!(!msg.contains("node-engine::"), "core code leaked: {msg}"); + } + + #[test] + fn a_successful_eval_reports_zero_and_carries_its_value() { + let resp = node_ok( + EvalOutcome { + result: serde_json::json!({ "n": 2 }), + logs: vec![log("log", "hi")], + registered: vec![], + }, + Some("rt-1".into()), + 3, + ); + assert_eq!(resp.exit_code, 0); + assert!(resp.success); + assert_eq!(resp.stdout, "hi\n"); + assert_eq!(resp.result, serde_json::json!({ "n": 2 })); + assert_eq!(resp.runtime_id.as_deref(), Some("rt-1")); + } +} + +// --- python --- + +use iii_python_core::error::{ErrorKind, PythonEngineError}; +use iii_python_core::manager::RunOutput; + +/// A successful python run. +/// +/// The streams arrive already separated — the sandbox captured two pipes — +/// so unlike the node path there is nothing to split. `truncated` becomes a +/// final stderr line rather than a wire field, because sandbox-code-runner's +/// response has nowhere else to say it and silence would be worse. +pub fn python_ok(out: RunOutput, duration_ms: u64) -> RunResponse { + let mut stderr = out.stderr; + if out.truncated { + stderr.push_str("[code-runner] output was truncated; further output is dropped\n"); + } + RunResponse { + runtime_id: None, + stdout: out.stdout, + stderr, + exit_code: 0, + success: true, + duration_ms, + result: out.result, + } +} + +/// A failed python run: a response when the tenant's own code failed, an +/// error when the sandbox did. +/// +/// The split mirrors the node path exactly. `Clean(n)` is the truest process +/// shape there is — a tenant `sys.exit(3)` — and python-core reports it as a +/// `PythonException` naming the status, which is why the message is carried +/// through to stderr rather than reshaped. +pub fn python_err(e: PythonEngineError, duration_ms: u64) -> Result { + let tenant = |e: PythonEngineError| { + let mut stderr = e.message.clone(); + stderr.push('\n'); + if let Some(tb) = &e.traceback { + stderr.push_str(tb); + if !tb.ends_with('\n') { + stderr.push('\n'); + } + } + RunResponse { + runtime_id: None, + stdout: String::new(), + stderr, + exit_code: 1, + success: false, + duration_ms, + result: serde_json::Value::Null, + } + }; + match e.kind { + ErrorKind::SyntaxError | ErrorKind::PythonException | ErrorKind::ResultTooLarge => { + Ok(tenant(e)) + } + ErrorKind::InvalidInput => Err(CodeRunnerError::InvalidRequest(e.message)), + ErrorKind::RuntimeNotFound => Err(CodeRunnerError::RuntimeNotFound(e.message)), + // Admission, not a mid-run kill: retrying later can succeed once a + // slot frees, which is exactly the distinction `resource_exhausted` + // exists to keep separate. + ErrorKind::Capacity => Err(CodeRunnerError::Capacity(e.message)), + ErrorKind::Timeout => Err(CodeRunnerError::Timeout), + // Both are mid-run caps: retrying identically will fail identically, + // which is exactly what `capacity` must NOT be used to say. + ErrorKind::OutOfMemory | ErrorKind::DiskQuotaExceeded => { + Err(CodeRunnerError::ResourceExhausted(e.message)) + } + ErrorKind::Internal => Err(CodeRunnerError::Engine(e.message)), + } +} + +#[cfg(test)] +mod python_tests { + use super::*; + + /// Same rule as the node side, and it must hold identically or the two + /// languages have different contracts behind one API. Mutation: move + /// `PythonException` into the error arm. + #[test] + fn a_python_exception_is_a_response_with_its_traceback_on_stderr() { + let mut e = PythonEngineError::new(ErrorKind::PythonException, "ValueError: boom"); + e.traceback = Some("Traceback (most recent call last):\n File \"\"".into()); + let r = python_err(e, 5).expect("a tenant exception must be a response"); + assert_eq!(r.exit_code, 1); + assert!(!r.success); + assert!(r.stderr.contains("ValueError: boom")); + assert!(r.stderr.contains(""), "the traceback must survive"); + assert_eq!(r.result, serde_json::Value::Null); + } + + #[test] + fn python_infrastructure_failures_stay_errors() { + for (kind, code) in [ + (ErrorKind::Timeout, "code-runner::timeout"), + (ErrorKind::OutOfMemory, "code-runner::resource_exhausted"), + ( + ErrorKind::DiskQuotaExceeded, + "code-runner::resource_exhausted", + ), + (ErrorKind::Internal, "code-runner::engine"), + (ErrorKind::InvalidInput, "code-runner::invalid_request"), + (ErrorKind::RuntimeNotFound, "code-runner::runtime_not_found"), + // Admission vs mid-run: `capacity` may succeed on retry, + // `resource_exhausted` will not. Folding them together would tell + // a caller the opposite of the truth. + (ErrorKind::Capacity, "code-runner::capacity"), + ] { + let got = + python_err(PythonEngineError::new(kind, "x"), 0).expect_err("must stay an error"); + assert_eq!(got.code(), code, "wrong mapping for {kind:?}"); + } + } + + /// A one-shot python run has nothing to address, and truncation must be + /// said out loud since the response has no field for it. + #[test] + fn a_successful_python_run_carries_its_streams_and_says_when_truncated() { + let r = python_ok( + RunOutput { + result: serde_json::json!(6), + stdout: "working\n".into(), + stderr: String::new(), + truncated: true, + }, + 9, + ); + assert_eq!(r.stdout, "working\n"); + assert_eq!(r.result, serde_json::json!(6)); + assert!(r.success); + assert!(r.runtime_id.is_none()); + assert!(r.stderr.contains("truncated"), "stderr was {:?}", r.stderr); + } +} diff --git a/code-runner/src/truncate.rs b/code-runner/src/truncate.rs new file mode 100644 index 0000000000..be944810bf --- /dev/null +++ b/code-runner/src/truncate.rs @@ -0,0 +1,181 @@ +//! Output truncation: cap result and stream payloads without breaking UTF-8. +//! +//! Oversized responses are replaced or elided with explicit markers naming +//! what was dropped and how big it was, mirroring the engine's +//! `include_payloads` omission and context-manager's cap marker. A capped +//! response is still `success: true` — the run succeeded; only the echo +//! is bounded. + +use serde_json::Value; + +/// Cap a result value, replacing oversized payloads with a marker string. +/// +/// If the serialized value fits in `max_bytes` or `max_bytes` is 0 (disabled), +/// returns the value unchanged. Otherwise, replaces it with a string marker +/// naming what was dropped and how to recover it: slicing, aggregation, +/// or write to `iii.files` and return a summary. +/// +/// # Marker format +/// +/// `` +/// +/// where `{KB}` is the original serialized size in kilobytes (bytes / 1024, +/// rounded down), and `{shape}` describes the structure: +/// - `N array elements` for arrays +/// - `N object keys` for objects +/// - `a N-char string` for strings (counting Unicode code points, not bytes) +/// - `a value` for other types +pub fn cap_result(value: Value, max_bytes: usize) -> Value { + if max_bytes == 0 { + return value; + } + + let serialized = serde_json::to_string(&value).unwrap_or_default(); + if serialized.len() <= max_bytes { + return value; + } + + let kb = serialized.len() / 1024; + let shape = match &value { + Value::Array(a) => format!("{} array elements", a.len()), + Value::Object(o) => format!("{} object keys", o.len()), + Value::String(s) => format!("a {}-char string", s.chars().count()), + _ => "a value".into(), + }; + + let marker = format!( + "", + kb, shape + ); + + Value::String(marker) +} + +/// Cap a stream, keeping head and tail around a truncation marker. +/// +/// If the string fits in `max_bytes` or `max_bytes` is 0 (disabled), +/// returns the string unchanged. Otherwise, keeps 60% of the available budget +/// for the head (floored to a UTF-8 character boundary) and 40% for the tail +/// (ceiled to a character boundary from the end), splicing a marker between. +/// +/// The marker names the stream and original size: `\n[…{kind} truncated: was ~{KB} KB; middle omitted]\n` +/// where `{KB}` is the original size in kilobytes (bytes / 1024, rounded down). +/// +/// This preserves both the first output (which often contains the first failure) +/// and the final summary line, while ensuring the total never exceeds +/// `max_bytes + marker allowance`. +pub fn cap_stream(kind: &str, s: String, max_bytes: usize) -> String { + if max_bytes == 0 || s.len() <= max_bytes { + return s; + } + + let kb = s.len() / 1024; + let marker = format!("\n[…{} truncated: was ~{} KB; middle omitted]\n", kind, kb); + let marker_len = marker.len(); + + // Budget for head and tail combined + let budget = max_bytes.saturating_sub(marker_len); + + // Head = 60% of budget, tail = 40% + let head_budget = (budget * 60) / 100; + let tail_budget = budget - head_budget; + + // Extract head: floor to char boundary + let head = floor_char_boundary(&s, head_budget); + + // Extract tail: ceil to char boundary from the end + let tail = ceil_char_boundary_from_end(&s, tail_budget); + + format!("{}{}{}", head, marker, tail) +} + +/// Find the floor of a character boundary at or before the given byte position. +/// +/// If `pos` is already at a character boundary, returns `pos`. +/// Otherwise, scans backward to find the last character boundary. +fn floor_char_boundary(s: &str, pos: usize) -> &str { + let pos = pos.min(s.len()); + let mut pos = pos; + while pos > 0 && !s.is_char_boundary(pos) { + pos -= 1; + } + &s[..pos] +} + +/// Find the ceil of a character boundary, taking the last `size` bytes of the string. +/// +/// Returns the rightmost `size` bytes (or fewer if fewer bytes are available), +/// floored to a character boundary. This extracts the tail of a string. +fn ceil_char_boundary_from_end(s: &str, size: usize) -> &str { + if size >= s.len() { + return s; + } + let start = s.len() - size; + let mut start = start; + // Scan forward from `start` to find the first valid character boundary + while start < s.len() && !s.is_char_boundary(start) { + start += 1; + } + &s[start..] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_values_pass_through_untouched() { + let v = serde_json::json!([1, 2, 3]); + assert_eq!(cap_result(v.clone(), 32_768), v); + assert_eq!(cap_stream("stdout", "hi\n".into(), 16_384), "hi\n"); + } + + #[test] + fn zero_disables_the_cap() { + let big = serde_json::json!(vec![0; 100_000]); + assert_eq!(cap_result(big.clone(), 0), big); + } + + #[test] + fn oversized_result_becomes_a_marker_string_naming_shape_and_size() { + let big = serde_json::json!((0..100_000).collect::>()); + let capped = cap_result(big, 32_768); + let s = capped.as_str().expect("marker is a string"); + assert!(s.starts_with("` and link-swaps it on change, styles-before-scripts on boot. +//! +//! The registration machinery (content function `code-runner::ui-content`, one +//! Message-path trigger per asset, `III_CODE_RUNNER_UI_WATCH` hot-reload +//! watcher) lives in the shared `iii-console-ui` crate (path-linked from +//! `workers/crates/console-ui`); this module only names the assets and embeds +//! their bytes. +//! +//! The assets are compiled from `ui/` by esbuild (react + @iii-dev/console-ui +//! external — they resolve through the console's import map at runtime) and +//! embedded at compile time so the worker stays one self-contained binary. +//! For the dev loop, set `III_CODE_RUNNER_UI_WATCH` to the build output +//! directory (or `1` for `ui/dist`): the worker polls both files and +//! re-registers a changed asset's trigger — every open console tab hot-swaps +//! it. + +use std::sync::Arc; + +use iii_console_ui::ConsoleUi; +use iii_sdk::IIIClient; + +pub const PAGE_PATH: &str = "code-runner/page.js"; +pub const STYLES_PATH: &str = "code-runner/styles.css"; + +/// The content function `ConsoleUi` publishes to serve the two assets. +/// +/// Declared here and passed EXPLICITLY below rather than left to +/// `ConsoleUi`'s `::ui-content` default, because this id must also be +/// SEEDED into the runtime manager's id registry (see +/// `functions::seeded_ids`). A const that merely happened to match the default +/// would silently stop matching if either side changed, and the failure mode is +/// a process abort — so the two reads come from one place. +pub const CONTENT_FUNCTION_ID: &str = "code-runner::ui-content"; + +/// Built by `build.rs` (esbuild over `ui/`). +const PAGE_JS: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/ui/dist/page.js")); +const STYLES_CSS: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/ui/dist/styles.css")); + +fn console_ui() -> ConsoleUi { + ConsoleUi::new("code-runner") + .content_function_id(CONTENT_FUNCTION_ID) + .script(PAGE_PATH, PAGE_JS) + .style(STYLES_PATH, STYLES_CSS) +} + +/// Register the code-runner worker's console UI. Call after +/// `functions::register_all`. +pub fn register(iii: &Arc) { + console_ui().register(iii); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ui_builder_accepts_the_assets() { + // The builder panics on any path/kind the console would reject. + let _ = console_ui(); + } + + #[test] + fn embedded_page_is_nonempty_esm() { + assert!(PAGE_JS.contains("export"), "built page.js looks wrong"); + } + + /// One renderer per user-facing op, all reachable from `setup(host)`. + /// Dropping one from `ui/src/function-trigger-message/index.tsx` silently + /// falls that op back to the console's raw-JSON card; this catches it. + #[test] + fn every_rendered_op_is_wired_in() { + for op in ["run", "register_function", "teardown"] { + assert!( + PAGE_JS.contains(&format!("code-runner::{op}")), + "no renderer for code-runner::{op} in the built page.js" + ); + } + } + + /// The Workers-tab configuration form ships in the same page asset. + /// Dropping the `host.configForms.register('code-runner', …)` call + /// silently falls the entry back to the console's generic schema form; + /// this catches it. + #[test] + fn the_config_form_is_wired_in() { + assert!( + PAGE_JS.contains("configForms"), + "page.js never registers the configuration form" + ); + assert!( + PAGE_JS.contains("cr-cfg-form"), + "page.js lost the config form component" + ); + } + + /// `inject-guidance` is a harness-internal `pre_generate` hook, not a call + /// anyone makes; rendering it would put a card in front of a mechanism. + #[test] + fn the_guidance_hook_is_never_rendered() { + assert!( + !PAGE_JS.contains(crate::functions::inject_guidance::GUIDANCE_HOOK_ID), + "the harness-internal guidance hook must not have a renderer" + ); + } + + /// A bundled React copy surfaces at runtime as a cryptic "Invalid hook + /// call" — the shared specifiers have to stay bare imports resolved by the + /// console's import map. + #[test] + fn react_stays_external() { + for internal in ["__SECRET_INTERNALS", "ReactCurrentDispatcher"] { + assert!( + !PAGE_JS.contains(internal), + "react appears to be bundled into page.js ({internal} found)" + ); + } + // Every card uses hooks, so react must be in there — as a bare import + // the console's import map resolves, never as bundled source. The + // closing quote matters: without it `from "react-dom/client"` and + // friends satisfy the check with react itself bundled. + assert!( + PAGE_JS.contains(r#"from "react""#), + "react should be imported, not bundled" + ); + } + + #[test] + fn embedded_styles_are_scoped() { + // esbuild prints the attribute selector unquoted ([data-iii-ui=code-runner]). + assert!( + STYLES_CSS.contains(r#"[data-iii-ui="code-runner"]"#) + || STYLES_CSS.contains("[data-iii-ui=code-runner]"), + "built styles.css must be scoped under the worker's data-iii-ui attribute" + ); + } + + /// The completion value is what this worker's wire adds over + /// `sandbox-code-runner`'s, and the `run` card is the only place a caller + /// sees it. A stylesheet that lost the block would render it unstyled. + #[test] + fn the_result_block_is_styled_and_rendered() { + assert!( + STYLES_CSS.contains("cr-ui-result-body"), + "styles.css lost the completion-value block" + ); + assert!( + PAGE_JS.contains("cr-ui-result-body"), + "page.js never renders the completion value" + ); + } + + /// This worker has no `network` field on any request — neither engine has + /// any network at all — so a chip claiming one must not survive the port + /// from sandbox-code-runner's UI, where it is a real create-time flag. + #[test] + fn nothing_claims_a_network_capability() { + assert!( + !PAGE_JS.contains("cr-run-net"), + "the network chip was ported from sandbox-code-runner, but this \ + worker's wire has no `network` field — the chip would claim a knob \ + that does not exist" + ); + } +} diff --git a/code-runner/tests/e2e/.gitignore b/code-runner/tests/e2e/.gitignore new file mode 100644 index 0000000000..d49fa14585 --- /dev/null +++ b/code-runner/tests/e2e/.gitignore @@ -0,0 +1,6 @@ +reports/* +!reports/.gitkeep +node_modules/ +dist/ +*.log +.DS_Store diff --git a/code-runner/tests/e2e/README.md b/code-runner/tests/e2e/README.md new file mode 100644 index 0000000000..00cf913246 --- /dev/null +++ b/code-runner/tests/e2e/README.md @@ -0,0 +1,73 @@ +# code-runner — end-to-end harness + +Self-asserting suite for the `code-runner` worker. Brings up a private engine, +starts the worker against it, and exercises the whole public surface — +`run`, `register_function`, `teardown` — over a real bus, **in both +languages**. + +No docker, no database, no `/dev/kvm`, and **no `python3` or `node` on the +host**: V8 is linked into the worker binary and the interpreter is CPython +compiled to WebAssembly and embedded in it, not shelled out to. The only host +dependency is the engine itself. + +## Run + +```sh +./run-tests.sh # everything +./run-tests.sh --filter register # only cases whose group/name matches +./run-tests.sh --filter 'non-ascii' # matches group or case name +./run-tests.sh --keep # leave engine + worker up for poking +``` + +Exits 0 on PASS, 1 on any failure. + +### Prerequisites + +- Rust toolchain (`cargo` on `$PATH`) +- Node.js 20+ (`npm` on `$PATH`) — for the harness worker, not for the sandbox +- The iii engine, either on `$PATH` as `iii` or via `III_BIN=/path/to/iii` + +## Groups + +| group | what it covers | +|---|---| +| `run` | one-shot runs in both languages, the shared response shape, non-ASCII round-trips, and guest `iii.trigger` reaching the bus | +| `keep` | `keep: true` → `runtime_id` → `teardown`, and that an id routes to its own engine without being told the language | +| `register` | handlers published on the real bus and invoked through it, in both languages, plus namespace teardown | +| `errors` | the taxonomy: which failures are responses and which are errors | + +### Why this suite and not more unit tests + +Three things only a live engine can show: + +- **A registered function actually reaches the catalog** and answers a + trigger. A unit test can prove the router called `Engine::register`; it + cannot prove a caller can then invoke the id. +- **The response shape is identical across engines** once it has been through + serde, the wire, and the SDK's decoder — the whole promise of this worker is + one API over two of them. +- **A duplicate function id would abort the process.** Node and python claim + ids in one shared registry precisely to prevent that; `register :: a function + id cannot be claimed by both engines` asserts the refusal *and* that the + worker is still serving afterwards, which is the half a panic would have + taken out. + +### Leaks fail later cases, not their own + +`max_runtimes` is shared across both engines, so a case that creates a runtime +or a namespace and does not tear it down fails a **later** case with a capacity +error that says nothing about the real cause. Every case here tears down what +it creates, in a `finally`. + +### Ports + +The engine listens on a random high port, never 49134 — a developer's own +stack usually holds that one, and a harness that hijacked it would take their +workers down. The port is verified free before use, because the engine logs +"address already in use" and then keeps running, which would otherwise produce +a harness talking to somebody else's engine and reporting nonsense about it. + +## Artifacts + +`reports/` holds `report.json` (machine-readable results) plus the engine, +worker and harness logs from the last run. All git-ignored. diff --git a/code-runner/tests/e2e/code-runner.config.yaml b/code-runner/tests/e2e/code-runner.config.yaml new file mode 100644 index 0000000000..8d8599507e --- /dev/null +++ b/code-runner/tests/e2e/code-runner.config.yaml @@ -0,0 +1,16 @@ +# code-runner configuration for the e2e harness, fed to the worker as its +# one-time `--config` seed for the configuration worker (there is no shipped +# config.yaml anymore — `CodeRunnerConfig::default()` in src/config.rs is the +# reference). Keys left unset (the output caps, inject_guidance) run at those +# struct defaults, and the caps case asserts against them. Both engines are +# configured from this one entry — `CodeRunnerConfig::python()` maps the +# shared keys onto the python engine, so a value here that only moved node +# would be a bug. +max_runtimes: 8 # live runtimes across both engines +default_timeout_ms: 5000 # per run when unspecified +max_timeout_ms: 30000 # ceiling a request's timeout_ms is clamped to +idle_ttl_secs: 900 # reap a runtime with no activity for this long +heap_mb: 128 # V8 object-heap cap per node runtime +external_mb: 64 # off-heap (ArrayBuffer) cap per node runtime +scratch_mb: 64 # `iii.files` scratch cap per node runtime +scratch_files: 256 # `iii.files` file-count cap per node runtime diff --git a/code-runner/tests/e2e/config.yaml b/code-runner/tests/e2e/config.yaml new file mode 100644 index 0000000000..4bea8a5d28 --- /dev/null +++ b/code-runner/tests/e2e/config.yaml @@ -0,0 +1,18 @@ +# iii engine configuration for the code-runner e2e harness — `iii -c config.yaml`. +# +# Infrastructure only. Neither code-runner nor the harness is engine-managed: +# run-tests.sh starts the engine, then spawns the code-runner binary as a host +# process, then runs the harness. No docker and no database are needed — this +# worker's only dependency is the engine itself. +workers: + - name: iii-worker-manager + config: + host: 127.0.0.1 + port: ${III_E2E_PORT} + - name: iii-observability + config: + enabled: true + service_name: code-runner-e2e + exporter: memory + logs_console_output: true + sampling_ratio: 1.0 diff --git a/code-runner/tests/e2e/reports/.gitkeep b/code-runner/tests/e2e/reports/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/code-runner/tests/e2e/run-tests.sh b/code-runner/tests/e2e/run-tests.sh new file mode 100755 index 0000000000..3adbc93c57 --- /dev/null +++ b/code-runner/tests/e2e/run-tests.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# End-to-end harness for the code-runner worker. +# +# Brings up a private engine on its own port, starts code-runner against it, +# and runs the self-asserting harness. Exits 0 on PASS, 1 on any FAIL. +# +# Covers BOTH engines through one worker, so a case that passes for node and +# fails for python is a case this suite is meant to catch. +# +# ./run-tests.sh # everything +# ./run-tests.sh --filter run # only cases whose group/name matches +# ./run-tests.sh --keep # leave the engine + worker running +# +# Deliberately uses a random high port, never 49134: a developer's own stack +# usually holds that one, and a harness that hijacks it would take their +# workers down with it. +set -uo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/../../.." && pwd)" +HARNESS="$HERE/workers/harness" +LOGS="$HERE/reports" +mkdir -p "$LOGS" + +FILTER="" +KEEP=0 +while [ $# -gt 0 ]; do + case "$1" in + --filter) + # Guarded: `shift 2` past the end of $@ shifts NOTHING, and with no + # value consumed this loop would spin on `--filter` forever. + [ $# -ge 2 ] || { echo "missing value for --filter" >&2; exit 2; } + FILTER="$2" + shift 2 + ;; + --filter=*) FILTER="${1#*=}"; shift ;; + --keep) KEEP=1; shift ;; + -h|--help) sed -n '2,12p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +III_BIN="${III_BIN:-$(command -v iii || true)}" +if [ -z "$III_BIN" ] || [ ! -x "$III_BIN" ]; then + echo "FAIL: no iii engine binary. Put it on PATH or set III_BIN=/path/to/iii" >&2 + exit 1 +fi +command -v npm >/dev/null 2>&1 || { echo "FAIL: npm not found" >&2; exit 1; } +command -v cargo >/dev/null 2>&1 || { echo "FAIL: cargo not found" >&2; exit 1; } + +# A free port, verified free rather than assumed: the engine logs "address +# already in use" and then keeps running, so an occupied port produces a +# harness that talks to somebody else's engine and reports nonsense. +pick_port() { + for _ in $(seq 1 40); do + local p=$(( (RANDOM % 10000) + 40000 )) + if ! (exec 3<>"/dev/tcp/127.0.0.1/$p") 2>/dev/null; then echo "$p"; return 0; fi + exec 3>&- 2>/dev/null || true + done + return 1 +} +PORT="$(pick_port)" || { echo "FAIL: could not find a free port" >&2; exit 1; } +URL="ws://127.0.0.1:$PORT" +echo "==> engine port $PORT" + +ENGINE_PID=""; WORKER_PID="" +cleanup() { + local code=$? + if [ "$KEEP" = "1" ]; then + echo "==> --keep: engine pid ${ENGINE_PID:-none}, worker pid ${WORKER_PID:-none} on $URL" + return + fi + # `|| true` on every guard AND every kill: `set -e` is on by the time this + # trap runs (turned on right after the harness invocation, and never turned + # back off), so a false `[ -n ... ]` test or a `kill -9` on a PID that + # already exited in response to the plain `kill` above — both ordinary, + # expected outcomes here — would otherwise abort this trap before it ever + # reaches `exit $code`, reporting the WRONG exit status regardless of what + # the suite actually did. `2>/dev/null` alone only silences the message, + # not the exit status `set -e` reacts to. + [ -n "$WORKER_PID" ] && kill "$WORKER_PID" 2>/dev/null || true + [ -n "$ENGINE_PID" ] && kill "$ENGINE_PID" 2>/dev/null || true + sleep 1 + [ -n "$WORKER_PID" ] && kill -9 "$WORKER_PID" 2>/dev/null || true + [ -n "$ENGINE_PID" ] && kill -9 "$ENGINE_PID" 2>/dev/null || true + exit $code +} +trap cleanup EXIT INT TERM + +echo "==> building code-runner (release)" +( cd "$ROOT/code-runner" && cargo build --release --bin code-runner ) \ + > "$LOGS/build.log" 2>&1 || { echo "FAIL: build failed, see $LOGS/build.log" >&2; tail -30 "$LOGS/build.log"; exit 1; } + +RUN_CFG="$LOGS/engine.config.yaml" +sed "s|\${III_E2E_PORT}|$PORT|" "$HERE/config.yaml" > "$RUN_CFG" + +echo "==> starting engine" +( cd "$LOGS" && "$III_BIN" -c "$RUN_CFG" --no-update-check ) > "$LOGS/engine.log" 2>&1 & +ENGINE_PID=$! + +for i in $(seq 1 60); do + if (exec 3<>"/dev/tcp/127.0.0.1/$PORT") 2>/dev/null; then exec 3>&- ; break; fi + kill -0 "$ENGINE_PID" 2>/dev/null || { echo "FAIL: engine exited during startup" >&2; tail -30 "$LOGS/engine.log"; exit 1; } + sleep 0.5 + [ "$i" = "60" ] && { echo "FAIL: engine never listened on $PORT" >&2; tail -30 "$LOGS/engine.log"; exit 1; } +done +echo "==> engine up" + +echo "==> starting code-runner worker" +( cd "$ROOT/code-runner" && ./target/release/code-runner --url "$URL" --config "$HERE/code-runner.config.yaml" ) \ + > "$LOGS/code-runner.log" 2>&1 & +WORKER_PID=$! +sleep 1 +kill -0 "$WORKER_PID" 2>/dev/null || { echo "FAIL: code-runner exited immediately" >&2; tail -30 "$LOGS/code-runner.log"; exit 1; } + +if [ ! -d "$HARNESS/node_modules" ]; then + echo "==> npm install" + ( cd "$HARNESS" && npm install ) > "$LOGS/npm.log" 2>&1 \ + || { echo "FAIL: npm install failed, see $LOGS/npm.log" >&2; tail -20 "$LOGS/npm.log"; exit 1; } +fi + +echo "==> running suite" +set +e +( cd "$HARNESS" && III_URL="$URL" HARNESS_FILTER="$FILTER" \ + HARNESS_REPORT_PATH="$LOGS/report.json" npm run --silent dev ) 2>&1 | tee "$LOGS/harness.log" +set -e +# `|| true`: grep exits 1 when the harness died before printing HARNESS_DONE, +# and set -e (restored just above) would kill the script HERE — before the +# "no result line" diagnostic below ever prints. +SUITE_LINE="$(grep -a 'HARNESS_DONE' "$LOGS/harness.log" | tail -1 || true)" + +echo +echo "================ code-runner e2e ================" +if [ -z "$SUITE_LINE" ]; then + echo "FAIL: harness produced no result line (crashed?). See $LOGS/harness.log" + exit 1 +fi +echo "$SUITE_LINE" +echo "report: $LOGS/report.json" +echo "=================================================" + +case "$SUITE_LINE" in *PASS*) exit 0 ;; *) exit 1 ;; esac diff --git a/code-runner/tests/e2e/workers/harness/iii.worker.yaml b/code-runner/tests/e2e/workers/harness/iii.worker.yaml new file mode 100644 index 0000000000..0bd526905c --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/iii.worker.yaml @@ -0,0 +1,8 @@ +name: harness +runtime: + language: typescript + package_manager: npm + entry: src/worker.ts +scripts: + install: 'npm install' + start: 'npm run dev' diff --git a/code-runner/tests/e2e/workers/harness/package-lock.json b/code-runner/tests/e2e/workers/harness/package-lock.json new file mode 100644 index 0000000000..1b6af6af6c --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/package-lock.json @@ -0,0 +1,1137 @@ +{ + "name": "code-runner-e2e-harness", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "code-runner-e2e-harness", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "iii-sdk": "0.22.1" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "tsx": "^4.0.0", + "typescript": "^5.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@iii-dev/helpers": { + "version": "0.22.1", + "resolved": "https://registry.npmjs.org/@iii-dev/helpers/-/helpers-0.22.1.tgz", + "integrity": "sha512-/lI2hOr7Y1mHll3e2bu3hrekgA1S0VRRSD/gk61kvEZGGFfNIbbpO8rhog1bnSzEqfiPGV5XQUT8ZI4Ie+BEDg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/api-logs": "^0.57.0", + "@opentelemetry/core": "^1.30.0", + "@opentelemetry/instrumentation": "^0.57.0", + "@opentelemetry/otlp-transformer": "^0.57.0", + "@opentelemetry/resources": "^1.30.0", + "@opentelemetry/sdk-logs": "^0.57.0", + "@opentelemetry/sdk-metrics": "^1.30.0", + "@opentelemetry/sdk-trace-base": "^1.30.0", + "@opentelemetry/sdk-trace-node": "^1.30.0", + "@opentelemetry/semantic-conventions": "^1.28.0", + "ws": "^8.18.3" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz", + "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/api-logs": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.57.2.tgz", + "integrity": "sha512-uIX52NnTM0iBh84MShlpouI7UKqkZ7MrUszTmaypHBu4r7NofznSnQRfJ+uUeDtQDj6w8eFGg5KBLDAwAPz1+A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@opentelemetry/context-async-hooks": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-1.30.1.tgz", + "integrity": "sha512-s5vvxXPVdjqS3kTLKMeBMvop9hbWkwzBpu+mUO2M7sZtlkyDJGwFe33wRKnbaYDo8ExRVBIIdwIGrqpxHuKttA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/core": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.30.1.tgz", + "integrity": "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/core/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", + "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@opentelemetry/instrumentation": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.57.2.tgz", + "integrity": "sha512-BdBGhQBh8IjZ2oIIX6F2/Q3LKm/FDDKi6ccYKcBTeilh6SNdNKveDOLk73BkSJjQLJk6qe4Yh+hHw1UPhCDdrg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@types/shimmer": "^1.2.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1", + "semver": "^7.5.2", + "shimmer": "^1.2.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-transformer": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.57.2.tgz", + "integrity": "sha512-48IIRj49gbQVK52jYsw70+Jv+JbahT8BqT2Th7C4H7RCM9d0gZ5sgNPoMpWldmfjvIsSgiGJtjfk9MeZvjhoig==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-logs": "0.57.2", + "@opentelemetry/sdk-metrics": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "protobufjs": "^7.3.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/propagator-b3": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-1.30.1.tgz", + "integrity": "sha512-oATwWWDIJzybAZ4pO76ATN5N6FFbOA1otibAVlS8v90B4S1wClnhRUk7K+2CHAwN1JKYuj4jh/lpCEG5BAqFuQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/propagator-jaeger": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-jaeger/-/propagator-jaeger-1.30.1.tgz", + "integrity": "sha512-Pj/BfnYEKIOImirH76M4hDaBSx6HyZ2CXUqk+Kj02m6BB80c/yo4BdWkn/1gDFfU+YPY+bPR2U0DKBfdxCKwmg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/resources": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.30.1.tgz", + "integrity": "sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/resources/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", + "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@opentelemetry/sdk-logs": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.57.2.tgz", + "integrity": "sha512-TXFHJ5c+BKggWbdEQ/inpgIzEmS2BGQowLE9UhsMd7YYlUfBQJ4uax0VF/B5NYigdM/75OoJGhAV3upEhK+3gg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.4.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-metrics": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-1.30.1.tgz", + "integrity": "sha512-q9zcZ0Okl8jRgmy7eNW3Ku1XSgg3sDLa5evHZpCwjspw7E8Is4K/haRPDJrBcX3YSn/Y7gUvFnByNYEKQNbNog==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.30.1.tgz", + "integrity": "sha512-jVPgBbH1gCy2Lb7X0AVQ8XAfgg0pJ4nvl8/IiQA6nxOsPvS+0zMJaFSs2ltXe0J6C8dqjcnpyqINDJmU30+uOg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", + "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@opentelemetry/sdk-trace-node": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-1.30.1.tgz", + "integrity": "sha512-cBjYOINt1JxXdpw1e5MlHmFRc5fgj4GW/86vsKFxJCJ8AL4PdVtYH41gWwl4qd4uQjqEL1oJVrXkSy5cnduAnQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/context-async-hooks": "1.30.1", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/propagator-b3": "1.30.1", + "@opentelemetry/propagator-jaeger": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "semver": "^7.5.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.43.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.43.0.tgz", + "integrity": "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@types/node": { + "version": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/shimmer": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz", + "integrity": "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg==", + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/iii-sdk": { + "version": "0.22.1", + "resolved": "https://registry.npmjs.org/iii-sdk/-/iii-sdk-0.22.1.tgz", + "integrity": "sha512-xgOtrmoTEBCBY7KFRfQse6EHlyK+qCVBA3QG+WiG0cHxpBamrqpkY3L+l14SbdLZR5ZoTtyrwiAUVZNHPNaY3w==", + "license": "Apache-2.0", + "dependencies": { + "@iii-dev/helpers": "0.22.1", + "@opentelemetry/api": "^1.9.0", + "ws": "^8.18.3" + } + }, + "node_modules/import-in-the-middle": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.15.0.tgz", + "integrity": "sha512-bpQy+CrsRmYmoPMAE/0G33iwRqwW4ouqdRg8jgbH3aKuCtOc8lxgmYXg2dMM92CRiGP660EtBcymH/eVUpCSaA==", + "license": "Apache-2.0", + "dependencies": { + "acorn": "^8.14.0", + "acorn-import-attributes": "^1.9.5", + "cjs-module-lexer": "^1.2.2", + "module-details-from-path": "^1.0.3" + } + }, + "node_modules/is-core-module": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", + "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/protobufjs": { + "version": "7.6.5", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz", + "integrity": "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/require-in-the-middle": { + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz", + "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "module-details-from-path": "^1.0.3", + "resolve": "^1.22.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/resolve": { + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shimmer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz", + "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==", + "license": "BSD-2-Clause" + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tsx": { + "version": "4.23.11", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.11.tgz", + "integrity": "sha512-Ry2oTEUnhBdeEdWIztY8kf3/nBGnPnjMLVGL0YfdRXMORuPER5NlKmayqxtxRxwB1xBN+RivRaJfe7PM1rtiyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/code-runner/tests/e2e/workers/harness/package.json b/code-runner/tests/e2e/workers/harness/package.json new file mode 100644 index 0000000000..1ee84ef437 --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/package.json @@ -0,0 +1,20 @@ +{ + "name": "code-runner-e2e-harness", + "version": "0.1.0", + "type": "module", + "private": true, + "description": "Self-asserting end-to-end harness for the iii code-runner worker.", + "scripts": { + "dev": "tsx src/worker.ts", + "build": "tsc" + }, + "dependencies": { + "iii-sdk": "0.22.1" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "tsx": "^4.0.0", + "typescript": "^5.4.0" + }, + "license": "Apache-2.0" +} diff --git a/code-runner/tests/e2e/workers/harness/src/cases-errors.ts b/code-runner/tests/e2e/workers/harness/src/cases-errors.ts new file mode 100644 index 0000000000..f06c07861a --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/cases-errors.ts @@ -0,0 +1,123 @@ +import { expectContains, expectEqual, type TestCase } from './cases.ts' + +/** + * The taxonomy, over the real wire. + * + * The load-bearing distinction this worker inherits from + * `sandbox-code-runner`: **a failing script is a RESPONSE, not an error.** A + * tenant exception comes back as a resolved call with `exit_code: 1` and the + * traceback in `stderr`; errors are reserved for infrastructure. Getting this + * backwards is the single most likely way to break a caller written against + * the sibling worker, so both halves are asserted in both languages. + */ +export const ERROR_CASES: TestCase[] = [ + { + name: 'node: a thrown error is a response with exit_code 1, not a bus error', + async run(ctx) { + const r = await ctx.call('code-runner::run', { + lang: 'node', + code: 'throw new Error("boom-n")', + }) + expectEqual(r.exit_code, 1, 'a thrown script exits 1') + expectEqual(r.success, false, 'a thrown script does not succeed') + expectContains(r.stderr, 'boom-n', 'the message belongs in stderr') + }, + }, + + { + name: 'python: a raised exception is a response with exit_code 1, not a bus error', + async run(ctx) { + const r = await ctx.call('code-runner::run', { + lang: 'python', + code: 'raise ValueError("boom-p")', + }) + expectEqual(r.exit_code, 1, 'a raising script exits 1') + expectEqual(r.success, false, 'a raising script does not succeed') + expectContains(r.stderr, 'boom-p', 'the message belongs in stderr') + }, + }, + + { + name: 'python: a syntax error is a response too, naming the line', + async run(ctx) { + const r = await ctx.call('code-runner::run', { lang: 'python', code: 'def (:' }) + expectEqual(r.exit_code, 1, 'a syntax error exits 1') + expectContains(r.stderr, 'line', 'the message should name the line') + }, + }, + + { + name: 'a script that keeps printing still returns, and its logs are capped', + async run(ctx) { + const r = await ctx.call('code-runner::run', { + lang: 'python', + code: 'for i in range(200000):\n print("x" * 40)\nresult = "done"', + timeout_ms: 25000, + }) + // Either it finished or it hit its budget; what must NOT happen is an + // unbounded response. The binding cap is the worker's max_stream_bytes + // (16 KiB default, unset in code-runner.config.yaml so this suite runs + // the shipped default), head+tail around a truncation marker — the + // small allowance covers the marker. The old 2 MiB bound let a doubled + // (or hundredfold) cap regression sail through. + expectEqual( + r.stdout.length <= 16 * 1024 + 200, + true, + `stdout should be capped at max_stream_bytes, got ${r.stdout.length} bytes`, + ) + }, + }, + + { + name: 'an infinite loop is killed at its own timeout, and the worker survives', + async run(ctx) { + for (const [lang, code] of [ + ['node', 'while (true) {}'], + ['python', 'while True:\n pass'], + ] as const) { + await ctx.expectError( + () => ctx.call('code-runner::run', { lang, code, timeout_ms: 1500 }), + 'code-runner::timeout', + ) + // Still serving, which is the whole point of the kill. + const after = await ctx.call('code-runner::run', { + lang, + code: lang === 'node' ? 'return 1' : 'result = 1', + }) + expectEqual(after.result, 1, `${lang} should still be serving after a timeout`) + } + }, + }, + + { + name: 'a run with no lang and no runtime_id is refused, saying which to pass', + async run(ctx) { + const err = await ctx.expectError( + () => ctx.call('code-runner::run', { code: 'return 1' }), + 'code-runner::invalid_request', + ) + expectContains(err.message ?? '', 'lang', 'the refusal should name the missing field') + }, + }, + + { + name: 'an unknown runtime_id is not found, not a generic engine error', + async run(ctx) { + await ctx.expectError( + () => ctx.call('code-runner::run', { runtime_id: 'rt-does-not-exist', code: 'return 1' }), + 'code-runner::runtime_not_found', + ) + }, + }, + + { + name: 'teardown refuses both runtime_id and namespace together, and neither', + async run(ctx) { + await ctx.expectError( + () => ctx.call('code-runner::teardown', { runtime_id: 'rt-x', namespace: 'ns' }), + 'code-runner::invalid_request', + ) + await ctx.expectError(() => ctx.call('code-runner::teardown', {}), 'code-runner::invalid_request') + }, + }, +] diff --git a/code-runner/tests/e2e/workers/harness/src/cases-keep.ts b/code-runner/tests/e2e/workers/harness/src/cases-keep.ts new file mode 100644 index 0000000000..657b4dd3c0 --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/cases-keep.ts @@ -0,0 +1,108 @@ +import { expect, expectEqual, type TestCase } from './cases.ts' + +/** + * `keep: true`, `runtime_id`, and `teardown`. + * + * Every case here tears down what it creates. `max_runtimes` is shared across + * both engines, so a leak fails a LATER case with a capacity error that says + * nothing about the real cause. + */ +export const KEEP_CASES: TestCase[] = [ + { + name: 'node: a kept runtime persists globals and files across calls', + async run(ctx) { + const first = await ctx.call('code-runner::run', { + lang: 'node', + keep: true, + code: 'globalThis.n = 41; await iii.files.write("f.txt", "kept"); return 1', + }) + const id = first.runtime_id + expect(typeof id === 'string' && id.length > 0, 'keep:true must mint a runtime_id') + + try { + const second = await ctx.call('code-runner::run', { + runtime_id: id, + code: 'return [globalThis.n + 1, await iii.files.readText("f.txt")]', + }) + expectEqual(second.result, [42, 'kept'], 'globals and files should both survive') + expectEqual(second.runtime_id, id, 'the response should echo the runtime it ran in') + } finally { + await ctx.call('code-runner::teardown', { runtime_id: id }) + } + }, + }, + + { + // The half that could not exist before park-and-loop landed: python's + // interpreter used to be one-shot, so `keep` persisted files only. + name: 'python: a kept runtime persists globals and files across calls', + async run(ctx) { + const first = await ctx.call('code-runner::run', { + lang: 'python', + keep: true, + code: 'import json\nn = 41\nopen("/work/f.txt", "w").write("kept")\nresult = 1', + }) + const id = first.runtime_id + expect(typeof id === 'string' && id.length > 0, 'keep:true must mint a runtime_id') + + try { + const second = await ctx.call('code-runner::run', { + runtime_id: id, + code: 'result = [n + 1, open("/work/f.txt").read(), json.dumps([1])]', + }) + expectEqual(second.result, [42, 'kept', '[1]'], 'globals, files and imported modules should all survive') + } finally { + await ctx.call('code-runner::teardown', { runtime_id: id }) + } + }, + }, + + { + name: 'a torn-down runtime_id is gone, in both languages', + async run(ctx) { + for (const lang of ['node', 'python'] as const) { + const started = await ctx.call('code-runner::run', { + lang, + keep: true, + code: lang === 'node' ? 'return 1' : 'result = 1', + }) + const torn = await ctx.call('code-runner::teardown', { runtime_id: started.runtime_id }) + expectEqual(torn.torn_down, true, `${lang}: teardown should report success`) + + await ctx.expectError( + () => ctx.call('code-runner::run', { runtime_id: started.runtime_id, code: 'return 1' }), + 'code-runner::runtime_not_found', + ) + } + }, + }, + + { + // Routing must not depend on reading the id — it is documented as a + // capability-secret — so the worker keeps an ownership map instead. + name: 'a runtime_id routes to its own engine without being told the language', + async run(ctx) { + const py = await ctx.call('code-runner::run', { + lang: 'python', + keep: true, + code: 'marker = "python"\nresult = 1', + }) + try { + // No `lang` on this call at all: the id alone has to route it. + const back = await ctx.call('code-runner::run', { + runtime_id: py.runtime_id, + code: 'result = marker', + }) + expectEqual(back.result, 'python', 'the id should have routed to the python engine') + + // And asking for the wrong one is refused rather than silently obeyed. + await ctx.expectError( + () => ctx.call('code-runner::run', { runtime_id: py.runtime_id, lang: 'node', code: 'return 1' }), + 'code-runner::invalid_request', + ) + } finally { + await ctx.call('code-runner::teardown', { runtime_id: py.runtime_id }) + } + }, + }, +] diff --git a/code-runner/tests/e2e/workers/harness/src/cases-register.ts b/code-runner/tests/e2e/workers/harness/src/cases-register.ts new file mode 100644 index 0000000000..213ab10353 --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/cases-register.ts @@ -0,0 +1,225 @@ +import { expect, expectContains, expectEqual, type TestCase, until } from './cases.ts' + +/** + * `code-runner::register_function` — a handler published on the real bus and + * invoked through it. + * + * This is the group that most needs to be end-to-end. A unit test can prove + * the router calls `Engine::register`; only a live engine proves the id + * reaches the catalog, that a caller can trigger it, and that its answer comes + * back over the wire. Every case tears its namespace down. + */ +export const REGISTER_CASES: TestCase[] = [ + { + name: 'node: a registered handler is callable through the bus', + async run(ctx) { + const r = await ctx.call('code-runner::register_function', { + function_id: 'e2e-node::greet', + lang: 'node', + description: 'e2e node handler', + // Node's source DEFINES `handler`, exactly like python's — the + // worker wraps it and publishes on its behalf. Calling + // `iii.registerFunction` here instead would register a second time + // under the same id, which is a registration failure, not a shortcut. + source: 'function handler(p) { return `hello ${p.who}` }', + }) + expectEqual(r.registered, true, 'registration should report success') + + try { + await until( + () => ctx.call('e2e-node::greet', { who: 'world' }).catch(() => undefined), + 'e2e-node::greet to be live on the bus', + ) + const answer = await ctx.call('e2e-node::greet', { who: 'world' }) + expectEqual(answer, 'hello world', 'the handler should answer through the bus') + } finally { + await ctx.call('code-runner::teardown', { namespace: 'e2e-node' }) + } + }, + }, + + { + // The capability this branch added. Python's guest has no + // `iii.registerFunction` — `python.wasm` exports `_start` and nothing + // else — so the host publishes on its behalf and dispatches each + // invocation as one turn on the namespace's pinned interpreter. + name: 'python: a registered handler is callable through the bus', + async run(ctx) { + const r = await ctx.call('code-runner::register_function', { + function_id: 'e2e-py::greet', + lang: 'python', + description: 'e2e python handler', + source: 'def handler(payload):\n return "hello " + payload["who"]', + }) + expectEqual(r.registered, true, 'registration should report success') + + try { + await until( + () => ctx.call('e2e-py::greet', { who: 'world' }).catch(() => undefined), + 'e2e-py::greet to be live on the bus', + ) + const answer = await ctx.call('e2e-py::greet', { who: 'world' }) + expectEqual(answer, 'hello world', 'the handler should answer through the bus') + } finally { + await ctx.call('code-runner::teardown', { namespace: 'e2e-py' }) + } + }, + }, + + { + // The reason python `register_function` could not exist before + // park-and-loop: a handler needs an interpreter that outlives the call. + name: 'python: a handler keeps the state its registration built', + async run(ctx) { + await ctx.call('code-runner::register_function', { + function_id: 'e2e-state::next', + lang: 'python', + source: [ + 'import itertools', + '_seq = itertools.count(1)', + 'def handler(payload):', + ' return next(_seq)', + ].join('\n'), + }) + + try { + await until( + () => ctx.call('e2e-state::next', {}).catch(() => undefined), + 'e2e-state::next to be live on the bus', + ) + // The first call may have been consumed by the `until` probe above, + // so assert the SEQUENCE rather than absolute values. + const a = await ctx.call('e2e-state::next', {}) + const b = await ctx.call('e2e-state::next', {}) + expectEqual(b, a + 1, 'the counter should advance across invocations') + } finally { + await ctx.call('code-runner::teardown', { namespace: 'e2e-state' }) + } + }, + }, + + { + name: 'python: source that defines no handler fails the registration', + async run(ctx) { + const err = await ctx.expectError( + () => + ctx.call('code-runner::register_function', { + function_id: 'e2e-bad::nope', + lang: 'python', + source: 'x = 1 # no handler here', + }), + 'code-runner::invalid_request', + ) + expectContains(err.message ?? '', 'handler(payload)', 'the refusal should say what to write') + + // Nothing was published, so the namespace does not exist to tear down. + await ctx.expectError( + () => ctx.call('code-runner::teardown', { namespace: 'e2e-bad' }), + 'code-runner::runtime_not_found', + ) + }, + }, + + { + // `request_format`/`response_format` must land in the engine's catalog — + // that is the only reason they exist. Asserted through the same + // functions::info a real caller reads, searching the serialized response + // for a marker property so the case does not pin info's exact envelope. + name: 'register formats show up in functions::info', + async run(ctx) { + await ctx.call('code-runner::register_function', { + function_id: 'e2e-fmt::double', + lang: 'node', + source: 'export function handler(p) { return p.fmt_marker_n * 2 }', + description: 'doubles fmt_marker_n', + request_format: { + type: 'object', + properties: { fmt_marker_n: { type: 'number' } }, + }, + response_format: { type: 'number' }, + }) + try { + const info = await ctx.call('engine::functions::info', { function_id: 'e2e-fmt::double' }) + const raw = JSON.stringify(info) + expectContains(raw, 'fmt_marker_n', 'request_format should reach the catalog') + // Not OR-ed with fmt_marker_n: the line above already proved that, + // which made the disjunction always-true. This entry carries BOTH + // formats, so no "any" fallback schema may survive anywhere in it. + expect(!raw.includes('"any"'), 'schema should replace any') + } finally { + await ctx.call('code-runner::teardown', { namespace: 'e2e-fmt' }) + } + }, + }, + + { + // Ids are claimed in ONE registry across both engines. Two registries + // would each believe they owned the id, both would reach the SDK's + // register_function, and the second would abort the process on its + // duplicate-id panic — so this case doubles as a liveness check: if the + // worker died, every later case fails too. + name: 'a function id cannot be claimed by both engines', + async run(ctx) { + await ctx.call('code-runner::register_function', { + function_id: 'e2e-clash::fn', + lang: 'python', + source: 'def handler(payload):\n return 1', + }) + + try { + await ctx.expectError( + () => + ctx.call('code-runner::register_function', { + function_id: 'e2e-clash::fn', + lang: 'node', + source: 'function handler() { return 2 }', + }), + 'code-runner::invalid_request', + ) + + // The worker is still serving, which is the half a duplicate-id panic + // would have taken out. + const alive = await ctx.call('code-runner::run', { lang: 'node', code: 'return 1' }) + expectEqual(alive.result, 1, 'the worker should still be serving runs') + } finally { + await ctx.call('code-runner::teardown', { namespace: 'e2e-clash' }) + } + }, + }, + + { + name: 'teardown by namespace unregisters the functions it reports', + async run(ctx) { + for (const id of ['e2e-down::a', 'e2e-down::b']) { + await ctx.call('code-runner::register_function', { + function_id: id, + lang: 'python', + source: `def handler(payload):\n return ${JSON.stringify(id)}`, + }) + } + await until(() => ctx.call('e2e-down::a', {}).catch(() => undefined), 'e2e-down::a to be live on the bus') + + const torn = await ctx.call('code-runner::teardown', { namespace: 'e2e-down' }) + expectEqual(torn.torn_down, true, 'teardown should report success') + expectEqual(torn.namespace, 'e2e-down::', 'the namespace should come back canonical') + expectEqual( + [...(torn.unregistered ?? [])].sort(), + ['e2e-down::a', 'e2e-down::b'], + 'both functions should be reported unregistered', + ) + + // Gone from the bus, and the id is free for a fresh registration. + await until( + async () => ((await ctx.call('e2e-down::a', {}).catch(() => 'gone')) === 'gone' ? true : undefined), + 'e2e-down::a to disappear from the bus', + ) + const again = await ctx.call('code-runner::register_function', { + function_id: 'e2e-down::a', + lang: 'python', + source: 'def handler(payload):\n return "reused"', + }) + expect(again.registered === true, 'teardown must release the ids it unregistered') + await ctx.call('code-runner::teardown', { namespace: 'e2e-down' }) + }, + }, +] diff --git a/code-runner/tests/e2e/workers/harness/src/cases-run.ts b/code-runner/tests/e2e/workers/harness/src/cases-run.ts new file mode 100644 index 0000000000..15e3205907 --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/cases-run.ts @@ -0,0 +1,112 @@ +import { expect, expectContains, expectEqual, type TestCase, until } from './cases.ts' + +/** + * One-shot `code-runner::run`, in both languages. + * + * Every case here runs `keep: false`, so nothing needs tearing down. The + * point of running the same assertion twice is that this worker's promise is + * ONE api over two engines — a response shape that differs by language is the + * defect this group exists to catch. + */ +export const RUN_CASES: TestCase[] = [ + { + name: 'all four functions are live on the bus with typed schemas', + async run(ctx) { + const ids = [ + 'code-runner::run', + 'code-runner::teardown', + 'code-runner::register_function', + 'code-runner::inject-guidance', + ] + const found = await until(async () => { + const info = await ctx.call('engine::functions::info', { function_ids: ids }) + const fns = (info?.functions ?? []).filter((f: any) => f && !f.error) + return fns.length === ids.length ? fns : undefined + }, 'all four code-runner functions to be live on the bus') + + const run = found.find((f: any) => f.function_id === 'code-runner::run') + expect( + Array.isArray(run.request_schema?.required) && run.request_schema.required.includes('code'), + `run.request_schema.required should include "code", got ${JSON.stringify(run.request_schema?.required)}`, + ) + }, + }, + + { + name: 'node: a one-shot run returns its value and a process-shaped response', + async run(ctx) { + const r = await ctx.call('code-runner::run', { lang: 'node', code: 'return 2 + 2' }) + expectEqual(r.result, 4, 'result should be the expression value') + expectEqual(r.exit_code, 0, 'a clean run exits 0') + expectEqual(r.success, true, 'a clean run succeeds') + expect(r.runtime_id === undefined, `keep:false must mint no runtime_id, got ${r.runtime_id}`) + expect(typeof r.duration_ms === 'number', 'duration_ms should be a number') + }, + }, + + { + name: 'python: a one-shot run returns its value and a process-shaped response', + async run(ctx) { + const r = await ctx.call('code-runner::run', { lang: 'python', code: 'result = 2 + 2' }) + expectEqual(r.result, 4, 'result should be what the code assigned') + expectEqual(r.exit_code, 0, 'a clean run exits 0') + expectEqual(r.success, true, 'a clean run succeeds') + expect(r.runtime_id === undefined, `keep:false must mint no runtime_id, got ${r.runtime_id}`) + }, + }, + + { + name: 'both languages report stdout and stderr on the same two fields', + async run(ctx) { + const node = await ctx.call('code-runner::run', { + lang: 'node', + code: 'console.log("out-n"); console.error("err-n"); return 1', + }) + expectContains(node.stdout, 'out-n', 'node stdout') + expectContains(node.stderr, 'err-n', 'node stderr') + + const py = await ctx.call('code-runner::run', { + lang: 'python', + code: 'import sys\nprint("out-p")\nprint("err-p", file=sys.stderr)\nresult = 1', + }) + expectContains(py.stdout, 'out-p', 'python stdout') + expectContains(py.stderr, 'err-p', 'python stderr') + }, + }, + + { + // Exercises the guest's ASCII-escaped envelope on the python side + // (wrapper.py: json.dumps defaults to ensure_ascii=True) and the plain + // UTF-8 path on the node side. Both must return the same string. + // + // The text is embedded in `code` rather than passed in: this wire has no + // `payload` field — it is sandbox-code-runner's, byte for byte, and that + // worker has none either. + name: 'non-ascii round-trips through both engines unchanged', + async run(ctx) { + const text = 'olá — 日本語 ±3°' + for (const [lang, code] of [ + ['node', `return ${JSON.stringify(text)}`], + ['python', `result = ${JSON.stringify(text)}`], + ] as const) { + const r = await ctx.call('code-runner::run', { lang, code }) + expectEqual(r.result, text, `${lang} should return the string unchanged`) + } + }, + }, + + { + name: 'python guest code can call back into the bus through iii.trigger', + async run(ctx) { + const r = await ctx.call('code-runner::run', { + lang: 'python', + code: [ + "answer = iii.trigger({'function_id': 'code-runner::run',", + " 'payload': {'lang': 'node', 'code': 'return 40 + 2'}})", + 'result = answer["result"]', + ].join('\n'), + }) + expectEqual(r.result, 42, 'the guest should see the inner run’s result') + }, + }, +] diff --git a/code-runner/tests/e2e/workers/harness/src/cases.ts b/code-runner/tests/e2e/workers/harness/src/cases.ts new file mode 100644 index 0000000000..1fc19d6867 --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/cases.ts @@ -0,0 +1,105 @@ +import type { IIIClient, InvocationError } from 'iii-sdk' + +/** + * What a case gets. + * + * `code-runner::run` with `keep: true` and `code-runner::register_function` + * both leave state behind, so a case that creates either MUST tear it down — + * `max_runtimes` is shared across both engines and a leak here fails a later + * case with a capacity error that says nothing about the real cause. + */ +export interface CaseContext { + /** Trigger any engine function. Returns parsed JSON; throws on engine error. */ + call: (functionId: string, payload?: unknown) => Promise + /** Direct SDK access, for anything `call` cannot express. */ + iii: IIIClient + /** + * Runs `fn`, asserts it rejects with an error whose MESSAGE mentions + * `kind`, and returns that error so the caller can go on to check it + * further. Message, not `code`: the SDK's `code` is its own transport-level + * one (`invocation_failed` for every handler error) and this worker's + * `code-runner::…` code travels inside the message. + */ + expectError: (fn: () => Promise, kind: string) => Promise +} + +export interface TestCase { + name: string + run(ctx: CaseContext): Promise +} + +export interface CaseGroup { + name: string + cases: TestCase[] +} + +export function expect(cond: boolean, msg: string): asserts cond { + if (!cond) throw new Error(msg) +} + +/** + * Stable JSON: object keys sorted, array order preserved. + * + * A value that round-trips through the engine comes back with its object keys + * in whatever order the JSON encoders on the way chose, which is not the order + * it was written in. Comparing raw `JSON.stringify` output therefore fails on + * equal objects — a false failure that says nothing about the worker. Array + * order is meaningful and is left alone. + */ +function canonical(v: unknown): string { + const walk = (x: unknown): unknown => { + if (Array.isArray(x)) return x.map(walk) + if (x && typeof x === 'object') { + return Object.fromEntries( + Object.keys(x as Record) + .sort() + .map((k) => [k, walk((x as Record)[k])]), + ) + } + return x + } + return JSON.stringify(walk(v)) +} + +export function expectEqual(actual: unknown, expected: unknown, msg: string): void { + if (canonical(actual) !== canonical(expected)) { + throw new Error(`${msg}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`) + } +} + +export function expectContains(haystack: string, needle: string, msg: string): void { + if (!haystack.includes(needle)) { + throw new Error(`${msg}: ${JSON.stringify(needle)} not found in ${JSON.stringify(haystack)}`) + } +} + +/** + * Poll until `fn()` returns a value, or give up. + * + * Registrations reach the bus asynchronously, and even a fixed catalog id + * like `code-runner::run` is only visible once the worker's own connection + * has finished registering it — worth polling for rather than assuming. A + * function published by `register_function` needs the same patience. + */ +export async function until( + fn: () => Promise, + what: string, + timeoutMs = 8000, + intervalMs = 100, +): Promise { + const deadline = Date.now() + timeoutMs + let last: unknown + for (;;) { + try { + const v = await fn() + if (v !== undefined) return v + } catch (e) { + last = e + } + if (Date.now() > deadline) { + const tail = last ? ` (last error: ${(last as any)?.message ?? last})` : '' + throw new Error(`timed out after ${timeoutMs}ms waiting for ${what}${tail}`) + } + await new Promise((r) => setTimeout(r, intervalMs)) + } +} diff --git a/code-runner/tests/e2e/workers/harness/src/groups.ts b/code-runner/tests/e2e/workers/harness/src/groups.ts new file mode 100644 index 0000000000..dfa8806e2b --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/groups.ts @@ -0,0 +1,13 @@ +import type { CaseGroup } from './cases.ts' +import { ERROR_CASES } from './cases-errors.ts' +import { KEEP_CASES } from './cases-keep.ts' +import { REGISTER_CASES } from './cases-register.ts' +import { RUN_CASES } from './cases-run.ts' + +/** Order matters only for readability; cases are independent by construction. */ +export const ALL_GROUPS: CaseGroup[] = [ + { name: 'run', cases: RUN_CASES }, + { name: 'keep', cases: KEEP_CASES }, + { name: 'register', cases: REGISTER_CASES }, + { name: 'errors', cases: ERROR_CASES }, +] diff --git a/code-runner/tests/e2e/workers/harness/src/runner.ts b/code-runner/tests/e2e/workers/harness/src/runner.ts new file mode 100644 index 0000000000..f6dc85a45d --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/runner.ts @@ -0,0 +1,112 @@ +import { mkdirSync, writeFileSync } from 'node:fs' +import { dirname } from 'node:path' +import type { IIIClient, InvocationError } from 'iii-sdk' +import type { CaseContext, CaseGroup, TestCase } from './cases.ts' +import { ALL_GROUPS } from './groups.ts' + +interface CaseResult { + group: string + case: string + status: 'PASS' | 'FAIL' + error?: string + duration_ms: number +} + +export interface RunnerOptions { + iii: IIIClient + reportPath: string + /** Substring filter on `group` or `group :: case`. */ + filter?: string + callTimeoutMs?: number +} + +export class Runner { + constructor(private opts: RunnerOptions) {} + + private async call(functionId: string, payload: unknown = {}): Promise { + return this.opts.iii.trigger({ + function_id: functionId, + payload: payload ?? {}, + timeoutMs: this.opts.callTimeoutMs ?? 20000, + }) + } + + private async runCase(group: string, c: TestCase): Promise { + const start = Date.now() + + const ctx: CaseContext = { + call: (id, payload) => this.call(id, payload), + iii: this.opts.iii, + expectError: async (fn, kind) => { + try { + await fn() + } catch (e: any) { + const err: InvocationError = e + // Matched against the MESSAGE, not `code`. The SDK reports its own + // transport-level code — `invocation_failed` for every handler + // error — and carries this worker's `code-runner::…` code inside + // the message. Asserting on `err.code` therefore passes or fails + // identically for every taxonomy entry, which is no assertion at + // all. node-engine's harness learned the same thing. + const msg = err?.message ?? String(e) + if (!msg.includes(kind)) { + throw new Error(`expected an error mentioning ${JSON.stringify(kind)}, got: ${msg}`) + } + return err + } + throw new Error(`expected a throw mentioning ${JSON.stringify(kind)}, but the call resolved`) + }, + } + + try { + await c.run(ctx) + return { group, case: c.name, status: 'PASS', duration_ms: Date.now() - start } + } catch (e: any) { + return { + group, + case: c.name, + status: 'FAIL', + error: e?.message ?? String(e), + duration_ms: Date.now() - start, + } + } + } + + async runAll(): Promise<{ pass: number; total: number; results: CaseResult[] }> { + const useColor = process.stdout.isTTY === true + const GREEN = useColor ? '\x1b[32m' : '' + const RED = useColor ? '\x1b[31m' : '' + const DIM = useColor ? '\x1b[2m' : '' + const RESET = useColor ? '\x1b[0m' : '' + + const groups: CaseGroup[] = ALL_GROUPS + const results: CaseResult[] = [] + + for (const g of groups) { + const selected = g.cases.filter( + (c) => + !this.opts.filter || `${g.name} :: ${c.name}`.includes(this.opts.filter) || g.name.includes(this.opts.filter), + ) + if (!selected.length) continue + console.log(`${DIM}--- ${g.name} (${selected.length})${RESET}`) + for (const c of selected) { + const r = await this.runCase(g.name, c) + results.push(r) + const color = r.status === 'PASS' ? GREEN : RED + const err = r.error ? ` ${DIM}${r.error}${RESET}` : '' + console.log(`[harness] ${color}${r.status}${RESET} ${r.case} (${r.duration_ms}ms)${err}`) + } + } + + const pass = results.filter((r) => r.status === 'PASS').length + const report = { + generated_at: new Date().toISOString(), + pass, + total: results.length, + results, + } + mkdirSync(dirname(this.opts.reportPath), { recursive: true }) + writeFileSync(this.opts.reportPath, `${JSON.stringify(report, null, 2)}\n`) + return { pass, total: results.length, results } + } +} diff --git a/code-runner/tests/e2e/workers/harness/src/worker.ts b/code-runner/tests/e2e/workers/harness/src/worker.ts new file mode 100644 index 0000000000..028b9aa08f --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/src/worker.ts @@ -0,0 +1,52 @@ +import { resolve } from 'node:path' +import { registerWorker } from 'iii-sdk' +import { Runner } from './runner.ts' + +// No default. 49134 is the port a developer's own stack usually holds, so a +// silent fallback would point the suite at their engine and report nonsense +// about it — see the harness README. run-tests.sh always sets this. +const URL = process.env.III_URL +if (!URL) throw new Error('III_URL is required — run this through ./run-tests.sh, which picks a free port') +const REPORT_PATH = resolve(process.env.HARNESS_REPORT_PATH ?? './reports/report.json') +const FILTER = process.env.HARNESS_FILTER || undefined + +const iii = registerWorker(URL) +const runner = new Runner({ iii, reportPath: REPORT_PATH, filter: FILTER }) + +console.log(`[harness] code-runner e2e harness registered url=${URL} filter=${FILTER ?? 'all'}`) + +;(async () => { + const useColor = process.stdout.isTTY === true + const GREEN = useColor ? '\x1b[32m' : '' + const RED = useColor ? '\x1b[31m' : '' + const RESET = useColor ? '\x1b[0m' : '' + let exitCode = 1 + try { + // The worker may still be connecting when we register. Probe until it + // answers rather than failing the whole suite on a startup race. + const deadline = Date.now() + 30000 + for (;;) { + try { + await iii.trigger({ function_id: 'code-runner::run', payload: { lang: 'node', code: '1' }, timeoutMs: 5000 }) + break + } catch (e) { + if (Date.now() > deadline) throw new Error(`code-runner never became callable: ${e}`) + await new Promise((r) => setTimeout(r, 250)) + } + } + const { pass, total } = await runner.runAll() + const status = pass === total && total > 0 ? 'PASS' : 'FAIL' + const color = status === 'PASS' ? GREEN : RED + console.log(`HARNESS_DONE: ${color}${status}${RESET} ${pass}/${total}`) + exitCode = status === 'PASS' ? 0 : 1 + } catch (e: any) { + console.error('[harness] fatal:', e?.stack ?? e) + console.log(`HARNESS_DONE: ${RED}FAIL${RESET} 0/0`) + exitCode = 1 + } + // Grace period lets the OS flush ws bytes; shutdown() does not await the + // close handshake. + await new Promise((r) => setTimeout(r, 200)) + await iii.shutdown() + process.exit(exitCode) +})() diff --git a/code-runner/tests/e2e/workers/harness/tsconfig.json b/code-runner/tests/e2e/workers/harness/tsconfig.json new file mode 100644 index 0000000000..cce77a2bbe --- /dev/null +++ b/code-runner/tests/e2e/workers/harness/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/code-runner/tests/golden/schemas/code-runner.inject-guidance.json b/code-runner/tests/golden/schemas/code-runner.inject-guidance.json new file mode 100644 index 0000000000..09229e1b24 --- /dev/null +++ b/code-runner/tests/golden/schemas/code-runner.inject-guidance.json @@ -0,0 +1,56 @@ +{ + "function_id": "code-runner::inject-guidance", + "description": "Internal pre_generate hook: appends code-runner usage guidance to the agent system prompt. Bound to harness::hook::pre-generate at worker startup; not called directly. Silenced by inject_guidance: false in the code-runner configuration.", + "request_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "PreGenerateEvent", + "description": "The slice of the `pre_generate` hook envelope we read (lenient: ignores every other field the harness sends). The harness nests the live generation context under `generate`.", + "type": "object", + "properties": { + "generate": { + "$ref": "#/definitions/GenerateContext" + } + }, + "definitions": { + "GenerateContext": { + "type": "object", + "properties": { + "system_prompt": { + "description": "The system prompt assembled so far (base + any prior hook's mutation).", + "default": "", + "type": "string" + } + } + } + } + }, + "response_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "PreGenerateResponse", + "description": "Hook envelope returned to the harness: the mutations to apply to the generation.", + "type": "object", + "required": [ + "mutations" + ], + "properties": { + "mutations": { + "$ref": "#/definitions/PreGenerateMutations" + } + }, + "definitions": { + "PreGenerateMutations": { + "description": "The harness applies `system_prompt` only when the key is present, so `None` serializes to an empty object: the safe no-op that preserves the harness's assembled prompt.", + "type": "object", + "properties": { + "system_prompt": { + "description": "Full replacement system prompt (base + appended guidance). The harness overwrites, it does not merge.", + "type": [ + "string", + "null" + ] + } + } + } + } + } +} diff --git a/code-runner/tests/golden/schemas/code-runner.register_function.json b/code-runner/tests/golden/schemas/code-runner.register_function.json new file mode 100644 index 0000000000..d6854584e6 --- /dev/null +++ b/code-runner/tests/golden/schemas/code-runner.register_function.json @@ -0,0 +1,75 @@ +{ + "function_id": "code-runner::register_function", + "description": "Publish a bus function whose handler runs in a sandbox. `source` must DEFINE handler(payload) in `lang`; one persistent runtime per namespace (function_id before `::`) AND lang is booted by the first registration and shared by later ones. Write a `description` for callers. Optional `request_format` / `response_format` (JSON Schema objects, max 16 KiB) are shown by engine::functions::info but NOT enforced at call time — validate inside the handler. Registrations stop resolving when the namespace is torn down or its runtime reaped for idleness.", + "request_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "RegisterRequest", + "type": "object", + "required": [ + "function_id", + "lang", + "source" + ], + "properties": { + "description": { + "description": "What `engine::functions::info` shows a caller — write one.", + "default": null, + "type": [ + "string", + "null" + ] + }, + "function_id": { + "description": "e.g. `my-app::greet`. The segment before the first `::` is the namespace. Each language keeps its own persistent runtime per namespace, created by its first registration — a namespace can hold node and python ids side by side.", + "type": "string" + }, + "lang": { + "description": "Which engine backs this namespace. Required here, unlike on `run`: a registration has no runtime to infer it from.", + "allOf": [ + { + "$ref": "#/definitions/Lang" + } + ] + }, + "request_format": { + "description": "Optional JSON Schema for the payload the registered function expects — `engine::functions::info` then shows it in place of \"any\". Must be a JSON object that actually constrains something (`type`, `properties`, `$ref`, …); at most 16 KiB serialized.", + "default": null + }, + "response_format": { + "description": "Optional JSON Schema for the value the handler returns; same rules as `request_format`.", + "default": null + }, + "source": { + "description": "Source that DEFINES `handler(payload)` in `lang`.\n\nNode publishes itself, by calling `iii.registerFunction`. Python's source just defines the name — the host publishes it — and anything else the source defines stays available to every later invocation, because the namespace runs on one pinned interpreter.", + "type": "string" + } + }, + "definitions": { + "Lang": { + "description": "Which engine backs a runtime.\n\nOnly `node` and `python` are accepted; anything else fails deserialization before a handler runs, so the schema itself is the validation.", + "type": "string", + "enum": [ + "node", + "python" + ] + } + } + }, + "response_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "RegisterResponse", + "type": "object", + "required": [ + "function_id", + "registered" + ], + "properties": { + "function_id": { + "type": "string" + }, + "registered": { + "type": "boolean" + } + } + } +} diff --git a/code-runner/tests/golden/schemas/code-runner.run.json b/code-runner/tests/golden/schemas/code-runner.run.json new file mode 100644 index 0000000000..63cbcd08b5 --- /dev/null +++ b/code-runner/tests/golden/schemas/code-runner.run.json @@ -0,0 +1,106 @@ +{ + "function_id": "code-runner::run", + "description": "Run code in an in-process sandbox — lang \"node\" or \"python\"; no network, no host filesystem, no package installs. One-shot by default; keep: true returns a runtime_id, and passing runtime_id later reuses that runtime (same globals and scratch) until code-runner::teardown or the idle TTL reaps it (then: code-runner::expired — retry without runtime_id). Code gets an `iii` global for bus calls. stdout/stderr/exit_code come back verbatim — a failing script is a response, not an error — and `result` carries the returned value: node code is a FUNCTION BODY (`return x`), python a MODULE (assign `result = x`).", + "request_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "RunRequest", + "type": "object", + "required": [ + "code" + ], + "properties": { + "code": { + "description": "Node: the body of an async function — `return x` yields the result, top-level `await` works. Python: a module — assign `result = x`. Both get a global `iii` that can trigger any bus function; node's can also register functions for the life of the runtime and reach its private scratch directory via `iii.files`, python's is synchronous and gets `/work` instead.", + "type": "string" + }, + "keep": { + "description": "Only meaningful when `runtime_id` is omitted. `false` (the default): one-shot — create a runtime, run `code`, return the result, destroy it. Nothing persists. `true`: leave it running; the response's `runtime_id` addresses it for later runs and is the capability `code-runner::teardown` needs to stop it.", + "default": false, + "type": "boolean" + }, + "lang": { + "description": "Required when `runtime_id` is omitted — picks the engine (\"node\" or \"python\"). On an existing runtime: omit it, or pass the runtime's own language; languages cannot be mixed in one runtime.", + "default": null, + "anyOf": [ + { + "$ref": "#/definitions/Lang" + }, + { + "type": "null" + } + ] + }, + "runtime_id": { + "description": "Run in a SPECIFIC runtime, sharing its scratch directory and its globals: the run lands in that runtime and it is NOT destroyed afterwards — you own it. Omit this to run one-shot (see `keep`).", + "default": null, + "type": [ + "string", + "null" + ] + }, + "timeout_ms": { + "description": "Wall-clock budget in milliseconds, clamped to the configured maximum.", + "default": null, + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0.0 + } + }, + "definitions": { + "Lang": { + "description": "Which engine backs a runtime.\n\nOnly `node` and `python` are accepted; anything else fails deserialization before a handler runs, so the schema itself is the validation.", + "type": "string", + "enum": [ + "node", + "python" + ] + } + } + }, + "response_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "RunResponse", + "type": "object", + "required": [ + "duration_ms", + "exit_code", + "result", + "stderr", + "stdout", + "success" + ], + "properties": { + "duration_ms": { + "type": "integer", + "format": "uint64", + "minimum": 0.0 + }, + "exit_code": { + "type": "integer", + "format": "int64" + }, + "result": { + "description": "The completion value: what the code returned (node) or assigned to `result` (python). Null when it returned nothing, when it returned something JSON cannot represent, or when the run failed.\n\nAlways present, never skipped — unlike `runtime_id`, a null result is information (\"the code returned nothing\") rather than an absence." + }, + "runtime_id": { + "description": "Present when this run addresses a runtime that outlives the call — a `keep: true` run that SUCCEEDED, or a `runtime_id` echoed back. Absent, not null, otherwise: there is nothing to address. Treat a present value as a secret.", + "type": [ + "string", + "null" + ] + }, + "stderr": { + "type": "string" + }, + "stdout": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + } +} diff --git a/code-runner/tests/golden/schemas/code-runner.teardown.json b/code-runner/tests/golden/schemas/code-runner.teardown.json new file mode 100644 index 0000000000..8e384ba476 --- /dev/null +++ b/code-runner/tests/golden/schemas/code-runner.teardown.json @@ -0,0 +1,61 @@ +{ + "function_id": "code-runner::teardown", + "description": "Destroy a runtime: unregister every bus function it registered, kill it, and free its slot. Pass exactly one of runtime_id (a kept run's runtime, from code-runner::run keep=true) or namespace (a register_function namespace, e.g. \"app\" for ids like app::greet) — never both, never neither.", + "request_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "TeardownRequest", + "description": "Exactly one of `runtime_id` (a kept run's runtime) or `namespace` (a `register_function` namespace) must be set — never both, never neither.", + "type": "object", + "properties": { + "namespace": { + "default": null, + "type": [ + "string", + "null" + ] + }, + "runtime_id": { + "default": null, + "type": [ + "string", + "null" + ] + } + } + }, + "response_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "TeardownResponse", + "type": "object", + "required": [ + "torn_down", + "unregistered" + ], + "properties": { + "namespace": { + "description": "Set when addressed by `namespace` — echoed in its canonical `app::` form, since more than one runtime (one per language) can back it and there is no single `runtime_id` to report.", + "type": [ + "string", + "null" + ] + }, + "runtime_id": { + "description": "Set when this teardown was addressed by `runtime_id`.", + "type": [ + "string", + "null" + ] + }, + "torn_down": { + "type": "boolean" + }, + "unregistered": { + "description": "Bus function ids this teardown unregistered, across every runtime it destroyed.", + "type": "array", + "items": { + "type": "string" + } + } + } + } +} diff --git a/code-runner/tests/manifest.rs b/code-runner/tests/manifest.rs new file mode 100644 index 0000000000..90025471e7 --- /dev/null +++ b/code-runner/tests/manifest.rs @@ -0,0 +1,31 @@ +use std::process::Command; + +use serde_json::Value; + +#[test] +fn manifest_subcommand_emits_valid_json() { + // Hyphen, not underscore: Cargo uses [[bin]].name verbatim here. + let bin = env!("CARGO_BIN_EXE_code-runner"); + let output = Command::new(bin) + .arg("--manifest") + .output() + .expect("spawn code-runner --manifest"); + + assert!( + output.status.success(), + "binary exited with {:?}; stderr: {}", + output.status, + String::from_utf8_lossy(&output.stderr), + ); + + let stdout = String::from_utf8(output.stdout).expect("manifest stdout is utf-8"); + let manifest: Value = serde_json::from_str(&stdout).expect("manifest stdout is valid JSON"); + + assert_eq!(manifest["name"], "code-runner"); + assert_eq!(manifest["version"], env!("CARGO_PKG_VERSION")); + assert!(manifest["default_config"].is_object()); + assert!(!manifest["supported_targets"] + .as_array() + .expect("supported_targets must be an array") + .is_empty()); +} diff --git a/code-runner/tests/schemas.rs b/code-runner/tests/schemas.rs new file mode 100644 index 0000000000..e24a3f70ac --- /dev/null +++ b/code-runner/tests/schemas.rs @@ -0,0 +1,137 @@ +//! Wire-schema snapshots for the statically registered `code-runner::*` +//! functions. `code_runner::functions::catalog()` is the single source of +//! truth; each entry is serialized to pretty JSON and compared against +//! `tests/golden/schemas/.json` (`::` maps to `.` in filenames). +//! +//! Regenerate with `UPDATE_GOLDENS=1 cargo test`. + +mod support; + +use code_runner::functions::{catalog, FunctionSpec}; + +fn golden_file_name(function_id: &str) -> String { + format!("schemas/{}.json", function_id.replace("::", ".")) +} + +fn spec_to_pretty_json(spec: &FunctionSpec) -> String { + let value = serde_json::json!({ + "function_id": spec.function_id, + "description": spec.description, + "request_schema": spec.request_schema, + "response_schema": spec.response_schema, + }); + let mut pretty = serde_json::to_string_pretty(&value).expect("spec serializes"); + pretty.push('\n'); + pretty +} + +#[test] +fn catalog_lists_every_function_in_registration_order() { + let ids: Vec<&str> = catalog().iter().map(|s| s.function_id).collect(); + assert_eq!( + ids, + vec![ + "code-runner::run", + "code-runner::teardown", + "code-runner::register_function", + "code-runner::inject-guidance" + ] + ); +} + +#[test] +fn wire_schema_snapshots_match_goldens() { + let mut failures = Vec::new(); + for spec in catalog() { + let rel = golden_file_name(spec.function_id); + if let Err(msg) = support::check_golden(&rel, &spec_to_pretty_json(&spec)) { + failures.push(msg); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n\n")); +} + +/// A `serde_json::Value` handler emits the permissive AnyValue schema, which +/// ships to the registry as "unknown". Every static function must be typed. +#[test] +fn every_schema_is_typed() { + for spec in catalog() { + for (kind, schema) in [ + ("request", &spec.request_schema), + ("response", &spec.response_schema), + ] { + support::assert_typed_schema(&format!("{} {kind}", spec.function_id), schema); + } + } +} + +/// `STATIC_IDS` seeds the IdRegistry; anything this worker registers but does +/// not seed can reach the SDK's duplicate-id panic, which aborts the process. +/// +/// What this proves, and only this: the two hand-maintained lists have not +/// drifted APART. An id missing from BOTH leaves them equal and passes — +/// neither direction catches a function added to `register_all` alone. That +/// case is covered where it can be: `register_all` asserts it registered +/// exactly `STATIC_IDS`. +/// +/// Compared as ordered slices, not sets. `register_all`'s assertion is +/// order-sensitive but runs only at startup, where a mismatch is a failed +/// deploy; pinning the order here too means the likeliest drift — a new +/// function appended to one list and inserted into the other — fails in CI +/// instead. +#[test] +fn static_ids_and_catalog_match_exactly() { + let cataloged: Vec<&str> = code_runner::functions::catalog() + .iter() + .map(|s| s.function_id) + .collect(); + assert_eq!( + code_runner::functions::STATIC_IDS, + cataloged.as_slice(), + "STATIC_IDS and catalog() must list the same ids in the same order — an \ + unseeded registration reopens the duplicate-id process abort (see crate::ids)" + ); +} + +/// The four ids have to agree across the catalog, `STATIC_IDS` and the golden +/// filenames. Any one out of step is a worker that advertises an id it does +/// not serve — and `sandbox-code-runner`'s own history is why this is pinned: +/// this worker's name was once its name, and `::eval` was once `::run`. +#[test] +fn the_advertised_ids_agree_across_catalog_static_ids_and_goldens() { + let catalog = code_runner::functions::catalog(); + assert!(catalog.iter().any(|s| s.function_id == "code-runner::run")); + assert!(!catalog.iter().any(|s| s.function_id == "code-runner::eval")); + assert!(code_runner::functions::STATIC_IDS.contains(&"code-runner::run")); + assert!(std::path::Path::new("tests/golden/schemas/code-runner.run.json").exists()); + assert!(!std::path::Path::new("tests/golden/schemas/code-runner.eval.json").exists()); +} + +/// A half-finished removal — the id gone from `STATIC_IDS` but the function +/// still registered, or a stale golden left on disk — passes every other test +/// in this file, because they compare two hand-maintained lists to each other. +#[test] +fn removed_functions_are_absent_from_the_catalog() { + let catalog = code_runner::functions::catalog(); + // Ids this worker deliberately does not serve: node-engine's retired + // pair, and the `::eval` spelling that predates `::run`. + for gone in [ + "code-runner::eject", + "code-runner::register_worker", + "code-runner::eval", + ] { + assert!( + !catalog.iter().any(|s| s.function_id == gone), + "{gone} is still in the catalog" + ); + assert!( + !code_runner::functions::STATIC_IDS.contains(&gone), + "{gone} is still in STATIC_IDS" + ); + let golden = format!("tests/golden/schemas/{}.json", gone.replace("::", ".")); + assert!( + !std::path::Path::new(&golden).exists(), + "{golden} still exists on disk" + ); + } +} diff --git a/code-runner/tests/support/mod.rs b/code-runner/tests/support/mod.rs new file mode 100644 index 0000000000..440e3bf0e6 --- /dev/null +++ b/code-runner/tests/support/mod.rs @@ -0,0 +1,118 @@ +//! Hand-rolled golden-file harness (deliberately no `insta`/snapshot +//! dependency). Goldens live under `tests/golden/` and are committed; +//! any wire-surface change must show up as an explicit, reviewed diff. +//! +//! Workflow: +//! - `cargo test` compares actual output against the committed goldens. +//! - `UPDATE_GOLDENS=1 cargo test` regenerates the files; review the git +//! diff, then commit the new goldens alongside the change that caused +//! them. + +#![allow(dead_code)] + +use std::fs; +use std::path::PathBuf; + +/// Root of the committed golden files. +pub fn golden_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden") +} + +fn update_mode() -> bool { + std::env::var("UPDATE_GOLDENS") + .map(|v| v == "1") + .unwrap_or(false) +} + +/// Compare `actual` against the golden file at `tests/golden/`. +/// Returns `Err(readable diff hint)` on mismatch or missing golden; +/// with `UPDATE_GOLDENS=1` the file is (re)written and the check passes. +pub fn check_golden(rel: &str, actual: &str) -> Result<(), String> { + let path = golden_root().join(rel); + if update_mode() { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?; + } + fs::write(&path, actual).map_err(|e| format!("write {}: {e}", path.display()))?; + return Ok(()); + } + let expected = fs::read_to_string(&path).map_err(|e| { + format!( + "golden file {} unreadable ({e}).\n\ + Run `UPDATE_GOLDENS=1 cargo test` to (re)generate, then review \ + and commit the diff.", + path.display() + ) + })?; + if expected == actual { + return Ok(()); + } + Err(diff_hint(rel, &expected, actual)) +} + +/// Readable first-divergence diff hint: line number, expected vs actual +/// around the mismatch, and the regeneration instructions. +fn diff_hint(rel: &str, expected: &str, actual: &str) -> String { + let exp_lines: Vec<&str> = expected.lines().collect(); + let act_lines: Vec<&str> = actual.lines().collect(); + let first_diff = exp_lines + .iter() + .zip(act_lines.iter()) + .position(|(e, a)| e != a) + .unwrap_or_else(|| exp_lines.len().min(act_lines.len())); + + const CONTEXT: usize = 3; + let lo = first_diff.saturating_sub(CONTEXT); + let hi = (first_diff + CONTEXT + 1).max(first_diff + 1); + + let mut out = format!( + "golden mismatch: tests/golden/{rel}\n\ + first divergence at line {} (expected {} lines, actual {} lines)\n", + first_diff + 1, + exp_lines.len(), + act_lines.len() + ); + out.push_str("--- expected (golden) ---\n"); + for (i, line) in exp_lines.iter().enumerate().skip(lo).take(hi - lo) { + let marker = if i == first_diff { ">" } else { " " }; + out.push_str(&format!("{marker} {:>4} | {line}\n", i + 1)); + } + out.push_str("--- actual ---\n"); + for (i, line) in act_lines.iter().enumerate().skip(lo).take(hi - lo) { + let marker = if i == first_diff { ">" } else { " " }; + out.push_str(&format!("{marker} {:>4} | {line}\n", i + 1)); + } + out.push_str( + "If this change is intentional, run `UPDATE_GOLDENS=1 cargo test`, \ + review the git diff, and commit the updated goldens.\n", + ); + out +} + +/// Assert a schemars-derived request/response schema is a *real* schema and +/// not the permissive `AnyValue` schema a `Value` handler emits (the "unknown" +/// schema this whole convention exists to prevent). A real schema carries at +/// least one schema-defining keyword. +pub fn assert_typed_schema(label: &str, schema: &schemars::schema::RootSchema) { + let value = serde_json::to_value(schema).expect("schema serializes"); + let obj = value + .as_object() + .unwrap_or_else(|| panic!("{label}: schema is not a JSON object")); + const DEFINING: [&str; 8] = [ + "type", + "properties", + "$ref", + "allOf", + "anyOf", + "oneOf", + "enum", + "items", + ]; + let has_defining = DEFINING.iter().any(|k| obj.contains_key(*k)); + assert!( + has_defining, + "{label}: schema is the permissive AnyValue/empty schema (no type/properties/$ref/…). \ + The handler is registered with `Value` — give it a typed struct deriving JsonSchema. \ + Got: {value}" + ); +} diff --git a/code-runner/ui/build.mjs b/code-runner/ui/build.mjs new file mode 100644 index 0000000000..f82434dd07 --- /dev/null +++ b/code-runner/ui/build.mjs @@ -0,0 +1,47 @@ +/** + * Build the worker's two console assets: + * + * page.tsx → dist/page.js (injected over `console:script`) + * styles.css → dist/styles.css (injected over `console:style`) + * + * The five shared specifiers stay EXTERNAL — they resolve at runtime through + * the console's import map. A bundled React copy surfaces as a cryptic + * "Invalid hook call", because the page's hooks would then be talking to a + * different React instance than the one that mounted them. Everything else + * the page needs gets bundled in. + * + * `--watch` pairs with the worker's III_CODE_RUNNER_UI_WATCH poller for the + * hot-reload dev loop. + * + * Unlike `sandbox-code-runner/ui`, there is no second bundle here: that worker + * also builds an `iii-sdk` bundle to plant into each microVM's + * /node_modules, because its guests are real Node processes with no registry + * access. code-runner's guests are a V8 isolate and a wasm CPython — their + * `iii` global is a host-implemented op surface and a framed stdio bridge, so + * there is nothing to plant and no npm graph to inline. + */ + +import esbuild from 'esbuild' + +const options = { + entryPoints: ['page.tsx', 'styles.css'], + bundle: true, + format: 'esm', + jsx: 'automatic', + outdir: 'dist', + external: [ + 'react', + 'react-dom', + 'react-dom/client', + 'react/jsx-runtime', + '@iii-dev/console-ui', + ], + logLevel: 'info', +} + +if (process.argv.includes('--watch')) { + const ctx = await esbuild.context(options) + await ctx.watch() +} else { + await esbuild.build(options) +} diff --git a/code-runner/ui/package.json b/code-runner/ui/package.json new file mode 100644 index 0000000000..1c30f3a388 --- /dev/null +++ b/code-runner/ui/package.json @@ -0,0 +1,23 @@ +{ + "name": "@iii-workers/code-runner-ui", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "build": "tsc --noEmit && node build.mjs", + "watch": "node build.mjs --watch", + "test": "vitest run" + }, + "dependencies": { + "@iii-dev/console-ui": "workspace:*" + }, + "devDependencies": { + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "esbuild": "^0.25.0", + "react": "^19.2.6", + "react-dom": "^19.2.6", + "typescript": "^5.9.2", + "vitest": "^4.1.6" + } +} diff --git a/code-runner/ui/page.tsx b/code-runner/ui/page.tsx new file mode 100644 index 0000000000..24e043322b --- /dev/null +++ b/code-runner/ui/page.tsx @@ -0,0 +1,34 @@ +/** + * Entry for the code-runner worker's injected console UI — compiled by esbuild + * (react + @iii-dev/console-ui external into dist/page.js) and served over the + * `console:script` trigger (see src/ui.rs). The stylesheet is its own asset: + * ./styles.css ships over `console:style` as code-runner/styles.css — the + * console mounts and link-swaps it, styles-before-scripts on boot. + * + * The worker's console contributions, one module each: + * + * - src/function-trigger-message/ — the per-op cards (run, register_function, + * teardown) + * - src/configuration/ — custom form for the `code-runner` + * configuration entry on the Workers tab + * - src/lib/shared.tsx — the frame the cards share + * + * Registrations go through `host` so the loader disposes them on hot reload / + * worker disconnect. + */ + +import type { Host } from '@iii-dev/console-ui' +import { CodeRunnerConfigForm } from './src/configuration' +import { createCodeRunnerRenderers } from './src/function-trigger-message' + +export default function setup(host: Host) { + const removers = createCodeRunnerRenderers(host).map((renderer) => host.functionTriggers.register(renderer)) + + removers.push(host.configForms.register('code-runner', CodeRunnerConfigForm)) + + // The loader already disposes every registration; returning the removers + // makes an early teardown (hot reload mid-session) explicit and ordered. + return () => { + for (const remove of removers) remove() + } +} diff --git a/code-runner/ui/src/configuration/index.tsx b/code-runner/ui/src/configuration/index.tsx new file mode 100644 index 0000000000..6d8d135b18 --- /dev/null +++ b/code-runner/ui/src/configuration/index.tsx @@ -0,0 +1,215 @@ +/** + * Custom configuration form for the `code-runner` configuration entry — + * registered through `host.configForms`, replacing the console's generic + * schema-driven form for this worker only. + * + * The form edits the working draft via `onChange`; dirty tracking, + * save/reset, and error mapping stay host-owned (the console's SaveBar + * below the form drives `configuration::set`). Mirrors CodeRunnerConfig + * (workers/code-runner/src/config.rs) and its reload split: the output caps + * and timeouts hot-apply on save, everything else is captured when the + * engines boot and applies at the next worker restart — each section says + * which it is, so an operator knows what to expect from the save. + */ + +import { useEffect, useRef } from 'react' +import type { ConfigFormProps, JsonValue } from '@iii-dev/console-ui' + +type JsonObject = { [key: string]: JsonValue } + +const DEFAULTS = { + max_runtimes: 32, + default_timeout_ms: 5000, + max_timeout_ms: 30000, + idle_ttl_secs: 900, + heap_mb: 128, + external_mb: 64, + scratch_mb: 8, + scratch_files: 64, + max_result_bytes: 32768, + max_stream_bytes: 16384, +} as const + +function asObject(v: JsonValue | undefined): JsonObject { + return v && typeof v === 'object' && !Array.isArray(v) ? { ...v } : {} +} + +function numberOr(v: JsonValue | undefined, fallback: number): number { + return typeof v === 'number' ? v : fallback +} + +/** "32768 → ≈32 KiB (~8k tokens)"; the caps exist to stop context flooding, + * so the token order of magnitude is the number an operator actually wants. */ +function bytesHint(bytes: number): string { + if (bytes === 0) return 'off — echoed uncapped' + const kib = bytes / 1024 + const tokens = Math.round(bytes / 4 / 100) * 100 + const kibLabel = Number.isInteger(kib) ? String(kib) : kib.toFixed(1) + return `≈${kibLabel} KiB (~${tokens >= 1000 ? `${Math.round(tokens / 100) / 10}k` : tokens} tokens)` +} + +export function CodeRunnerConfigForm(props: ConfigFormProps) { + const value = asObject(props.value) + + const setNumber = (field: keyof typeof DEFAULTS, raw: string) => { + const next = { ...value } + if (raw.trim() === '') delete next[field] + else { + const n = Number(raw) + if (!Number.isInteger(n) || n < 0) return + next[field] = n + } + props.onChange(next) + } + + const numberField = ( + field: keyof typeof DEFAULTS, + label: string, + hint?: string, + ) => ( +
+ + setNumber(field, e.target.value)} + /> + {hint ? {hint} : null} +
+ ) + + // Deep-link focus (`#/workers/configuration/code-runner/`): the + // host's own scroll+focus targets schema-form DOM ids, so a custom form + // honors `focusField` itself. + const rootRef = useRef(null) + useEffect(() => { + const field = props.focusField?.[0] + if (!field || !rootRef.current) return + // CSS.escape: the field name rides in on the URL fragment, and an + // unescaped `"` or `]` makes querySelector throw during commit — + // unmounting the whole form instead of skipping the focus. + const target = rootRef.current.querySelector( + `[data-field="${CSS.escape(field)}"]`, + ) + target?.focus() + target?.scrollIntoView({ block: 'center' }) + }, [props.focusField]) + + const resultBytes = numberOr(value.max_result_bytes, DEFAULTS.max_result_bytes) + const streamBytes = numberOr(value.max_stream_bytes, DEFAULTS.max_stream_bytes) + const footprintMb = + numberOr(value.max_runtimes, DEFAULTS.max_runtimes) * + numberOr(value.scratch_mb, DEFAULTS.scratch_mb) + + return ( +
+ + custom form · shipped by the code-runner worker + + +
+ + output caps hot-applies on save + + + Oversized run echoes are what flood a session's context: over the + cap, `result` becomes an omission marker (write big values to + iii.files instead) and stdout/stderr keep head+tail around a + truncation marker. 0 turns a cap off. + + {numberField('max_result_bytes', 'max result bytes', bytesHint(resultBytes))} + {numberField('max_stream_bytes', 'max bytes per stream (stdout / stderr)', bytesHint(streamBytes))} +
+ +
+ + agent guidance hot-applies on save + + + + props.onChange({ ...value, inject_guidance: e.target.checked }) + } + /> + + + + The pre-generate hook that teaches agents this worker's surface + (return conventions, keep/runtime_id, register_function). Off, the + hook answers with a no-op and agents see only the function catalog. + +
+ +
+ + timeouts hot-applies on save + + {numberField('default_timeout_ms', 'default timeout (ms, when a run omits timeout_ms)')} + {numberField('max_timeout_ms', 'max timeout (ms, requests are clamped down to this)')} +
+ +
+ + runtimes & memory{' '} + applies at next worker restart + + {numberField('max_runtimes', 'max live runtimes (both engines)')} + {numberField('idle_ttl_secs', 'idle TTL (seconds before an unused runtime is reaped)')} + {numberField('heap_mb', 'V8 heap per node runtime (MiB)')} + {numberField('external_mb', 'V8 off-heap per node runtime (MiB, ArrayBuffers)')} +
+ +
+ + scratch (node iii.files — python's /work budget is fixed by its engine){' '} + applies at next worker restart + + {numberField( + 'scratch_mb', + 'scratch quota per node runtime (MiB, 0 removes the surface)', + `worst-case host footprint: ${footprintMb} MiB — tmpfs (host RAM) on most Linux hosts unless scratch root points at real disk`, + )} + {numberField('scratch_files', 'max files per scratch directory')} +
+ + { + const next = { ...value } + if (e.target.value === '') delete next.scratch_root + else next.scratch_root = e.target.value + props.onChange(next) + }} + /> +
+
+ + {props.errors && props.errors.size > 0 ? ( +
+ {[...props.errors.entries()].map(([pointer, message]) => ( +
+ {pointer ? `${pointer}: ` : ''} + {message} +
+ ))} +
+ ) : null} +
+ ) +} diff --git a/code-runner/ui/src/function-trigger-message/index.tsx b/code-runner/ui/src/function-trigger-message/index.tsx new file mode 100644 index 0000000000..b672765474 --- /dev/null +++ b/code-runner/ui/src/function-trigger-message/index.tsx @@ -0,0 +1,47 @@ +/** + * The code-runner function-trigger renderers — one module per rendered op: + * + * code-runner::run → ./run + * code-runner::register_function → ./register-function + * code-runner::teardown → ./teardown + * + * Registered through `host.functionTriggers`, so they dispatch BEFORE the + * console's first-party families and override how those calls render in chat + * and in the traces span tab. + * + * The console asks EVERY registered renderer on every message (`isMatch` is + * only used to pick a `FunctionIdLabel`), so each `tryRender*` gates on its own + * function id and returns null to fall through. + * + * These cards do NOT fall through on error outputs: code-runner's error + * messages quote the `runtime_id` by design (`unknown runtime_id {id}` — + * error.rs), and a runtime id is a capability, so the console's default error + * view would print it verbatim. Each card renders its own `ErrorCard` with the + * message routed through `redactRuntimeIds`. + * + * `code-runner::inject-guidance` is deliberately NOT rendered: it is a + * harness-internal `pre_generate` hook that appends usage guidance to an + * agent's system prompt, not a call anyone makes on purpose. It keeps the + * console's default card. + */ + +import type { FunctionTriggerRenderer, Host } from '@iii-dev/console-ui' +import { redactRuntimeIdsDeep } from '../lib/shared' +import { createRegisterFunctionRenderer } from './register-function' +import { createRunRenderer } from './run' +import { createTeardownRenderer } from './teardown' + +/** + * `redactRaw` is attached here rather than card by card: the console's + * function-trigger card mounts a `raw json` tab (and a copy button) that + * renders `input`/`output` verbatim whatever the card does, and EVERY + * code-runner payload can carry a `runtime_id` — in a field, in a line of + * program output, in a returned completion value, in one of the error messages + * that quote it by design (error.rs). It is a property of the worker's + * payloads, not of any one op, so a renderer cannot opt out by omission. + */ +export function createCodeRunnerRenderers(host: Host): FunctionTriggerRenderer[] { + return [createRunRenderer(host), createRegisterFunctionRenderer(host), createTeardownRenderer(host)].map( + (renderer) => ({ ...renderer, redactRaw: redactRuntimeIdsDeep }), + ) +} diff --git a/code-runner/ui/src/function-trigger-message/register-function.tsx b/code-runner/ui/src/function-trigger-message/register-function.tsx new file mode 100644 index 0000000000..d04bfc05a5 --- /dev/null +++ b/code-runner/ui/src/function-trigger-message/register-function.tsx @@ -0,0 +1,420 @@ +/** + * Injected function-trigger renderer for `code-runner::register_function`. + * + * The default card prints the request as JSON, which turns `source` — the + * whole point of the call — into one escaped single-line string, and buries + * the two things that decide whether the registration did what the caller + * meant: + * + * - the NAMESPACE the id claims (the segment before `::`). The first + * registration in a namespace claims it and every later id there must + * share it. code-runner claims ids for BOTH engines in ONE registry + * (`RuntimeManager::ids()`), so `app::greet` cannot exist in node and + * python at once — that is the common surprise, and it gets its own line + * rather than being a substring of a blob. + * - whether the source actually defines `handler(payload)`. Both engines + * WRAP what you send: node's `wrap_register` evaluates the source and + * then looks for `handler`, and python's registration execs the source + * and then asserts `callable(handler)`. So the source DEFINES the + * handler; it does not register itself. + * + * ONE function per call: this request carries a single `function_id` + + * `source` pair. + * + * NO `runtime_id` ON THIS WIRE: the runtime backing a namespace is an + * implementation detail this call never sees or names — `lang` (required) + * decides which engine it needs, and code-runner creates or reuses that + * namespace's runtime itself. A python namespace's interpreter is PINNED + * (exempt from the idle sweep), so `teardown namespace=` is the only way to + * reclaim it. + * + * A python registration that leaves no callable `handler` fails the + * REGISTRATION rather than the first call — the id never reaches the catalog, + * and a corrected redeploy of the same id works. That is why the handler + * advisory below matters before you approve, not after. + * + * No capability lives on this request, but a caller is free to name a + * function, description, or source after a runtime id it holds from elsewhere + * — every free-text field still goes through `redactRuntimeIds` as + * belt-and-braces, and errors render through this card's own `ErrorCard` + * rather than falling through to the console's default view. + */ + +import { + CodeHighlight, + type FunctionTriggerMessage, + type FunctionTriggerRenderer, + type Host, +} from '@iii-dev/console-ui' +import { useState } from 'react' +import { + asRecord, + CardShell, + DeniedCard, + deniedInfo, + ErrorCard, + errorInfo, + langToPrism, + opName, + redactRuntimeIds, + unwrapEnvelope, +} from '../lib/shared' + +const FUNCTION_ID = 'code-runner::register_function' + +/** Lines of source shown before the block collapses behind a toggle… */ +const COLLAPSE_AFTER = 14 +/** …and a character ceiling, for the one-line source a bundler emitted. */ +const SOURCE_CHAR_CAP = 2000 + +/* --- request ------------------------------------------------------------- */ + +/** The free-text fields `RegisterRequest` declares — `lang` is excluded: it is + * a closed enum, not free text, checked separately below. */ +const STRING_FIELDS = ['function_id', 'source', 'description'] as const + +type Lang = 'node' | 'python' + +interface RegisterRequest { + functionId?: string + source?: string + description?: string + /** Required on the wire; `undefined` here means missing or invalid — only + * ever a value `langToPrism` can honestly map. */ + lang?: Lang + /** Fields the request carried with a non-string value — surfaced, not + * dropped. */ + malformed: string[] +} + +function parseRequest(input: unknown): RegisterRequest { + const obj = asRecord(input) ?? {} + const str = (k: string) => (typeof obj[k] === 'string' ? obj[k] : undefined) + return { + functionId: str('function_id'), + source: str('source'), + description: str('description'), + lang: obj.lang === 'node' || obj.lang === 'python' ? obj.lang : undefined, + malformed: STRING_FIELDS.filter((k) => k in obj && obj[k] !== null && typeof obj[k] !== 'string'), + } +} + +/** The request's own `lang`, when present. */ +function LangChip({ req }: { req: RegisterRequest }) { + if (!req.lang) return null + return ( + + lang + {req.lang} + + ) +} + +/** + * The namespace this id claims: `app::greet` → `app::`. `undefined` when the + * id has no `::` or nothing after it — exactly the two shapes the worker + * refuses, so the card can say so before the call lands. + */ +function namespaceOf(functionId: string): string | undefined { + const i = functionId.indexOf('::') + if (i <= 0 || i + 2 >= functionId.length) return undefined + return `${functionId.slice(0, i)}::` +} + +/** + * A Prism id when the source is unmistakably one language, `undefined` + * otherwise → rendered as `text`, i.e. unhighlighted. Only reached when the + * request's own `lang` is missing or invalid — `lang` is required on this + * wire, so this is a fallback for a malformed request, not the normal case. + * + * This is a HINT, never a claim. `def` is checked first because it is the one + * marker JavaScript cannot produce. + */ +function guessPrism(source: string): string | undefined { + if (/^[ \t]*(async[ \t]+)?def[ \t]+\w/m.test(source)) return 'python' + if (/\bexport\s+function\b|\bfunction\s+\w|=>/.test(source)) return 'javascript' + return undefined +} + +/** The approval gate clips every string to 256 code points + `…`. */ +function looksClipped(value: string | undefined): boolean { + return value?.endsWith('…') === true +} + +/* --- body pieces --------------------------------------------------------- */ + +function MalformedFields({ names }: { names: readonly string[] }) { + if (names.length === 0) return null + return ( +
+ · the request carries a non-string {names.join(', ')} — the worker rejects it +
+ ) +} + +function Head({ + req, + resId, + status, +}: { + req: RegisterRequest + /** + * The response's `function_id` — the id actually live on the bus. Falls back + * into the display when the request carried none, so a card can never say + * "no function_id in the request" beside a green `registered` badge while + * hiding the id that is actually callable. `undefined` in the + * pending/running states, where there is no response yet. + */ + resId?: string + /** Undefined until the response settles, or when it carried no flag. */ + status?: 'live' | 'refused' +}) { + // The request is still the id of record when it has one — a caller-echoed + // response could in principle disagree, and `SettledView`'s mismatch note + // covers that. `resId` only fills the gap when the request had nothing. + const displayId = req.functionId ?? resId + const ns = displayId ? namespaceOf(displayId) : undefined + return ( +
+
function
+
+ + {req.functionId + ? redactRuntimeIds(req.functionId) + : resId + ? `${redactRuntimeIds(resId)} (from the response — the request carried no function_id)` + : 'no function_id in the request'} + + {status === 'live' ? registered : null} + {status === 'refused' ? not registered : null} +
+ {displayId ? ( +
+ {ns ? ( + <> + claims {redactRuntimeIds(ns)} — the first registration takes the namespace, and ids are + claimed across BOTH engines, so this id cannot also exist in the other language + + ) : ( + <> + no namespace — an id must look like app::name, which this one does not + + )} +
+ ) : null} +
+ {req.description + ? redactRuntimeIds(req.description) + : 'no description — engine::functions::info will show callers nothing'} +
+
+ ) +} + +/** + * The source, clamped by both line count and character count (a one-line + * bundle has no newlines to clamp on) and further capped in height by + * `.cr-ui-code`. + * + * `clipped` means the string is the approval gate's excerpt, not the program: + * its line count is meaningless, so the toggle drops the "+N more lines" + * arithmetic. + */ +function SourceSection({ source, lang, clipped }: { source: string; lang?: Lang; clipped: boolean }) { + const [expanded, setExpanded] = useState(false) + const safe = redactRuntimeIds(source) + const lines = safe.split('\n') + const long = lines.length > COLLAPSE_AFTER || safe.length > SOURCE_CHAR_CAP + const collapsed = long && !expanded + const shown = collapsed ? lines.slice(0, COLLAPSE_AFTER).join('\n').slice(0, SOURCE_CHAR_CAP) : safe + const hidden = lines.length - COLLAPSE_AFTER + const known = langToPrism(lang) + const guessed = known === undefined ? guessPrism(safe) : undefined + const prism = known ?? guessed + + return ( +
+
{clipped ? 'source (excerpt)' : 'source'}
+
+ +
+ {long ? ( + + ) : null} + {guessed ? ( +
+ highlighted as {guessed} — guessed from the source; this request's lang field is missing or invalid, so the + engine it will actually run under is unconfirmed +
+ ) : null} +
+ ) +} + +/** + * The source has to DEFINE `handler(payload)` — both engines wrap it and then + * look the name up. Quiet, because a substring check is not a parser: it is an + * advisory, never a verdict. Suppressed on a clipped excerpt, where the + * definition may simply be past the cut. + * + * On python the consequence is sharper than on node, and the text says so: the + * worker asserts `callable(handler)` in the same turn as the exec, so a source + * without one fails the registration outright instead of registering and then + * failing on every call. + */ +function HandlerAdvisory({ source, lang, clipped }: { source: string; lang?: Lang; clipped: boolean }) { + if (clipped || /\bhandler\b/.test(source)) return null + return ( +
+ · nothing named `handler` in this source —{' '} + {lang === 'python' + ? 'the worker execs the source and then checks callable(handler), so this registration will be REFUSED' + : 'the worker evaluates the source and then looks for handler, so a source that never defines it cannot be registered'} +
+ ) +} + +/** Source block plus its advisories, or the placeholder when there is none. */ +function SourceBlock({ req, clipped }: { req: RegisterRequest; clipped: boolean }) { + if (req.source === undefined) { + return ( +
+ · no source in the request — the worker rejects a registration without one +
+ ) + } + if (req.source.length === 0) { + return ( +
+ · empty source — the worker rejects it; it must define handler(payload) +
+ ) + } + return ( + <> + + + + ) +} + +/* --- cards --------------------------------------------------------------- */ + +function SettledView({ message }: { message: FunctionTriggerMessage }) { + const req = parseRequest(message.input) + const res = asRecord(unwrapEnvelope(message.output)) ?? {} + const registered = typeof res.registered === 'boolean' ? res.registered : undefined + const resId = typeof res.function_id === 'string' ? res.function_id : undefined + const mismatch = resId !== undefined && req.functionId !== undefined && resId !== req.functionId + + return ( + }> + + {registered === undefined ? ( +
+ · the response carried no `registered` flag, so whether this id is on the bus is unconfirmed +
+ ) : null} + {registered === false ? ( +
+ · the response reports `registered: false` — the function is not callable on the bus +
+ ) : null} + {mismatch ? ( +
+ · the response registered {redactRuntimeIds(resId)}, not the id in the request +
+ ) : null} + + +
+ ) +} + +/** + * Not settled yet: in flight, or held at the approval gate. + * + * At the gate the `input` may be the gate's `arguments_excerpt` — every string + * clipped to 256 code points with a trailing `…`. This is the one card gating + * arbitrary code publication onto the bus, so a clipped source is labelled an + * excerpt rather than presented as the whole program. + */ +function PendingView({ message, running }: { message: FunctionTriggerMessage; running: boolean }) { + const req = parseRequest(message.input) + const clipped = looksClipped(req.source) + const anyClipped = clipped || looksClipped(req.description) || looksClipped(req.functionId) + + return ( + }> +
+ {running ? '· registering…' : '· will register this function:'} +
+ {anyClipped ? ( +
+ · the approval gate clips strings to 256 characters — anything ending in … is partial +
+ ) : null} + + + +
+ ) +} + +export function createRegisterFunctionRenderer(host: Host): FunctionTriggerRenderer { + void host // this card reads nothing off the host + const isMatch = (functionId: string) => functionId === FUNCTION_ID + + const render = (message: FunctionTriggerMessage, running: boolean): React.ReactNode | null => { + if (!isMatch(message.functionId)) return null + // The host draws the approval bar around `tryRenderPreview`. + if (message.pendingApproval) return null + // Not a record — e.g. a double-encoded (stringified) payload, which the + // default card knows how to unpack and this one does not. Fall through + // rather than asserting "no source in the request" about a call that + // publishes arbitrary code. + if (!asRecord(message.input)) return null + if (running) return + // Denied at the gate — no source was ever published to the bus, so this + // must not read as one of the infrastructure failures `ErrorCard` means. + // Checked before `errorInfo`: a denial is also `'error' in output`-shaped. + const denied = deniedInfo(message.output) + if (denied) { + return + } + // Our own error card, never the default one: this request has no + // runtime_id, but a caller-chosen function_id/description/source could + // still embed one from elsewhere, and errorInfo's message goes through + // redactRuntimeIds either way — belt-and-braces over trusting the default + // view. + const err = errorInfo(message.output) + if (err) { + return + } + // No parseable response body — an aborted call, or a reloaded session + // whose last call never paired. That is a normal state, not a completed + // registration, so let the console's own "response · empty" card say so. + if (!asRecord(unwrapEnvelope(message.output))) return null + return + } + + return { + id: 'code-runner/page.js#register-function', + isMatch, + tryRender: (message) => render(message, !!message.running), + tryRenderRunning: (message) => render(message, true), + // Worth a preview: the approver is about to publish code onto the bus, and + // the namespace it claims is what they most need to check before saying + // yes. + tryRenderPreview: (message) => + isMatch(message.functionId) && message.pendingApproval && asRecord(message.input) ? ( + + ) : null, + } +} diff --git a/code-runner/ui/src/function-trigger-message/result.test.tsx b/code-runner/ui/src/function-trigger-message/result.test.tsx new file mode 100644 index 0000000000..dae6e01b6e --- /dev/null +++ b/code-runner/ui/src/function-trigger-message/result.test.tsx @@ -0,0 +1,187 @@ +/** + * The completion value — `result` — is the field code-runner's wire adds over + * `sandbox-code-runner`'s, so it is the part of this UI that is NOT a proven + * port and needs its own tests. + * + * Three things are asserted here: + * + * 1. A value RENDERS, and renders as JSON rather than as `[object Object]`. + * 2. A NULL result renders explicitly, with the engine's return convention + * beside it. `result` is always present on the wire and never skipped, + * because a null result is information ("the code returned nothing"), not + * an absence (run.rs) — and the overwhelmingly common cause is the + * convention mismatch: node code is a function body (`return 2 + 2`), + * python code is a module (assign `result`). A card that hid the null, or + * showed it without the hint, would leave the reader with no way to tell a + * working call from a mis-written one. + * 3. A runtime id INSIDE the result is redacted. This is the leak the + * `RuntimeChip` does not cover: a script that calls back into the engine + * can RETURN its runtime id, and `JSON.stringify` of the raw value would + * carry the capability into the feed. + * + * Renders through `react-dom/server` against a stubbed `@iii-dev/console-ui` + * (the real package's JS entry throws — it is compile-time-only, served at + * runtime by the console's import map). The stub still renders every prop it is + * handed, so a card that stopped routing text through `redactRuntimeIds` is + * caught here rather than hidden behind an inert mock. + */ + +import type { FunctionTriggerMessage, Host } from '@iii-dev/console-ui' +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it, vi } from 'vitest' +import { truncateRuntimeId } from '../lib/shared' +import { createRunRenderer } from './run' + +// Hoisted above the imports by vitest, so the renderer module resolves the +// stub, never the real package's throwing JS entry. +vi.mock('@iii-dev/console-ui', () => ({ + Tooltip: ({ children }: { children?: React.ReactNode }) => <>{children}, + TooltipTrigger: ({ children }: { children?: React.ReactNode }) => <>{children}, + TooltipContent: ({ children }: { children?: React.ReactNode }) => {children}, + CodeHighlight: ({ code }: { code: string }) =>
{code}
, + JsonHighlight: ({ code }: { code: string }) =>
{code}
, +})) + +/** Both engines mint `rt-` — node-core's and python-core's `manager.rs` + * alike (`format!("rt-{}", Uuid::new_v4())`). */ +const RUNTIME_ID = 'rt-3f9a2c1e-7b64-4d0a-9c11-5e8ab2d4f077' +const TRUNCATED = truncateRuntimeId(RUNTIME_ID) + +const FUNCTION_ID = 'code-runner::run' +const HOST = {} as unknown as Host + +function msg(input: unknown, output: unknown): FunctionTriggerMessage { + return { + id: 'm1', + role: 'function-trigger', + functionId: FUNCTION_ID, + input, + output, + running: false, + createdAt: 0, + } as FunctionTriggerMessage +} + +/** The settled card's HTML for one request/response pair. */ +function renderSettled(input: unknown, output: unknown): string { + const node = createRunRenderer(HOST).tryRender(msg(input, output)) + expect(node).not.toBeNull() + return renderToStaticMarkup(node as React.ReactElement) +} + +/** A well-formed response, with `result` swapped per case. */ +function response(result: unknown, extra: Record = {}) { + return { + stdout: '', + stderr: '', + exit_code: 0, + success: true, + duration_ms: 12, + result, + ...extra, + } +} + +describe('the completion value', () => { + it('renders an object result as JSON', () => { + const html = renderSettled({ lang: 'python', code: 'result = {"n": 42}' }, response({ n: 42 })) + expect(html).toContain('result') + expect(html).toContain('"n"') + expect(html).toContain('42') + // Never the useless stringification of an object. + expect(html).not.toContain('[object Object]') + }) + + it('renders a scalar result', () => { + const html = renderSettled({ lang: 'node', code: 'return 4' }, response(4)) + expect(html).toContain('4') + }) + + it('renders a null result explicitly rather than hiding the section', () => { + const html = renderSettled({ lang: 'node', code: '2 + 2' }, response(null)) + expect(html).toContain('null') + expect(html).toContain('returned nothing') + }) + + /** + * The `return`-vs-`result` mismatch is the single most common way a call + * comes back null having "worked", so the null state names the convention + * for the engine that actually ran. + */ + it('explains node’s return convention on a null result', () => { + const html = renderSettled({ lang: 'node', code: '2 + 2' }, response(null)) + expect(html).toContain('function body') + expect(html).toContain('return') + }) + + it('explains python’s result convention on a null result', () => { + const html = renderSettled({ lang: 'python', code: '2 + 2' }, response(null)) + expect(html).toContain('module') + expect(html).toContain('result') + }) + + /** + * A reuse can omit `lang` (the language belongs to the runtime), and there is + * then no honest convention to quote — so the null still renders, without a + * hint invented for an engine we cannot name. + */ + it('omits the convention hint when the request did not say which engine', () => { + const html = renderSettled({ runtime_id: RUNTIME_ID, code: 'whatever' }, response(null)) + expect(html).toContain('returned nothing') + expect(html).not.toContain('function body') + expect(html).not.toContain('module') + }) + + /** + * `result` is always present on this wire, so a response without it is + * malformed — and saying so beats rendering a card that silently implies the + * code returned nothing. + */ + it('reports a response that carried no result field at all', () => { + const { result: _dropped, ...withoutResult } = response(null) + const html = renderSettled({ lang: 'node', code: 'return 1' }, withoutResult) + expect(html).toContain('no `result` field') + }) + + /** + * The leak `RuntimeChip` does not cover: a script that calls back into the + * engine can RETURN its runtime id, and the stringified raw value would + * otherwise carry the capability into the feed. + */ + it('redacts a runtime id returned inside the result', () => { + const html = renderSettled({ lang: 'python', code: 'result = rt' }, response({ created: RUNTIME_ID })) + expect(html).not.toContain(RUNTIME_ID) + expect(html).toContain(TRUNCATED) + }) + + it('redacts a runtime id nested deep inside the result', () => { + const html = renderSettled({ lang: 'node', code: 'return x' }, response({ runtimes: [{ id: RUNTIME_ID }] })) + expect(html).not.toContain(RUNTIME_ID) + }) + + /** Object KEYS carry ids too — a payload can map by runtime. */ + it('redacts a runtime id used as a result object key', () => { + const html = renderSettled({ lang: 'node', code: 'return x' }, response({ [RUNTIME_ID]: 'alive' })) + expect(html).not.toContain(RUNTIME_ID) + }) + + /** + * A non-zero exit is a RESPONSE, not an error: the card must still render, + * still show the result slot, and must not escalate to the alert tone that + * means the worker failed. + */ + it('still renders the result on a non-zero exit', () => { + const html = renderSettled( + { lang: 'python', code: 'raise ValueError("nope")' }, + response(null, { + exit_code: 1, + success: false, + stderr: 'ValueError: nope\n', + }), + ) + expect(html).toContain('exit 1') + expect(html).toContain('ValueError: nope') + expect(html).toContain('returned nothing') + expect(html).not.toContain('cr-ui-alert') + }) +}) diff --git a/code-runner/ui/src/function-trigger-message/run.tsx b/code-runner/ui/src/function-trigger-message/run.tsx new file mode 100644 index 0000000000..a46b5e7cca --- /dev/null +++ b/code-runner/ui/src/function-trigger-message/run.tsx @@ -0,0 +1,334 @@ +/** + * Injected function-trigger renderer for `code-runner::run`. + * + * The default card prints the request as JSON, which turns `code` into one + * escaped single-line string and `stdout`/`stderr` into two more — + * unreadable, and this is the worker's highest-traffic call. Here the source + * is highlighted in the language it will actually run as, and the response is + * rendered as what it is: a process result PLUS a completion value. + * + * What this card exists to make obvious: + * + * - A NON-ZERO EXIT IS NOT AN ERROR. code-runner reserves errors for + * infrastructure failures (`error.rs`); a script that throws comes back as + * an ordinary response with its own traceback in `stderr`. So a failing + * exit reads as "your code exited N, here is stderr" (warn), never as a + * system fault (alert) — see `ExitStatus` in ../lib/shared. + * - `result` — the completion value, and the field + * `sandbox-code-runner`'s wire does not have. It is always present and + * never skipped, because a null result is information rather than an + * absence (run.rs). A null one shows the engine's return convention, + * because the usual cause is the convention mismatch: node code is a + * FUNCTION BODY (`return 2 + 2`), python code is a MODULE (assign + * `result`). A bare `2 + 2` in node returns nothing and is the single most + * common "it worked but I got null" call. + * - Which runtime the call ran in, and for how long. Three cases, and the + * card names exactly which one applies: a `runtime_id` in the request + * means a REUSE of a runtime the caller already holds; `keep: true` with + * none means the call is minting one to keep; neither means ONE-SHOT — the + * default — which creates a runtime, runs the code, and destroys it before + * this response is even sent. A one-shot response carries no `runtime_id` + * (there is nothing left to address). + * - That `runtime_id` is a capability: only ever shown through + * `RuntimeChip` (truncated, full value on an explicit copy), and every + * other string on the card — stdout, stderr, an error message, the + * completion value, even the submitted source — routed through + * `redactRuntimeIds` first. + * + * There is deliberately NO network chip: unlike `sandbox-code-runner`, this + * worker's request has no `network` field at all, because neither engine has + * any network. Rendering an "off" chip would imply a knob exists. + * + * Error outputs render their own compact card rather than falling through: + * code-runner's error messages quote the `runtime_id` BY DESIGN (`unknown + * runtime_id {id}` — error.rs), so the console's default view would print the + * capability verbatim on an ordinary mistake. + */ + +import { + CodeHighlight, + type FunctionTriggerMessage, + type FunctionTriggerRenderer, + type Host, +} from '@iii-dev/console-ui' +import { useState } from 'react' +import { + asRecord, + CardShell, + DeniedCard, + deniedInfo, + ErrorCard, + ExitStatus, + errorInfo, + langToPrism, + opName, + ResultValue, + RuntimeChip, + redactRuntimeIds, + resultConvention, + Stream, + TimeoutChip, + unwrapEnvelope, +} from '../lib/shared' + +const FUNCTION_ID = 'code-runner::run' + +/** Lines of source shown before the block collapses behind a toggle… */ +const CODE_CLAMP_LINES = 14 +/** …and a character ceiling, for the one-line 400 KB blob a minifier emits. */ +const CODE_CLAMP_CHARS = 2000 + +type Lang = 'node' | 'python' + +interface RunRequest { + code?: string + runtimeId?: string + /** Only ever a value `langToPrism` can honestly map; anything else is + * dropped rather than echoed as a claim about what will execute. */ + lang?: Lang + /** Only meaningful when `runtimeId` is absent — see `Chips`. */ + keep: boolean + timeoutMs?: number +} + +function parseRequest(input: unknown): RunRequest { + const obj = asRecord(input) ?? {} + return { + code: typeof obj.code === 'string' ? obj.code : undefined, + runtimeId: typeof obj.runtime_id === 'string' ? obj.runtime_id : undefined, + lang: obj.lang === 'node' || obj.lang === 'python' ? obj.lang : undefined, + keep: obj.keep === true, + timeoutMs: typeof obj.timeout_ms === 'number' ? obj.timeout_ms : undefined, + } +} + +/** + * Header chips. `runtimeId` is the effective one (the response's, falling back + * to the request's) and is absent on the one-shot path — nothing was left + * running to address. + */ +function Chips({ req, runtimeId }: { req: RunRequest; runtimeId?: string }) { + return ( + <> + {runtimeId ? : null} + {req.runtimeId ? ( + reused runtime + ) : req.keep ? ( + + keeps the runtime + + ) : ( + + one-shot + + )} + {req.lang ? ( + + lang + {req.lang} + + ) : null} + + + ) +} + +/** + * The submitted source, highlighted as the language it runs as and clamped so + * a generated 5000-line program cannot own the viewport. + * + * `lang` is `undefined` on a reuse that omitted it (the language belongs to + * the runtime, and the request does not say) — that renders unhighlighted + * rather than guessing, since a wrong language reads as a claim. + * + * `clipped` means the string came from the approval gate's + * `arguments_excerpt`, already truncated: its line count is not the program's, + * so no count is quoted from it. + */ +function CodeSection({ code, lang, clipped }: { code: string; lang?: Lang; clipped?: boolean }) { + const [expanded, setExpanded] = useState(false) + + // Source can embed a runtime id — a script that calls back into the engine + // carries one as a literal. The feed is not the caller that already holds it. + const safe = redactRuntimeIds(code) + if (safe.trim().length === 0) { + return
· empty code — nothing to run
+ } + + const lines = safe.split('\n') + const long = lines.length > CODE_CLAMP_LINES || safe.length > CODE_CLAMP_CHARS + const collapsed = long && !expanded + const shown = collapsed ? lines.slice(0, CODE_CLAMP_LINES).join('\n').slice(0, CODE_CLAMP_CHARS) : safe + + return ( +
+
{clipped ? 'code (excerpt)' : 'code'}
+
+ +
+ {long ? ( + + ) : null} +
+ ) +} + +/** + * One process stream. A present-but-not-a-string field is a malformed + * response, which gets a placeholder — dropping it silently would show a card + * that quietly disagrees with the payload. + */ +function StreamOrNote({ label, value, tone }: { label: string; value: unknown; tone?: 'out' | 'err' }) { + if (typeof value === 'string') { + return + } + if (value === undefined || value === null) return null + return ( +
+ · {label} was not a string ({typeof value}) — malformed response +
+ ) +} + +function SettledView({ message }: { message: FunctionTriggerMessage }) { + const req = parseRequest(message.input) + const res = asRecord(unwrapEnvelope(message.output)) ?? {} + const runtimeId = typeof res.runtime_id === 'string' ? res.runtime_id : req.runtimeId + // The language that actually ran: the request's when it said, otherwise + // unknown (a reuse inherits it from the runtime). Only used to explain a + // null result, so an unknown one simply explains nothing. + const convention = resultConvention(req.lang) + + return ( + }> + {/* The verdict first: in a chat feed you want "did it run?" before you + want the source, and a failing exit points at the stderr below. */} + + {/* Then what it returned. `result` is always on the wire, so its absence + from the response is itself worth reporting rather than hiding. */} + {'result' in res ? ( + + ) : ( +
+ · the response carried no `result` field — it is always present on this wire, so this response is malformed +
+ )} + {req.code === undefined ? ( +
· the request carried no code
+ ) : ( + + )} + + + {res.stdout === '' && res.stderr === '' ? ( +
· no output on stdout or stderr
+ ) : null} +
+ ) +} + +/** In-flight: what is being run, and where. No verdict to show yet. */ +function RunningView({ message }: { message: FunctionTriggerMessage }) { + const req = parseRequest(message.input) + return ( + }> +
· running…
+ {req.code === undefined ? null : } +
+ ) +} + +/** + * Pending approval: the source that is about to run, before saying yes. + * + * The approval gate may hand this renderer `arguments_excerpt` instead of the + * real request — every string clipped to 256 code points with a trailing `…`. + * A trailing `…` is that marker, so the code is labeled a possibly-partial + * excerpt rather than presented as the whole program on the one card gating + * arbitrary code execution. + */ +function PreviewView({ message, code }: { message: FunctionTriggerMessage; code: string }) { + const req = parseRequest(message.input) + const clipped = code.endsWith('…') + return ( + }> +
will run this code:
+ {clipped ? ( +
+ · clipped to 256 characters by the approval gate — an excerpt, not necessarily the whole program +
+ ) : null} + +
+ ) +} + +export function createRunRenderer(host: Host): FunctionTriggerRenderer { + void host // the run card reads nothing off the host + + const render = (message: FunctionTriggerMessage, running: boolean): React.ReactNode | null => { + if (message.functionId !== FUNCTION_ID) return null + if (message.pendingApproval) return null // tryRenderPreview handles it + // Not a record — e.g. a double-encoded (stringified) payload, which the + // default card knows how to unpack and this one does not. Fall through + // rather than asserting anything about a request we cannot read. + if (!asRecord(message.input)) return null + if (running) return + // Denied at the gate — this call never reached a runtime, so it must not + // read as one of the infrastructure failures `ErrorCard` means. Checked + // before `errorInfo`: a denial is also `'error' in output`-shaped. + const denied = deniedInfo(message.output) + if (denied) { + return + } + // Our own error card, never a fall-through: code-runner's error messages + // carry the runtime_id capability by design (error.rs), so the console's + // default view would print it unredacted. + const err = errorInfo(message.output) + if (err) { + return ( + + ) + } + // No parseable response body — an aborted call, or a reloaded session + // whose last call never paired. A normal state, and NOT a completed run, + // so let the console's own "response · empty" card have it rather than + // asserting an exit status that never happened. + if (!asRecord(unwrapEnvelope(message.output))) return null + return + } + + return { + id: 'code-runner/page.js#run', + isMatch: (functionId) => functionId === FUNCTION_ID, + tryRender: (message) => render(message, !!message.running), + tryRenderRunning: (message) => render(message, true), + tryRenderPreview: (message) => { + if (!message.pendingApproval) return null + if (message.functionId !== FUNCTION_ID) return null + if (!asRecord(message.input)) return null + // No readable `code`: the gate's default card shows the raw payload, + // which is strictly more than this card could honestly claim on an + // approval prompt for arbitrary code execution. + const { code } = parseRequest(message.input) + if (code === undefined) return null + return + }, + } +} diff --git a/code-runner/ui/src/function-trigger-message/teardown.tsx b/code-runner/ui/src/function-trigger-message/teardown.tsx new file mode 100644 index 0000000000..363ec8e469 --- /dev/null +++ b/code-runner/ui/src/function-trigger-message/teardown.tsx @@ -0,0 +1,212 @@ +/** + * `code-runner::teardown` — destroys one or more runtimes: it unregisters + * every bus function they put on the bus and disposes the engine state behind + * them (a V8 isolate and its scratch directory, or a CPython interpreter and + * its working directory). + * + * No microVM is involved, unlike `sandbox-code-runner` — these runtimes live + * in this worker's own process, which is the reason it needs no /dev/kvm. + * + * The card answers one question: WHICH function ids stopped resolving. That is + * the consequence a reader cannot recover from anywhere else. An empty + * `unregistered` list is the COMMON case — a runtime that only ever ran code + * registered nothing — so it reads as normal, never as a failure. + * + * TWO addressing modes, never both, never neither: `runtime_id` (a kept run's + * runtime — `code-runner::run keep=true`) or `namespace` (every runtime + * backing a `register_function` namespace, across both engines). The response + * echoes whichever one addressed the call, never both — see `targetOf`. + * + * The namespace path is the only way to reclaim a python namespace's + * interpreter: it is PINNED, i.e. deliberately exempt from the idle sweep, so + * a registration's runtime outlives its own idleness and nothing else will + * ever collect it. + * + * A preview IS offered even for this single-field-or-the-other request, for + * the same reason the error card is rendered here rather than fallen through + * to: the console's default card prints `runtime_id` in full, and a runtime id + * is a capability (see ../lib/shared.tsx). The one case that still falls + * through is a non-record `input` — see `tryRenderPreview`. + */ + +import type { FunctionTriggerMessage, FunctionTriggerRenderer, Host } from '@iii-dev/console-ui' +import { useState } from 'react' +import { + asRecord, + CardShell, + DeniedCard, + deniedInfo, + ErrorCard, + errorInfo, + RegisteredIds, + RuntimeChip, + redactRuntimeIds, + unwrapEnvelope, +} from '../lib/shared' + +const FUNCTION_ID = 'code-runner::teardown' + +/** Ids listed before the list collapses. */ +const GONE_CLAMP = 12 + +type Target = { kind: 'runtime'; id: string } | { kind: 'namespace'; name: string } + +/** + * Which of the two addressing modes a record (request or response) carries. + * `runtime_id` wins if a malformed record somehow carried both non-empty — the + * worker itself refuses that combination, so this is purely a display + * tie-break, never a claim about what the worker did. + */ +function targetOf(value: unknown): Target | undefined { + const rec = asRecord(value) + const id = rec?.runtime_id + if (typeof id === 'string' && id.length > 0) return { kind: 'runtime', id } + const ns = rec?.namespace + if (typeof ns === 'string' && ns.length > 0) return { kind: 'namespace', name: ns } + return undefined +} + +function TargetChip({ target }: { target?: Target }) { + if (!target) return null + if (target.kind === 'runtime') return + return ( + + namespace + {redactRuntimeIds(target.name)} + + ) +} + +/** + * `unregistered`, with non-string entries kept as visible placeholders rather + * than filtered away — a dropped entry would understate the blast radius. + * `undefined` when the field is absent or not an array, so the card can say + * "the response didn't list them" instead of claiming zero. + */ +function goneIds(result: Record | undefined) { + const raw = result?.unregistered + if (!Array.isArray(raw)) return undefined + return raw.map((v, i) => (typeof v === 'string' ? v : `⟨malformed entry ${i + 1}⟩`)) +} + +function SettledView({ message }: { message: FunctionTriggerMessage }) { + const [expanded, setExpanded] = useState(false) + const result = asRecord(unwrapEnvelope(message.output)) + const gone = goneIds(result) + // Only `torn_down === false` is a claim; a missing field is not. + const kept = result?.torn_down === false + // The response echoes whichever target addressed the call; the request is + // the fallback (e.g. an error response that carries neither). + const target = targetOf(result) ?? targetOf(message.input) + + const collapsed = !!gone && gone.length > GONE_CLAMP && !expanded + const shown = collapsed ? gone.slice(0, GONE_CLAMP) : (gone ?? []) + + return ( + }> +
+
+ {kept + ? '· the worker reported this was NOT torn down' + : target?.kind === 'namespace' + ? '· destroyed — every runtime backing this namespace was disposed' + : '· destroyed — its isolate or interpreter was disposed, along with its working directory'} +
+
+ {gone === undefined + ? '· the response did not list which function ids were unregistered' + : gone.length === 0 + ? '· it had registered no functions, so nothing stopped resolving on the bus' + : gone.length === 1 + ? '· 1 function id no longer resolves on the bus' + : `· ${gone.length} function ids no longer resolve on the bus`} +
+
+
+ + {gone && gone.length > GONE_CLAMP ? ( +
+ +
+ ) : null} +
+
+ ) +} + +function RunningView({ message }: { message: FunctionTriggerMessage }) { + // `input` is the only source of the target here, and a non-record one simply + // means no chip — the card claims nothing either way. Falling through + // instead would hand the raw request to the default card, which prints the + // capability in full. + return ( + }> +
· tearing down…
+
+ ) +} + +/** Pending approval: what is about to be destroyed. */ +function PreviewView({ message }: { message: FunctionTriggerMessage }) { + // The approval gate clips string arguments to 256 code points; a + // `rt-` is 39 and a namespace is short, so the value shown (and + // copied) here is always whole. + const target = targetOf(message.input) + return ( + }> +
+ {target?.kind === 'namespace' + ? 'will destroy every runtime backing this namespace — every function it registered stops resolving on the bus, and a pinned python interpreter is reclaimed' + : 'will destroy this runtime — every function it registered stops resolving on the bus, and its isolate or interpreter is disposed along with its working directory'} +
+
+ ) +} + +export function createTeardownRenderer(host: Host): FunctionTriggerRenderer { + void host + const render = (message: FunctionTriggerMessage, running: boolean): React.ReactNode | null => { + if (message.functionId !== FUNCTION_ID) return null + if (message.pendingApproval) return null // tryRenderPreview handles it + if (running) return + // Denied at the gate — no runtime was ever touched, so this must not read + // as one of the infrastructure failures `ErrorCard` means. Checked before + // `errorInfo`: a denial is also `'error' in output`-shaped. + const denied = deniedInfo(message.output) + if (denied) { + return + } + // Our own error card, never a fall-through: code-runner's error MESSAGES + // carry the runtime_id by design on the by-id path — `unknown runtime_id + // {id}` (error.rs) — and the default view would print that capability + // verbatim on an ordinary stale-id mistake. `ErrorCard` redacts either way. + const err = errorInfo(message.output) + if (err) { + const target = targetOf(message.input) + return ( + + ) + } + // No response body at all (aborted call, or a reloaded session whose last + // call never paired). Fall through so the console shows its own + // "response · empty" card — never assert a teardown that may not have + // happened. + if (!asRecord(unwrapEnvelope(message.output))) return null + return + } + return { + id: 'code-runner/page.js#teardown', + isMatch: (functionId) => functionId === FUNCTION_ID, + tryRender: (message) => render(message, !!message.running), + tryRenderRunning: (message) => render(message, true), + // A non-record `input` falls through: the console's default card decodes + // double-encoded payloads, and an approver of a destructive call must see + // the real request rather than a card that quietly shows no target. + tryRenderPreview: (message) => + message.pendingApproval && message.functionId === FUNCTION_ID && asRecord(message.input) ? ( + + ) : null, + } +} diff --git a/code-runner/ui/src/lib/shared.tsx b/code-runner/ui/src/lib/shared.tsx new file mode 100644 index 0000000000..bf4b59ab7d --- /dev/null +++ b/code-runner/ui/src/lib/shared.tsx @@ -0,0 +1,541 @@ +/** + * Shared building blocks for every code-runner function-trigger renderer. + * + * The three cards (run / register_function / teardown) differ only in their + * body — the frame, the runtime-id chip, the terminal streams, the exit + * status, the completion value and the id list are identical, and live here. + * + * SECURITY — `runtime_id` is a capability: whoever holds one can run into or + * tear down that runtime. It is NEVER rendered in full. `RuntimeChip` is the + * only sanctioned way to show one: truncated, with the full value reachable + * only by an explicit click-to-copy. Any other text that could embed one (an + * error message, a line of stdout, a function id) goes through + * `redactRuntimeIds` first. + * + * What code-runner is: ONE api over TWO in-process engines — untrusted + * JavaScript in a deno_core V8 isolate, untrusted Python as CPython compiled + * to WebAssembly in wasmtime. No microVM, no /dev/kvm. A run returns a + * PROCESS result — stdout, stderr, exit code — AND a completion value, which + * is the one field `sandbox-code-runner`'s wire does not carry. `Stream`, + * `ExitStatus` and `ResultValue` exist to keep those two things distinct: the + * streams are what the code printed, `result` is what it returned. + * + * A non-zero exit is NOT an error. code-runner reserves errors for + * infrastructure failures (`error.rs`); a script that throws comes back as an + * ordinary response with its own message in `stderr`. + */ + +import { Tooltip, TooltipContent, TooltipTrigger } from '@iii-dev/console-ui' +import { useCallback, useState } from 'react' + +/* --- payload helpers -------------------------------------------------- */ + +/** Narrow to a plain object, or `undefined` for anything else (incl. arrays). */ +export function asRecord(value: unknown): Record | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined + return value as Record +} + +/** `{ content: [...], details }` harness result envelope → details. */ +export function unwrapEnvelope(value: unknown): unknown { + if (!value || typeof value !== 'object' || Array.isArray(value)) return value + const obj = value as Record + if (Array.isArray(obj.content) && 'details' in obj) return obj.details + return value +} + +export function isErrorOutput(value: unknown): boolean { + return !!value && typeof value === 'object' && !Array.isArray(value) && 'error' in (value as Record) +} + +export const FUNCTION_PREFIX = 'code-runner::' + +/** `code-runner::run` → `run` (the op pill's label). */ +export function opName(functionId: string): string { + return functionId.startsWith(FUNCTION_PREFIX) ? functionId.slice(FUNCTION_PREFIX.length) : functionId +} + +/** + * The Prism id for a request's `lang`, or `undefined` when there is no honest + * answer — which renders unhighlighted. Never guess a language onto a code + * block: a wrong one reads as a claim about what will execute. + */ +export function langToPrism(lang: unknown): string | undefined { + if (lang === 'node') return 'javascript' + if (lang === 'python') return 'python' + return undefined +} + +/** + * How a run's code is evaluated, per engine — the thing that decides whether + * a given snippet returns anything at all. + * + * Node source is a FUNCTION BODY: `return 2 + 2` yields 4, a bare `2 + 2` + * yields nothing. Python source is a MODULE: assigning `result` is what + * returns a value. Getting this wrong is the single most common way a call + * comes back `result: null` having "worked", so the card says which + * convention applied rather than leaving the reader to guess. + */ +export function resultConvention(lang: unknown): string | undefined { + if (lang === 'node') return 'node code is a function body — `return` to yield a value' + if (lang === 'python') return 'python code is a module — assign `result` to yield a value' + return undefined +} + +/* --- runtime id (capability) ------------------------------------------ */ + +/** `rt-3f9a2c1e-…` → `rt-3f9a…`. Short ids are shown whole. */ +export function truncateRuntimeId(runtimeId: string): string { + return runtimeId.length > 8 ? `${runtimeId.slice(0, 7)}…` : runtimeId +} + +/** + * BOTH engines mint `rt-` — `format!("rt-{}", Uuid::new_v4())` in + * node-core's `manager.rs` and python-core's `manager.rs` alike — and + * code-runner's own error MESSAGES quote it by design (`RuntimeNotFound` is + * "unknown runtime_id {id}"; a documented exception to the redaction + * convention, since those go to the caller who already holds the id). The + * console feed is not that caller, so every string that could embed one — an + * error message, a line of program output, a bus function id — runs through + * this before it is rendered. + * + * No `\b` anchors: hex digits are word characters, so an id glued to + * `[A-Za-z0-9_]` (`_worker`, `app::_a`, `/work/_out.json`) matches + * neither boundary and would pass through whole. Matching the bare 39-char + * shape unanchored can only redact MORE, never less — it is the capability + * regardless of what touches it. + */ +const RUNTIME_ID_PATTERN = /rt-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi + +/** Replace every `rt-` substring of `text` with its truncated form. */ +export function redactRuntimeIds(text: string): string { + return text.replace(RUNTIME_ID_PATTERN, (id) => truncateRuntimeId(id)) +} + +/** + * `redactRuntimeIds` over EVERY string in an arbitrary JSON-ish value — + * object keys included. Objects, arrays, numbers, booleans and null keep + * their shape; the input is never mutated. + * + * This is what the renderers hand the console as `redactRaw`: the card's + * `raw json` tab renders the request/response verbatim and its copy button + * copies them, so a card that shows only `RuntimeChip` has not contained the + * capability until the raw value is filtered too. + * + * `seen` is the current PATH, not every visited node: a value referenced + * twice is redacted twice (correct), while a cycle collapses to + * `'[circular]'` rather than hanging the console. JSON off the wire cannot be + * cyclic, but `redactRaw` must be total for whatever it is handed. + */ +export function redactRuntimeIdsDeep(value: unknown, seen: WeakSet = new WeakSet()): unknown { + if (typeof value === 'string') return redactRuntimeIds(value) + if (value === null || typeof value !== 'object') return value + if (seen.has(value)) return '[circular]' + seen.add(value) + const out = Array.isArray(value) + ? value.map((entry) => redactRuntimeIdsDeep(entry, seen)) + : Object.fromEntries( + Object.entries(value as Record).map(([k, v]) => [ + redactRuntimeIds(k), + redactRuntimeIdsDeep(v, seen), + ]), + ) + seen.delete(value) + return out +} + +async function copyText(text: string): Promise { + try { + // Undefined outside a secure context (plain http:// over a LAN). + if (navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text) + return true + } + } catch { + /* fall through to the textarea path */ + } + const ta = document.createElement('textarea') + ta.value = text + ta.style.position = 'fixed' + ta.style.opacity = '0' + document.body.appendChild(ta) + try { + ta.select() + return document.execCommand('copy') + } catch { + return false + } finally { + // finally, not the success path: a throwing select/execCommand must not + // leave one orphaned textarea in per failed copy. + document.body.removeChild(ta) + } +} + +/** + * The truncated runtime-id chip. The full id is a capability, so it is only + * ever handed over on an explicit click (copied to the clipboard), never + * printed into the feed. + */ +export function RuntimeChip({ runtimeId }: { runtimeId: string }) { + const [state, setState] = useState<'idle' | 'copied' | 'failed'>('idle') + + const copy = useCallback(() => { + void copyText(runtimeId).then((ok) => { + setState(ok ? 'copied' : 'failed') + window.setTimeout(() => setState('idle'), 1400) + }) + }, [runtimeId]) + + return ( + + + + + + A runtime id is a capability — anyone holding it can run into or tear down that runtime, so only a prefix is + shown. Click to copy the full id. + + + ) +} + +/* --- card frame -------------------------------------------------------- */ + +/** + * The frame every code-runner card shares: op pill, caller-supplied chips, + * the "code-runner ui" attribution tag (so an override is distinguishable + * from first-party rendering), and the body. + */ +export function CardShell({ + op, + running, + tag = 'code-runner ui', + chips, + children, +}: { + op: string + running?: boolean + tag?: string + chips?: React.ReactNode + children?: React.ReactNode +}) { + return ( +
+
+ {op} + {chips} + {tag} +
+ {children} +
+ ) +} + +/* --- terminal streams --------------------------------------------------- */ + +/** Lines of a stream shown before it collapses behind a toggle. */ +const STREAM_CLAMP_LINES = 12 +/** …and a character ceiling, for the one 400 KB line a minifier emits. */ +const STREAM_CLAMP_CHARS = 2000 + +/** + * `stdout` / `stderr` as terminal output: monospace, whitespace preserved, + * clamped so a chatty script cannot flood the chat (the CSS caps the height + * and scrolls; this caps what is in the DOM at all). `null` for an empty + * string — the caller decides what "no output" should say, if anything. + * + * `tone="err"` tints the stream, and nothing more: stderr on a non-zero exit + * is the user's own traceback or runtime message, not a system error. + */ +export function Stream({ label, text, tone = 'out' }: { label: string; text: string; tone?: 'out' | 'err' }) { + const [expanded, setExpanded] = useState(false) + if (text.length === 0) return null + + const safe = redactRuntimeIds(text) + const lines = safe.split('\n') + const long = lines.length > STREAM_CLAMP_LINES || safe.length > STREAM_CLAMP_CHARS + const collapsed = long && !expanded + const shown = collapsed ? lines.slice(0, STREAM_CLAMP_LINES).join('\n').slice(0, STREAM_CLAMP_CHARS) : safe + + return ( +
+
{label}
+
{shown}
+ {long ? ( + + ) : null} +
+ ) +} + +/* --- completion value --------------------------------------------------- */ + +/** Characters of pretty-printed JSON shown before the block collapses. */ +const RESULT_CLAMP_CHARS = 1200 + +/** + * The run's `result` — the completion value, which is what makes + * code-runner's wire a SUPERSET of `sandbox-code-runner`'s rather than a copy + * of it. + * + * `result` is always present on the wire and never skipped, because a null + * result is information ("the code returned nothing"), not an absence + * (run.rs). So this renders `null` explicitly rather than hiding the section: + * a reader who returned something and got null back needs to see that, and it + * is usually the `return`-vs-`result` convention mismatch that `hint` + * explains. + * + * The value is arbitrary tenant JSON, so it goes through + * `redactRuntimeIdsDeep` before being stringified — a script that calls back + * into the engine can return a runtime id, and the string form would + * otherwise carry the capability into the feed. + */ +export function ResultValue({ + value, + hint, +}: { + value: unknown + /** The engine's return convention, shown only when the result is null. */ + hint?: string +}) { + const [expanded, setExpanded] = useState(false) + + const isNull = value === null || value === undefined + let text: string + try { + text = JSON.stringify(redactRuntimeIdsDeep(value) ?? null, null, 2) ?? 'null' + } catch { + // Non-serializable (a BigInt survives the wire as a string, but be total). + text = String(value) + } + + const long = text.length > RESULT_CLAMP_CHARS + const collapsed = long && !expanded + const shown = collapsed ? text.slice(0, RESULT_CLAMP_CHARS) : text + + return ( +
+
result
+ {isNull ? ( +
+ null — the code returned nothing + {hint ? · {hint} : null} +
+ ) : ( + <> +
{shown}
+ {long ? ( + + ) : null} + + )} +
+ ) +} + +/* --- exit status -------------------------------------------------------- */ + +/** + * The one-line verdict on a run: exit code, what it means, how long it took. + * + * A non-zero exit is NOT an error. code-runner reserves errors for + * infrastructure failures; a script that throws comes back as an ordinary + * response with its message in `stderr`. So a failing exit is `--color-warn` + * ("your program failed") and never `--color-alert` ("the system failed"). + */ +export function ExitStatus({ + exitCode, + success, + durationMs, +}: { + exitCode?: number + success?: boolean + durationMs?: number +}) { + const cleanExit = exitCode === 0 + // An omitted `success` never gets promoted to a claim either way. What must + // NOT happen is treating `success: false` on a 0 exit code as the ordinary + // "non-zero exit" case — the note has to describe what is actually shown + // (`exit 0`), not contradict it. + const ok = cleanExit && success !== false + const note = + exitCode === undefined + ? 'no exit code in the response' + : ok + ? 'clean exit' + : cleanExit + ? 'exit 0, but the response reported success: false — its own message is in stderr' + : 'the script exited non-zero — its own message is in stderr' + + return ( +
+ + {exitCode === undefined ? 'exit ?' : `exit ${exitCode}`} + + {note} + {durationMs === undefined ? null : {durationMs}ms} +
+ ) +} + +/* --- registered function ids ------------------------------------------- */ + +/** + * Compact list of bus function ids a call touched. `null` when empty. + * + * The shared sink for every id list in this UI — `id` is redacted here so + * every call site gets the fix once. Ids are caller-chosen, but nothing stops + * a caller naming one after its runtime. + */ +export function RegisteredIds({ ids }: { ids: readonly string[] }) { + if (ids.length === 0) return null + return ( +
+ {ids.map((id) => ( + + {redactRuntimeIds(id)} + + ))} +
+ ) +} + +/* --- timeout chip ------------------------------------------------------- */ + +/** `timeout_ms`, when the request carried one. */ +export function TimeoutChip({ ms }: { ms?: number }) { + if (ms === undefined) return null + return ( + + timeout + {ms}ms + + ) +} + +/* --- errors -------------------------------------------------------------- */ + +/** + * Pull the message out of a code-runner error output. Checked at both the raw + * value and its unwrapped envelope — the same two places every renderer's + * `isErrorOutput` check looks — since which level carries the `{ error }` key + * depends on the path the failure took. + */ +export function errorInfo(output: unknown): { message: string } | undefined { + const direct = asRecord(output) + const nested = asRecord(unwrapEnvelope(output)) + const rec = isErrorOutput(direct) ? direct : isErrorOutput(nested) ? nested : undefined + if (!rec) return undefined + const err = rec.error + const errObj = asRecord(err) + // JSON.stringify(undefined) is undefined, not a string — and `{ error: + // undefined }` passes isErrorOutput's `'error' in rec` check. The fallback + // keeps `message` total so ErrorCard renders an error instead of throwing. + const message = + typeof err === 'string' + ? err + : typeof errObj?.message === 'string' + ? errObj.message + : (JSON.stringify(err) ?? 'unknown error') + return { message } +} + +/** + * The error card every code-runner renderer shows instead of falling through + * to the console's default error view: code-runner's error MESSAGES carry the + * runtime_id capability by design (`unknown runtime_id {id}` — error.rs), so + * the unredacted default view would print it verbatim on an ordinary mistake. + * + * This is an infrastructure failure — the runtime is gone, an engine refused, + * the deadline blew, a cap was hit. A script that merely exited non-zero + * never lands here. A call the approval gate DENIED never lands here either — + * see `DeniedCard`. + */ +export function ErrorCard({ op, runtimeId, message }: { op: string; runtimeId?: string; message: string }) { + return ( + : null}> +
{redactRuntimeIds(message)}
+
+ ) +} + +/* --- gate denials ------------------------------------------------------- */ + +/** + * A deny/timeout resolution from the approval gate rides in `error.details` + * as the gate's DenialEnvelope (`{ status: 'denied', denied_by, reason, + * args_excerpt, … }`). This mirrors the console's own `isDeniedOutput` so the + * two agree on what a denial looks like — checked at both the raw value and + * its unwrapped envelope, the same two places `errorInfo` looks. + */ +export function isDeniedOutput(output: unknown): boolean { + const direct = asRecord(output) + const nested = asRecord(unwrapEnvelope(output)) + const rec = isErrorOutput(direct) ? direct : isErrorOutput(nested) ? nested : undefined + if (!rec) return false + const details = asRecord(asRecord(rec.error)?.details) + return !!details && details.status === 'denied' && 'denied_by' in details +} + +export interface DenialInfo { + reason: string + deniedBy?: string +} + +/** `{ reason, deniedBy }` out of a denial output, or `undefined` when + * `output` is not one — see `isDeniedOutput`. */ +export function deniedInfo(output: unknown): DenialInfo | undefined { + if (!isDeniedOutput(output)) return undefined + const direct = asRecord(output) + const nested = asRecord(unwrapEnvelope(output)) + const rec = (isErrorOutput(direct) ? direct : nested) as Record + const err = asRecord(rec.error) + const details = asRecord(err?.details) ?? {} + const reason = + typeof details.reason === 'string' + ? details.reason + : typeof err?.message === 'string' + ? err.message + : 'denied at the gate' + const deniedBy = typeof details.denied_by === 'string' ? details.denied_by : undefined + return { reason, deniedBy } +} + +/** + * A gate denial: the call was stopped at the approval gate and never reached + * an engine. Distinct from `ErrorCard` on purpose — `ErrorCard` means an + * infrastructure failure AFTER the call landed, and its RuntimeChip would + * wrongly imply a runtime was involved in a call that never reached one. The + * envelope's `args_excerpt` can carry the runtime_id capability (a caller is + * free to pass one as an argument), so this never falls through to the + * console's default view and never renders anything but the redacted + * `reason` — the envelope itself is not printed. + */ +export function DeniedCard({ op, reason, deniedBy }: { op: string; reason: string; deniedBy?: string }) { + return ( + +
+ · denied at the gate — this never ran + {deniedBy ? ` · denied by ${deniedBy}` : ''} +
+
{redactRuntimeIds(reason)}
+
+ ) +} diff --git a/code-runner/ui/styles.css b/code-runner/ui/styles.css new file mode 100644 index 0000000000..80a32c3bfe --- /dev/null +++ b/code-runner/ui/styles.css @@ -0,0 +1,437 @@ +/* + * The code-runner worker's console stylesheet, shipped as its own + * `console:style` asset (code-runner/styles.css) — the console mounts it as a + * in document.head and link-swaps it on hot reload, styles-before- + * scripts on boot. + * + * Every rule is scoped under `[data-iii-ui="code-runner"]`, the wrapper the + * console mounts around every injected render. No :root/html/body/bare element + * selectors and no @font-face — injected CSS is unlayered, so an unscoped rule + * would silently beat the console's own document-wide. Colours are design + * tokens only, so light/dark theming is free. + * + * Shared shell first (`cr-ui-*`, used by every card), then one section per + * renderer (`cr--*`, used by exactly one). Anything a second renderer + * needs moves up into the shell rather than being copied. + * + * `@keyframes` names are global even here, so they carry the prefix too. + * + * Two deliberate differences from `sandbox-code-runner/ui/styles.css`, which + * this is otherwise a port of: there are no `.cr-run-net` rules (this worker's + * request has no `network` field — neither engine has any network, so a chip + * would imply a knob exists), and there is a `.cr-ui-result-*` block for the + * completion value, which is the field this worker's wire adds. + */ + +/* --- card frame -------------------------------------------------------- */ +[data-iii-ui="code-runner"] .cr-ui-msg { + border-top: 1px solid var(--color-rule-2); + background: var(--color-bg); + font-family: var(--font-mono, ui-monospace, monospace); + color: var(--color-ink); +} +[data-iii-ui="code-runner"] .cr-ui-msg-head { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + flex-wrap: wrap; +} +[data-iii-ui="code-runner"] .cr-ui-pill { + border: 1px solid var(--color-accent); + color: var(--color-accent); + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.08em; + padding: 1px 8px; +} +[data-iii-ui="code-runner"] .cr-ui-pill.quiet { + border-color: var(--color-rule); + color: var(--color-ink-faint); +} +[data-iii-ui="code-runner"] .cr-ui-msg-tag { + margin-left: auto; + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--color-ink-ghost); +} +[data-iii-ui="code-runner"] .cr-ui-msg-note { + padding: 0 12px 10px; + font-size: 12px; + color: var(--color-ink-faint); +} +[data-iii-ui="code-runner"] .cr-ui-msg-note.pulse { + animation: cr-ui-pulse 1.6s ease-in-out infinite; +} +@keyframes cr-ui-pulse { + 0%, 100% { opacity: 1 } + 50% { opacity: 0.35 } +} +@media (prefers-reduced-motion: reduce) { + [data-iii-ui="code-runner"] .cr-ui-msg-note.pulse { + animation: none; + } +} + +/* --- chips ------------------------------------------------------------- */ +[data-iii-ui="code-runner"] .cr-ui-chip { + border: 1px solid var(--color-rule); + color: var(--color-ink); + font-size: 11.5px; + padding: 1px 8px; + white-space: nowrap; +} +[data-iii-ui="code-runner"] .cr-ui-chip .k { color: var(--color-ink-ghost); } + +/* The runtime-id capability chip: a button, because it copies on click. */ +[data-iii-ui="code-runner"] .cr-ui-rt { + border: 1px dashed var(--color-rule); + background: transparent; + color: var(--color-ink); + font-family: inherit; + font-size: 11.5px; + padding: 1px 8px; + cursor: pointer; + white-space: nowrap; +} +[data-iii-ui="code-runner"] .cr-ui-rt .k { color: var(--color-ink-ghost); } +[data-iii-ui="code-runner"] .cr-ui-rt:hover { border-color: var(--color-accent); } +[data-iii-ui="code-runner"] .cr-ui-rt:focus-visible { + outline: 1px solid var(--color-ring); + outline-offset: 1px; +} +[data-iii-ui="code-runner"] .cr-ui-rt.copied { border-color: var(--color-ok); color: var(--color-ok); } +[data-iii-ui="code-runner"] .cr-ui-rt.failed { border-color: var(--color-alert); color: var(--color-alert); } +[data-iii-ui="code-runner"] .cr-ui-rt-flash { font-size: 10.5px; letter-spacing: 0.06em; } + +/* --- terminal streams (stdout / stderr) -------------------------------- */ +/* Process output, not log records: no per-line level gutter, whitespace + preserved, and a hard height ceiling so a chatty script scrolls inside its + own box instead of pushing the conversation off screen. */ +[data-iii-ui="code-runner"] .cr-ui-stream { + border-top: 1px solid var(--color-rule-2); + padding: 6px 12px 8px; + display: flex; + flex-direction: column; +} +[data-iii-ui="code-runner"] .cr-ui-stream-label { + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--color-ink-ghost); + margin-bottom: 4px; +} +[data-iii-ui="code-runner"] .cr-ui-stream-body { + margin: 0; + font-family: inherit; + font-size: 12px; + line-height: 1.5; + color: var(--color-ink); + white-space: pre-wrap; + overflow-wrap: anywhere; + max-height: 260px; + overflow: auto; +} +/* stderr is the user's own compiler/runtime message on a failed script — + informational, so it is tinted, not alarmed. */ +[data-iii-ui="code-runner"] .cr-ui-stream.err .cr-ui-stream-label, +[data-iii-ui="code-runner"] .cr-ui-stream.err .cr-ui-stream-body { + color: var(--color-warn); +} + +/* --- exit status -------------------------------------------------------- */ +[data-iii-ui="code-runner"] .cr-ui-exit { + border-top: 1px solid var(--color-rule-2); + display: flex; + align-items: baseline; + gap: 8px; + flex-wrap: wrap; + padding: 6px 12px; + font-size: 12px; +} +[data-iii-ui="code-runner"] .cr-ui-exit-code { + border: 1px solid var(--color-rule); + font-size: 11.5px; + padding: 1px 8px; + white-space: nowrap; +} +[data-iii-ui="code-runner"] .cr-ui-exit-code.ok { + border-color: var(--color-ok); + color: var(--color-ok); +} +/* warn, never alert: a non-zero exit is the script failing, not the worker. */ +[data-iii-ui="code-runner"] .cr-ui-exit-code.failed { + border-color: var(--color-warn); + color: var(--color-warn); +} +[data-iii-ui="code-runner"] .cr-ui-exit-note { color: var(--color-ink-faint); } +[data-iii-ui="code-runner"] .cr-ui-exit-dur { + margin-left: auto; + color: var(--color-ink-ghost); + font-size: 11.5px; +} + +/* --- registered ids ----------------------------------------------------- */ +[data-iii-ui="code-runner"] .cr-ui-ids { + display: flex; + flex-wrap: wrap; + gap: 4px; + padding: 0 12px 10px; +} +[data-iii-ui="code-runner"] .cr-ui-id { + border: 1px solid var(--color-rule-2); + background: var(--color-paper-2); + color: var(--color-ink); + font-size: 11.5px; + padding: 1px 6px; +} + +/* --- completion value ---------------------------------------------------- */ +/* `result` is what the code RETURNED, as distinct from what it printed: the + streams above are stdout/stderr, this is the value. Pretty-printed JSON, so + it needs the same monospace + scroll treatment as a stream, with a lower + ceiling — a result is usually small and a huge one is better expanded. */ +[data-iii-ui="code-runner"] .cr-ui-result-body { + margin: 0; + font-family: inherit; + font-size: 12px; + line-height: 1.5; + color: var(--color-ink); + white-space: pre-wrap; + overflow-wrap: anywhere; + max-height: 220px; + overflow: auto; +} +/* A null result is the routine "returned nothing", not a fault — ghost weight, + never warn: the overwhelmingly common cause is a `return`-vs-`result` + convention mismatch, which the hint beside it explains. */ +[data-iii-ui="code-runner"] .cr-ui-result-null { + font-size: 12px; + line-height: 1.5; + color: var(--color-ink-faint); +} +[data-iii-ui="code-runner"] .cr-ui-result-hint { + color: var(--color-ink-ghost); +} + +/* --- renderer body slots ----------------------------------------------- */ +[data-iii-ui="code-runner"] .cr-ui-section { + border-top: 1px solid var(--color-rule-2); + padding: 8px 12px; +} +[data-iii-ui="code-runner"] .cr-ui-section-label { + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.1em; + color: var(--color-ink-ghost); + margin-bottom: 6px; +} +[data-iii-ui="code-runner"] .cr-ui-code { + border: 1px solid var(--color-rule-2); + background: var(--color-panel); + font-size: 12px; + max-height: 320px; + overflow: auto; +} +[data-iii-ui="code-runner"] .cr-ui-warn { color: var(--color-warn); } +[data-iii-ui="code-runner"] .cr-ui-alert { color: var(--color-alert); } + +/* The "expand · N lines" / "collapse" link. Shared by every collapsible + block: the streams, run's source, register_function's source. */ +[data-iii-ui="code-runner"] .cr-ui-toggle { + align-self: flex-start; + margin-top: 4px; + background: transparent; + border: 0; + padding: 0; + font-family: inherit; + font-size: 11px; + color: var(--color-accent); + cursor: pointer; + text-decoration: underline; +} + +/* --- run card ------------------------------------------------------------ */ +/* A runtime the call CREATED is a resource the caller now owns and has to + tear down — the warn tint marks "you are holding something", not an error. */ +[data-iii-ui="code-runner"] .cr-run-fresh { + border-color: var(--color-warn); + color: var(--color-warn); +} + +/* --- register_function card ---------------------------------------------- */ +[data-iii-ui="code-runner"] .cr-register-function-head { + display: flex; + align-items: baseline; + gap: 8px; + flex-wrap: wrap; +} +/* A function id runs to hundreds of bytes and a description further still; + neither may push the conversation off screen. */ +[data-iii-ui="code-runner"] .cr-register-function-id { + font-size: 15px; + color: var(--color-accent); + overflow-wrap: anywhere; + max-height: 84px; + overflow: auto; +} +[data-iii-ui="code-runner"] .cr-register-function-desc { + font-size: 12px; + line-height: 1.5; + color: var(--color-ink-faint); + margin-top: 2px; + overflow-wrap: anywhere; + max-height: 120px; + overflow: auto; +} +/* `.cr-ui-warn` alone is the same specificity as the two rules above, so + whichever sits later in this file would otherwise win regardless of which + one is more meaningful — an empty id or description would render at full + accent/ink-faint weight instead of the warn tint. These compound selectors + outrank both so the warn treatment always applies when the class is + actually present on the element. */ +[data-iii-ui="code-runner"] .cr-register-function-id.cr-ui-warn, +[data-iii-ui="code-runner"] .cr-register-function-desc.cr-ui-warn { + color: var(--color-warn); +} +[data-iii-ui="code-runner"] .cr-register-function-status { + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.08em; + border: 1px solid var(--color-rule); + padding: 0 6px; +} +[data-iii-ui="code-runner"] .cr-register-function-status.live { + border-color: var(--color-ok); + color: var(--color-ok); +} +[data-iii-ui="code-runner"] .cr-register-function-status.refused { + border-color: var(--color-warn); + color: var(--color-warn); +} +/* The namespace the id claims for its runtime — the surprise this card exists + to spoil, so it sits under the id rather than in a chip row. */ +[data-iii-ui="code-runner"] .cr-register-function-ns { + margin-top: 4px; + font-size: 12px; + line-height: 1.5; + color: var(--color-ink-faint); + overflow-wrap: anywhere; +} +/* Same specificity fight as `.cr-register-function-id`/`-desc` above: an id + with no namespace must read as warn, not the routine ink-faint tone. */ +[data-iii-ui="code-runner"] .cr-register-function-ns.cr-ui-warn { + color: var(--color-warn); +} +[data-iii-ui="code-runner"] .cr-register-function-ns code { + font-family: inherit; + color: var(--color-ink); +} +/* The highlighting is a guess (this request has no `lang`), so it is labelled + as one — quietly, at ghost weight. */ +[data-iii-ui="code-runner"] .cr-register-function-lang { + margin-top: 4px; + font-size: 11px; + line-height: 1.4; + color: var(--color-ink-ghost); +} + +/* --- teardown card: ids that no longer resolve -------------------------- */ +/* Struck through, because these ids stopped resolving on the bus. Ids are + caller-chosen strings, so one long unbroken id must wrap inside its chip + rather than push the card sideways. (The count is clamped in the DOM by the + card itself — a runtime may hold up to 64 functions.) */ +[data-iii-ui="code-runner"] .cr-teardown-gone .cr-ui-id { + color: var(--color-ink-faint); + text-decoration: line-through; + text-decoration-color: var(--color-ink-ghost); + overflow-wrap: anywhere; +} +/* The "expand · N ids" toggle sits below the chips, on the list's padding. */ +[data-iii-ui="code-runner"] .cr-teardown-more { + padding: 0 12px 10px; +} + +/* --- configuration form (Workers tab, `code-runner` entry) -------------- */ +/* Same field grammar as the state worker's form: mono, token colors only, + * host owns the SaveBar below. The section badges carry the reload split — + * green-ish accent for hot-applied, faint for restart-applied — because that + * split is the one thing an operator must know before saving. */ +[data-iii-ui="code-runner"] .cr-cfg-form { + display: flex; + flex-direction: column; + gap: 22px; + font-family: var(--font-mono, ui-monospace, monospace); + color: var(--color-ink); +} +[data-iii-ui="code-runner"] .cr-cfg-caption { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.12em; + color: var(--color-ink-ghost); +} +[data-iii-ui="code-runner"] .cr-cfg-section { + display: flex; + flex-direction: column; + gap: 12px; +} +[data-iii-ui="code-runner"] .cr-cfg-section-title { + display: flex; + align-items: baseline; + gap: 8px; + font-size: 12.5px; + color: var(--color-ink); + border-bottom: 1px solid var(--color-rule-2); + padding-bottom: 6px; +} +[data-iii-ui="code-runner"] .cr-cfg-live, +[data-iii-ui="code-runner"] .cr-cfg-restart { + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.08em; +} +[data-iii-ui="code-runner"] .cr-cfg-live { color: var(--color-accent); } +[data-iii-ui="code-runner"] .cr-cfg-restart { color: var(--color-ink-ghost); } +[data-iii-ui="code-runner"] .cr-cfg-field { + display: flex; + flex-direction: column; + gap: 6px; +} +[data-iii-ui="code-runner"] .cr-cfg-field > label { + font-size: 12px; + color: var(--color-ink-faint); +} +[data-iii-ui="code-runner"] .cr-cfg-field .hint, +[data-iii-ui="code-runner"] .cr-cfg-section > .hint { + font-size: 11.5px; + line-height: 1.5; + color: var(--color-ink-ghost); +} +[data-iii-ui="code-runner"] .cr-cfg-input { + border: 1px solid var(--color-rule); + background: var(--color-bg); + color: var(--color-ink); + font-family: inherit; + font-size: 12.5px; + padding: 7px 10px; + max-width: 420px; +} +[data-iii-ui="code-runner"] .cr-cfg-input:focus { + outline: 1px solid var(--color-accent); + outline-offset: -1px; +} +[data-iii-ui="code-runner"] .cr-cfg-error { + border: 1px solid var(--color-alert); + color: var(--color-alert); + padding: 10px 12px; + font-size: 12.5px; +} +[data-iii-ui="code-runner"] .cr-cfg-checkrow { + display: flex; + align-items: center; + gap: 8px; + font-size: 12.5px; + color: var(--color-ink); +} +[data-iii-ui="code-runner"] .cr-cfg-checkrow input { accent-color: var(--color-accent); } diff --git a/code-runner/ui/tsconfig.json b/code-runner/ui/tsconfig.json new file mode 100644 index 0000000000..e5ac605406 --- /dev/null +++ b/code-runner/ui/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["page.tsx", "src"] +} diff --git a/crates/node-core/Cargo.lock b/crates/node-core/Cargo.lock new file mode 100644 index 0000000000..6897e9d94b --- /dev/null +++ b/crates/node-core/Cargo.lock @@ -0,0 +1,1945 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "az" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be5eb007b7cacc6c660343e96f650fedf4b5a77512399eb952ca6642cf8d13f7" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn 2.0.119", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "boxed_error" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17d4f95e880cfd28c4ca5a006cf7f6af52b4bcb7b5866f573b2faa126fb7affb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + +[[package]] +name = "capacity_builder" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f2d24a6dcf0cd402a21b65d35340f3a49ff3475dc5fdac91d22d2733e6641c6" +dependencies = [ + "capacity_builder_macros", + "itoa", +] + +[[package]] +name = "capacity_builder_macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b4a6cae9efc04cc6cbb8faf338d2c497c165c83e74509cf4dbedea948bbf6e5" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cooked-waker" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147be55d677052dabc6b22252d5dd0fd4c29c8c27aa4f2fbef0f94aa003b406f" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "serde", + "uuid", +] + +[[package]] +name = "deno_core" +version = "0.409.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b44f6f84139c39ec2f8d1b838412eb84ecaa9837103f7b12169896fd8778b4" +dependencies = [ + "anyhow", + "az", + "base64", + "bincode", + "bit-set", + "bit-vec", + "boxed_error", + "bytes", + "capacity_builder", + "cooked-waker", + "deno_error", + "deno_ops", + "deno_path_util", + "deno_unsync", + "futures", + "indexmap", + "inventory", + "libc", + "num-bigint", + "parking_lot", + "percent-encoding", + "pin-project", + "serde", + "serde_json", + "serde_v8", + "smallvec", + "sourcemap", + "static_assertions", + "sys_traits", + "thiserror", + "tokio", + "url", + "uuid", + "v8", + "wasm_dep_analyzer", + "windows-sys 0.59.0", +] + +[[package]] +name = "deno_error" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfafd2219b29886a71aecbb3449e462deed1b2c474dc5b12f855f0e58c478931" +dependencies = [ + "deno_error_macro", + "libc", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "deno_error_macro" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c28ede88783f14cd8aae46ca89f230c226b40e4a81ab06fa52ed72af84beb2f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "deno_ops" +version = "0.285.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c02fede673301e8b47d19368e0f3146d020e5dfcc5ee31d020cbbe542b2a50" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "stringcase", + "strum", + "strum_macros", + "syn 2.0.119", + "syn-match", + "thiserror", +] + +[[package]] +name = "deno_path_util" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c7e98943f0d068928906db0c7bde89de684fa32c6a8018caacc4cee2cdd72b" +dependencies = [ + "deno_error", + "percent-encoding", + "sys_traits", + "thiserror", + "url", +] + +[[package]] +name = "deno_unsync" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6742a724e8becb372a74c650a1aefb8924a5b8107f7d75b3848763ea24b27a87" +dependencies = [ + "futures-util", + "parking_lot", + "tokio", +] + +[[package]] +name = "diplomat" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26fdfa02eb9a2e1ff82a375524be1ce9fd50ae63787f5737da6951b25d21e857" +dependencies = [ + "diplomat_core", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "diplomat-runtime" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae517853d9f82b2d144393b1c32c34c46c2e361de2b6c44a8fdfce23beb211cd" + +[[package]] +name = "diplomat_core" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4ede23809e2fcc555d8b2e10ffa7a1c31331ebca8e5477f4f2b48ab8a0a9a6b" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "smallvec", + "strck", + "syn 3.0.3", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "either" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fslock" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" + +[[package]] +name = "futures-executor" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a" + +[[package]] +name = "futures-macro" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "futures-sink" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307" + +[[package]] +name = "futures-task" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" + +[[package]] +name = "futures-util" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "gzip-header" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86848f4fd157d91041a62c78046fb7b248bcc2dce78376d436a1756e9a038577" +dependencies = [ + "crc32fast", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "icu_calendar" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b2acc6263f494f1df50685b53ff8e57869e47d5c6fe39c23d518ae9a4f3e45" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar_data", + "icu_locale", + "icu_locale_core", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_calendar_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "118577bcf3a0fa7c6ac0a7d6e951814da84ee56b9b1f68fb4d8d10b08cefaf4d" + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a396343c7208121dc86e35623d3dfe19814a7613cfd14964994cdc9c9a2e26" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5fdcc9ac77c6d74ff5cf6e65ef3181d6af32003b16fce3a77fb451d2f695993" + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "if_chain" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb" + +[[package]] +name = "iii-node-core" +version = "0.1.0" +dependencies = [ + "deno_core", + "deno_error", + "futures", + "libc", + "once_cell", + "schemars", + "serde", + "serde_json", + "tempfile", + "tokio", + "tracing", + "uuid", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "inventory" +version = "0.3.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "ixdtf" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ceaf4c6c48465bead8cb6a0b7c4ee0c86ecbb31239032b9c66ab9a08d2f3ee1" + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", + "rand", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "resb" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22d392791f3c6802a1905a509e9d1a6039cbbcb5e9e00e5a6d3661f7c874f390" +dependencies = [ + "potential_utf", + "serde_core", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_v8" +version = "0.318.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb994c8fd6bc9746ac605f1c38219fc5eaa99ca4509db1b6519eefa0219b04a0" +dependencies = [ + "deno_error", + "num-bigint", + "serde", + "smallvec", + "thiserror", + "v8", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sourcemap" +version = "9.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "314d62a489431668f719ada776ca1d49b924db951b7450f8974c9ae51ab05ad7" +dependencies = [ + "base64-simd", + "bitvec", + "data-encoding", + "debugid", + "if_chain", + "rustc-hash", + "serde", + "serde_json", + "unicode-id-start", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strck" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42316e70da376f3d113a68d138a60d8a9883c604fe97942721ec2068dab13a9f" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "stringcase" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72abeda133c49d7bddece6c154728f83eec8172380c80ab7096da9487e20d27c" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn-match" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b8f0a9004d6aafa6a588602a1119e6cdaacec9921aa1605383e6e7d6258fd6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sys_traits" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88826d6169418c98e8bc52a43f79d50907dfa3e87ba5161930d42c6f980b35ee" +dependencies = [ + "sys_traits_macros", +] + +[[package]] +name = "sys_traits_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "181f22127402abcf8ee5c83ccd5b408933fec36a6095cf82cda545634692657e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "temporal_capi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f48eb9ca4ca22caaa48d1e7a534ad3fd598a23d1a71945e8ad5ac0be501fa5f2" +dependencies = [ + "diplomat", + "diplomat-runtime", + "icu_calendar", + "icu_locale_core", + "num-traits", + "temporal_rs", + "timezone_provider", + "writeable", + "zoneinfo64", +] + +[[package]] +name = "temporal_rs" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a978fef907a27736827d336c0bfaab14fb8a7509dd6dc2b43c44e51d59aca5b" +dependencies = [ + "calendrical_calculations", + "core_maths", + "icu_calendar", + "icu_locale_core", + "ixdtf", + "num-traits", + "timezone_provider", + "tinystr", + "writeable", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "timezone_provider" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52" +dependencies = [ + "tinystr", + "zerotrie", + "zerovec", + "zoneinfo64", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-id-start" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81b79ad29b5e19de4260020f8919b443b2ef0277d242ce532ec7b7a2cc8b6007" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "v8" +version = "150.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42a978ff11f15b24e5c05a7123cf2b68f41e763546699781a924ef4e2cf43a49" +dependencies = [ + "bindgen", + "bitflags", + "fslock", + "gzip-header", + "home", + "miniz_oxide", + "paste", + "temporal_capi", + "which", +] + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm_dep_analyzer" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a10e6b67c951a84de7029487e0e0a496860dae49f6699edd279d5ff35b8fbf54" +dependencies = [ + "deno_error", + "thiserror", +] + +[[package]] +name = "which" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" +dependencies = [ + "either", + "home", + "rustix 0.38.44", + "winsafe", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zoneinfo64" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed6eb2607e906160c457fd573e9297e65029669906b9ac8fb1b5cd5e055f0705" +dependencies = [ + "calendrical_calculations", + "icu_locale_core", + "potential_utf", + "resb", + "serde", +] diff --git a/crates/node-core/Cargo.toml b/crates/node-core/Cargo.toml new file mode 100644 index 0000000000..edac179305 --- /dev/null +++ b/crates/node-core/Cargo.toml @@ -0,0 +1,50 @@ +[workspace] + +[package] +name = "iii-node-core" +version = "0.1.0" +edition = "2021" +description = "Evaluate untrusted JavaScript in per-namespace V8 isolates — the runtime, ops, guest prelude and manager, with no bus dependency" +license = "Apache-2.0" +repository = "https://github.com/iii-hq/workers" +# Deliberately unpublished: workers in this repo link it by path, the same way +# they link crates/console-ui. +publish = false + +# NO iii-sdk, and no feature to add one back. +# +# The bus seam is `trait Engine` (engine.rs) — five methods over `BoxFuture` +# and `serde_json::Value`, nothing else. The production implementation lives +# in the worker that owns a connection; this crate never sees one. +# +# A `default-features = false` feature gate (the llm-router → provider-* +# pattern) was considered and rejected: it would preserve the OPTION of +# pulling `iii-sdk = "=0.21.6"` in here, which is exactly the exact-pin +# collision crates/console-ui/Cargo.toml documents — workers on this repo's +# SDK line carry their own pins (0.21.6 for most, 0.21.8 for harness/eval) +# and a crate in the middle must never be what forces one of them. A crate +# with no SDK dependency has no pin to collide. +[dependencies] +deno_core = "=0.409.0" +deno_error = "0.7" +tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros", "sync", "time"] } +futures = "0.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +# `LogLine` reaches the wire through the hosting worker's response type, so +# its `JsonSchema` derive has to live with the struct. Must stay on the same +# schemars major as iii-sdk so the derived schema matches what +# `RegisterFunction` emits at registration time. +schemars = "0.8" +uuid = { version = "1", features = ["v4"] } +once_cell = "1" +tracing = "0.1" +# Per-runtime scratch directories: `Builder::tempdir_in` gives an +# independently random suffix (never derived from `runtime_id`, which is a +# capability), O_EXCL creation, and 0700 on unix, in one call. +tempfile = "3" + +[target.'cfg(unix)'.dependencies] +# `O_NOFOLLOW` for the scratch opens. The flag's value is platform-specific, +# so it cannot be hardcoded into `custom_flags`. +libc = "0.2" diff --git a/crates/node-core/src/allocator.rs b/crates/node-core/src/allocator.rs new file mode 100644 index 0000000000..dd29a5411f --- /dev/null +++ b/crates/node-core/src/allocator.rs @@ -0,0 +1,271 @@ +//! A cap on the memory V8 allocates OUTSIDE its object heap. +//! +//! `heap_limits` bounds the object heap and nothing else. `ArrayBuffer` — and +//! everything built on it, so every `TypedArray` — is backed by V8's +//! `ArrayBuffer::Allocator`, which is not part of that budget. A runtime +//! configured `heap_mb: 128` could hold hundreds of megabytes resident and +//! still OOM correctly on the object heap, because the two are accounted +//! separately. On a worker running untrusted code for many tenants at once, +//! that is a way for one tenant to exhaust the host. +//! +//! This is the same hazard class the log buffer and `op_iii_call` payloads +//! already guard against: Rust-side memory reachable through a sanctioned +//! path, invisible to `heap_limits`. +//! +//! # Panic safety +//! +//! Every function here is called by V8 through `extern "C"`. Unwinding across +//! that boundary aborts the process — killing every other tenant's runtime, +//! the exact failure this worker's id registry exists to prevent. So nothing +//! below can panic: no `unwrap`, no indexing, no formatting, no arithmetic +//! that can overflow. Allocation failure returns null, and V8 treats that as +//! unrecoverable: the asking runtime dies with `node-engine::oom`, which is +//! the same way exceeding `heap_mb` ends. + +use std::alloc::{alloc, alloc_zeroed, dealloc, Layout}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use deno_core::v8; + +/// Every block is allocated AND freed with this alignment, so `free` can +/// rebuild the exact `Layout` `alloc` used from the length V8 hands back. +/// V8 expects malloc-grade alignment; 16 satisfies it on every target here. +const ALIGN: usize = 16; + +/// What a zero-length allocation returns. `Layout` permits a zero size but +/// `alloc` does not, and V8 accepts any aligned non-null pointer for an empty +/// buffer. Never freed, never counted — see `free`. +const EMPTY: *mut c_void = ALIGN as *mut c_void; + +/// Live off-heap bytes for one isolate, and the ceiling they may reach. +pub struct ExternalMemoryCap { + used: AtomicUsize, + cap: usize, +} + +impl ExternalMemoryCap { + /// Bytes currently held in off-heap buffers. Test/observability only. + pub fn used(&self) -> usize { + self.used.load(Ordering::Acquire) + } + + /// Take `len` from the budget, or refuse. `checked_add` because a + /// caller-driven size is untrusted input like any other. + fn reserve(&self, len: usize) -> bool { + let mut current = self.used.load(Ordering::Relaxed); + loop { + let Some(next) = current.checked_add(len) else { + return false; + }; + if next > self.cap { + return false; + } + match self.used.compare_exchange_weak( + current, + next, + Ordering::AcqRel, + Ordering::Relaxed, + ) { + Ok(_) => return true, + Err(actual) => current = actual, + } + } + } + + /// Return `len` to the budget, saturating at zero. A plain `fetch_sub` + /// would wrap to a huge value if V8 ever freed a length we did not count, + /// and a wrapped counter refuses every later allocation for the life of + /// the isolate. + fn release(&self, len: usize) { + let mut current = self.used.load(Ordering::Relaxed); + loop { + let next = current.saturating_sub(len); + match self.used.compare_exchange_weak( + current, + next, + Ordering::AcqRel, + Ordering::Relaxed, + ) { + Ok(_) => return, + Err(actual) => current = actual, + } + } + } +} + +fn layout_for(len: usize) -> Option { + Layout::from_size_align(len, ALIGN).ok() +} + +fn allocate_inner(cap: &ExternalMemoryCap, len: usize, zeroed: bool) -> *mut c_void { + if len == 0 { + return EMPTY; + } + if !cap.reserve(len) { + return std::ptr::null_mut(); + } + let Some(layout) = layout_for(len) else { + cap.release(len); + return std::ptr::null_mut(); + }; + // SAFETY: `layout` has a non-zero size, checked above. + let ptr = unsafe { + if zeroed { + alloc_zeroed(layout) + } else { + alloc(layout) + } + }; + if ptr.is_null() { + // The OS refused; give the budget back rather than leaking it. + cap.release(len); + } + ptr.cast() +} + +/// # Safety +/// Called only by V8, with a `handle` that outlives every allocation. +unsafe extern "C" fn allocate(handle: &ExternalMemoryCap, len: usize) -> *mut c_void { + allocate_inner(handle, len, true) +} + +/// # Safety +/// Called only by V8, with a `handle` that outlives every allocation. +unsafe extern "C" fn allocate_uninitialized(handle: &ExternalMemoryCap, len: usize) -> *mut c_void { + allocate_inner(handle, len, false) +} + +/// # Safety +/// `data` must be a pointer this allocator returned for exactly `len` bytes. +unsafe extern "C" fn free(handle: &ExternalMemoryCap, data: *mut c_void, len: usize) { + if len == 0 || data.is_null() { + // The `EMPTY` sentinel was never allocated and never counted. + return; + } + let Some(layout) = layout_for(len) else { + return; + }; + // SAFETY: same layout `allocate_inner` used — ALIGN is fixed and `len` is + // the length V8 recorded for this block. + unsafe { dealloc(data.cast(), layout) }; + handle.release(len); +} + +/// # Safety +/// Called once by V8 when the allocator is destroyed, with the pointer handed +/// to `new_rust_allocator`. +unsafe extern "C" fn drop_handle(handle: *const ExternalMemoryCap) { + // Reclaim the reference `into_raw` leaked; the isolate's copy is going + // away, and the manager may still hold its own. + unsafe { drop(Arc::from_raw(handle)) }; +} + +static VTABLE: v8::RustAllocatorVtable = v8::RustAllocatorVtable { + allocate, + allocate_uninitialized, + free, + drop: drop_handle, +}; + +/// An allocator that refuses past `cap_bytes`, plus a handle for reading the +/// live total. +/// +/// V8 treats a null from this allocator as unrecoverable rather than throwing +/// a catchable `RangeError`, so a tenant that blows the cap loses its runtime +/// with `node-engine::oom` — the same outcome as exceeding `heap_mb`. That is +/// the intended trade: the runtime that asked for too much dies, the worker +/// and every other tenant carry on. +pub fn capped(cap_bytes: usize) -> (Arc, v8::UniqueRef) { + let state = Arc::new(ExternalMemoryCap { + used: AtomicUsize::new(0), + cap: cap_bytes, + }); + let raw = Arc::into_raw(state.clone()); + // SAFETY: `raw` is a live `Arc` pointer that `drop_handle` reclaims + // exactly once, and `VTABLE` is built for this handle type. + let allocator = unsafe { v8::new_rust_allocator(raw, &VTABLE) }; + (state, allocator) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cap(bytes: usize) -> ExternalMemoryCap { + ExternalMemoryCap { + used: AtomicUsize::new(0), + cap: bytes, + } + } + + #[test] + fn reserves_up_to_the_cap_and_refuses_past_it() { + let c = cap(1000); + assert!(c.reserve(600)); + assert!(c.reserve(400)); + assert_eq!(c.used(), 1000); + assert!(!c.reserve(1), "cap must be a ceiling"); + c.release(400); + assert!(c.reserve(400), "freed bytes return to the budget"); + } + + /// A wrapped counter would refuse every later allocation for the life of + /// the isolate, which is a worse failure than the miscount it came from. + #[test] + fn releasing_more_than_was_reserved_saturates_at_zero() { + let c = cap(1000); + c.reserve(100); + c.release(100_000); + assert_eq!(c.used(), 0); + assert!(c.reserve(1000), "still usable after an over-release"); + } + + #[test] + fn an_overflowing_request_is_refused_not_wrapped() { + let c = cap(usize::MAX); + assert!(c.reserve(16)); + assert!(!c.reserve(usize::MAX), "checked_add must refuse"); + assert_eq!(c.used(), 16); + } + + #[test] + fn zero_length_allocations_are_free_and_uncounted() { + let c = cap(64); + let p = allocate_inner(&c, 0, true); + assert!( + !p.is_null(), + "V8 needs a non-null pointer for an empty buffer" + ); + assert_eq!(c.used(), 0); + // SAFETY: the zero-length path never allocated, and `free` returns + // early on len 0 without touching the pointer. + unsafe { free(&c, p, 0) }; + assert_eq!(c.used(), 0); + } + + #[test] + fn a_real_allocation_round_trips_through_the_budget() { + let c = cap(4096); + let p = allocate_inner(&c, 1024, true); + assert!(!p.is_null()); + assert_eq!(c.used(), 1024); + // Zeroed as promised: `allocate` (not `allocate_uninitialized`) must + // hand V8 cleared memory. + // SAFETY: 1024 readable bytes were just allocated. + let first = unsafe { *(p as *const u8) }; + assert_eq!(first, 0); + // SAFETY: allocated here with exactly this length. + unsafe { free(&c, p, 1024) }; + assert_eq!(c.used(), 0); + } + + #[test] + fn an_allocation_over_the_cap_returns_null_and_costs_nothing() { + let c = cap(1024); + let p = allocate_inner(&c, 4096, true); + assert!(p.is_null(), "over-cap must refuse, not allocate"); + assert_eq!(c.used(), 0, "a refused request must not consume budget"); + } +} diff --git a/crates/node-core/src/config.rs b/crates/node-core/src/config.rs new file mode 100644 index 0000000000..f5bb31ba57 --- /dev/null +++ b/crates/node-core/src/config.rs @@ -0,0 +1,147 @@ +use std::time::Duration; + +use serde::Deserialize; + +/// Operator-facing runtime limits. Every field has a `serde(default)` so an +/// empty or partial config still yields a fully-populated struct. +/// +/// Deserialization lives here; READING a file does not. `load_config` stays +/// with the worker that owns a `config.yaml`, which is what keeps `serde_yaml` +/// and `anyhow` out of this crate. +#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct NodeEngineConfig { + #[serde(default = "default_max_runtimes")] + pub max_runtimes: usize, + #[serde(default = "default_default_timeout_ms")] + pub default_timeout_ms: u64, + #[serde(default = "default_max_timeout_ms")] + pub max_timeout_ms: u64, + #[serde(default = "default_heap_mb")] + pub heap_mb: usize, + /// Ceiling on memory allocated OUTSIDE the V8 object heap — every + /// `ArrayBuffer`, and so every `TypedArray`. `heap_mb` does not cover it: + /// the two are accounted separately, so without this a runtime could hold + /// hundreds of megabytes resident and still OOM correctly on its object + /// heap. Exceeding it kills that runtime with `node-engine::oom`, the same + /// way exceeding `heap_mb` does; the worker and other runtimes carry on. + #[serde(default = "default_external_mb")] + pub external_mb: usize, + #[serde(default = "default_idle_ttl_secs")] + pub idle_ttl_secs: u64, + /// Per-runtime private scratch directory (`iii.files`), total bytes. + /// + /// 0 disables the feature entirely: no directory is created and + /// `iii.files` is absent from the guest surface. That kill switch exists + /// because this is the FIRST filesystem this sandbox has ever had — an + /// operator upgrading would otherwise get one they never asked for, on + /// every existing tenant's isolate, from a version bump. + /// + /// Worst-case host footprint is `max_runtimes * scratch_mb` — 256 MiB at + /// the defaults. That matters because the system temp directory is tmpfs + /// (host RAM) on most Linux hosts; see `scratch_root` to move it. + /// + /// Deliberately NOT cross-validated against `external_mb`: a read of a + /// max-size file allocates that many bytes in V8, so a `scratch_mb` above + /// `external_mb` makes such a read OOM the runtime. Left unvalidated to + /// match this crate's existing treatment of the + /// `idle_ttl_secs`/`default_timeout_ms` relationship. + #[serde(default = "default_scratch_mb")] + pub scratch_mb: usize, + /// Maximum number of files in that directory. Also the bound on the + /// per-write scan, which is what keeps the derived quota cheap. + #[serde(default = "default_scratch_files")] + pub scratch_files: usize, + /// Where scratch directories are created. `None` uses the system temp + /// directory, which is tmpfs (host RAM) on most Linux hosts — point this + /// at real disk on a memory-tight host. Deliberately not `TMPDIR`, which + /// is process-global and shared with everything else the worker does. + #[serde(default)] + pub scratch_root: Option, +} + +pub fn default_max_runtimes() -> usize { + 32 +} +pub fn default_default_timeout_ms() -> u64 { + 5_000 +} +pub fn default_max_timeout_ms() -> u64 { + 30_000 +} +pub fn default_heap_mb() -> usize { + 128 +} +pub fn default_external_mb() -> usize { + 64 +} +pub fn default_idle_ttl_secs() -> u64 { + 900 +} +pub fn default_scratch_mb() -> usize { + 8 +} +pub fn default_scratch_files() -> usize { + 64 +} + +impl Default for NodeEngineConfig { + fn default() -> Self { + Self { + max_runtimes: default_max_runtimes(), + default_timeout_ms: default_default_timeout_ms(), + max_timeout_ms: default_max_timeout_ms(), + heap_mb: default_heap_mb(), + external_mb: default_external_mb(), + idle_ttl_secs: default_idle_ttl_secs(), + scratch_mb: default_scratch_mb(), + scratch_files: default_scratch_files(), + scratch_root: None, + } + } +} + +impl NodeEngineConfig { + /// Resolve a request's `timeout_ms`: absent falls back to the configured + /// default, present is clamped to `max_timeout_ms`. Zero is treated as + /// absent rather than as "expire immediately", which would make every + /// call fail in a way that reads like a bug. + pub fn clamp_timeout(&self, requested: Option) -> Duration { + let ms = match requested { + None | Some(0) => self.default_timeout_ms, + Some(v) => v.min(self.max_timeout_ms), + }; + Duration::from_millis(ms) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Was `defaults_from_empty_yaml`. Driven through JSON here because + /// `serde_yaml` is the worker's dependency, not this crate's — serde's + /// field defaults are format-independent, so this asserts the same + /// property. The YAML-shaped tests live beside `load_config`. + #[test] + fn defaults_from_empty_input() { + let cfg: NodeEngineConfig = serde_json::from_str("{}").unwrap(); + assert_eq!(cfg, NodeEngineConfig::default()); + } + + #[test] + fn clamp_timeout_uses_default_when_absent_or_zero() { + let cfg = NodeEngineConfig::default(); + assert_eq!(cfg.clamp_timeout(None), Duration::from_millis(5_000)); + assert_eq!(cfg.clamp_timeout(Some(0)), Duration::from_millis(5_000)); + } + + #[test] + fn clamp_timeout_caps_at_max() { + let cfg = NodeEngineConfig::default(); + assert_eq!(cfg.clamp_timeout(Some(1_000)), Duration::from_millis(1_000)); + assert_eq!( + cfg.clamp_timeout(Some(999_999)), + Duration::from_millis(30_000) + ); + } +} diff --git a/crates/node-core/src/engine.rs b/crates/node-core/src/engine.rs new file mode 100644 index 0000000000..c0372ff0b1 --- /dev/null +++ b/crates/node-core/src/engine.rs @@ -0,0 +1,621 @@ +//! The seam between this engine and whatever hosts it. +//! +//! Everything that talks to the iii bus goes through [`Engine`], so ops, +//! runtimes and handlers are all testable without a live engine — and this +//! crate carries no SDK dependency at all. The production implementation +//! lives in the hosting worker, which is the only thing that owns a +//! connection; tests here use [`FakeEngine`]. + +use std::sync::Arc; + +use futures::future::BoxFuture; +use serde_json::Value; + +pub type CallResult = Result; + +/// A JS handler exposed to the bus. Dynamic registrations are `Value`-in / +/// `Value`-out by nature: the schema lives in the evaluated JavaScript, not in +/// Rust types. +pub type ProxyHandler = Arc BoxFuture<'static, CallResult> + Send + Sync>; + +pub type UnregisterFn = Box; + +pub trait Engine: Send + Sync + 'static { + /// Invoke any engine function. Unrestricted by design — the deployment's + /// `iii-permissions.yaml` is the gate (see the spec's accepted risks). + /// + /// `action` routes the call the way the iii-sdk's own `trigger()` does + /// (omit for plain request/response). It crosses as a string because the + /// isolate boundary has exactly one representation to reason about — see + /// `op_iii_call`, whose `iii.trigger` caller is what sends a non-`None` + /// value. + fn call( + &self, + fn_id: String, + payload: Value, + timeout_ms: u64, + action: Option, + ) -> BoxFuture<'static, CallResult>; + + /// Publish a dynamically-created function. The returned closure removes it. + /// + /// `description` is what `engine::functions::info` shows a caller. `None` + /// falls back to a generic line naming node-engine (see + /// [`DEFAULT_DYNAMIC_DESC`]) — a registration with no description at all + /// is indistinguishable from a missing function in the catalog, which is + /// worse than a generic line. + /// + /// `request_format`/`response_format` are caller-supplied JSON Schemas + /// for the catalog: when present they replace the auto-extracted "any" + /// schema a dynamic `Value → Value` registration otherwise carries, so + /// `engine::functions::info` can show the real shapes. Validated before + /// they get here (`wire::register::validate_format`). + fn register( + &self, + fn_id: String, + description: Option, + request_format: Option, + response_format: Option, + handler: ProxyHandler, + ) -> UnregisterFn; + + /// Register a trigger on the caller's behalf. Returns the trigger id, + /// which is what `unregister_trigger` needs. + fn register_trigger(&self, input: Value) -> BoxFuture<'static, Result>; + + /// Remove a trigger by the id `register_trigger` returned. + fn unregister_trigger(&self, trigger_id: String) -> BoxFuture<'static, Result<(), String>>; + + /// Publish a trigger TYPE. The engine calls `handler` when a trigger of + /// this type is registered or unregistered; the payload carries a + /// `method` field naming which. The returned closure removes the type. + fn register_trigger_type( + &self, + type_id: String, + description: Option, + handler: ProxyHandler, + ) -> UnregisterFn; +} + +/// Stands in when a caller registers without a description, on node-engine's +/// own connection. +pub const DEFAULT_DYNAMIC_DESC: &str = + "Registered at runtime by node-engine; implemented in JavaScript."; + +/// A trigger registration as the GUEST writes it, which is the **node** sdk's +/// shape — its `type` field is what `iii.registerTrigger` documents and what +/// `prelude.js` validates. +/// +/// The Rust sdk spells that same field `trigger_type` +/// (`iii_sdk::protocol::RegisterTriggerInput`) and carries no serde alias, so +/// the two ends of this worker's own boundary disagree on one key. Do NOT +/// "simplify" this back into `serde_json::from_value::` +/// on the guest's object: that deserialized the node-shaped input against the +/// Rust struct and made `iii.registerTrigger` fail for EVERY documented call +/// with ``missing field `trigger_type` `` — a defect no unit test could see, +/// because `FakeEngine` took a bare `Value` and never deserialized at all. +/// +/// This type is also why a malformed registration is reported in the guest's +/// own vocabulary: a missing `type` says `type`, not `trigger_type`. +/// Deliberately does NOT accept `trigger_type` — the guest contract is +/// node-shaped, and one field must have one spelling. +#[derive(serde::Deserialize)] +pub struct GuestTriggerInput { + pub r#type: String, + pub function_id: String, + pub config: Value, + #[serde(default)] + pub metadata: Option, +} + +/// Parse and validate a guest trigger registration, in the guest's own +/// vocabulary. The hosting worker renames the one field onto the Rust sdk's +/// struct; `FakeEngine` calls this directly, so the two refuse identically. +pub fn parse_guest_trigger(input: Value) -> Result { + serde_json::from_value(input).map_err(|e| format!("invalid trigger registration: {e}")) +} + +/// A trigger-type callback as the engine describes it, in this crate's own +/// vocabulary rather than the SDK's `TriggerConfig`. +/// +/// It exists because [`trigger_callback_payload`] must stay ONE function (see +/// its doc) while living in a crate that cannot name an SDK type. The hosting +/// worker converts its `TriggerConfig` into this on the way in; the field +/// names are deliberately identical so the mapping is obviously total. +pub struct TriggerCallback { + pub id: String, + pub function_id: String, + pub config: Value, + pub metadata: Option, +} + +/// The wire shape a trigger-type callback's payload takes crossing from the +/// engine into a runtime's proxy handler (`op_iii_register_trigger_type`, +/// `ops.rs`) — the full callback, plus which of the two `TriggerHandler` +/// methods fired. ONE function builds it, used by both the hosting worker's +/// live `TriggerHandler` adapter and [`FakeEngine::fire_trigger_type_config`] +/// (its test double), so the two cannot drift into different shapes the way +/// `{method, config}` vs. `{method, id, function_id, config, metadata}` +/// already did once — a node-engine review caught a guest trigger-type +/// handler silently losing `id`/`function_id` because the fake it was tested +/// against never sent them. +/// +/// Keeping this one function shared is why `TriggerCallback` exists rather +/// than the worker simply building the JSON itself. +pub fn trigger_callback_payload(config: TriggerCallback, method: &str) -> Value { + serde_json::json!({ + "method": method, + "id": config.id, + "function_id": config.function_id, + "config": config.config, + "metadata": config.metadata, + }) +} + +/// What each id was published with: `(id, description, handler)`. +#[cfg(test)] +type RegisteredHandlers = Arc, ProxyHandler)>>>; +#[cfg(test)] +type RegisteredFormats = + Arc, Option)>>>; + +#[cfg(test)] +#[derive(Default)] +pub struct FakeEngine { + responses: std::sync::Mutex>, + /// Per-id queue of responses, indexed by how many times that id has + /// already been called (pinned at the last entry once exhausted, rather + /// than falling off the end) — models an answer that changes across + /// repeated polls, e.g. a readiness check that comes back `not_found` + /// once and resolved after. + sequenced_responses: + std::sync::Mutex, usize)>>, + calls: std::sync::Mutex>, + /// `timeout_ms` for every call, in the same order as `calls` — a + /// separate list rather than widening `calls`'s tuple, so the many + /// existing `assert_eq!(fake.calls(), vec![(...)])` call sites across the + /// test suite don't all need a third field they don't care about. + timeouts: std::sync::Mutex>, + /// `Arc` so the `'static` unregister closure can remove its own entry — + /// a fake whose unregister only counted would let a later task assert + /// "torn-down functions are uncallable" and pass without teardown ever + /// removing anything. + handlers: RegisteredHandlers, + /// `(request_format, response_format)` per registered id — a separate + /// map rather than widening the `handlers` tuple, for the same reason + /// `timeouts` is separate from `calls`. + formats: RegisteredFormats, + unregisters: Arc, + hang: std::sync::atomic::AtomicBool, + route_back: std::sync::atomic::AtomicBool, + delay: std::sync::Mutex>, + /// `(id, input)` for every trigger currently registered. + triggers: std::sync::Mutex>, + /// Trigger-type handlers, keyed by type id. `Arc` for the same reason as + /// `handlers`: `register_trigger_type`'s returned `'static` closure must + /// be able to remove its own entry after this method returns. + trigger_types: Arc>>, +} + +#[cfg(test)] +impl FakeEngine { + pub fn new() -> Arc { + Arc::new(Self::default()) + } + + /// The `(request_format, response_format)` pair `register` received for + /// `fn_id` — `None` when the id is not currently registered, so an + /// unregistered id and a never-registered one read the same. + pub fn formats_of(&self, fn_id: &str) -> Option<(Option, Option)> { + self.formats.lock().unwrap().get(fn_id).cloned() + } + + pub fn with_response(&self, fn_id: &str, result: CallResult) { + self.responses + .lock() + .unwrap() + .insert(fn_id.to_string(), result); + } + + /// Queue `results` for `fn_id`, one per call to it, so a test can model a + /// value that changes across repeated polls of the SAME id (a readiness + /// wait that sees `not_found` once, then resolved). Once every entry has + /// been served once, later calls keep getting the LAST entry rather than + /// falling through to `with_response`'s single value or the default + /// "no such function" error — a queue that quietly stopped answering + /// would make a caller that polls past it look like it timed out. + pub fn with_response_sequence(&self, fn_id: &str, results: Vec) { + assert!(!results.is_empty(), "an empty sequence answers nothing"); + self.sequenced_responses + .lock() + .unwrap() + .insert(fn_id.to_string(), (results, 0)); + } + + pub fn calls(&self) -> Vec<(String, Value)> { + self.calls.lock().unwrap().clone() + } + + /// `timeout_ms` as received by `Engine::call`, one per entry in + /// `calls()`, same order. What `op_iii_call`'s `iii.trigger` timeout + /// clamp is verified against — the fake doesn't enforce or interpret the + /// value, only records it. + pub fn call_timeouts(&self) -> Vec { + self.timeouts.lock().unwrap().clone() + } + + pub fn registered_ids(&self) -> Vec { + self.handlers + .lock() + .unwrap() + .iter() + .map(|(id, _, _)| id.clone()) + .collect() + } + + /// What each id was published with — the fake's only view of the + /// description reaching the bus, so a test can prove it is not dropped. + pub fn registered_descriptions(&self) -> Vec<(String, Option)> { + self.handlers + .lock() + .unwrap() + .iter() + .map(|(id, desc, _)| (id.clone(), desc.clone())) + .collect() + } + + pub fn unregister_count(&self) -> usize { + self.unregisters.load(std::sync::atomic::Ordering::SeqCst) + } + + /// Make `call` return a future that never resolves. A real engine call is + /// pending for a while; the default fake resolves instantly, which would + /// make in-flight accounting untestable because the counter would return + /// to zero before the next call started. + pub fn hang_calls(&self) { + self.hang.store(true, std::sync::atomic::Ordering::SeqCst); + } + + /// Make `call` resolve only after `delay`, so its settlement lands in a + /// LATER event-loop pump than the eval that started it. + /// + /// This distinction is load-bearing for the detached-work test. The + /// default fake resolves synchronously, so deno_core dispatches the op, + /// resolves it, and runs its `.then`/`.catch` all inside ONE + /// `poll_event_loop` call — while the initiating eval is still pending and + /// its own deadline still covers everything. A real engine call crosses a + /// socket and cannot do that; this models the real timing. + pub fn delay_calls(&self, delay: std::time::Duration) { + *self.delay.lock().unwrap() = Some(delay); + } + + /// Make `call(fn_id, …)` dispatch to the handler registered under the same + /// id, so an in-isolate call re-enters the isolate the way the engine does. + pub fn route_calls_to_registrations(&self) { + self.route_back + .store(true, std::sync::atomic::Ordering::SeqCst); + } + + /// Drive a registered proxy the way the engine would. + pub async fn invoke(&self, fn_id: &str, payload: Value) -> CallResult { + let handler = self + .handlers + .lock() + .unwrap() + .iter() + .find(|(id, _, _)| id == fn_id) + .map(|(_, _, h)| h.clone()); + match handler { + Some(h) => h(payload).await, + None => Err(format!("no such registered function: {fn_id}")), + } + } + + /// The `input` each currently-registered trigger was registered with. + pub fn registered_triggers(&self) -> Vec { + self.triggers + .lock() + .unwrap() + .iter() + .map(|(_, input)| input.clone()) + .collect() + } + + pub fn registered_trigger_types(&self) -> Vec { + self.trigger_types.lock().unwrap().keys().cloned().collect() + } + + /// Drive a registered trigger type's callback the way the engine would. + /// `method` is `"registerTrigger"` or `"unregisterTrigger"`. + /// + /// Sends `{method, config}` — narrower than the live engine's + /// `TriggerHandlerAdapter`, which also sends `id`/`function_id`/ + /// `metadata` (see `fire_trigger_type_config` for that full shape). + /// Kept at this 3-argument signature — pinned since Task 9 — for + /// `engine.rs`'s own `Engine` trait tests below, which only assert on + /// `method`/`config` reaching a `ProxyHandler` and have no reason to + /// carry the extra fields. + pub async fn fire_trigger_type( + &self, + type_id: &str, + method: &str, + config: Value, + ) -> Result { + let handler = self.trigger_types.lock().unwrap().get(type_id).cloned(); + match handler { + Some(h) => h(serde_json::json!({ "method": method, "config": config })).await, + None => Err(format!("no such trigger type: {type_id}")), + } + } + + /// Drive a registered trigger type's callback with the FULL wire shape + /// the live engine sends — `trigger_callback_payload`, the same builder + /// `TriggerHandlerAdapter` uses — rather than `fire_trigger_type`'s + /// abbreviated `{method, config}`. Use this for anything that exercises + /// `op_iii_register_trigger_type`'s proxy handler: a real + /// `TriggerHandler` implementation needs `id` (which trigger instance) + /// and `function_id` (which function to invoke), neither recoverable + /// from `config` alone, and `fire_trigger_type`'s narrower shape cannot + /// prove either one crosses into the guest. + pub async fn fire_trigger_type_config( + &self, + type_id: &str, + method: &str, + config: TriggerCallback, + ) -> Result { + let handler = self.trigger_types.lock().unwrap().get(type_id).cloned(); + match handler { + Some(h) => h(trigger_callback_payload(config, method)).await, + None => Err(format!("no such trigger type: {type_id}")), + } + } +} + +#[cfg(test)] +impl Engine for FakeEngine { + fn call( + &self, + fn_id: String, + payload: Value, + timeout_ms: u64, + _action: Option, + ) -> BoxFuture<'static, CallResult> { + self.calls + .lock() + .unwrap() + .push((fn_id.clone(), payload.clone())); + self.timeouts.lock().unwrap().push(timeout_ms); + + if self.hang.load(std::sync::atomic::Ordering::SeqCst) { + return Box::pin(std::future::pending()); + } + + if self.route_back.load(std::sync::atomic::Ordering::SeqCst) { + let handler = self + .handlers + .lock() + .unwrap() + .iter() + .find(|(id, _, _)| *id == fn_id) + .map(|(_, _, h)| h.clone()); + if let Some(h) = handler { + return Box::pin(async move { h(payload).await }); + } + } + + { + let mut sequenced = self.sequenced_responses.lock().unwrap(); + if let Some((seq, next)) = sequenced.get_mut(&fn_id) { + let i = (*next).min(seq.len() - 1); + *next += 1; + let out = seq[i].clone(); + drop(sequenced); + let delay = *self.delay.lock().unwrap(); + return Box::pin(async move { + if let Some(d) = delay { + tokio::time::sleep(d).await; + } + out + }); + } + } + + let out = self + .responses + .lock() + .unwrap() + .get(&fn_id) + .cloned() + .unwrap_or_else(|| Err(format!("no such function: {fn_id}"))); + let delay = *self.delay.lock().unwrap(); + Box::pin(async move { + if let Some(d) = delay { + tokio::time::sleep(d).await; + } + out + }) + } + + fn register( + &self, + fn_id: String, + description: Option, + request_format: Option, + response_format: Option, + handler: ProxyHandler, + ) -> UnregisterFn { + self.formats + .lock() + .unwrap() + .insert(fn_id.clone(), (request_format, response_format)); + self.handlers + .lock() + .unwrap() + .push((fn_id.clone(), description, handler)); + let counter = self.unregisters.clone(); + let handlers = self.handlers.clone(); + let formats = self.formats.clone(); + Box::new(move || { + // Remove, not just count: the fake must be able to show that an + // unregistered id is genuinely gone. + formats.lock().unwrap().remove(&fn_id); + handlers.lock().unwrap().retain(|(id, _, _)| *id != fn_id); + counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + }) + } + + fn register_trigger(&self, input: Value) -> BoxFuture<'static, Result> { + // Deserialize through the SAME `guest_trigger_input` the live engine + // uses, and refuse what it refuses. Pushing the raw `Value` was the + // hole that hid the `type`/`trigger_type` mismatch: every test fed + // this the node-shaped object a guest really sends, the fake stored it + // untouched, and nothing ever discovered that `IIIEngine` could not + // parse it. A fake that accepts what production rejects is not a + // stand-in, it is a second implementation. + // + // It still STORES the guest's own object — `registered_triggers()` is + // asserted against the shape callers wrote, which is the readable + // thing to compare — so only the refusal is borrowed from production. + if let Err(e) = parse_guest_trigger(input.clone()) { + return Box::pin(async move { Err(e) }); + } + let id = uuid::Uuid::new_v4().to_string(); + self.triggers.lock().unwrap().push((id.clone(), input)); + Box::pin(async move { Ok(id) }) + } + + fn unregister_trigger(&self, trigger_id: String) -> BoxFuture<'static, Result<(), String>> { + let existed = { + let mut triggers = self.triggers.lock().unwrap(); + let before = triggers.len(); + triggers.retain(|(id, _)| *id != trigger_id); + triggers.len() != before + }; + Box::pin(async move { + if existed { + Ok(()) + } else { + Err(format!("no such trigger: {trigger_id}")) + } + }) + } + + fn register_trigger_type( + &self, + type_id: String, + _description: Option, + handler: ProxyHandler, + ) -> UnregisterFn { + self.trigger_types + .lock() + .unwrap() + .insert(type_id.clone(), handler); + let types = self.trigger_types.clone(); + Box::new(move || { + types.lock().unwrap().remove(&type_id); + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[tokio::test] + async fn fake_records_calls_and_returns_canned_responses() { + let fake = FakeEngine::new(); + fake.with_response("state::get", Ok(json!({ "value": 7 }))); + let out = fake + .call("state::get".into(), json!({ "key": "k" }), 1_000, None) + .await; + assert_eq!(out, Ok(json!({ "value": 7 }))); + assert_eq!( + fake.calls(), + vec![("state::get".to_string(), json!({ "key": "k" }))] + ); + } + + #[tokio::test] + async fn fake_returns_error_for_unconfigured_ids() { + let fake = FakeEngine::new(); + let out = fake + .call("nope::missing".into(), json!({}), 1_000, None) + .await; + assert_eq!(out, Err("no such function: nope::missing".to_string())); + } + + #[tokio::test] + async fn fake_register_exposes_the_handler_and_counts_unregisters() { + let fake = FakeEngine::new(); + let handler: ProxyHandler = Arc::new(|p: serde_json::Value| { + Box::pin(async move { Ok(json!({ "echo": p })) }) as BoxFuture<'static, CallResult> + }); + let un = fake.register("ns::hello".into(), None, None, None, handler); + assert_eq!(fake.registered_ids(), vec!["ns::hello".to_string()]); + assert_eq!( + fake.invoke("ns::hello", json!({ "a": 1 })).await, + Ok(json!({ "echo": { "a": 1 } })) + ); + un(); + assert_eq!(fake.unregister_count(), 1); + // The fake must actually forget it, so a later task cannot assert + // "teardown makes functions uncallable" and pass spuriously. + assert!(fake.registered_ids().is_empty()); + assert!(fake.invoke("ns::hello", json!({ "a": 1 })).await.is_err()); + } + + #[tokio::test] + async fn the_fake_engine_records_trigger_registrations() { + let engine = FakeEngine::new(); + let id = engine + .register_trigger(json!({ + "type": "state", + "function_id": "app::react", + "config": { "key": "k" } + })) + .await + .unwrap(); + assert!(!id.is_empty(), "a registered trigger must get an id"); + assert_eq!(engine.registered_triggers().len(), 1); + + engine.unregister_trigger(id.clone()).await.unwrap(); + assert!(engine.registered_triggers().is_empty()); + } + + #[tokio::test] + async fn unregister_trigger_reports_an_unknown_id() { + let engine = FakeEngine::new(); + let err = engine + .unregister_trigger("no-such-trigger".to_string()) + .await + .unwrap_err(); + assert!(err.contains("no-such-trigger")); + } + + #[tokio::test] + async fn fake_trigger_type_records_registrations_and_fires_the_handler() { + let engine = FakeEngine::new(); + let handler: ProxyHandler = Arc::new(|p: Value| { + Box::pin(async move { Ok(json!({ "saw": p })) }) as BoxFuture<'static, CallResult> + }); + let un = engine.register_trigger_type("state".into(), None, handler); + assert_eq!(engine.registered_trigger_types(), vec!["state".to_string()]); + + let out = engine + .fire_trigger_type("state", "registerTrigger", json!({ "key": "k" })) + .await + .unwrap(); + assert_eq!( + out, + json!({ "saw": { "method": "registerTrigger", "config": { "key": "k" } } }) + ); + + un(); + assert!(engine.registered_trigger_types().is_empty()); + assert!(engine + .fire_trigger_type("state", "unregisterTrigger", json!({})) + .await + .is_err()); + } +} diff --git a/crates/node-core/src/error.rs b/crates/node-core/src/error.rs new file mode 100644 index 0000000000..bfb2926abe --- /dev/null +++ b/crates/node-core/src/error.rs @@ -0,0 +1,162 @@ +//! The error taxonomy. Every variant maps to a stable +//! `node-engine::` wire code; the hosting worker converts into +//! its SDK error so the engine surfaces `code: message` to callers. +//! +//! The `From for iii_sdk::errors::Error` impl that used to +//! live here is gone with this crate's SDK dependency — with both types +//! foreign to the worker, the orphan rule forbids it there. The worker +//! supplies a plain function instead, whose output is byte-identical +//! (`Error::Handler(e.to_string())`). + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NodeEngineError { + /// The evaluated code threw, or its promise rejected. + /// + /// Carries the logs captured BEFORE the throw. A host that reports a + /// failing script as a normal process-shaped response — non-zero exit + /// code, traceback on stderr — needs its stdout verbatim, and this used + /// to be discarded at both failure sites in `runtime.rs`. + EvalFailed { + message: String, + logs: Vec, + }, + /// An eval or handler invocation blew its deadline. The isolate is killed. + Timeout, + /// The isolate hit its V8 heap cap and was killed. + Oom, + RuntimeNotFound(String), + /// The runtime died (timeout/OOM/shutdown) while a call was in flight. + RuntimeGone(String), + /// `max_runtimes` live isolates already exist. + Capacity(usize), + NamespaceDenied { + id: String, + namespace: String, + }, + /// Another runtime — or this worker itself — already registered this id. + /// Deliberately carries only the id: the owning `runtime_id` is a + /// capability and must never be disclosed to a caller who does not hold it. + IdTaken(String), + InvalidRequest(String), +} + +impl NodeEngineError { + pub fn code(&self) -> &'static str { + match self { + Self::EvalFailed { .. } => "node-engine::eval_failed", + Self::Timeout => "node-engine::timeout", + Self::Oom => "node-engine::oom", + Self::RuntimeNotFound(_) => "node-engine::runtime_not_found", + Self::RuntimeGone(_) => "node-engine::runtime_gone", + Self::Capacity(_) => "node-engine::capacity", + Self::NamespaceDenied { .. } => "node-engine::namespace_denied", + Self::IdTaken(_) => "node-engine::id_taken", + Self::InvalidRequest(_) => "node-engine::invalid_request", + } + } + + /// The human half of the error, without the `node-engine::` prefix + /// `Display` adds. Hosting workers surface THIS to callers and guests — + /// they re-code errors under their own taxonomy, so the core's prefix + /// would only echo a retired worker name nobody can call. + pub fn message(&self) -> String { + match self { + Self::EvalFailed { message, .. } => message.clone(), + Self::Timeout => "execution exceeded its deadline; the runtime was terminated".into(), + Self::Oom => "heap limit exceeded; the runtime was terminated".into(), + Self::RuntimeNotFound(id) => format!("unknown runtime_id {id}"), + Self::RuntimeGone(id) => format!("runtime {id} is no longer alive"), + Self::Capacity(max) => format!("all {max} runtime slots are in use"), + // Shared by both `op_iii_register` and `op_iii_unregister` (see + // ops.rs), so the wording stays neutral between them rather than + // prescribing a register-only fix like "rename the id" — reusing + // one variant for both is what makes "not yours" and "not found" + // the same answer on the unregister path. + Self::NamespaceDenied { id, namespace } => format!( + "id {id:?} must start with this runtime's namespace {namespace:?} — a runtime \ + can only register or unregister ids inside its own namespace" + ), + // Shared by function AND trigger-type registration (both live in + // the same namespaced id space), so the wording names neither. + Self::IdTaken(id) => format!("id {id} is already registered"), + Self::InvalidRequest(m) => m.clone(), + } + } +} + +impl NodeEngineError { + /// An eval failure with no logs — the compile-error and envelope-decode + /// paths, where nothing tenant-authored ran. + pub fn eval_failed(message: impl Into) -> Self { + Self::EvalFailed { + message: message.into(), + logs: Vec::new(), + } + } + + /// Attach the logs an eval produced before it failed. A no-op on every + /// other variant, so a call site can apply it unconditionally. + pub fn with_logs(self, logs: Vec) -> Self { + match self { + Self::EvalFailed { message, .. } => Self::EvalFailed { message, logs }, + other => other, + } + } +} + +impl std::fmt::Display for NodeEngineError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.code(), self.message()) + } +} + +impl std::error::Error for NodeEngineError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_stable_wire_strings() { + assert_eq!( + NodeEngineError::eval_failed("x").code(), + "node-engine::eval_failed" + ); + assert_eq!(NodeEngineError::Timeout.code(), "node-engine::timeout"); + assert_eq!(NodeEngineError::Oom.code(), "node-engine::oom"); + assert_eq!( + NodeEngineError::RuntimeNotFound("r".into()).code(), + "node-engine::runtime_not_found" + ); + assert_eq!( + NodeEngineError::RuntimeGone("r".into()).code(), + "node-engine::runtime_gone" + ); + assert_eq!(NodeEngineError::Capacity(3).code(), "node-engine::capacity"); + assert_eq!( + NodeEngineError::NamespaceDenied { + id: "state::get".into(), + namespace: "ns::".into() + } + .code(), + "node-engine::namespace_denied" + ); + assert_eq!( + NodeEngineError::IdTaken("app::a".into()).code(), + "node-engine::id_taken" + ); + assert_eq!( + NodeEngineError::InvalidRequest("x".into()).code(), + "node-engine::invalid_request" + ); + } + + #[test] + fn display_is_code_colon_message() { + let e = NodeEngineError::RuntimeNotFound("rt-7".into()); + assert_eq!( + e.to_string(), + "node-engine::runtime_not_found: unknown runtime_id rt-7" + ); + } +} diff --git a/crates/node-core/src/ids.rs b/crates/node-core/src/ids.rs new file mode 100644 index 0000000000..e3cca6f6be --- /dev/null +++ b/crates/node-core/src/ids.rs @@ -0,0 +1,172 @@ +//! Which runtime owns each registered function id. +//! +//! `iii-sdk`'s `register_function_inner` panics when an id is already +//! registered on the same client (`iii.rs:944`). That call happens inside +//! `op_iii_register`, a `#[op2(fast)]` V8 callback with an `extern "C"` ABI — +//! and unwinding out of `extern "C"` aborts. A duplicate id therefore kills +//! the process and every tenant's runtime with it, so every path that reaches +//! `Engine::register` must claim here first. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +/// Owner recorded for ids the worker registers itself. `create` generates +/// runtime ids as `rt-`, so no runtime can equal this and +/// `release_owner` can never free a worker id. +pub const WORKER_OWNER: &str = ""; + +/// id -> owning runtime id, or [`WORKER_OWNER`]. +/// +/// Cheap to clone: every runtime holds the same map. +#[derive(Clone, Default)] +pub struct IdRegistry(Arc>>); + +impl IdRegistry { + /// Seed with the ids this worker registers itself. Omitting one is a + /// process abort waiting to happen — see the module comment. + pub fn with_worker_ids(ids: &[&str]) -> Self { + let map = ids + .iter() + .map(|id| ((*id).to_string(), WORKER_OWNER.to_string())) + .collect(); + IdRegistry(Arc::new(Mutex::new(map))) + } + + /// Claim one id. True when it was unclaimed or already owned by `owner`. + pub fn claim(&self, id: &str, owner: &str) -> bool { + let mut map = self.0.lock().unwrap(); + match map.get(id) { + Some(current) if current != owner => false, + _ => { + map.insert(id.to_string(), owner.to_string()); + true + } + } + } + + /// Claim every id or none. `Err` carries the first conflicting id. + /// + /// One lock for the check and the inserts, so two concurrent batches + /// cannot both observe an id as free. + pub fn claim_all(&self, ids: &[String], owner: &str) -> Result<(), String> { + let mut map = self.0.lock().unwrap(); + if let Some(taken) = ids + .iter() + .find(|id| map.get(*id).is_some_and(|held| held != owner)) + { + return Err(taken.clone()); + } + for id in ids { + map.insert(id.clone(), owner.to_string()); + } + Ok(()) + } + + /// Free `ids` still held by `owner`. Two callers, two different reasons + /// the id is safe to free: the failure arm of `RuntimeManager::register` + /// releases ids that provably never reached the bus, and + /// `OpsState::unregister` (ops.rs) releases an id that DID reach the bus + /// but was just explicitly unpublished by its own owner — the `owner` + /// check above is what makes either caller safe, not which one is + /// calling. + pub fn release_ids(&self, ids: &[String], owner: &str) { + let mut map = self.0.lock().unwrap(); + for id in ids { + if map.get(id).is_some_and(|held| held == owner) { + map.remove(id); + } + } + } + + /// Free everything owned by `owner`. Called from `RuntimeManager::destroy` + /// — teardown, reap, and the idle sweep — and nowhere else. + pub fn release_owner(&self, owner: &str) { + self.0.lock().unwrap().retain(|_, held| held != owner); + } +} + +// Never the map itself: the values are runtime ids, which are capabilities. +// `RuntimeOpts` derives `Debug`, so this type needs one. +impl std::fmt::Debug for IdRegistry { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "IdRegistry({} ids)", self.0.lock().unwrap().len()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn claims_an_unclaimed_id() { + let reg = IdRegistry::default(); + assert!(reg.claim("app::a", "rt-1")); + } + + #[test] + fn re_claiming_your_own_id_succeeds() { + let reg = IdRegistry::default(); + assert!(reg.claim("app::a", "rt-1")); + // Preserves today's "re-registering swaps only the JS handler". + assert!(reg.claim("app::a", "rt-1")); + } + + #[test] + fn another_owner_cannot_claim() { + let reg = IdRegistry::default(); + assert!(reg.claim("app::a", "rt-1")); + assert!(!reg.claim("app::a", "rt-2")); + } + + #[test] + fn worker_ids_are_seeded_and_unclaimable() { + let reg = IdRegistry::with_worker_ids(&["node-engine::eval"]); + assert!(!reg.claim("node-engine::eval", "rt-1")); + } + + #[test] + fn release_owner_frees_only_that_owners_ids() { + let reg = IdRegistry::with_worker_ids(&["node-engine::eval"]); + assert!(reg.claim("app::a", "rt-1")); + assert!(reg.claim("app::b", "rt-2")); + reg.release_owner("rt-1"); + assert!(reg.claim("app::a", "rt-2"), "rt-1's id should be free"); + assert!( + !reg.claim("app::b", "rt-1"), + "rt-2's id should still be held" + ); + assert!( + !reg.claim("node-engine::eval", "rt-1"), + "a worker id must never be released by a runtime release" + ); + } + + #[test] + fn claim_all_is_atomic() { + let reg = IdRegistry::default(); + assert!(reg.claim("app::b", "rt-other")); + let ids = vec!["app::a".to_string(), "app::b".to_string()]; + assert_eq!(reg.claim_all(&ids, "rt-1"), Err("app::b".to_string())); + // The conflict must have rolled back `app::a` too. + assert!(reg.claim("app::a", "rt-2"), "partial claim leaked"); + } + + #[test] + fn claim_all_tolerates_ids_you_already_own() { + let reg = IdRegistry::default(); + assert!(reg.claim("app::a", "rt-1")); + let ids = vec!["app::a".to_string(), "app::b".to_string()]; + assert_eq!(reg.claim_all(&ids, "rt-1"), Ok(())); + } + + /// The map's values are runtime ids, which are capabilities. `RuntimeOpts` + /// derives `Debug`, so this type needs one — and it must not print them. + #[test] + fn debug_does_not_leak_owners() { + let reg = IdRegistry::default(); + assert!(reg.claim("app::a", "rt-secret")); + let shown = format!("{reg:?}"); + assert!(!shown.contains("rt-secret"), "leaked an owner: {shown}"); + assert!(!shown.contains("app::a"), "leaked an id: {shown}"); + } +} diff --git a/crates/node-core/src/lib.rs b/crates/node-core/src/lib.rs new file mode 100644 index 0000000000..d38658a936 --- /dev/null +++ b/crates/node-core/src/lib.rs @@ -0,0 +1,20 @@ +//! iii-node-core: evaluate untrusted JavaScript in per-namespace V8 isolates. +//! +//! Everything here is bus-free. The only way this crate reaches an iii engine +//! is through [`engine::Engine`], a five-method trait over `serde_json::Value` +//! that the hosting worker implements against its own connection — so nothing +//! in this tree depends on `iii-sdk`, and nothing in it pins an SDK version. +//! +//! The wire types (`RunRequest`, `RunResponse`, …), the function registrations +//! and the console UI all live with that worker. + +pub mod allocator; +pub mod config; +pub mod engine; +pub mod error; +pub mod ids; +pub mod manager; +pub mod ops; +pub mod protocol; +pub mod runtime; +pub mod wire; diff --git a/crates/node-core/src/manager.rs b/crates/node-core/src/manager.rs new file mode 100644 index 0000000000..f32c7e2fce --- /dev/null +++ b/crates/node-core/src/manager.rs @@ -0,0 +1,2897 @@ +//! Ownership and lifecycle for the live isolates. +//! +//! Evals against one runtime are serialised by a per-runtime async mutex, so +//! the log buffer and the registration delta belong unambiguously to one +//! caller. Handler invocations still interleave — they come in through the +//! runtime's own command channel, not through here. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use tokio::sync::oneshot; + +use crate::config::NodeEngineConfig; +use crate::engine::Engine; +use crate::error::NodeEngineError; +use crate::ops::{MAX_DESCRIPTION_BYTES, MAX_FUNCTION_ID_BYTES}; +use crate::runtime::{Command, RuntimeOpts, RuntimeThread, Unregisters}; +use crate::wire::register::{RegisterRequest, RegisterResponse}; +use crate::wire::run::{RunRequest, RunResponse}; +use crate::wire::teardown::{TeardownRequest, TeardownResponse}; + +/// A worker name becomes a namespace prefix and a display name, so it is kept +/// to a shape that cannot change how an id parses and cannot render two +/// different names alike: lowercase ASCII, digits, and `.`/`_`/`-`. +const MAX_WORKER_NAME_BYTES: usize = 64; + +/// A namespace's first segment IS a worker name on the bus (see +/// `normalize_namespace`), so it is held to the same shape upstream +/// `iii-worker` requires of one (`iii-worker/src/core/types.rs`): a name +/// becomes a path segment under `~/.iii/logs/` in that program, so +/// being looser here would accept a namespace stem this crate happily runs +/// with, only for `iii worker add` to refuse the equivalent name minutes +/// later, in another program. +fn validate_worker_name(name: &str) -> Result<(), String> { + if name.is_empty() { + return Err("worker name must not be empty; it becomes the namespace, \ + so pass something like \"my-app\"" + .to_string()); + } + if name.len() > MAX_WORKER_NAME_BYTES { + return Err(format!( + "worker name is {} bytes; the limit is {MAX_WORKER_NAME_BYTES}", + name.len() + )); + } + if name.contains("::") { + return Err(format!( + "worker name {name:?} must not contain \"::\" — the name IS the \ + namespace, so pass \"my-app\", not \"my-app::\"" + )); + } + if name.contains("..") { + return Err(format!( + "worker name {name:?} must not contain \"..\" — it becomes a \ + directory name, so pass \"my-app\", not \"my..app\"" + )); + } + if name.starts_with('.') { + return Err(format!( + "worker name {name:?} must not start with \".\" — it becomes a \ + directory name, so pass \"my-app\", not \".my-app\"" + )); + } + if let Some(bad) = name + .chars() + .find(|c| !(c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))) + { + return Err(format!( + "worker name {name:?} contains {bad:?}; use lowercase letters, \ + digits, and \".\", \"_\" or \"-\"" + )); + } + Ok(()) +} + +/// Canonical form of a caller-supplied namespace: `foo::`. +/// +/// The guard in `op_iii_register` is a prefix test, so the prefix's shape +/// carries its whole security value: `""` would let a runtime register +/// `state::get`, and `"app"` would let it register `application::anything`. +/// The ONE near-miss that is repaired rather than rejected is the delimiter: +/// trailing colons are stripped and exactly two appended, so `app`, `app:`, +/// and `app::` all become `app::`. Every result is a strictly NARROWER prefix +/// than the string the caller passed, so normalizing can only reduce what a +/// runtime may register, never widen it. Writing the namespace without its +/// trailing `::` is the mistake everyone makes first, because the ids read that +/// way in prose. +/// +/// What survives that trim must be ONE worker name — literally +/// `validate_worker_name`, because a namespace's first segment IS a worker +/// name on the bus: the engine splits `service::sub::function` into service +/// `service` (`iii/engine/src/services.rs`), and a worker name may never +/// contain `:` (`iii-worker/src/core/types.rs`). So `a::b::` names an identity +/// the engine cannot represent, and is refused rather than published. +/// +/// Nothing expressive is lost, which is the non-obvious part: the guard is a +/// PREFIX test, so `myapp::v2::save` still registers under namespace `myapp::`. +/// Only the namespace itself is held to one segment. +/// +/// Deliberately STRICTER than upstream `iii`, which allows any +/// `is_ascii_alphanumeric` in a worker name (`types.rs`): `MyApp` is refused +/// here though `iii` would install it. LOOSER than upstream would be the bug, +/// since it defers the refusal to `iii worker add`, in another program, +/// minutes later. +/// +/// `Err` is the message the caller sees. `""`, `":"` and `"::"` leave nothing +/// to build a prefix from and keep their own diagnosis, which draws a concrete +/// suggestion from `ids` — hence that parameter, empty where the caller sent +/// none to draw on. +/// Canonicalise a namespace and enforce the charset rule. +/// +/// Public because `code-runner` registers **python** handlers too, and the two +/// languages must agree byte-for-byte on what a legal namespace is. A second +/// copy of this rule elsewhere is how `app::x` becomes legal in one language +/// and not the other — and the rule is not cosmetic: the charset check is what +/// closed a YAML-injection reachable through the old `eject`. +pub fn normalize_namespace(ns: &str, ids: &[String]) -> Result { + let stem = ns.trim_end_matches(':'); + if stem.is_empty() { + return Err(empty_namespace_message(ns, ids)); + } + validate_worker_name(stem).map_err(|why| invalid_namespace_message(ns, stem, &why))?; + Ok(format!("{stem}::")) +} + +/// The one namespace we cannot repair. Suggests a concrete value taken from +/// the caller's own ids when there are any, because "write a prefix" is advice +/// and `"app::"` is an answer. +fn empty_namespace_message(ns: &str, ids: &[String]) -> String { + let suggestion = ids + .iter() + .find_map(|id| id.split_once("::")) + .map(|(head, _)| format!("{head}::")); + match suggestion { + Some(s) => format!( + "namespace {ns:?} names no prefix. Your ids start with {s:?} — pass that as the \ + namespace." + ), + None => format!( + "namespace {ns:?} names no prefix. Pass the prefix your ids start with, such as \ + \"app::\" for ids like \"app::save\"." + ), + } +} + +/// The other namespace we cannot repair: a stem that is not one worker name. +/// +/// `validate_worker_name`'s own text is written for a `name` field, and its +/// `"::"` case tells the caller to drop the delimiter a namespace legitimately +/// ends with — advice that is simply wrong here. So that one reason is +/// restated, and every reason is wrapped in a sentence that says what a +/// namespace has to be and what nesting still works. +fn invalid_namespace_message(ns: &str, stem: &str, why: &str) -> String { + let reason = if stem.contains("::") { + format!("{stem:?} is more than one segment") + } else { + why.to_string() + }; + format!( + "namespace {ns:?} is not one worker name: {reason}. A namespace's first segment IS the \ + worker name on the bus, so pass a single segment — \"my-app::\", with lowercase letters, \ + digits, \".\", \"_\" or \"-\". Ids may still nest below it: \"my-app::v2::save\" \ + registers fine under namespace \"my-app::\"." + ) +} + +struct Runtime { + thread: RuntimeThread, + /// Serialises evals so per-eval logs and registrations are exact. + eval_lock: Arc>, + unregisters: Unregisters, + /// Shared with the isolate thread via `RuntimeOpts.last_activity` — see + /// `ops::OpsState::last_activity` for why an owned `Mutex` is not enough: + /// an INVOKE proxied straight from the bus to the isolate's command + /// channel never reaches `run`/`register`, so only a handle the isolate + /// thread can also write through keeps such a runtime from looking idle. + last_activity: Arc>, + /// Required prefix for ids this runtime may register. + namespace: String, +} + +pub struct RuntimeManager { + cfg: Arc, + engine: Arc, + runtimes: Mutex>>, + ids: crate::ids::IdRegistry, + /// Namespace → the runtime serving its registered functions. Distinct + /// from `runtimes`, which is keyed by runtime id: this is the only way + /// to reach a registration runtime, since its id is never returned to + /// any caller. + namespaces: Mutex>, + /// Serialises namespace creation. Without it, two first-registrations + /// racing on one namespace each create a runtime and one is orphaned — + /// unreachable, holding a slot until the idle sweep. + namespace_create_lock: Mutex<()>, +} + +impl RuntimeManager { + /// `worker_ids` are the function ids the hosting worker registers on its + /// own client. They seed the [`crate::ids::IdRegistry`] so a runtime can + /// never claim — and then abort on — one of them. This crate cannot know + /// them: which functions a host registers is the host's business, so the + /// list crosses the seam as an argument rather than being reached for. + pub fn new( + cfg: Arc, + engine: Arc, + worker_ids: &[&str], + ) -> Arc { + Arc::new(Self { + cfg, + engine, + runtimes: Mutex::new(HashMap::new()), + ids: crate::ids::IdRegistry::with_worker_ids(worker_ids), + namespaces: Mutex::new(HashMap::new()), + namespace_create_lock: Mutex::new(()), + }) + } + + /// The id registry this manager claims into. + /// + /// Public so `code-runner` can claim **python** function ids in the SAME + /// registry. Two registries would each believe they owned `app::greet`, + /// both would reach `iii_sdk`'s `register_function`, and the second would + /// hit its duplicate-id panic — which aborts the process. Every path that + /// can register a function must claim here, including the guest-driven + /// `iii.registerFunction` op, which already does. + pub fn ids(&self) -> &crate::ids::IdRegistry { + &self.ids + } + + /// The existing runtime for `namespace`, or a freshly created one — + /// race-safe against two first-registrations landing on the same + /// namespace at once (the "thundering herd"). Double-checked locking: + /// the fast path never takes `namespace_create_lock` once a namespace's + /// runtime exists, so steady-state registrations pay only the + /// `namespaces` lock, not the create lock. + /// + /// Private rather than `pub(crate)`: its only caller (`register`) lives + /// in this same module. `teardown`'s namespace dispatch deliberately + /// does NOT call this — it must never mint a runtime just to destroy it, + /// so it calls `live_namespace_runtime` directly instead. + fn namespace_runtime( + &self, + namespace: &str, + ) -> Result<(String, Arc), NodeEngineError> { + // Fast path: an existing, still-live runtime. + if let Some(rt) = self.live_namespace_runtime(namespace) { + return Ok(rt); + } + let _create = self.namespace_create_lock.lock().unwrap(); + // Re-check under the lock — another caller may have created it + // between the fast path and here. + if let Some(rt) = self.live_namespace_runtime(namespace) { + return Ok(rt); + } + let (id, runtime) = self.create(Some(namespace.to_string()))?; + self.namespaces + .lock() + .unwrap() + .insert(namespace.to_string(), id.clone()); + Ok((id, runtime)) + } + + /// The namespace's runtime, but only if it is still in `runtimes`. A + /// torn-down or swept runtime leaves a stale map entry; handing that id + /// back would answer with a runtime that no longer exists. + fn live_namespace_runtime(&self, namespace: &str) -> Option<(String, Arc)> { + let id = self.namespaces.lock().unwrap().get(namespace).cloned()?; + let runtime = self.runtimes.lock().unwrap().get(&id).cloned()?; + Some((id, runtime)) + } + + /// Live runtimes. Tests assert on this to prove disposal actually + /// happened rather than trusting a returned error. + pub fn live_runtime_count(&self) -> usize { + self.runtimes.lock().unwrap().len() + } + + fn create(&self, namespace: Option) -> Result<(String, Arc), NodeEngineError> { + let mut runtimes = self.runtimes.lock().unwrap(); + if runtimes.len() >= self.cfg.max_runtimes { + return Err(NodeEngineError::Capacity(self.cfg.max_runtimes)); + } + + let runtime_id = format!("rt-{}", uuid::Uuid::new_v4()); + + let namespace = match namespace { + // Exempt from the one-segment rule by construction, not by flag: + // this is the `None` arm, so it never passes through + // `normalize_namespace` — which would refuse it, since + // `code-runner::` is two segments. Its FIRST segment + // is `code-runner`, the hosting worker's own name on the bus, which + // is what the rule actually protects; the runtime_id below it only + // keeps two eval runtimes from colliding. Leave it: routing it + // through validation would refuse every namespace-less eval. + None => format!("code-runner::{runtime_id}::"), + Some(ns) => normalize_namespace(&ns, &[]).map_err(NodeEngineError::InvalidRequest)?, + }; + // Built BEFORE `spawn` and cloned into `RuntimeOpts` so the manager + // and the isolate thread share the SAME clock rather than each + // keeping its own — see `ops::OpsState::last_activity`. + let last_activity = Arc::new(Mutex::new(Instant::now())); + let thread = RuntimeThread::spawn( + RuntimeOpts { + heap_mb: self.cfg.heap_mb, + external_mb: self.cfg.external_mb, + namespace: namespace.clone(), + call_timeout_ms: self.cfg.default_timeout_ms, + max_timeout_ms: self.cfg.max_timeout_ms, + ids: self.ids.clone(), + runtime_id: runtime_id.clone(), + last_activity: last_activity.clone(), + scratch_mb: self.cfg.scratch_mb, + scratch_files: self.cfg.scratch_files, + scratch_root: self.cfg.scratch_root.clone(), + }, + self.engine.clone(), + ); + let runtime = Arc::new(Runtime { + unregisters: thread.unregisters(), + thread, + eval_lock: Arc::new(tokio::sync::Mutex::new(())), + last_activity, + namespace, + }); + runtimes.insert(runtime_id.clone(), runtime.clone()); + Ok((runtime_id, runtime)) + } + + fn lookup(&self, runtime_id: &str) -> Result, NodeEngineError> { + self.runtimes + .lock() + .unwrap() + .get(runtime_id) + .cloned() + .ok_or_else(|| NodeEngineError::RuntimeNotFound(runtime_id.to_string())) + } + + pub async fn run(&self, req: RunRequest) -> Result { + let (runtime_id, runtime) = match req.runtime_id.as_deref() { + Some(id) => { + if req.namespace.is_some() { + return Err(NodeEngineError::InvalidRequest( + "namespace is accepted only when creating a runtime (omit runtime_id)" + .into(), + )); + } + (id.to_string(), self.lookup(id)?) + } + None => self.create(req.namespace.clone())?, + }; + // Whether THIS call minted the runtime — the only case where its + // lifetime is ours to decide. A caller-supplied `runtime_id` is + // never disposed here regardless of `req.keep`: that runtime + // belongs to the caller. + let created = req.runtime_id.is_none(); + + let timeout = self.cfg.clamp_timeout(req.timeout_ms); + let _guard = runtime.eval_lock.clone().lock_owned().await; + + // Re-verify membership under the lock. Between `lookup` above and + // here the sweeper or an explicit teardown may have removed this + // runtime; running on would answer the caller "successfully" for an id + // that no longer resolves and orphan anything this eval registers. + if !self.runtimes.lock().unwrap().contains_key(&runtime_id) { + return Err(NodeEngineError::RuntimeNotFound(runtime_id)); + } + + // Mark activity at the START of the eval, not only on completion. A + // runtime idle for nearly the whole TTL that then receives an eval + // would otherwise still look stale to the sweeper while it runs. + *runtime.last_activity.lock().unwrap() = Instant::now(); + + let (reply, rx) = oneshot::channel(); + if runtime + .thread + .send(Command::Eval { + code: req.code, + timeout, + reply, + }) + .is_err() + { + self.reap(&runtime_id); + return Err(NodeEngineError::RuntimeGone(runtime_id)); + } + + let outcome = match rx.await { + Ok(Ok(o)) => o, + Ok(Err(e)) => { + // Timeout and OOM kill the isolate; drop it so callers get a + // clean not-found instead of talking to a corpse. + // + // On a CREATE, reap on ANY error. The caller never received + // this runtime_id and the error carries no id, so nothing can + // ever address the runtime again — it holds one of + // `max_runtimes` until the idle sweep, minutes later. A syntax + // error is the ordinary case while someone iterates on a + // snippet, so this leaked a slot per typo. Same reasoning as + // the `register` failure arm. + if req.runtime_id.is_none() + || matches!(e, NodeEngineError::Timeout | NodeEngineError::Oom) + { + self.reap(&runtime_id); + } + return Err(e); + } + Err(_) => { + self.reap(&runtime_id); + return Err(NodeEngineError::RuntimeGone(runtime_id)); + } + }; + + *runtime.last_activity.lock().unwrap() = Instant::now(); + // Disposed on the way out when this call minted the runtime and + // nobody asked to keep it: nothing survives to address, so + // returning an id would be a lie. + let keep_alive = !created || req.keep; + if !keep_alive { + // Drop the guard before reaping: `reap` takes the runtimes lock + // and destroys the isolate thread this guard belongs to. + drop(_guard); + self.reap(&runtime_id); + } + Ok(RunResponse { + runtime_id: keep_alive.then_some(runtime_id), + result: outcome.result, + logs: outcome.logs, + registered: outcome.registered, + }) + } + + /// One function, into its namespace's persistent runtime — created on the + /// first registration, reused by every later one. The backing runtime and + /// its id are never returned: this is the property that makes `teardown`'s + /// namespace path necessary at all, since a caller has nothing else to + /// address it by. + pub async fn register( + &self, + req: RegisterRequest, + ) -> Result { + let invalid = |m: String| NodeEngineError::InvalidRequest(m); + + if req.function_id.len() > MAX_FUNCTION_ID_BYTES { + return Err(invalid(format!( + "function id {:?}… is {} bytes; the limit is {MAX_FUNCTION_ID_BYTES}", + req.function_id.chars().take(40).collect::(), + req.function_id.len() + ))); + } + if let Some(desc) = &req.description { + if desc.len() > MAX_DESCRIPTION_BYTES { + return Err(invalid(format!( + "description is {} bytes; the limit is {MAX_DESCRIPTION_BYTES}", + desc.len() + ))); + } + } + + // The namespace IS the first segment; an id with no `::` cannot name + // one and is refused rather than silently placed in a default. + let namespace = match req.function_id.split_once("::") { + Some((head, _)) if !head.is_empty() => format!("{head}::"), + _ => { + return Err(invalid(format!( + "function id {:?} has no namespace; pass something like \ + \"my-app::greet\"", + req.function_id + ))) + } + }; + // The existing validator, unchanged: it trims trailing colons and + // applies the worker-name charset rule to the stem. + let namespace = normalize_namespace(&namespace, std::slice::from_ref(&req.function_id)) + .map_err(invalid)?; + + // Claim BEFORE creating: a registration doomed by a taken id must not + // have booted a runtime first. + // + // The owner passed here matters. `op_iii_register` (ops.rs) claims + // every id it registers too, keyed by the RUNTIME's own id — the + // check that stands between it and `Engine::register`'s panic on a + // duplicate, and it fires for every path into that op, not just this + // one. For that claim to succeed rather than see a foreign owner + // where this call already approved one, the two have to agree. + // + // When the namespace already has a live runtime, its id is right + // there — claim under it directly, and re-registering an id this + // SAME runtime already holds is then just a `claim()` an owner + // reclaims for free, so it survives this check unchanged. Only on + // the very first registration for a namespace is there no runtime_id + // yet to claim under; `&namespace` stands in for it until one + // exists, then hands off — see the release right after + // `namespace_runtime` below. + let existing = self.live_namespace_runtime(&namespace).map(|(id, _)| id); + let claim_owner = existing.as_deref().unwrap_or(&namespace); + self.ids + .claim_all(std::slice::from_ref(&req.function_id), claim_owner) + .map_err(|_| NodeEngineError::IdTaken(req.function_id.clone()))?; + + let (runtime_id, runtime) = match self.namespace_runtime(&namespace) { + Ok(rt) => rt, + Err(e) => { + self.ids + .release_ids(std::slice::from_ref(&req.function_id), claim_owner); + return Err(e); + } + }; + + // The placeholder claim only stood in for a runtime_id that did not + // exist yet. One does now — hand off to it so `op_iii_register`'s own + // claim (below, inside `define_handler`'s eval) sees an owner it + // recognises rather than `&namespace`. + if existing.is_none() { + self.ids + .release_ids(std::slice::from_ref(&req.function_id), &namespace); + } + + match self.define_handler(&runtime_id, &runtime, &req).await { + Ok(()) => Ok(RegisterResponse { + function_id: req.function_id, + namespace, + }), + Err(e) => { + // Release ONLY if this id never reached the bus. On the reuse + // path `claim_owner` IS the runtime that may already hold a + // LIVE registration for this exact id from an earlier, + // successful call — an ordinary typo'd redeploy fails before + // `iii.registerFunction` ever runs, and unconditionally + // releasing here would free that live claim out from under + // it, letting a second runtime claim the same id and reach + // `Engine::register` on a duplicate — the process abort + // `op_iii_register`'s own claim exists to prevent. Mirrors the + // old batch loop's guard: `unregisters` names every id that + // provably reached the bus, so its absence is what "never + // landed" actually means — checked and released under ONE + // lock acquisition so a concurrent success cannot land in the + // gap between the check and the release. + // + // Kind-AGNOSTIC on purpose, matching `OpsState::unregister`'s + // predicate (ops.rs): `ids` tracks id ownership flatly, so + // "may this claim be released" is "does ANY kind still hold + // this id", never "does a Function hold it". Scoped to + // `Function` this released a live TRIGGER TYPE's claim — + // trivially reachable, since `req.source` runs arbitrary + // statements in the namespace runtime and can call + // `iii.registerTriggerType('app::x', …)` before failing to + // define `handler`. The freed id then let a second runtime in + // the same namespace claim it and silently clobber the first's + // trigger-type handler. + let held = runtime.unregisters.lock().unwrap(); + if !held.iter().any(|(_, id, _)| *id == req.function_id) { + self.ids + .release_ids(std::slice::from_ref(&req.function_id), claim_owner); + } + drop(held); + Err(e) + } + } + } + + /// Resolve `req.source` to `handler(payload)` inside `runtime`, and + /// register it. Extracted from the old batch loop's per-function body — + /// `wrap_register`, the resolved-form protocol, and its error mapping are + /// all unchanged; only the shape feeding them is (one function, not a + /// slice of `FunctionDef`). Routed through `run` rather than talking to + /// `runtime.thread` directly so eval serialisation, activity tracking, + /// and Timeout/Oom classification stay exactly what every other eval + /// gets — this is not a special path. + async fn define_handler( + &self, + runtime_id: &str, + runtime: &Arc, + req: &RegisterRequest, + ) -> Result<(), NodeEngineError> { + debug_assert!( + req.function_id.starts_with(&runtime.namespace), + "namespace_runtime({:?}) returned a runtime whose namespace does not cover {:?}", + runtime.namespace, + req.function_id + ); + let code = crate::protocol::wrap_register( + &req.function_id, + &req.source, + req.description.as_deref(), + req.request_format.as_ref(), + req.response_format.as_ref(), + ); + self.run(RunRequest { + code, + runtime_id: Some(runtime_id.to_string()), + namespace: None, + // This IS the namespace's persistent runtime; a registration + // attempt — successful or not — must never be the thing that + // disposes it out from under a namespace other calls still rely + // on. `run` only reaps a caller-supplied runtime on Timeout/Oom, + // same as it would for any other eval into it. + keep: true, + timeout_ms: None, + }) + .await + // `run`'s `RuntimeNotFound`/`RuntimeGone` messages quote `runtime_id` + // verbatim (error.rs) — fine for `run`'s own caller, who already + // holds that id, but `register_function`'s caller never does and + // must never learn it: it addresses the whole namespace's shared + // runtime, not a runtime of their own. Reachable if the idle sweep + // (or a concurrent teardown) drops this runtime between + // `namespace_runtime` resolving it and `run`'s own re-check. + // Redacted rather than dropping the variant, so the wire error CODE + // stays what it always was. + .map_err(|e| match e { + NodeEngineError::RuntimeNotFound(_) => { + NodeEngineError::RuntimeNotFound("".into()) + } + NodeEngineError::RuntimeGone(_) => { + NodeEngineError::RuntimeGone("".into()) + } + other => other, + })?; + Ok(()) + } + + pub async fn teardown_runtime( + &self, + runtime_id: &str, + ) -> Result { + // Look up WITHOUT removing, so the eval lock is taken first. + let runtime = self.lookup(runtime_id)?; + + // Wait for any in-flight eval. Tearing down underneath one lets it run + // to completion and answer its caller "successfully" for a runtime that + // no longer exists — and anything it registers after `destroy` drains + // the list becomes a permanent bus orphan: the id no longer resolves, + // so nothing can ever unregister it. Bounded wait: an eval holds this + // for at most its own clamped timeout. + let _eval_guard = runtime.eval_lock.clone().lock_owned().await; + + // Re-check under the guard — a concurrent teardown or the sweeper may + // have won the race while we waited. + let removed = self.runtimes.lock().unwrap().remove(runtime_id); + let Some(removed) = removed else { + return Err(NodeEngineError::RuntimeNotFound(runtime_id.to_string())); + }; + Ok(TeardownResponse { + unregistered: self.destroy(runtime_id, removed), + }) + } + + /// Dispatches on which selector the caller sent — exactly one of + /// `runtime_id` or `namespace` — and delegates to `teardown_runtime`. + /// + /// The namespace path resolves through `live_namespace_runtime`, which + /// looks up WITHOUT creating: `namespace_runtime` would mint a fresh + /// runtime for an unknown namespace just to immediately destroy it, + /// turning a not-found into a false "torn down". + pub async fn teardown( + &self, + req: TeardownRequest, + ) -> Result { + let runtime_id = match (req.runtime_id, req.namespace) { + (Some(id), None) => id, + (None, Some(ns)) => { + let ns = normalize_namespace(&ns, &[]).map_err(NodeEngineError::InvalidRequest)?; + self.live_namespace_runtime(&ns) + .map(|(id, _)| id) + .ok_or(NodeEngineError::RuntimeNotFound(ns))? + } + _ => { + return Err(NodeEngineError::InvalidRequest( + "pass exactly one of runtime_id or namespace".into(), + )); + } + }; + self.teardown_runtime(&runtime_id).await + } + + /// Remove a runtime that already died, ignoring the case where another + /// caller got there first. + fn reap(&self, runtime_id: &str) { + // Two statements on purpose: an `if let` would hold the map's guard + // for the whole body, and `destroy` blocks joining the isolate thread. + let removed = self.runtimes.lock().unwrap().remove(runtime_id); + if let Some(runtime) = removed { + self.destroy(runtime_id, runtime); + } + } + + fn destroy(&self, runtime_id: &str, runtime: Arc) -> Vec { + // Both callers (`reap` and `teardown_runtime`) already removed this + // id from `runtimes` before calling in, so this is the one place a + // dying runtime's id can still be reached: through a namespace entry + // pointing at it. Pruned here rather than duplicated in both + // callers, so `namespaces` cannot grow one stale entry per teardown + // no matter which path disposed of the runtime. + self.namespaces + .lock() + .unwrap() + .retain(|_, id| id != runtime_id); + let mut ids = Vec::new(); + // ONE critical section spanning the drain AND the release, held against + // `op_iii_register`'s claim→register→push. Splitting them lets a + // registration land on the bus after its claim was freed, leaving an id + // live, unclaimed and impossible to unregister — the abort this registry + // closes. The only release point that frees a whole owner: no failure + // path releases wholesale, because a registration committed before a + // mid-batch throw stays live on the bus (`register`'s failure arm + // releases only the ids that provably never landed). + { + let mut held = runtime.unregisters.lock().unwrap(); + for (_, id, unregister) in held.drain(..) { + unregister(); + ids.push(id); + } + self.ids.release_owner(runtime_id); + } + // NOT necessarily the last Arc: both callers keep their own clone + // alive for the rest of their body, so the channel-close and the + // thread join actually happen at the caller's scope exit — after its + // `eval_lock` guard has dropped, which is what releases a waiting eval + // first. + drop(runtime); + ids + } + + /// Drop runtimes idle for longer than `idle_ttl_secs`. Returns the ids + /// reaped, for logging by the caller. + pub fn sweep_idle(&self) -> Vec { + let ttl = Duration::from_secs(self.cfg.idle_ttl_secs); + let candidates: Vec<(String, Arc)> = { + let runtimes = self.runtimes.lock().unwrap(); + runtimes + .iter() + .filter(|(_, r)| r.last_activity.lock().unwrap().elapsed() >= ttl) + .map(|(id, r)| (id.clone(), r.clone())) + .collect() + }; + + let mut reaped = Vec::new(); + for (id, runtime) in candidates { + // Never reap a runtime with an eval in flight. Killing one mid-eval + // hands its caller a success for a runtime_id that no longer + // exists, and orphans forever any function the eval's tail + // registered after `destroy` took its snapshot — nothing can + // unregister those, because the id can no longer be looked up. + let Ok(_eval_guard) = runtime.eval_lock.try_lock() else { + continue; + }; + // Re-check under that guard: an eval may have finished between the + // scan above and now, bumping `last_activity`. + if runtime.last_activity.lock().unwrap().elapsed() < ttl { + continue; + } + self.reap(&id); + reaped.push(id); + } + reaped + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::engine::FakeEngine; + + /// Stand-in for the ids a hosting worker registers on its own client. + /// The real list is the worker's (`node_engine::functions::STATIC_IDS`); + /// this crate only needs one of them to prove the seed is honoured — see + /// `a_runtime_cannot_claim_an_id_the_worker_owns`. + const TEST_WORKER_IDS: &[&str] = &[ + "node-engine::run", + "node-engine::teardown", + "node-engine::register_function", + "node-engine::inject-guidance", + ]; + use crate::wire::register::RegisterRequest; + use crate::wire::run::RunRequest; + use serde_json::json; + + fn manager(cfg: NodeEngineConfig) -> (Arc, Arc) { + crate::runtime::init_v8_platform(); + let fake = FakeEngine::new(); + ( + RuntimeManager::new(Arc::new(cfg), fake.clone(), TEST_WORKER_IDS), + fake, + ) + } + + fn req(code: &str, runtime_id: Option<&str>) -> RunRequest { + RunRequest { + code: code.to_string(), + runtime_id: runtime_id.map(str::to_string), + namespace: None, + keep: false, + timeout_ms: Some(2_000), + } + } + + /// `req(...)` with `keep: true` — for tests whose runtime must survive + /// the call, to be reused or torn down afterward. `req`'s own default is + /// `keep: false` on purpose (most tests want the ordinary one-shot + /// path), so this is the opt-in for the rest. + fn kept(mut r: RunRequest) -> RunRequest { + r.keep = true; + r + } + + /// The id out of a response built with `kept`. Panics rather than + /// silently building a fresh-runtime request if a test forgets `kept` + /// somewhere upstream — a `None` here means the assumption the test + /// relies on already broke. + fn addr(r: &RunResponse) -> &str { + r.runtime_id + .as_deref() + .expect("test runtime must have been kept alive") + } + + #[test] + fn accepts_ordinary_worker_names() { + // "my.app" and "app.v2" are a single INTERIOR dot each — not a + // leading dot and not ".." — so they stay accepted; only the two + // upstream directory-safety shapes are refused, below. + for name in ["app", "my-app", "my_app", "app.v2", "my.app", "a", "app2"] { + assert!( + validate_worker_name(name).is_ok(), + "{name:?} should be valid" + ); + } + } + + /// The name becomes a namespace prefix, so anything that could change how + /// an id parses, or make two names render alike, is refused. + #[test] + fn refuses_names_that_are_not_safe_as_a_prefix() { + for bad in ["", "App", "my app", "app::x", "app:", "a/b", "a\nb", "ünï"] { + let err = validate_worker_name(bad).unwrap_err(); + assert!(!err.is_empty(), "{bad:?} must explain itself"); + } + let long = "a".repeat(MAX_WORKER_NAME_BYTES + 1); + assert!(validate_worker_name(&long).is_err()); + } + + /// Mirrors upstream `iii-worker`'s own directory-safety rules: a name + /// that could traverse out of, or land inside, a hidden control + /// directory once joined into `~/.iii/logs/`. Being looser than + /// upstream here is the bug this test guards against — see the doc + /// comment on `validate_worker_name`. + #[test] + fn refuses_dotdot_and_leading_dot() { + for bad in ["..", "a..b", ".", ".hidden"] { + let err = validate_worker_name(bad).unwrap_err(); + assert!(!err.is_empty(), "{bad:?} must explain itself"); + } + } + + #[tokio::test] + async fn eval_without_a_runtime_id_creates_one() { + let (m, _) = manager(NodeEngineConfig::default()); + let out = m.run(kept(req("return 1", None))).await.unwrap(); + assert!(out.runtime_id.is_some()); + assert_eq!(out.result, json!(1)); + m.teardown_runtime(addr(&out)).await.unwrap(); + } + + #[tokio::test] + async fn eval_with_a_runtime_id_reuses_the_isolate() { + let (m, _) = manager(NodeEngineConfig::default()); + let first = m + .run(kept(req("globalThis.n = 5; return null", None))) + .await + .unwrap(); + let second = m + .run(req("return globalThis.n", Some(addr(&first)))) + .await + .unwrap(); + assert_eq!(second.runtime_id.as_deref(), Some(addr(&first))); + assert_eq!(second.result, json!(5)); + m.teardown_runtime(addr(&first)).await.unwrap(); + } + + #[tokio::test] + async fn unknown_runtime_id_is_runtime_not_found() { + let (m, _) = manager(NodeEngineConfig::default()); + let err = m.run(req("return 1", Some("rt-nope"))).await.unwrap_err(); + assert_eq!(err.code(), "node-engine::runtime_not_found"); + assert_eq!( + m.teardown_runtime("rt-nope").await.unwrap_err().code(), + "node-engine::runtime_not_found" + ); + } + + #[tokio::test] + async fn namespace_with_an_existing_runtime_is_an_invalid_request() { + let (m, _) = manager(NodeEngineConfig::default()); + let first = m.run(kept(req("return 1", None))).await.unwrap(); + let mut second = req("return 1", Some(addr(&first))); + second.namespace = Some("other::".into()); + assert_eq!( + m.run(second).await.unwrap_err().code(), + "node-engine::invalid_request" + ); + m.teardown_runtime(addr(&first)).await.unwrap(); + } + + #[tokio::test] + async fn the_default_namespace_is_derived_from_the_runtime_id() { + let (m, fake) = manager(NodeEngineConfig::default()); + let created = m.run(kept(req("return 1", None))).await.unwrap(); + let ns = format!("code-runner::{}::", addr(&created)); + + let ok = m + .run(req( + &format!("iii.registerFunction('{ns}hello', () => 1); return null"), + Some(addr(&created)), + )) + .await + .unwrap(); + assert_eq!(ok.registered, vec![format!("{ns}hello")]); + assert_eq!(fake.registered_ids(), vec![format!("{ns}hello")]); + + // Anything outside that prefix is refused. + let denied = m + .run(req( + "try { iii.registerFunction('state::get', () => 1); return 'no throw' } \ + catch (e) { return 'denied' }", + Some(addr(&created)), + )) + .await + .unwrap(); + assert_eq!(denied.result, json!("denied")); + assert_eq!(fake.registered_ids().len(), 1); + + m.teardown_runtime(addr(&created)).await.unwrap(); + } + + /// The guard is a prefix test, so an EMPTY prefix would silently disable + /// it. A prefix merely missing its delimiter is repaired instead — see + /// `normalize_namespace` — so these are the values that name no prefix at + /// all. A stem that is not one worker name is refused too, by the same + /// function; `a_namespace_that_is_not_one_worker_name_is_refused` covers it. + #[tokio::test] + async fn a_malformed_namespace_is_rejected() { + let (m, _) = manager(NodeEngineConfig::default()); + for bad in ["", "::", ":"] { + let mut req = req("return 1", None); + req.namespace = Some(bad.to_string()); + assert_eq!( + m.run(req).await.unwrap_err().code(), + "node-engine::invalid_request", + "namespace {bad:?} should have been rejected" + ); + } + assert_eq!( + m.live_runtime_count(), + 0, + "a rejected namespace must not leak a runtime" + ); + } + + #[tokio::test] + async fn a_custom_namespace_is_honoured_on_creation() { + let (m, _) = manager(NodeEngineConfig::default()); + let mut first = req( + "iii.registerFunction('app::go', () => 1); return null", + None, + ); + first.namespace = Some("app::".into()); + let out = m.run(kept(first)).await.unwrap(); + assert_eq!(out.registered, vec!["app::go".to_string()]); + m.teardown_runtime(addr(&out)).await.unwrap(); + } + + #[tokio::test] + async fn teardown_unregisters_everything_and_frees_the_slot() { + let (m, fake) = manager(NodeEngineConfig { + max_runtimes: 1, + ..Default::default() + }); + let mut first = req( + "iii.registerFunction('app::go', () => 1); return null", + None, + ); + first.namespace = Some("app::".into()); + let out = m.run(kept(first)).await.unwrap(); + + let torn = m.teardown_runtime(addr(&out)).await.unwrap(); + assert_eq!(torn.unregistered, vec!["app::go".to_string()]); + assert_eq!(fake.unregister_count(), 1); + + // Slot is free again — and with the default one-shot behaviour, this + // call disposes its own runtime immediately, freeing the slot again + // too, so there is nothing left to tear down afterward. + m.run(req("return 1", None)).await.unwrap(); + } + + #[tokio::test] + async fn exceeding_max_runtimes_is_a_capacity_error() { + let (m, _) = manager(NodeEngineConfig { + max_runtimes: 1, + ..Default::default() + }); + // Must occupy the slot for the second call to hit capacity: with the + // default one-shot behaviour it would free its own slot immediately. + let first = m.run(kept(req("return 1", None))).await.unwrap(); + assert_eq!( + m.run(req("return 1", None)).await.unwrap_err().code(), + "node-engine::capacity" + ); + m.teardown_runtime(addr(&first)).await.unwrap(); + } + + #[tokio::test] + async fn a_timed_out_runtime_is_reaped_so_the_next_eval_is_not_found() { + let (m, _) = manager(NodeEngineConfig::default()); + let created = m.run(kept(req("return 1", None))).await.unwrap(); + let mut busy = req("for(;;){}", Some(addr(&created))); + busy.timeout_ms = Some(300); + assert_eq!( + m.run(busy).await.unwrap_err().code(), + "node-engine::timeout" + ); + assert_eq!( + m.run(req("return 1", Some(addr(&created)))) + .await + .unwrap_err() + .code(), + "node-engine::runtime_not_found" + ); + } + + /// The dangerous case is not "sweep after an eval" but "sweep DURING one": + /// a runtime idle for nearly the TTL that receives a fresh eval. + #[tokio::test] + async fn the_idle_sweep_does_not_reap_a_runtime_mid_eval() { + let (m, _) = manager(NodeEngineConfig { + idle_ttl_secs: 0, + ..Default::default() + }); + let created = m.run(kept(req("return 1", None))).await.unwrap(); + let id = addr(&created).to_string(); + + // A slow eval holds this runtime's eval lock while the sweep runs. + let manager_handle = m.clone(); + let eval_id = id.clone(); + let slow = tokio::spawn(async move { + let mut r = req("await new Promise(() => {}); return 1", Some(&eval_id)); + r.timeout_ms = Some(1_500); + manager_handle.run(r).await + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + + assert!( + m.sweep_idle().is_empty(), + "swept a runtime with an eval in flight" + ); + + // The eval owns its own fate: it times out rather than being told the + // runtime vanished underneath it. + assert_eq!( + slow.await.unwrap().unwrap_err().code(), + "node-engine::timeout" + ); + } + + #[tokio::test] + async fn the_idle_sweep_reaps_stale_runtimes() { + let (m, _) = manager(NodeEngineConfig { + idle_ttl_secs: 0, + ..Default::default() + }); + let created = m.run(kept(req("return 1", None))).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert_eq!(m.sweep_idle(), vec![addr(&created).to_string()]); + assert_eq!( + m.run(req("return 1", Some(addr(&created)))) + .await + .unwrap_err() + .code(), + "node-engine::runtime_not_found" + ); + } + + /// The bug this guards: an INVOKE proxied straight from the bus to the + /// isolate's command channel (`op_iii_register`'s handler, in `ops.rs`) + /// never passes through `RuntimeManager::run`/`register`, so a runtime + /// doing exactly what it exists for — sitting on the bus and answering + /// calls — used to look idle to `sweep_idle` and get reaped mid-service. + /// + /// One second of real sleep on each side is unavoidable: `idle_ttl_secs` + /// is whole seconds, and the assertion only means anything if the runtime + /// is aged PAST the ttl before each check — a check taken immediately + /// after registering would pass even without the fix, since `register` + /// itself just set `last_activity`. + #[tokio::test] + async fn an_invoke_through_the_registered_proxy_counts_as_activity() { + let (m, fake) = manager(NodeEngineConfig { + idle_ttl_secs: 1, + ..Default::default() + }); + m.register(reg( + "app::ping", + "export function handler(p) { return p.n + 1 }", + None, + )) + .await + .unwrap(); + // The namespace runtime's id is never returned by `register` — this + // test reaches it directly through the same-module `namespace_runtime` + // lookup (`teardown`'s own namespace dispatch uses the non-creating + // `live_namespace_runtime` instead, since it must never mint a + // runtime just to destroy it). + let (runtime_id, _) = m.namespace_runtime("app::").unwrap(); + + // Age the runtime past the ttl BEFORE invoking it, so a clean sweep + // afterward can only be explained by the invoke itself resetting the + // clock. + tokio::time::sleep(std::time::Duration::from_millis(1_100)).await; + assert_eq!( + fake.invoke("app::ping", json!({ "n": 1 })).await, + Ok(json!(2)) + ); + + assert!( + m.sweep_idle().is_empty(), + "an invoke through the registered proxy must count as activity" + ); + assert_eq!(m.live_runtime_count(), 1); + + // No further activity: the SAME runtime is now stale on the SAME ttl. + tokio::time::sleep(std::time::Duration::from_millis(1_100)).await; + assert_eq!(m.sweep_idle(), vec![runtime_id]); + assert_eq!(m.live_runtime_count(), 0); + } + + /// The regression test for a process abort: with the real `iii-sdk`, the + /// second registration reaches a `panic!` inside a `#[op2(fast)]` callback + /// and kills the worker. + #[tokio::test] + async fn the_same_id_from_two_runtimes_is_refused_and_the_worker_survives() { + let (m, _) = manager(NodeEngineConfig::default()); + + let mut first = req( + "iii.registerFunction('app::dup', () => 1); return 'ok'", + None, + ); + first.namespace = Some("app::".into()); + let a = m.run(kept(first)).await.unwrap(); + assert_eq!(a.registered, vec!["app::dup".to_string()]); + + let mut second = req( + "try { iii.registerFunction('app::dup', () => 2); return 'registered' } \ + catch (e) { return 'refused' }", + None, + ); + second.namespace = Some("app::".into()); + let b = m.run(kept(second)).await.unwrap(); + assert_eq!(b.result, json!("refused")); + assert!(b.registered.is_empty()); + + // Still serving: the process did not die. + let c = m.run(kept(req("return 1 + 1", None))).await.unwrap(); + assert_eq!(c.result, json!(2)); + + m.teardown_runtime(addr(&a)).await.unwrap(); + m.teardown_runtime(addr(&b)).await.unwrap(); + m.teardown_runtime(addr(&c)).await.unwrap(); + } + + /// The highest-value scratch test: four lifecycle exits, one assertion + /// shape. `scratch_root` makes the directory observable from the host + /// without ever handing a path to the guest. + /// + /// Mutation: `std::mem::forget` the `TempDir`, or move it into a + /// `static` — the count stays at 1 after every exit. + #[tokio::test] + async fn the_scratch_directory_dies_with_its_runtime() { + let root = tempfile::Builder::new() + .prefix("node-core-lifecycle-") + .tempdir() + .expect("tempdir"); + let count = || { + std::fs::read_dir(root.path()) + .map(|d| d.flatten().count()) + .unwrap_or(0) + }; + let cfg = NodeEngineConfig { + scratch_root: Some(root.path().to_string_lossy().into_owned()), + idle_ttl_secs: 0, + ..NodeEngineConfig::default() + }; + let (m, _) = manager(cfg); + + // 1. explicit teardown + let out = m + .run(kept(req("iii.files.write('a', 'x'); return 1", None))) + .await + .unwrap(); + assert_eq!(count(), 1, "a kept runtime must own a directory"); + m.teardown_runtime(addr(&out)).await.unwrap(); + assert_eq!(count(), 0, "teardown must remove it"); + + // 2. one-shot: created and destroyed inside the call + m.run(req("iii.files.write('a', 'x'); return 1", None)) + .await + .unwrap(); + assert_eq!(count(), 0, "a one-shot run must leave nothing behind"); + + // 3. the idle sweep + m.run(kept(req("return 1", None))).await.unwrap(); + assert_eq!(count(), 1); + let reaped = m.sweep_idle(); + assert_eq!(reaped.len(), 1, "the sweep must have reaped it"); + assert_eq!(count(), 0, "the sweep must remove its directory"); + + // 4. a timeout kill + let killed = m + .run(kept(RunRequest { + timeout_ms: Some(50), + ..req("while (true) {}", None) + })) + .await; + assert!(killed.is_err(), "the runaway must have been killed"); + assert_eq!(count(), 0, "a killed runtime must not leak its directory"); + } + + /// `scratch_mb: 0` is the operator kill switch: no directory, and the + /// guest surface is gone rather than present-and-refusing. Mutation: + /// delete the `drop_files` interpolation in `runtime.rs`. + #[tokio::test] + async fn scratch_mb_zero_removes_the_guest_surface() { + let cfg = NodeEngineConfig { + scratch_mb: 0, + ..NodeEngineConfig::default() + }; + let (m, _) = manager(cfg); + let out = m + .run(req("return typeof iii.files === 'undefined'", None)) + .await + .unwrap(); + assert_eq!(out.result, json!(true)); + } + + /// `namespace: "node-engine::"` passes shape validation, so without the + /// worker-id seed a single request could claim `node-engine::run`, reach + /// `engine.register`, and abort. + #[tokio::test] + async fn a_runtime_cannot_claim_an_id_the_worker_owns() { + let (m, _) = manager(NodeEngineConfig::default()); + let mut r = req( + "try { iii.registerFunction('node-engine::run', () => 1); return 'registered' } \ + catch (e) { return 'refused' }", + None, + ); + r.namespace = Some("node-engine::".into()); + let out = m.run(kept(r)).await.unwrap(); + assert_eq!(out.result, json!("refused")); + + let alive = m.run(kept(req("return 'alive'", None))).await.unwrap(); + assert_eq!(alive.result, json!("alive")); + + m.teardown_runtime(addr(&out)).await.unwrap(); + m.teardown_runtime(addr(&alive)).await.unwrap(); + } + + #[tokio::test] + async fn teardown_releases_the_claim_for_a_later_runtime() { + let (m, _) = manager(NodeEngineConfig::default()); + let mut first = req("iii.registerFunction('app::x', () => 1); return 'ok'", None); + first.namespace = Some("app::".into()); + let a = m.run(kept(first)).await.unwrap(); + m.teardown_runtime(addr(&a)).await.unwrap(); + + let mut second = req("iii.registerFunction('app::x', () => 2); return 'ok'", None); + second.namespace = Some("app::".into()); + let b = m.run(kept(second)).await.unwrap(); + assert_eq!(b.registered, vec!["app::x".to_string()]); + m.teardown_runtime(addr(&b)).await.unwrap(); + } + + #[tokio::test] + async fn re_registering_within_one_runtime_still_succeeds() { + let (m, _) = manager(NodeEngineConfig::default()); + let mut r = req( + "iii.registerFunction('app::y', () => 1); \ + iii.registerFunction('app::y', () => 2); \ + return 'ok'", + None, + ); + r.namespace = Some("app::".into()); + let out = m.run(kept(r)).await.unwrap(); + assert_eq!(out.result, json!("ok")); + m.teardown_runtime(addr(&out)).await.unwrap(); + } + + fn reg(function_id: &str, source: &str, description: Option<&str>) -> RegisterRequest { + RegisterRequest { + function_id: function_id.to_string(), + source: source.to_string(), + description: description.map(str::to_string), + request_format: None, + response_format: None, + } + } + + /// The two formats must survive the whole node chain — wire → + /// `wrap_register`'s generated JS → the prelude's options object → + /// `op_iii_register` → `Engine::register` — because the bus registration + /// is where `engine::functions::info` reads them from. Mutation: any hop + /// dropping either field (the generated `__def`, the options literal, the + /// op's pass-through). + #[tokio::test] + async fn register_formats_reach_the_engine() { + let (m, fake) = manager(NodeEngineConfig::default()); + let request = json!({"type": "object", "properties": {"n": {"type": "number"}}}); + let response = json!({"type": "number"}); + let mut req = reg( + "app::typed", + "export function handler(p) { return p.n }", + None, + ); + req.request_format = Some(request.clone()); + req.response_format = Some(response.clone()); + m.register(req).await.expect("registers"); + assert_eq!( + fake.formats_of("app::typed"), + Some((Some(request), Some(response))) + ); + } + + /// No formats supplied → none invented: the pair reaches the engine as + /// `(None, None)`, leaving the SDK's own auto-extraction (the any-schema) + /// in charge, exactly as before the fields existed. + #[tokio::test] + async fn register_without_formats_sends_none() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::plain", + "export function handler(p) { return p }", + None, + )) + .await + .expect("registers"); + assert_eq!(fake.formats_of("app::plain"), Some((None, None))); + } + + /// A redeploy that supplies formats but no description must still hit the + /// bus: the SDK only carries metadata at registration time, and the old + /// early-return skipped the bus write whenever the DESCRIPTION was + /// absent — which would silently discard the formats. Mutation: the swap + /// branch's early-return condition not extended to the formats. + #[tokio::test] + async fn a_redeploy_with_new_formats_republishes() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::x", + "export function handler(p) { return 1 }", + None, + )) + .await + .expect("first registration"); + assert_eq!(fake.formats_of("app::x"), Some((None, None))); + + let mut req = reg("app::x", "export function handler(p) { return 2 }", None); + req.request_format = Some(json!({"type": "object"})); + m.register(req).await.expect("redeploy"); + assert_eq!( + fake.formats_of("app::x"), + Some((Some(json!({"type": "object"})), None)) + ); + } + + /// Guest-level `iii.registerFunction` takes the same options — the + /// worker path rides through it, so tenant code in a kept runtime gets + /// the surface for free. + #[tokio::test] + async fn guest_register_options_carry_formats() { + let (m, fake) = manager(NodeEngineConfig::default()); + let out = m + .run(RunRequest { + code: "iii.registerFunction(iii.namespace + 'g', (p) => p, \ + {request_format: {type: 'string'}}); return iii.namespace" + .into(), + runtime_id: None, + namespace: None, + keep: true, + timeout_ms: None, + }) + .await + .expect("evaluates"); + let ns = out.result.as_str().expect("a string namespace"); + assert_eq!( + fake.formats_of(&format!("{ns}g")), + Some((Some(json!({"type": "string"})), None)) + ); + } + + /// The host, not the tenant-replaceable prelude check, is the boundary: a + /// format that is not an object, one that constrains nothing, and one + /// over the size cap are each refused with an error that says what to + /// write. + #[tokio::test] + async fn guest_register_refuses_bad_formats() { + let (m, _fake) = manager(NodeEngineConfig::default()); + for (option, expected) in [ + ("{request_format: 'nope'}", "plain object"), + ("{request_format: {}}", "constrains nothing"), + ( + "{request_format: {type: 'object', description: 'x'.repeat(20000)}}", + "the limit is", + ), + ] { + let err = m + .run(RunRequest { + code: format!( + "iii.registerFunction(iii.namespace + 'b', (p) => p, {option}); return 1" + ), + runtime_id: None, + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .expect_err("a bad format must fail the eval"); + assert!(err.to_string().contains(expected), "{option}: {err}"); + } + } + + #[tokio::test] + async fn registering_creates_the_namespace_runtime_and_the_function_answers() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let out = m + .register(RegisterRequest { + function_id: "app::double".into(), + source: "export function handler(p) { return p.n * 2 }".into(), + description: Some("doubles n".into()), + request_format: None, + response_format: None, + }) + .await + .unwrap(); + assert_eq!(out.function_id, "app::double"); + assert_eq!(out.namespace, "app::"); + assert_eq!(m.live_runtime_count(), 1); + } + + #[tokio::test] + async fn a_second_registration_reuses_the_namespace_runtime() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + m.register(RegisterRequest { + function_id: "app::a".into(), + source: "export function handler() { return 1 }".into(), + description: None, + request_format: None, + response_format: None, + }) + .await + .unwrap(); + m.register(RegisterRequest { + function_id: "app::b".into(), + source: "export function handler() { return 2 }".into(), + description: None, + request_format: None, + response_format: None, + }) + .await + .unwrap(); + assert_eq!( + m.live_runtime_count(), + 1, + "the second registration created a runtime" + ); + } + + /// Claim before you create. The sibling worker shipped the reverse and + /// booted a whole VM for a registration that was already doomed. + #[tokio::test] + async fn a_doomed_registration_creates_no_runtime() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + // node-engine's own ids seed the registry, so this one is always taken. + let err = m + .register(RegisterRequest { + function_id: "node-engine::run".into(), + source: "export function handler() { return 1 }".into(), + description: None, + request_format: None, + response_format: None, + }) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::id_taken"); + assert_eq!( + m.live_runtime_count(), + 0, + "a doomed registration created a runtime" + ); + } + + /// Two functions in one namespace, both actually invokable through the + /// engine — `registering_creates_the_namespace_runtime_and_the_function_ + /// answers` proves the response shape; this proves the handler that lands + /// on the bus is the right one, for both the first and a later id sharing + /// its runtime. + #[tokio::test] + async fn registered_functions_are_invokable_and_share_one_runtime() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::a", + "export function handler(p) { return p.n * 2 }", + None, + )) + .await + .unwrap(); + m.register(reg( + "app::b", + "export function handler(p) { return p.n + 1 }", + None, + )) + .await + .unwrap(); + assert_eq!( + fake.invoke("app::a", json!({ "n": 21 })).await, + Ok(json!(42)) + ); + assert_eq!(fake.invoke("app::b", json!({ "n": 1 })).await, Ok(json!(2))); + assert_eq!(fake.registered_ids().len(), 2); + assert_eq!(m.live_runtime_count(), 1); + } + + /// Redeploying a function is just calling `register_function` again with + /// the same `function_id` — there is no `runtime_id` to reuse anymore, so + /// this is the only way to update one. The pre-claim in `register` must + /// not mistake this for a conflict with itself. + #[tokio::test] + async fn re_registering_the_same_function_id_redeploys_the_handler() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::x", + "export function handler() { return 1 }", + None, + )) + .await + .expect("first registration"); + let out = m + .register(reg( + "app::x", + "export function handler() { return 2 }", + None, + )) + .await + .expect("redeploy"); + assert_eq!(out.function_id, "app::x"); + assert_eq!(fake.invoke("app::x", json!({})).await, Ok(json!(2))); + assert_eq!( + m.live_runtime_count(), + 1, + "redeploy must not spawn a runtime" + ); + } + + /// A definition failure's stack is entirely prelude internals — `Array.map`, + /// the generated eval wrapper, `toHandler` itself. It buried the one line + /// that told the caller what to do. + #[tokio::test] + async fn a_definition_error_carries_no_internal_stack() { + let (m, _) = manager(NodeEngineConfig::default()); + let err = m.register(reg("app::a", "42", None)).await.unwrap_err(); + + let msg = err.to_string(); + for frame in ["code-runner:prelude", "code-runner:eval", "Array.map", "\n"] { + assert!( + !msg.contains(frame), + "definition error leaked {frame:?}: {msg}" + ); + } + } + + /// The old bare-expression handler (`"(p) => p.n * 2"`) is the ability + /// this task retires: `source` must DEFINE `handler`, and with nothing + /// bound to that name the generated wrapper's own `typeof handler !== + /// "function"` check throws a `TypeError` rather than silently + /// registering the expression's value. + #[tokio::test] + async fn a_bare_expression_handler_is_refused() { + let (m, fake) = manager(NodeEngineConfig::default()); + let err = m + .register(reg("app::a", "(p) => p.n * 2", None)) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert!(fake.registered_ids().is_empty()); + } + + /// The other bare-expression shape: `"payload.n * 2"` evaluates `payload` + /// at definition time and dies with a ReferenceError before the + /// "must define handler" check is ever reached, so naming the contract is + /// on that error arm specifically. + /// + /// The second half is the real point. `toHandler`'s hint used to + /// interpolate `src`, which since `wrap_register` became its only caller + /// is the GENERATED WRAPPER — and that wrapper contains the literal text + /// `source must define handler(payload)`. So an assertion that the + /// message "names the contract" passed on a ~1,400-character dump of + /// machine-written code rather than on any message (the E2E case + /// `a bare expression that never defines handler is refused` was doing + /// exactly that). Asserting the wrapper is ABSENT is what keeps this + /// honest. + #[tokio::test] + async fn a_definition_time_reference_error_names_the_contract_without_dumping_the_wrapper() { + let (m, _) = manager(NodeEngineConfig::default()); + let err = m + .register(reg("app::a", "payload.n * 2", None)) + .await + .unwrap_err(); + + assert_eq!(err.code(), "node-engine::eval_failed"); + let msg = err.to_string(); + assert!( + msg.contains("source must define handler(payload)"), + "must name the contract: {msg}" + ); + for wrapper_token in ["var handler", "typeof handler===", "__def", "function(){"] { + assert!( + !msg.contains(wrapper_token), + "the generated wrapper leaked into the message via {wrapper_token:?}: {msg}" + ); + } + } + + /// A GENUINE syntax error (unlike `"(p) => p.n * 2"` above, which parses + /// fine and just binds nothing) fails `toHandler`'s internal + /// expression-then-body fallback on BOTH attempts. `toHandler`'s only + /// caller is `wrap_register` now, so that fallback exists solely to serve + /// THIS contract — the message it produces must recommend defining + /// `handler(payload)`, not the bare-expression/function-body forms this + /// task retired. Telling an agent to fix malformed JS by writing exactly + /// what the worker no longer accepts is worse than no hint at all. + #[tokio::test] + async fn a_syntax_error_in_source_recommends_the_current_contract_not_the_retired_forms() { + let (m, _) = manager(NodeEngineConfig::default()); + let err = m + .register(reg("app::a", "function(", None)) + .await + .unwrap_err(); + + assert_eq!(err.code(), "node-engine::eval_failed"); + let msg = err.to_string(); + assert!( + msg.contains("source must define handler(payload)"), + "must recommend the current contract: {msg}" + ); + assert!( + !msg.contains("(payload) => payload.n * 2"), + "must not recommend the retired bare-expression form: {msg}" + ); + assert!( + !msg.contains("a function body containing"), + "must not recommend the retired function-body-only form: {msg}" + ); + } + + /// CROSS-TASK: the failure arm of `register` released the id's + /// worker-global claim whenever no FUNCTION held it — but `release_ids` + /// is kind-agnostic, so a live TRIGGER TYPE at the same id had its claim + /// freed out from under it. Reachable in one call: `source` executes + /// arbitrary statements in the namespace runtime, so it can publish a + /// trigger type and THEN fail to define `handler`. The freed id let a + /// second runtime in the same namespace claim it and silently clobber the + /// first's trigger-type handler (`register_trigger_type` overwrites + /// rather than panicking, so this is a hijack, not the process abort the + /// function path would have been). + #[tokio::test] + async fn a_doomed_registration_does_not_release_a_live_trigger_types_claim() { + let (m, fake) = manager(NodeEngineConfig::default()); + + // The seed is what makes this test discriminate, and it is not + // incidental setup. `release_ids` is OWNER-scoped (ids.rs), and the + // failure arm passes `claim_owner`. On a FIRST registration into a + // namespace there is no runtime yet, so `claim_owner` is the + // `"app::"` placeholder — which `register` already released at the + // hand-off before `define_handler` runs. The release then no-ops on + // the owner check no matter what the predicate says, and the bug is + // unreachable. Only on the REUSE path is `claim_owner` the live + // runtime_id that actually owns the trigger type's claim. + m.register(reg( + "app::seed", + "export function handler(p) { return 1 }", + None, + )) + .await + .expect("the seed registration creates the namespace runtime"); + + let err = m + .register(reg( + "app::x", + "iii.registerTriggerType({ id: 'app::x' }, \ + { registerTrigger() {}, unregisterTrigger() {} });", + None, + )) + .await + .expect_err("the source defines no handler, so the registration must fail"); + assert_eq!(err.code(), "node-engine::eval_failed"); + + // The side effect landed even though the registration failed: the + // trigger type is live on the bus and must stay claimed. + assert_eq!(fake.registered_trigger_types(), vec!["app::x".to_string()]); + assert!( + !m.ids.claim("app::x", "some-other-runtime"), + "a live trigger type's claim was released by an unrelated failed registration" + ); + } + + /// `export` is stripped only as the source's FIRST token, so a leading + /// statement ahead of it leaves a bare `export` inside the generated + /// wrapper and the whole thing fails to parse. That is fine as a + /// limitation; recommending the exact form the author already wrote is + /// not — the message has to name the actual rule. + #[tokio::test] + async fn an_export_after_a_leading_statement_says_export_must_come_first() { + let (m, _) = manager(NodeEngineConfig::default()); + let err = m + .register(reg( + "app::a", + "const helper = 2;\nexport function handler(p) { return helper }", + None, + )) + .await + .unwrap_err(); + + assert_eq!(err.code(), "node-engine::eval_failed"); + let msg = err.to_string(); + assert!( + msg.contains("only recognised as the first token"), + "must state the actual rule rather than recommending what was written: {msg}" + ); + } + + /// `toHandler` resolves the wrapper via `new Function`, which runs in + /// sloppy mode: an undeclared `handler = ...` assignment — exactly what + /// "source must define handler(payload)" invites just as much as + /// `function handler(p) {}` — creates an IMPLICIT GLOBAL in the shared + /// namespace isolate rather than a local. Without a local `handler` + /// already shadowing it, a LATER registration whose source binds nothing + /// at all would resolve `typeof handler` up the scope chain to a + /// PREVIOUS registration's leaked global and silently register that + /// stale handler under the new id. + #[tokio::test] + async fn a_source_that_binds_nothing_cannot_see_a_previous_registrations_implicit_global() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg("app::a", "handler = (p) => \"TENANT-A-SECRET\"", None)) + .await + .expect("registers via a bare, undeclared assignment"); + + let err = m + .register(reg("app::b", "var somethingElse = 1;", None)) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert!( + fake.invoke("app::b", json!({})).await.is_err(), + "app::b must never have registered another tenant's handler" + ); + } + + /// `const`/`let handler = ...` are exactly as valid a way to "define + /// handler(payload)" as `function handler(p) {}` — `export const + /// handler = async (p) => ...` is the canonical ESM idiom. An earlier + /// version of the generated wrapper put `var handler;` in the SAME + /// scope as the source, which collides with a `let`/`const` of the same + /// name (`SyntaxError: Identifier 'handler' has already been + /// declared`) and refused both forms outright. + #[tokio::test] + async fn const_and_let_handler_forms_register_and_invoke() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg("app::c", "const handler = (p) => p.n + 1;", None)) + .await + .expect("const handler registers"); + m.register(reg("app::l", "let handler = (p) => p.n + 2;", None)) + .await + .expect("let handler registers"); + assert_eq!(fake.invoke("app::c", json!({ "n": 1 })).await, Ok(json!(2))); + assert_eq!(fake.invoke("app::l", json!({ "n": 1 })).await, Ok(json!(3))); + } + + /// `class handler {}` is, by JS semantics, `typeof handler === + /// "function"`, so it passes the wrapper's own check and REGISTERS — and + /// then fails on every single call, because a class constructor has no + /// `[[Call]]`. This test pins that asymmetry end to end; it used to + /// assert the registration alone, which is why the guidance and the + /// README could go on recommending `class handler {}` as a working form + /// with nothing to contradict them. + /// + /// The accept is deliberate, not an oversight to fix here: refusing it at + /// definition time needs source-text sniffing + /// (`Function.prototype.toString` starts with `class`), which is a + /// heuristic that a bound or transpiled class slips past anyway, so it + /// would buy a guarantee it cannot actually keep. The invoke-time + /// `TypeError` names the exact problem. The docs no longer recommend the + /// form; this test is what keeps the real behaviour honest. + #[tokio::test] + async fn a_class_named_handler_registers_but_can_never_be_invoked() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg("app::k", "class handler {}", None)) + .await + .expect("class handler registers"); + + let err = fake + .invoke("app::k", json!({})) + .await + .expect_err("a class constructor cannot be invoked without 'new'"); + assert!( + err.to_string().contains("without 'new'"), + "expected the class-constructor TypeError, got: {err}" + ); + } + + /// A tenant's own `"use strict"` directive must survive the wrapper. + /// The earlier single-scope version put `var handler;` ahead of the + /// source, which is not a valid directive-prologue position (a + /// directive must be the first statement(s) of a function body), so the + /// directive was silently dropped: a typo that should throw + /// `ReferenceError` at invoke time instead created an implicit global + /// and ran to completion. Giving the source its own inner function + /// scope (nothing precedes it there) restores prologue position. + #[tokio::test] + async fn a_sources_own_use_strict_directive_still_applies() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::strict", + "\"use strict\";\nfunction handler(p) { typoedVar = 1; return 1; }", + None, + )) + .await + .expect("registers"); + assert!( + fake.invoke("app::strict", json!({})).await.is_err(), + "the source's own strict mode should have caught the undeclared assignment" + ); + } + + /// The description crosses Rust → generated JS → the prelude → the op → + /// `Engine::register`, and only the far end is observable. Asserting it + /// there is the only way to know the whole chain carried it: every earlier + /// link can be intact while the value is still dropped at the next one. + #[tokio::test] + async fn a_supplied_description_reaches_the_engine() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::documented", + "export function handler() { return 1 }", + Some("Adds one. Payload: {}"), + )) + .await + .expect("registers"); + m.register(reg( + "app::bare", + "export function handler() { return 2 }", + None, + )) + .await + .expect("registers"); + + assert_eq!( + fake.registered_descriptions(), + vec![ + ( + "app::documented".to_string(), + Some("Adds one. Payload: {}".to_string()) + ), + // Omitted stays None here: `IIIEngine` substitutes + // DEFAULT_DYNAMIC_DESC, so the fake sees the caller's intent. + ("app::bare".to_string(), None), + ] + ); + } + + /// Quotes and newlines in a description are interpolated into generated + /// JavaScript, same as the id and the source. If they escaped their + /// literal the script would not parse — so a clean round-trip is also the + /// escaping proof. + #[tokio::test] + async fn a_description_with_javascript_metacharacters_round_trips() { + let (m, fake) = manager(NodeEngineConfig::default()); + let nasty = "quote \" backslash \\ newline \n `backtick` ${expr} */"; + m.register(reg( + "app::x", + "export function handler() { return 1 }", + Some(nasty), + )) + .await + .expect("registers"); + + assert_eq!( + fake.registered_descriptions(), + vec![("app::x".to_string(), Some(nasty.to_string()))] + ); + } + + #[tokio::test] + async fn register_rejects_an_over_long_description() { + let (m, fake) = manager(NodeEngineConfig::default()); + let long = "x".repeat(MAX_DESCRIPTION_BYTES + 1); + let err = m + .register(reg( + "app::x", + "export function handler() { return 1 }", + Some(&long), + )) + .await + .unwrap_err(); + + assert_eq!(err.code(), "node-engine::invalid_request"); + assert!(fake.registered_ids().is_empty()); + assert_eq!( + m.live_runtime_count(), + 0, + "rejected before a runtime is created" + ); + } + + #[tokio::test] + async fn teardown_by_namespace_disposes_the_registration_runtime() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + m.register(RegisterRequest { + function_id: "app::hello".into(), + source: "export function handler() { return 1 }".into(), + description: None, + request_format: None, + response_format: None, + }) + .await + .unwrap(); + assert_eq!(m.live_runtime_count(), 1); + + let out = m + .teardown(TeardownRequest { + runtime_id: None, + namespace: Some("app::".into()), + }) + .await + .unwrap(); + assert!(out.unregistered.contains(&"app::hello".to_string())); + assert_eq!(m.live_runtime_count(), 0); + } + + #[tokio::test] + async fn teardown_requires_exactly_one_selector() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + for (rid, ns) in [ + (None, None), + (Some("rt-x".to_string()), Some("app::".to_string())), + ] { + let err = m + .teardown(TeardownRequest { + runtime_id: rid, + namespace: ns, + }) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::invalid_request"); + } + } + + #[tokio::test] + async fn teardown_of_an_unknown_namespace_is_not_found() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let err = m + .teardown(TeardownRequest { + runtime_id: None, + namespace: Some("nobody::".into()), + }) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::runtime_not_found"); + } + + /// Unknown namespace must be reported not-found, never a runtime minted + /// just to destroy: `teardown` uses `live_namespace_runtime` (no create), + /// not `namespace_runtime`. A regression to the creating lookup would + /// still return `runtime_not_found` on the SECOND call (nothing was ever + /// registered into it) but would leave a live, unreachable runtime behind + /// — this asserts the slot was never spent at all. + #[tokio::test] + async fn teardown_of_an_unknown_namespace_creates_no_runtime() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let _ = m + .teardown(TeardownRequest { + runtime_id: None, + namespace: Some("nobody::".into()), + }) + .await + .unwrap_err(); + assert_eq!( + m.live_runtime_count(), + 0, + "teardown of an unregistered namespace must not mint a runtime" + ); + } + + /// A behavioural check on the teardown → re-register sequence, NOT a + /// guard on `destroy`'s `namespaces` prune: `namespace_runtime`'s create + /// path unconditionally `.insert()`s on every fresh creation (overwriting + /// any stale entry regardless of whether it was pruned), and + /// `live_namespace_runtime` independently re-checks the resolved id + /// against `runtimes` before trusting it — so this sequence passes + /// whether or not the prune runs at all. See + /// `teardown_by_namespace_prunes_the_dead_map_entry` below for the test + /// that actually falsifies on a disabled prune. + #[tokio::test] + async fn a_registration_after_namespace_teardown_gets_a_fresh_runtime() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + m.register(reg( + "app::hello", + "export function handler() { return 1 }", + None, + )) + .await + .unwrap(); + assert_eq!(m.live_runtime_count(), 1); + + m.teardown(TeardownRequest { + runtime_id: None, + namespace: Some("app::".into()), + }) + .await + .unwrap(); + assert_eq!(m.live_runtime_count(), 0); + + // Documents current behaviour on re-registration; does not by + // itself prove `namespaces` was pruned (see the comment on this + // test above). + let out = m + .register(reg( + "app::hello", + "export function handler() { return 2 }", + None, + )) + .await + .unwrap(); + assert_eq!(out.namespace, "app::"); + assert_eq!(m.live_runtime_count(), 1, "namespace runtime was not fresh"); + + // And it really is the new registration answering, not a ghost of + // the old one. + m.teardown(TeardownRequest { + runtime_id: None, + namespace: Some("app::".into()), + }) + .await + .unwrap(); + assert_eq!(m.live_runtime_count(), 0); + } + + /// The property `destroy`'s prune (`self.namespaces.lock().unwrap() + /// .retain(|_, id| id != runtime_id)`) actually guards: `namespaces` + /// must not grow one dead entry per teardown that is never followed by a + /// re-registration into the same namespace. Reads the map directly + /// rather than going through any lookup, because both + /// `namespace_runtime` (unconditional `.insert()` on every create) and + /// `live_namespace_runtime` (re-checks the id against `runtimes` before + /// trusting it) tolerate a stale entry just fine — a test that + /// re-registers and asserts on behaviour, like the one above, cannot + /// fail even with the prune line deleted. Three distinct namespaces, so + /// a single surviving stale entry is unmistakable rather than lost in + /// rounding. + /// + /// Mutation-tested: commenting out the `retain` call in `destroy` turns + /// this test red (`left: 3, right: 0`) while the rest of the suite, + /// including the test above, stays green — see task-8-report.md. + #[tokio::test] + async fn teardown_by_namespace_prunes_the_dead_map_entry() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + for ns in ["a", "b", "c"] { + m.register(reg( + &format!("{ns}::hello"), + "export function handler() { return 1 }", + None, + )) + .await + .unwrap(); + m.teardown(TeardownRequest { + runtime_id: None, + namespace: Some(format!("{ns}::")), + }) + .await + .unwrap(); + } + assert_eq!( + m.namespaces.lock().unwrap().len(), + 0, + "a torn-down namespace with nothing re-registered into it leaked a map entry" + ); + } + + /// Normalizing (unchanged: it repairs a namespace string missing its + /// trailing `::`, and never WIDENS a prefix) is exercised directly here — + /// `register` no longer has an independent `namespace` field to feed it a + /// mismatched value, since the namespace IS the id's own first segment. + #[tokio::test] + async fn normalize_namespace_repairs_the_delimiter_and_never_widens() { + let norm = |ns: &str| normalize_namespace(ns, &[]); + assert_eq!(norm("app").unwrap(), "app::"); + assert_eq!(norm("app:").unwrap(), "app::"); + assert_eq!(norm("app::").unwrap(), "app::"); + assert_eq!(norm("app:::").unwrap(), "app::"); + // Nothing to build a prefix from. + for empty in ["", ":", "::"] { + let why = norm(empty).unwrap_err(); + assert!(why.contains("names no prefix"), "ns {empty:?}: {why}"); + } + // One segment only: `a::b` names an identity the bus cannot represent. + // The stem is a WORKER NAME, so `validate_worker_name`'s rule applies + // whole — including its byte limit, which is bytes and not chars. + for bad in [ + "a::b", + "my app", + "MyApp", + &"a".repeat(65), + // 33 chars, 66 bytes: a char-counted limit would let this past. + &"é".repeat(33), + ] { + let why = norm(bad).unwrap_err(); + assert!( + why.contains("is not one worker name") && why.contains("my-app::"), + "ns {bad:?}: {why}" + ); + } + assert!(norm(&"é".repeat(33)).unwrap_err().contains("66 bytes")); + let max = "a".repeat(MAX_WORKER_NAME_BYTES); + assert_eq!(norm(&max).unwrap(), format!("{max}::")); + } + + /// A namespace's first segment IS a worker name on the bus, so the id's + /// own prefix has to be one — `validate_worker_name`'s rule, applied to + /// whatever `function_id` puts in front of the first `::`. Every one of + /// these is refused before an isolate exists, which is why none of them + /// leaves a runtime behind. + #[tokio::test] + async fn a_namespace_that_is_not_one_worker_name_is_refused() { + let (m, fake) = manager(NodeEngineConfig::default()); + let long = "a".repeat(65); + // 33 chars, 66 bytes: a char-counted limit would wave this through. + let multibyte = "é".repeat(33); + // Not `"a::b"`: `function_id.split_once("::")` always stops at the + // FIRST `::`, so a derived namespace can never itself contain one — + // `"a::b::x"` derives namespace `"a::"`, one clean segment, and + // nests `b::x` below it exactly as `myapp::v2::save` is meant to. + for stem in ["my app", "MyApp", long.as_str(), multibyte.as_str()] { + let id = format!("{stem}::x"); + let err = m + .register(reg(&id, "export function handler() {}", None)) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::invalid_request", "stem {stem:?}"); + let msg = err.to_string(); + assert!( + msg.contains("my-app::"), + "must say what to pass instead: {msg}" + ); + assert_eq!(m.live_runtime_count(), 0, "stem {stem:?} leaked a runtime"); + assert!(fake.registered_ids().is_empty(), "stem {stem:?}"); + } + } + + /// An id with no `::` at all, or nothing before it, cannot name a + /// namespace and is refused with a concrete example rather than silently + /// placed in a default. + #[tokio::test] + async fn a_function_id_with_no_namespace_is_refused() { + let (m, _) = manager(NodeEngineConfig::default()); + for id in ["bare-id", "::save"] { + let err = m + .register(reg(id, "export function handler() {}", None)) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::invalid_request", "id {id:?}"); + assert!( + err.to_string().contains("my-app::greet"), + "must show a working example: {err}" + ); + assert_eq!(m.live_runtime_count(), 0, "id {id:?} leaked a runtime"); + } + } + + #[tokio::test] + async fn register_rejects_once_the_runtime_holds_the_registration_cap() { + let (m, _) = manager(NodeEngineConfig::default()); + for i in 0..crate::ops::MAX_REGISTRATIONS_PER_RUNTIME { + m.register(reg( + &format!("app::f{i}"), + "export function handler() { return 1 }", + None, + )) + .await + .unwrap_or_else(|e| panic!("registration {i} failed: {e}")); + } + assert_eq!(m.live_runtime_count(), 1, "one namespace, one runtime"); + + let err = m + .register(reg( + "app::over", + "export function handler() { return 1 }", + None, + )) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert!( + err.to_string() + .contains(&crate::ops::MAX_REGISTRATIONS_PER_RUNTIME.to_string()), + "must name the cap: {err}" + ); + assert_eq!(m.live_runtime_count(), 1, "the namespace runtime survives"); + } + + /// Evaluated code that wants to register has to satisfy a prefix it had no + /// way to read. Guessing costs a `namespace_denied` after the work is done. + #[tokio::test] + async fn evaluated_code_can_read_its_own_namespace() { + let (m, _) = manager(NodeEngineConfig::default()); + + let res = m + .run(RunRequest { + code: "return iii.namespace".into(), + runtime_id: None, + namespace: Some("app::".into()), + keep: false, + timeout_ms: None, + }) + .await + .expect("evaluates"); + assert_eq!(res.result, serde_json::json!("app::")); + + // The default runtime namespace is equally unguessable from inside, so + // it has to be readable too. `keep: true`: its id is reused below. + let derived = m + .run(RunRequest { + code: "return iii.namespace".into(), + runtime_id: None, + namespace: None, + keep: true, + timeout_ms: None, + }) + .await + .expect("evaluates"); + let ns = derived.result.as_str().expect("a string namespace"); + assert!( + ns.starts_with("code-runner::rt-") && ns.ends_with("::"), + "default namespace should be readable: {ns}" + ); + + // And it is the value the op actually enforces: registering under it + // succeeds where a guess would not. + let ok = m + .run(RunRequest { + code: "iii.registerFunction(iii.namespace + 'x', () => 1); return 'ok'".into(), + runtime_id: derived.runtime_id.clone(), + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .expect("registers under the published namespace"); + assert_eq!(ok.registered, vec![format!("{ns}x")]); + } + + /// `heap_limits` bounds the object heap only. An `ArrayBuffer` is backed + /// by V8's array-buffer allocator, accounted separately, so before the cap + /// a runtime could hold hundreds of megabytes resident while its object + /// heap stayed healthy — one tenant exhausting the host for all of them. + #[tokio::test] + async fn off_heap_memory_is_capped_independently_of_the_object_heap() { + let cfg = NodeEngineConfig { + external_mb: 8, + ..NodeEngineConfig::default() + }; + let (m, _) = manager(cfg); + + // Under the cap: allowed, and the bytes are real. `keep: true`: its + // id is reused below to push the same runtime over the cap. + let ok = m + .run(RunRequest { + code: "const b = new ArrayBuffer(4*1024*1024); return b.byteLength".into(), + runtime_id: None, + namespace: None, + keep: true, + timeout_ms: None, + }) + .await + .expect("4 MiB is under the 8 MiB cap"); + assert_eq!(ok.result, serde_json::json!(4 * 1024 * 1024)); + + // Over the cap: refused. V8 treats a null from the array-buffer + // allocator as unrecoverable rather than throwing a catchable + // RangeError, so this surfaces as `oom` and the isolate dies — the + // same outcome as exceeding `heap_mb`, which is the point: the tenant + // that asked for too much loses its runtime and nobody else does. + let err = m + .run(RunRequest { + code: "return new ArrayBuffer(64*1024*1024).byteLength".into(), + runtime_id: ok.runtime_id.clone(), + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .expect_err("64 MiB must be refused"); + assert_eq!(err.code(), "node-engine::oom"); + + // Reaped like any OOM, so the slot is not stranded, and the WORKER is + // unharmed — a fresh runtime still works. `keep: true` so the + // `teardown` below has something to address. + assert_eq!( + m.live_runtime_count(), + 0, + "a killed runtime must not hold its slot" + ); + let fresh = m + .run(RunRequest { + code: "return 'alive'".into(), + runtime_id: None, + namespace: None, + keep: true, + timeout_ms: None, + }) + .await + .expect("the worker survives a tenant blowing its own cap"); + assert_eq!(fresh.result, serde_json::json!("alive")); + m.teardown_runtime(addr(&fresh)).await.unwrap(); + } + + /// WebAssembly.Memory is backed by V8's own reservation, not the capped + /// array-buffer allocator, so it was the one remaining way to take memory + /// the cap cannot see. It is also not part of what this worker offers. + #[tokio::test] + async fn webassembly_is_not_reachable() { + let (m, _) = manager(NodeEngineConfig::default()); + let res = m + .run(RunRequest { + code: "return [typeof WebAssembly, typeof globalThis.WebAssembly]".into(), + runtime_id: None, + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .expect("evaluates"); + assert_eq!(res.result, serde_json::json!(["undefined", "undefined"])); + } + + /// `description` is published metadata — it is what the next caller reads + /// out of `engine::functions::info`. The SDK carries it only at + /// registration time, so a re-bind that kept the old registration + /// reported success and left the catalog showing the old text. There is + /// no `runtime_id` to reuse anymore, so "re-bind" is just calling + /// `register` again with the same `function_id`. + #[tokio::test] + async fn re_registering_with_a_new_description_updates_the_published_one() { + let (m, fake) = manager(NodeEngineConfig::default()); + + m.register(reg( + "app::x", + "export function handler() { return 1 }", + Some("ORIGINAL"), + )) + .await + .expect("registers"); + + m.register(reg( + "app::x", + "export function handler() { return 2 }", + Some("CHANGED"), + )) + .await + .expect("re-binds"); + + assert_eq!( + fake.registered_descriptions(), + vec![("app::x".to_string(), Some("CHANGED".to_string()))], + "the published description must follow the re-bind" + ); + // Still exactly one live registration, and the handler swapped too. + assert_eq!(fake.registered_ids(), vec!["app::x".to_string()]); + assert_eq!( + fake.invoke("app::x", serde_json::json!({})).await.unwrap(), + 2 + ); + + // Omitting the description on a re-bind leaves the published one alone + // rather than blanking it. + m.register(reg( + "app::x", + "export function handler() { return 3 }", + None, + )) + .await + .expect("re-binds again"); + assert_eq!( + fake.registered_descriptions(), + vec![("app::x".to_string(), Some("CHANGED".to_string()))], + "an omitted description must not erase the published one" + ); + assert_eq!(m.live_runtime_count(), 1); + } + + /// The schema promises `result` is null for a value JSON cannot + /// represent. `JSON.stringify` has TWO failure modes and only one throws: + /// a function, a symbol, or a `toJSON` returning undefined is DROPPED, so + /// stringifying `{ok: v}` in one step produced `{}` — an envelope with + /// neither key, which surfaced to the caller as `eval_failed`. + #[tokio::test] + async fn unrepresentable_return_values_come_back_as_null_not_an_error() { + let (m, _) = manager(NodeEngineConfig::default()); + for code in [ + "return function foo(){}", + "return Symbol('s')", + "return {toJSON(){return undefined}}", + "const a={};a.self=a;return a", + "return 1n", + "return undefined", + "return [function(){}, Symbol('x'), 1]", + ] { + let res = m + .run(RunRequest { + code: code.into(), + runtime_id: None, + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .unwrap_or_else(|e| panic!("{code:?} must not error: {e}")); + assert!( + res.result.is_null() || res.result.is_array(), + "{code:?} gave {:?}", + res.result + ); + } + } + + /// `settle`'s return value IS the envelope Rust parses, so a global it + /// resolves at call time is a way to forge one. Overwriting + /// `JSON.stringify` reported a THROWN error as a successful result. + /// + /// Each case names the ONE pre-captured primitive in `prelude.js` it + /// guards, and each was checked by reverting that capture to the global + /// and confirming this test then fails. That check found two of these + /// cases had gone dead: cases 2 and 3 hand `settle` a FAKE thenable, and + /// since `thenPromise` is `Promise.prototype.then` pre-bound, a fake + /// thenable now dies on the real `then` whatever `resolvePromise` is — + /// so they passed with `resolvePromise` reverted. Case 4 is the one that + /// actually exercises it: a `Promise.resolve` replacement that returns a + /// REAL promise, which the real `then` is happy to consume. + #[tokio::test] + async fn tenant_code_cannot_forge_the_result_envelope() { + let (m, _) = manager(NodeEngineConfig::default()); + for forge in [ + // 1. `stringify`, ok arm. + r#"JSON.stringify = () => '{"ok":"FORGED"}'; throw new Error("real failure");"#, + // 2. `thenPromise`, via a fake thenable off a replaced Promise. + r#"globalThis.Promise = { resolve: () => ({ then: () => '{"ok":"FORGED"}' }) }; throw new Error("real failure");"#, + // 3. `thenPromise`, replaced directly on the prototype. + r#"Promise.prototype.then = () => '{"ok":"FORGED"}'; throw new Error("real failure");"#, + // 4. `resolvePromise`. The forged value rides a REAL promise, so + // the real `Promise.prototype.then` resolves it normally and + // only the pre-captured `Promise.resolve` stands between a + // throw and a reported success. + r#"const R = Promise.resolve.bind(Promise); globalThis.Promise = { resolve: () => R({ pwned: "FORGED" }) }; throw new Error("real failure");"#, + ] { + let err = m + .run(RunRequest { + code: forge.into(), + runtime_id: None, + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .expect_err("a throw must stay an error"); + assert_eq!(err.code(), "node-engine::eval_failed", "forge: {forge}"); + assert!( + !err.to_string().contains("FORGED"), + "forged value surfaced: {err}" + ); + // The tenant's REAL error has to be what reaches the caller. This + // is what pins `settle`'s error-arm `stringify`: reverting that + // one capture to the global lets case 1's replacement rewrite the + // `{"err":…}` payload, and while the template cannot be closed + // into a success, the caller stops being told what actually + // failed. + assert!( + err.to_string().contains("real failure"), + "the tenant's own error must survive the forge: {err}" + ); + } + } + + /// A create-path eval that fails leaves a runtime nothing can address — + /// the caller never got the id and the error does not carry one — so it + /// would hold a slot until the idle sweep. A syntax error is the ordinary + /// case while someone iterates, so this leaked one slot per typo. + #[tokio::test] + async fn a_failed_eval_that_created_its_runtime_does_not_strand_it() { + let (m, _) = manager(NodeEngineConfig::default()); + + for code in ["this is not javascript", "throw new Error('boom')"] { + let err = m + .run(RunRequest { + code: code.into(), + runtime_id: None, + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert_eq!(m.live_runtime_count(), 0, "{code:?} stranded a runtime"); + } + + // The caller's OWN runtime is never reaped out from under them: they + // hold the id and may still be using the isolate. `keep: true`: its + // id is reused for the two calls below. + let mine = m + .run(RunRequest { + code: "globalThis.keep = 1; return 'ok'".into(), + runtime_id: None, + namespace: None, + keep: true, + timeout_ms: None, + }) + .await + .expect("creates"); + let _ = m + .run(RunRequest { + code: "throw new Error('boom')".into(), + runtime_id: mine.runtime_id.clone(), + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .unwrap_err(); + assert_eq!( + m.live_runtime_count(), + 1, + "a caller-owned runtime must survive" + ); + let still = m + .run(RunRequest { + code: "return globalThis.keep".into(), + runtime_id: mine.runtime_id.clone(), + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .expect("still alive"); + assert_eq!(still.result, serde_json::json!(1)); + m.teardown_runtime(addr(&mine)).await.unwrap(); + } + + #[tokio::test] + async fn register_rejects_an_over_long_id() { + let (m, _) = manager(NodeEngineConfig::default()); + let long = format!("app::{}", "x".repeat(600)); + let err = m + .register(reg(&long, "export function handler() { return 1 }", None)) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::invalid_request"); + assert_eq!(m.live_runtime_count(), 0); + } + + /// A bad handler is the likeliest caller error. Unlike the old per-call + /// runtime, this one is the namespace's PERSISTENT runtime — a failed + /// registration must not be the thing that tears it down out from under + /// whatever else that namespace already holds. + #[tokio::test] + async fn a_failed_registration_leaves_the_namespace_runtime_alive() { + let (m, _) = manager(NodeEngineConfig::default()); + let err = m.register(reg("app::bad", "42", None)).await.unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert_eq!( + m.live_runtime_count(), + 1, + "a failed registration must not tear down the namespace runtime" + ); + } + + /// The headroom that matters is the Rust-heap claim map, not V8's + /// `heap_limits` — so before the failure arm released them, every failed + /// registration into an already-live namespace left a fresh claim behind, + /// and a caller could loop forever growing it. + #[tokio::test] + async fn failed_registrations_on_a_live_namespace_do_not_grow_the_claim_map() { + let (m, _) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::a", + "export function handler() { return 1 }", + None, + )) + .await + .unwrap(); + let baseline = format!("{:?}", m.ids); + + for i in 0..3 { + let id = format!("app::bad{i}"); + let err = m.register(reg(&id, "42", None)).await.unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + } + + assert_eq!( + format!("{:?}", m.ids), + baseline, + "claims for ids that never reached the bus were not released" + ); + // And the successful registration keeps its claim: it IS live on the + // bus, so releasing it would reopen the duplicate-id abort. + assert!( + !m.ids.claim("app::a", "rt-other"), + "released a claim for an id that is live on the bus" + ); + assert_eq!(m.live_runtime_count(), 1); + } + + /// The bug this guards: unconditionally releasing the claim whenever + /// `define_handler` fails, without checking whether the id is already + /// live on the bus from an EARLIER, successful call. An ordinary + /// typo'd redeploy fails before `iii.registerFunction` ever runs, and on + /// the reuse path the claim's owner IS the namespace runtime that still + /// actively serves the id — so a release here is not a release of THIS + /// call's own (never-claimed) attempt, it is freeing a live one. + /// Checked two ways: the id must still be unclaimable by a third party, + /// AND a second runtime's `iii.registerFunction` for the same id — the + /// actual guard against `Engine::register`'s panic on a duplicate — must + /// still be refused, not just the Rust-side registry. + #[tokio::test] + async fn a_failed_redeploy_does_not_release_the_live_claim() { + let (m, fake) = manager(NodeEngineConfig::default()); + m.register(reg( + "app::x", + "export function handler() { return 1 }", + None, + )) + .await + .expect("first registration"); + + let err = m.register(reg("app::x", "42", None)).await.unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert!( + !m.ids.claim("app::x", "rt-someone-else"), + "a failed redeploy released a claim that is still live on the bus" + ); + assert_eq!(fake.registered_ids(), vec!["app::x".to_string()]); + + // A different runtime under the same namespace (an ad-hoc `run()`, + // not the persistent one) must still be refused the id. + let denied = m + .run(RunRequest { + code: "try { iii.registerFunction('app::x', () => 2); return 'registered' } \ + catch (e) { return 'refused' }" + .into(), + runtime_id: None, + namespace: Some("app::".into()), + keep: false, + timeout_ms: None, + }) + .await + .expect("evaluates"); + assert_eq!(denied.result, json!("refused")); + assert_eq!( + fake.invoke("app::x", json!({})).await, + Ok(json!(1)), + "the original handler must still be the one that answers" + ); + } + + /// `define_handler` routes through `run`, whose `RuntimeNotFound` / + /// `RuntimeGone` messages quote the runtime_id verbatim (error.rs) — the + /// right behaviour for `run`'s own caller, who supplied that id, but + /// wrong here: `register_function`'s caller never receives the + /// namespace runtime's id and must never learn it through an error + /// either. Reachable if the runtime vanishes (idle sweep, a concurrent + /// teardown) between `namespace_runtime` resolving it and `run`'s own + /// re-check — reproduced directly by tearing it down and calling + /// `define_handler` with the now-stale id, rather than racing the sweep. + #[tokio::test] + async fn a_vanished_namespace_runtime_does_not_leak_its_id_through_the_error() { + let (m, _fake) = manager(NodeEngineConfig::default()); + let (runtime_id, runtime) = m.namespace_runtime("app::").unwrap(); + m.teardown_runtime(&runtime_id).await.unwrap(); + + let err = m + .define_handler( + &runtime_id, + &runtime, + ®("app::x", "export function handler() { return 1 }", None), + ) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::runtime_not_found"); + assert!( + !err.to_string().contains(&runtime_id), + "the namespace runtime's id leaked into the error: {err}" + ); + assert!( + !err.to_string().contains("rt-"), + "a runtime-id shape leaked into the error: {err}" + ); + } + + #[tokio::test] + async fn a_one_shot_run_disposes_its_runtime_and_returns_no_id() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let out = m + .run(RunRequest { + code: "return 1 + 1".into(), + runtime_id: None, + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!(2)); + assert!( + out.runtime_id.is_none(), + "a one-shot run must not return an id" + ); + assert_eq!(m.live_runtime_count(), 0, "the runtime was not disposed"); + } + + #[tokio::test] + async fn keep_true_returns_an_addressable_runtime() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let out = m + .run(RunRequest { + code: "globalThis.x = 41; return 1".into(), + runtime_id: None, + namespace: None, + keep: true, + timeout_ms: None, + }) + .await + .unwrap(); + let id = out.runtime_id.expect("keep: true must return an id"); + assert_eq!(m.live_runtime_count(), 1); + + let again = m + .run(RunRequest { + code: "return globalThis.x + 1".into(), + runtime_id: Some(id), + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .unwrap(); + assert_eq!( + again.result, + serde_json::json!(42), + "globals were not shared" + ); + assert_eq!( + m.live_runtime_count(), + 1, + "a run into a caller-owned runtime must not dispose it" + ); + } + + /// The failure path is where the sibling worker leaked: a runtime created + /// by this call and then failed is unaddressable, so nothing can ever + /// reclaim it but the idle sweep. + #[tokio::test] + async fn a_failing_one_shot_run_leaves_no_runtime_behind() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let err = m + .run(RunRequest { + code: "throw new Error('boom')".into(), + runtime_id: None, + namespace: None, + keep: false, + timeout_ms: None, + }) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert_eq!(m.live_runtime_count(), 0); + } + + #[tokio::test] + async fn one_runtime_serves_a_namespace_across_calls() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let (first, _) = m.namespace_runtime("app::").unwrap(); + let (second, _) = m.namespace_runtime("app::").unwrap(); + assert_eq!(first, second, "a namespace must reuse its runtime"); + assert_eq!(m.live_runtime_count(), 1); + + let (other, _) = m.namespace_runtime("other::").unwrap(); + assert_ne!(other, first); + assert_eq!(m.live_runtime_count(), 2); + } + + #[tokio::test] + async fn concurrent_first_calls_create_one_runtime_not_two() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let a = m.clone(); + let b = m.clone(); + let (ra, rb) = tokio::join!( + tokio::task::spawn_blocking(move || a.namespace_runtime("app::").map(|(id, _)| id)), + tokio::task::spawn_blocking(move || b.namespace_runtime("app::").map(|(id, _)| id)), + ); + assert_eq!(ra.unwrap().unwrap(), rb.unwrap().unwrap()); + assert_eq!( + m.live_runtime_count(), + 1, + "the thundering herd created two runtimes" + ); + } + + #[tokio::test] + async fn tearing_down_a_namespace_runtime_lets_the_next_call_recreate_it() { + let (m, _fake) = manager(NodeEngineConfig { + max_runtimes: 4, + ..Default::default() + }); + let (first, _) = m.namespace_runtime("app::").unwrap(); + m.teardown_runtime(&first).await.unwrap(); + assert_eq!(m.live_runtime_count(), 0); + let (second, _) = m.namespace_runtime("app::").unwrap(); + assert_ne!(second, first, "a stale map entry was handed back"); + assert_eq!(m.live_runtime_count(), 1); + } + + /// `declared.rs` existed so `eject` could write handler sources to disk + /// later. With eject gone, retaining tenant code buys nothing and keeps a + /// secret alive in host memory for the life of the runtime. + #[test] + fn the_manager_type_retains_no_tenant_source() { + let src = include_str!("manager.rs"); + // Built at runtime, not written as one literal: `include_str!` reads + // this very file, so spelling the deleted type's name out whole, + // right here, would make the assertion below match its own source and + // fail forever, deleted or not. + let needle = format!("{}{}", "Declared", "Function"); + assert!( + !src.contains(&needle), + "manager.rs still references {needle}" + ); + assert!( + !std::path::Path::new("src/declared.rs").exists(), + "src/declared.rs still exists" + ); + } +} diff --git a/crates/node-core/src/ops.rs b/crates/node-core/src/ops.rs new file mode 100644 index 0000000000..1e0cc7a063 --- /dev/null +++ b/crates/node-core/src/ops.rs @@ -0,0 +1,1688 @@ +//! The entire Rust↔JS boundary. Ops are the only way out of an isolate, so +//! this file is the worker's attack surface — keep it small and obvious. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use deno_core::{extension, op2, OpState}; +use deno_error::JsErrorBox; +use futures::future::BoxFuture; +use tokio::sync::mpsc; + +use crate::engine::{CallResult, Engine, ProxyHandler, UnregisterFn}; +use crate::error::NodeEngineError; +use crate::runtime::{Command, LogLine}; + +/// Which kind of registration an `OpsState::unregisters` entry is. +/// +/// Function ids, trigger-type ids, and trigger ids all cross as plain +/// strings and share ONE list — see `OpsState::unregisters` — and a function +/// and a trigger type CAN legitimately be given the identical literal id (a +/// tenant has no reason to know the other exists). Without the kind as part +/// of the lookup key, `op_iii_register`'s dedup check, `op_iii_register_ +/// trigger_type`'s dedup check, and `OpsState::unregister`'s removal all +/// match on id alone, so registering one kind under an id another kind +/// already holds either silently no-ops (reports success, never reaches the +/// bus) or evicts the wrong registration — and unregistering one kind can +/// remove a live registration of a different kind entirely. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RegistrationKind { + Function, + Trigger, + TriggerType, +} + +/// Per-isolate state the ops read and write. Lives in deno_core's `OpState`, +/// which is thread-local to the isolate, so plain `RefCell` access is enough +/// for everything except the unregister list shared with the manager. +pub struct OpsState { + pub engine: Arc, + /// Required prefix for ids the evaluated code may register. + pub namespace: String, + /// Buffer for the eval currently in flight. Capped — see `op_iii_log`. + pub logs: Vec, + /// Bytes of message text currently buffered, tracked incrementally so a + /// flood costs O(1) per line rather than a re-sum of the whole buffer. + pub log_bytes: usize, + /// Whether the truncation marker has already been appended. + pub log_truncated: bool, + /// Bytes logged from console calls made with no eval in flight. Its own + /// budget, reset when an eval begins — those lines go to worker tracing, + /// never to a caller's response. + pub detached_log_bytes: usize, + /// False between evals: lines from an interleaved handler invocation with + /// no eval running go to worker tracing instead of a caller's response. + pub capturing: bool, + /// Ids registered by the eval currently in flight, reported back as + /// `EvalOutcome::registered`. Kind-tagged for the same reason + /// `unregisters` is: a function and a trigger type may hold the identical + /// literal id, and a kind-blind `retain` on removal dropped BOTH entries + /// — an eval that registered `app::x` as both and unregistered one + /// reported `registered: []` while the other was still live on the bus. + pub registered: Vec<(RegistrationKind, String)>, + /// Every live registration, shared with the manager so teardown can undo + /// them from the main thread. Functions, triggers, AND trigger types all + /// live in this one list — see `MAX_REGISTRATIONS_PER_RUNTIME` — so its + /// length is the single source of truth the cap checks against. Tagged + /// with `RegistrationKind` because the three kinds' ids share one string + /// namespace as far as this list is concerned — see that type's doc + /// comment. + pub unregisters: Arc>>, + /// `op_iii_register_trigger` calls that have reserved a slot against + /// `MAX_REGISTRATIONS_PER_RUNTIME` but not yet pushed into `unregisters` + /// — it is async (`Engine::register_trigger` awaits the engine), so + /// without a reservation taken BEFORE that await, a tenant firing many + /// un-awaited `registerTrigger()` calls at once could have all of them + /// pass the same cap check before any of them lands, the same TOCTOU + /// `op_iii_call`'s `inflight_calls` already guards against. Functions and + /// trigger types register synchronously (no `.await` inside the + /// critical section that checks-and-pushes), so neither needs this. + pub pending_registrations: usize, + /// Worker-global id ownership. Claimed before `Engine::register`, because + /// a duplicate there aborts the process. + pub ids: crate::ids::IdRegistry, + /// Ownership key for `ids`. + pub runtime_id: String, + pub call_timeout_ms: u64, + /// Ceiling a guest-supplied `iii.trigger({..., timeout})` is clamped to — + /// see `RuntimeOpts::max_timeout_ms`. + pub max_timeout_ms: u64, + /// Calls to `iii.trigger` currently awaiting their engine response. + /// Bounds `op_iii_call`'s Rust-heap footprint — see `MAX_INFLIGHT_CALLS`. + pub inflight_calls: usize, + /// Weak on purpose: a strong sender here would keep the runtime's channel + /// open forever and deadlock every shutdown. + pub command_tx: mpsc::WeakUnboundedSender, + pub invoke_timeout_ms: u64, + /// Shared with `manager::Runtime::last_activity`. An INVOKE dispatched + /// straight from the bus to this isolate's command channel never passes + /// through `RuntimeManager::run`/`register`, so without this a runtime + /// doing exactly what `register_function` is for — + /// sitting on the bus and answering calls — would still be reaped as + /// idle. Bumped by `op_iii_register`'s proxy closure, not here: this + /// field only carries the handle to the isolate thread that built it. + pub last_activity: Arc>, + /// This runtime's private scratch directory, or `None` when `scratch_mb` + /// is 0. + /// + /// Owned HERE, not by the manager. `OpsState` lives in the isolate's + /// `OpState`, which dies when the `JsRuntime` is dropped at `run_loop` + /// scope exit — so `TempDir::drop` removes the directory on teardown, on + /// reap, on the idle sweep, on a timeout/OOM kill AND on an unwind, + /// without any of those paths needing to know it exists. + pub scratch: Option, + pub scratch_max_bytes: u64, + pub scratch_max_files: usize, +} + +impl OpsState { + /// Undo one of THIS runtime's own registrations: the mirror of the + /// critical section in `op_iii_register`. `unregisters` is created fresh + /// per runtime (see `RuntimeThread::spawn`) and never shared, so a + /// lookup here can only ever find an entry this same runtime pushed — + /// there is nothing to check ownership of that isn't already implied by + /// which `Vec` we're looking in. A no-op if `fn_id` was never registered + /// (or was already unregistered): same idempotent shape as + /// `op_iii_register`'s re-registration path, and it means a runtime + /// unregistering something inside its own namespace that doesn't exist + /// gets the same quiet success a register-side re-registration gets, + /// rather than a special error that would leak existence information. + /// + /// Also drops `fn_id` from `registered` — the current eval's reported + /// delta, echoed back as `RunResponse.registered`. Without this, a + /// register-then-unregister in one eval would tell the caller it + /// published something that is not live, and with one-shot `run` that + /// response is often the only record the caller ever sees. + /// + /// Both the claim release and the `registered` trim are gated on the + /// bus removal ACTUALLY having found a `(kind, fn_id)` entry — a + /// review caught this scoped only by `fn_id` in an earlier round: a + /// function and a trigger type can share the identical literal id, and + /// `unregister(TriggerType, "app::x")` against a live FUNCTION `app::x` + /// found nothing to remove (correct) but still released `app::x`'s + /// worker-global claim (wrong) — freeing another runtime to claim it and + /// reach `Engine::register` on a duplicate, which panics inside an + /// `extern "C"` op and aborts the process (see `ids.rs`'s module doc). + /// + /// The claim release ALSO checks whether another kind still holds this + /// exact id after this removal: `ids` tracks id ownership flatly, not + /// per kind, so a tenant who deliberately registered a function AND a + /// trigger type under the same string must not have the claim freed + /// out from under the one still live when the other is unregistered. + fn unregister(&mut self, kind: RegistrationKind, fn_id: &str) { + let mut registrations = self.unregisters.lock().unwrap(); + let Some(index) = registrations + .iter() + .position(|(k, id, _)| *k == kind && id == fn_id) + else { + return; + }; + let (_, _, unregister) = registrations.swap_remove(index); + let still_claimed_by_another_kind = registrations.iter().any(|(_, id, _)| id == fn_id); + drop(registrations); + unregister(); + if !still_claimed_by_another_kind { + self.ids.release_ids(&[fn_id.to_string()], &self.runtime_id); + } + self.registered.retain(|(k, id)| *k != kind || id != fn_id); + } +} + +/// Caps on the per-eval log buffer. +/// +/// This buffer lives on the Rust heap, outside V8's `heap_limits` accounting, +/// so without a cap `for(;;) console.log(i)` would let one tenant allocate +/// process memory for its whole timeout window — routing around the very +/// heap limit the isolate is configured with, through a sanctioned op. The +/// byte cap is the real bound; the line cap keeps a flood of empty strings +/// from growing the `Vec` itself. +const MAX_LOG_LINES: usize = 1_000; +const MAX_LOG_BYTES: usize = 256 * 1024; + +#[op2(fast)] +fn op_iii_log(state: &mut OpState, #[string] level: String, #[string] message: String) { + let ops = state.borrow_mut::(); + + if !ops.capturing { + // Tenant-controlled text going straight into the worker's log stream + // at an unbounded rate — the one instance of this hazard class that + // was left uncapped. Its own counter, not the eval buffer: these lines + // belong to no eval and must not be reported as one. `escape_debug` + // because the formatter does not escape newlines, so raw text could + // forge records that look like the worker's own. + if ops.detached_log_bytes >= MAX_LOG_BYTES { + return; + } + ops.detached_log_bytes += message.len(); + tracing::info!( + target: "code-runner::js", + namespace = %ops.namespace, + %level, + message = %message.escape_debug(), + "console output outside an eval" + ); + return; + } + + if ops.logs.len() >= MAX_LOG_LINES || ops.log_bytes >= MAX_LOG_BYTES { + if !ops.log_truncated { + ops.log_truncated = true; + ops.logs.push(LogLine { + level: "warn".to_string(), + message: format!( + "[code-runner] log output truncated at {MAX_LOG_LINES} lines / \ + {MAX_LOG_BYTES} bytes; further console output is dropped" + ), + }); + } + return; + } + + ops.log_bytes += message.len(); + ops.logs.push(LogLine { level, message }); +} + +/// Caps on the TEXT `op_iii_call` copies to the Rust heap at argument +/// dispatch. All three of its `#[string]` arguments are capped, so that text +/// is bounded at `MAX_INFLIGHT_CALLS * (MAX_FUNCTION_ID_BYTES + +/// MAX_CALL_PAYLOAD_BYTES + MAX_ACTION_BYTES)` per runtime — a little over +/// 32 MiB at these values — independently of V8's own `heap_mb`. +/// +/// That is the whole claim. It is NOT a bound on what stays resident across +/// `engine.call`'s await: `payload_json` is dropped the moment it parses, and +/// the parsed `serde_json::Value` that replaces it is what is actually pinned +/// there. A parsed value is routinely much larger than its own text — 32 +/// in-flight copies of a ~976 KiB amplifying payload (`[1,1,1,…]`) measured +/// at 1098 MiB RSS, roughly 34x the figure above. Capping the parsed value is +/// a design change, deliberately not attempted here. +const MAX_INFLIGHT_CALLS: usize = 32; +const MAX_CALL_PAYLOAD_BYTES: usize = 1024 * 1024; +/// `#[string] action` is byte-copied to the Rust heap at argument-dispatch +/// time — before this function's body even runs, and independently of +/// `MAX_CALL_PAYLOAD_BYTES` two lines up — so an uncapped `action` is the +/// exact same heap-pinning hazard `payload_json` is capped against, just +/// easy to miss because every valid action is tiny (`"void"`, or a small +/// JSON object like `{"type":"enqueue","queue":"..."}`). Generous relative +/// to any real action; nowhere near `MAX_CALL_PAYLOAD_BYTES`. +const MAX_ACTION_BYTES: usize = 512; + +/// Invoke any engine function. Payload and result cross as JSON text so the +/// isolate boundary has exactly one representation to reason about. +/// +/// `action` and `timeout_ms_arg` carry `iii.trigger`'s optional `action` and +/// `timeout` fields across the same one-representation boundary: an empty +/// string means "no action" (plain request/response) and `0` means "use the +/// configured default timeout" — JS `undefined` is not a value `#[string]`/ +/// `#[number]` args can carry, so the prelude substitutes these sentinels +/// before the op ever sees the call. `action` is capped at +/// `MAX_ACTION_BYTES`; a non-zero `timeout_ms_arg` is clamped to +/// `max_timeout_ms`, the same ceiling `NodeEngineConfig::clamp_timeout` +/// applies to the RPC-level eval budget. +// Plain `#[op2]` on an `async fn` IS the eager-async form in deno_ops 0.285 — +// the same shape deno_core's own `op_add_async` uses. Do not write +// `#[op2(async)]`: the bare flag requires parentheses in this version +// (`async(deferred)`, `async(lazy)`), and the bare form fails to compile with +// "expected attribute arguments in parentheses: `async(...)`". +#[op2] +#[string] +async fn op_iii_call( + state: Rc>, + #[string] fn_id: String, + #[string] payload_json: String, + #[string] action: String, + #[number] timeout_ms_arg: u64, +) -> Result { + // Same hazard the log buffer had: everything below lives on the RUST heap, + // outside V8's `heap_limits`. `trigger` is async, so tenant code can + // fire it in a loop without awaiting, and each argument copy is made + // eagerly — deno_core byte-copies every `#[string]` into an owned Rust + // `String` at dispatch, before this body runs at all — and pinned for up + // to `call_timeout_ms`. Without these caps a tenant routes around its own + // isolate's memory limit through a sanctioned op: one eval passing an + // 8 MiB `function_id` 32 times took a runtime from 36 MiB to 316 MiB RSS + // with nothing refused, because only `payload_json` and `action` were + // checked. All three checks run BEFORE `inflight_calls` is touched below, + // so none of them needs its own `release_inflight` call — there is + // nothing yet to release. + if fn_id.len() > MAX_FUNCTION_ID_BYTES { + return Err(JsErrorBox::type_error(format!( + "function id is {} bytes; the limit is {MAX_FUNCTION_ID_BYTES}", + fn_id.len() + ))); + } + if payload_json.len() > MAX_CALL_PAYLOAD_BYTES { + return Err(JsErrorBox::type_error(format!( + "payload is {} bytes; the limit is {MAX_CALL_PAYLOAD_BYTES}", + payload_json.len() + ))); + } + if action.len() > MAX_ACTION_BYTES { + return Err(JsErrorBox::type_error(format!( + "action is {} bytes; the limit is {MAX_ACTION_BYTES}", + action.len() + ))); + } + + let action = (!action.is_empty()).then_some(action); + + let (engine, timeout_ms) = { + let mut borrowed = state.borrow_mut(); + let ops = borrowed.borrow_mut::(); + if ops.inflight_calls >= MAX_INFLIGHT_CALLS { + return Err(JsErrorBox::generic(format!( + "too many concurrent iii.trigger calls (limit \ + {MAX_INFLIGHT_CALLS}); await earlier calls before making more" + ))); + } + ops.inflight_calls += 1; + // A requested timeout is a CEILING clamp, not a fixed override: below + // `max_timeout_ms` it passes through unchanged, so a short request is + // still short. `0` (unset) falls back to the configured default + // rather than being clamped, matching `NodeEngineConfig::clamp_timeout`'s + // "absent, not zero-duration" treatment. + let timeout_ms = if timeout_ms_arg == 0 { + ops.call_timeout_ms + } else { + timeout_ms_arg.min(ops.max_timeout_ms) + }; + (ops.engine.clone(), timeout_ms) + }; + + let payload: serde_json::Value = match serde_json::from_str(&payload_json) { + Ok(v) => v, + Err(e) => { + release_inflight(&state); + return Err(JsErrorBox::type_error(format!("payload is not JSON: {e}"))); + } + }; + // The text copy is dead once parsed; free it before parking on the await. + drop(payload_json); + + let result = engine.call(fn_id, payload, timeout_ms, action).await; + release_inflight(&state); + + match result { + Ok(value) => serde_json::to_string(&value) + .map_err(|e| JsErrorBox::generic(format!("result is not JSON: {e}"))), + Err(message) => Err(JsErrorBox::generic(message)), + } +} + +/// Decrement the in-flight counter. Done explicitly at each exit rather than +/// via a `Drop` guard: a guard would have to borrow the `RefCell` while the +/// future is being dropped, which during isolate teardown can collide with an +/// outstanding borrow and panic. A counter leaked by a cancelled future dies +/// with the `OpsState` it lives in. +fn release_inflight(state: &Rc>) { + let mut borrowed = state.borrow_mut(); + let ops = borrowed.borrow_mut::(); + ops.inflight_calls = ops.inflight_calls.saturating_sub(1); +} + +/// Caps on registration — the third instance of the same hazard as +/// `MAX_LOG_*` and `MAX_INFLIGHT_CALLS`. Each registration pins several owned +/// `String`s and an `Arc` on the Rust heap for the life of the +/// runtime, outside V8's `heap_limits`, AND fires a real `Engine::register` +/// into the trusted bus. Uncapped, one `for` loop in tenant JS is both an +/// unbounded allocation and an unbounded write to the bus. The count cap also +/// bounds the linear de-dup scan below, keeping it trivially cheap. +pub const MAX_REGISTRATIONS_PER_RUNTIME: usize = 256; +pub const MAX_FUNCTION_ID_BYTES: usize = 512; +pub const MAX_DESCRIPTION_BYTES: usize = 4 * 1024; + +/// The refusal every registration kind — function, trigger, trigger type — +/// gives once this runtime's shared `MAX_REGISTRATIONS_PER_RUNTIME` budget is +/// exhausted. One function so the three call sites cannot drift into three +/// different wordings for what is, from a tenant's perspective, one cap. +/// Decode one guest-supplied format argument: "" is "not supplied", +/// anything else must parse as JSON and pass the shared wire rule +/// (`wire::register::validate_format`). Raw length is checked BEFORE parsing +/// so an oversized blob is refused for its size, not after the host paid to +/// parse it — the raw string IS the serialized form (the prelude sends +/// `JSON.stringify` output), so the two length checks are the same rule. +fn parse_format(field: &'static str, raw: &str) -> Result, JsErrorBox> { + if raw.is_empty() { + return Ok(None); + } + if raw.len() > crate::wire::register::MAX_FORMAT_BYTES { + return Err(JsErrorBox::type_error(format!( + "{field} is {} bytes serialized; the limit is {}", + raw.len(), + crate::wire::register::MAX_FORMAT_BYTES + ))); + } + let value: serde_json::Value = serde_json::from_str(raw) + .map_err(|e| JsErrorBox::type_error(format!("{field} is not valid JSON: {e}")))?; + crate::wire::register::validate_format(field, &value).map_err(JsErrorBox::type_error)?; + Ok(Some(value)) +} + +fn registration_cap_exceeded() -> JsErrorBox { + JsErrorBox::generic(format!( + "this runtime already holds {MAX_REGISTRATIONS_PER_RUNTIME} registrations \ + (functions, triggers, and trigger types share one budget); reuse an id or \ + tear the runtime down" + )) +} + +/// The one authorization check that gates both adding and removing a +/// registration: a runtime may only touch ids inside its own namespace +/// prefix. Shared by `op_iii_register` and `op_iii_unregister` rather than +/// copied, so the two can never drift into refusing differently — see +/// `op_iii_unregister`'s doc comment for why "not yours" and "not there" +/// must be the exact same refusal. +fn require_own_namespace(namespace: &str, fn_id: String) -> Result { + if fn_id.starts_with(namespace) { + Ok(fn_id) + } else { + Err(JsErrorBox::type_error( + NodeEngineError::NamespaceDenied { + id: fn_id, + namespace: namespace.to_string(), + } + .message(), + )) + } +} + +/// Publish a JS handler as a real engine function. +/// +/// The proxy runs on the engine's thread: it pushes an `Invoke` into this +/// isolate's command channel and awaits the reply, so JS never runs anywhere +/// but its own thread. +#[op2(fast)] +fn op_iii_register( + state: &mut OpState, + #[string] fn_id: String, + #[string] description: String, + #[string] request_format: String, + #[string] response_format: String, +) -> Result<(), JsErrorBox> { + let ops = state.borrow_mut::(); + + if fn_id.len() > MAX_FUNCTION_ID_BYTES { + return Err(JsErrorBox::type_error(format!( + "function id is {} bytes; the limit is {MAX_FUNCTION_ID_BYTES}", + fn_id.len() + ))); + } + + // Tenant-supplied text that leaves this worker and lands in the engine's + // function catalog, where every caller of `engine::functions::info` reads + // it back. Capped for the same reason the id is. + if description.len() > MAX_DESCRIPTION_BYTES { + return Err(JsErrorBox::type_error(format!( + "description is {} bytes; the limit is {MAX_DESCRIPTION_BYTES}", + description.len() + ))); + } + + let request_format = parse_format("request_format", &request_format)?; + let response_format = parse_format("response_format", &response_format)?; + // Empty means "not supplied": the prelude sends "" when the caller omits + // the argument, and `Engine::register` substitutes its default. + let description = (!description.is_empty()).then_some(description); + + let fn_id = require_own_namespace(&ops.namespace, fn_id)?; + + let weak_tx = ops.command_tx.clone(); + let last_activity = ops.last_activity.clone(); + let timeout = std::time::Duration::from_millis(ops.invoke_timeout_ms); + let proxy_id = fn_id.clone(); + let handler: ProxyHandler = Arc::new(move |payload: serde_json::Value| { + let weak_tx = weak_tx.clone(); + let last_activity = last_activity.clone(); + let fn_id = proxy_id.clone(); + Box::pin(async move { + let Some(tx) = weak_tx.upgrade() else { + return Err(NodeEngineError::RuntimeGone(fn_id).to_string()); + }; + let (reply, rx) = tokio::sync::oneshot::channel(); + if tx + .send(Command::Invoke { + fn_id: fn_id.clone(), + payload, + timeout, + reply, + method: None, + }) + .is_err() + { + return Err(NodeEngineError::RuntimeGone(fn_id).to_string()); + } + // Bump at SEND, not at reply. `invoke_timeout_ms` (always the + // configured `default_timeout_ms`, typically 5000 ms) is roughly + // 180x below `idle_ttl_secs` (900s default), so a handler that just + // opened this window cannot possibly outlive it — bumping here + // is enough to keep the runtime alive for the whole call. Note: no + // validation ensures `idle_ttl_secs` and `default_timeout_ms` stay + // separated; a misconfiguration could sweep the runtime mid-invoke, + // but the caller gets `node-engine::runtime_gone` (bounded, clean, + // no hang or orphan). This is the ONLY place an INVOKE proxied + // straight from the bus touches activity at all: it never reaches + // `RuntimeManager::run`, so without this a runtime doing exactly + // what `register_function` exists for — serving + // calls — would still be swept as idle at `idle_ttl_secs`. + *last_activity.lock().unwrap() = Instant::now(); + match rx.await { + Ok(result) => result.map_err(|e| e.to_string()), + Err(_) => Err(NodeEngineError::RuntimeGone(fn_id).to_string()), + } + }) as BoxFuture<'static, CallResult> + }); + + // ONE critical section: de-dup, cap, claim, bus write, record. `destroy` + // holds this same guard across its drain AND `release_owner`, so a + // registration can never land on the bus after its claim was released — + // that id would be live, unclaimed and impossible to unregister, reopening + // the duplicate-id abort. Lock order is `unregisters` → `ids` on both + // sides; neither `Engine::register` nor the unregister closure re-enters + // `unregisters`, and there is no `.await` in this path. + { + let mut registrations = ops.unregisters.lock().unwrap(); + + // Re-registering an id swaps the JS handler (the prelude's Map does + // that) and the bus registration already exists, so it normally needs + // no bus write. Checked before the cap so a re-registration never + // trips it. + // + // The exception is a NEW description or format. Both are published metadata — + // `engine::functions::info` is where the next caller reads what this + // function does — and the SDK only carries it at registration time, so + // keeping the existing registration would silently discard it: the + // call reports success and the catalog still shows the old text. Drop + // the old registration and make a new one carrying the description. + // Safe to do here: the claim is already ours, so no other runtime can + // take the id in the gap, and `destroy` cannot interleave because it + // holds this same guard. + // Scoped to `RegistrationKind::Function` alone, and no longer + // additionally gated on `ops.registered.contains(&fn_id)` — that + // flat, kind-blind list is what let a same-eval `registerTriggerType + // ({id: 'test::x'}, …); registerFunction('test::x', …)` treat the + // function as "already registered" (it was not: `held` is `None`), + // silently skip the bus write, and still report success and + // `registered: ["test::x"]`. `held` (kind-tagged, checked against + // `unregisters`, which is NOT eval-scoped) is the reliable source of + // truth for "is a FUNCTION already registered under this id" in + // every case `ops.registered.contains` was meant to catch. + // + // The two lists are NOT in lockstep and this must not be rewritten to + // assume they are: `registered` is the current EVAL's delta (cleared + // at the start of every eval, see `runtime.rs`) while `unregisters` + // is every live registration for the life of the runtime, and the + // description-swap branch just below re-registers without pushing to + // `registered` at all. They agree only on the one thing + // `OpsState::unregister` keeps aligned: a removal drops the matching + // `(kind, id)` from both. + let held = registrations + .iter() + .position(|(k, id, _)| *k == RegistrationKind::Function && *id == fn_id); + if let Some(index) = held { + if description.is_none() && request_format.is_none() && response_format.is_none() { + return Ok(()); + } + let (_, _, unregister) = registrations.swap_remove(index); + unregister(); + // Wholesale replacement, never a merge: the SDK only carries + // metadata at registration time, so a re-registration supplying + // formats but no description falls back to the default + // description rather than keeping the previous one. + let fresh = ops.engine.register( + fn_id.clone(), + description, + request_format, + response_format, + handler, + ); + registrations.push((RegistrationKind::Function, fn_id, fresh)); + return Ok(()); + } + + // `pending_registrations` counts `op_iii_register_trigger` calls + // reserved but not yet landed — see its doc comment on `OpsState`. + // Functions share the one budget with triggers and trigger types. + if registrations.len() + ops.pending_registrations >= MAX_REGISTRATIONS_PER_RUNTIME { + return Err(registration_cap_exceeded()); + } + + // Claim before touching the bus. `Engine::register` on an id another + // runtime already holds reaches a `panic!` inside this `extern "C"` + // callback, which aborts the process rather than unwinding. + if !ops.ids.claim(&fn_id, &ops.runtime_id) { + return Err(JsErrorBox::generic( + NodeEngineError::IdTaken(fn_id).message(), + )); + } + + let unregister = ops.engine.register( + fn_id.clone(), + description, + request_format, + response_format, + handler, + ); + registrations.push((RegistrationKind::Function, fn_id.clone(), unregister)); + } + ops.registered.push((RegistrationKind::Function, fn_id)); + Ok(()) +} + +/// Remove a function this runtime registered. +/// +/// The namespace check is the authorization: a runtime may only unpublish +/// inside its own prefix, and the refusal names the id without revealing +/// whether it exists — "not yours" and "not there" must be one answer, or +/// this op becomes a way to enumerate other tenants' registrations. +/// +/// Split out from the `#[op2]` function below so it can be exercised +/// directly in a test with a hand-built `OpsState`. That seam matters here +/// specifically: the prelude's `registerFunction` only ever hands +/// `op_iii_unregister` an id that already passed THIS runtime's own +/// `op_iii_register` namespace check (`unregister()` closes over the id from +/// a successful registration), so there is no way to hand this op a foreign +/// id through the guest-visible surface at all. The check below is +/// defense-in-depth against that surface changing later, and a JS-level test +/// can only prove the surface still refuses early — not that this line does +/// its job. Calling it directly is the only way to do that. +/// +/// `kind` is which registration list entry this id refers to — see +/// `RegistrationKind`'s doc comment for why a bare id is not enough: +/// `op_iii_unregister` and `op_iii_unregister_trigger_type` both route +/// through this, and a function and a trigger type can share the identical +/// literal id. +fn unregister_checked( + ops: &mut OpsState, + kind: RegistrationKind, + fn_id: String, +) -> Result<(), JsErrorBox> { + let fn_id = require_own_namespace(&ops.namespace, fn_id)?; + ops.unregister(kind, &fn_id); + Ok(()) +} + +#[op2(fast)] +fn op_iii_unregister(state: &mut OpState, #[string] fn_id: String) -> Result<(), JsErrorBox> { + unregister_checked( + state.borrow_mut::(), + RegistrationKind::Function, + fn_id, + ) +} + +/// Register a trigger on the caller's behalf. Async because +/// `Engine::register_trigger` is: the trigger id only exists once the engine +/// call returns, unlike a function's id (chosen by the caller up front, so +/// `op_iii_register` never has to await anything to know what it is). +/// +/// Counts against `MAX_REGISTRATIONS_PER_RUNTIME` alongside functions and +/// trigger types via `pending_registrations` — see that field's doc comment +/// for why the slot is reserved BEFORE the `.await`, not just checked. +#[op2] +#[string] +async fn op_iii_register_trigger( + state: Rc>, + #[string] config_json: String, +) -> Result { + // Same hazard `MAX_CALL_PAYLOAD_BYTES`/`MAX_ACTION_BYTES` guard in + // `op_iii_call`: deno_core byte-copies a `#[string]` argument to the Rust + // heap at dispatch time, before this body runs at all. Checked first and + // before any counter is touched, so no release is needed on this path. + if config_json.len() > MAX_CALL_PAYLOAD_BYTES { + return Err(JsErrorBox::type_error(format!( + "trigger config is {} bytes; the limit is {MAX_CALL_PAYLOAD_BYTES}", + config_json.len() + ))); + } + + let config: serde_json::Value = match serde_json::from_str(&config_json) { + Ok(v) => v, + Err(e) => { + return Err(JsErrorBox::type_error(format!( + "trigger config is not JSON: {e}" + ))) + } + }; + // The text copy is dead once parsed; free it before parking on the await. + drop(config_json); + + let engine = { + let mut borrowed = state.borrow_mut(); + let ops = borrowed.borrow_mut::(); + let held = ops.unregisters.lock().unwrap().len(); + if held + ops.pending_registrations >= MAX_REGISTRATIONS_PER_RUNTIME { + return Err(registration_cap_exceeded()); + } + // Reserve BEFORE the await below: without this, a tenant firing many + // un-awaited `registerTrigger()` calls at once could have all of + // them observe the same "under the cap" snapshot before any of them + // pushes into `unregisters` — the exact TOCTOU `inflight_calls` + // already guards against in `op_iii_call`. + ops.pending_registrations += 1; + ops.engine.clone() + }; + + let result = engine.register_trigger(config).await; + + let mut borrowed = state.borrow_mut(); + let ops = borrowed.borrow_mut::(); + ops.pending_registrations -= 1; + + let trigger_id = result.map_err(JsErrorBox::generic)?; + + let unregister_engine = ops.engine.clone(); + let unregister_id = trigger_id.clone(); + let unregister: UnregisterFn = Box::new(move || { + // `Engine::unregister_trigger` is async only to satisfy the trait — + // both implementations (`IIIEngine`, `FakeEngine`) resolve on their + // very first poll, with no real suspension inside (a lock and a map + // removal, nothing awaited) — so driving it here with a bare + // executor cannot block whichever thread calls this closure: the + // isolate thread (`op_iii_unregister_trigger`) or the manager's + // teardown drain (`RuntimeManager::destroy`), neither of which is + // otherwise inside an async fn. + let _ = futures::executor::block_on( + unregister_engine.unregister_trigger(unregister_id.clone()), + ); + }); + ops.unregisters.lock().unwrap().push(( + RegistrationKind::Trigger, + trigger_id.clone(), + unregister, + )); + + Ok(trigger_id) +} + +/// Remove a trigger this runtime registered. Trigger ids are UUIDs the +/// engine mints (`Engine::register_trigger`), never tenant-chosen — unlike +/// `op_iii_unregister`, there is no namespace to check: ownership is +/// entirely "does THIS runtime's own `unregisters` list contain it", which +/// is already all `OpsState::unregister` looks at. +#[op2(fast)] +fn op_iii_unregister_trigger( + state: &mut OpState, + #[string] trigger_id: String, +) -> Result<(), JsErrorBox> { + if trigger_id.len() > MAX_FUNCTION_ID_BYTES { + return Err(JsErrorBox::type_error(format!( + "trigger id is {} bytes; the limit is {MAX_FUNCTION_ID_BYTES}", + trigger_id.len() + ))); + } + state + .borrow_mut::() + .unregister(RegistrationKind::Trigger, &trigger_id); + Ok(()) +} + +/// Publish a trigger TYPE. Mirrors `op_iii_register` closely — same +/// namespace check, same shared cap, same claim-before-bus-write ordering — +/// because a trigger type's id lives in the SAME id space a function's does +/// (`require_own_namespace`), and `IIIClient::register_trigger_type` merely +/// overwrites a duplicate id rather than panicking the way +/// `register_function` does, which is proof against a same-process abort but +/// not against a SECOND runtime silently clobbering the first's handler. +/// +/// Unlike `op_iii_register`, a re-registration under an id THIS runtime +/// already holds is always a no-op rather than swapping in a new +/// description: the prelude's `registerTriggerType` updates the JS-side +/// `triggerTypes` map unconditionally on every call, and the proxy built +/// below looks that map up FRESH on every invocation (never a captured +/// function reference — see `prelude.js`'s `invoke`), so the existing bus +/// registration keeps routing to whatever handler is current without a +/// second `Engine::register_trigger_type` call. +/// ponytail: this drops the "swap in a new description on re-registration" +/// refinement `op_iii_register` has; add it if a trigger type's published +/// description ever needs to change after its first registration. +#[op2(fast)] +fn op_iii_register_trigger_type( + state: &mut OpState, + #[string] type_id: String, + #[string] description: String, +) -> Result<(), JsErrorBox> { + let ops = state.borrow_mut::(); + + if type_id.len() > MAX_FUNCTION_ID_BYTES { + return Err(JsErrorBox::type_error(format!( + "trigger type id is {} bytes; the limit is {MAX_FUNCTION_ID_BYTES}", + type_id.len() + ))); + } + if description.len() > MAX_DESCRIPTION_BYTES { + return Err(JsErrorBox::type_error(format!( + "description is {} bytes; the limit is {MAX_DESCRIPTION_BYTES}", + description.len() + ))); + } + + let type_id = require_own_namespace(&ops.namespace, type_id)?; + + let weak_tx = ops.command_tx.clone(); + let last_activity = ops.last_activity.clone(); + let timeout = std::time::Duration::from_millis(ops.invoke_timeout_ms); + let proxy_type_id = type_id.clone(); + let handler: ProxyHandler = Arc::new(move |payload: serde_json::Value| { + let weak_tx = weak_tx.clone(); + let last_activity = last_activity.clone(); + let type_id = proxy_type_id.clone(); + Box::pin(async move { + // `payload` is the ENGINE's own wrapper — `{method, id, + // function_id, config, metadata}` on the live path + // (`TriggerHandlerAdapter::payload` / `TriggerConfig`), or a + // subset of those keys from a test double. `method` selects + // which of the two guest methods `__iii.invoke` calls and is + // stripped out; every OTHER key is forwarded verbatim as that + // method's entire argument — `id` (which trigger instance) and + // `function_id` (which function to invoke) are exactly what a + // real `TriggerHandler` implementation needs and cannot recover + // from `config` alone (the tenant's own opaque blob). An earlier + // version of this forwarded `config` alone, verified against + // `FakeEngine::fire_trigger_type`'s narrower `{method, config}` + // shape — that made the test evidence about the fake, not the + // live wrapper `TriggerHandlerAdapter` actually sends. + let Some(obj) = payload.as_object() else { + return Err("trigger-type callback payload must be an object".to_string()); + }; + let Some(method) = obj.get("method").and_then(serde_json::Value::as_str) else { + return Err("trigger-type callback payload missing method".to_string()); + }; + let method = method.to_string(); + let mut forwarded = obj.clone(); + forwarded.remove("method"); + let forwarded = serde_json::Value::Object(forwarded); + + let Some(tx) = weak_tx.upgrade() else { + return Err(NodeEngineError::RuntimeGone(type_id).to_string()); + }; + let (reply, rx) = tokio::sync::oneshot::channel(); + if tx + .send(Command::Invoke { + fn_id: type_id.clone(), + payload: forwarded, + timeout, + reply, + method: Some(method), + }) + .is_err() + { + return Err(NodeEngineError::RuntimeGone(type_id).to_string()); + } + // Same rationale as `op_iii_register`'s proxy: this is the only + // place an INVOKE dispatched straight from the bus touches + // activity at all, and `invoke_timeout_ms` is far below + // `idle_ttl_secs`, so bumping at send is enough to cover the + // whole call. + *last_activity.lock().unwrap() = Instant::now(); + match rx.await { + Ok(result) => result.map_err(|e| e.to_string()), + Err(_) => Err(NodeEngineError::RuntimeGone(type_id).to_string()), + } + }) as BoxFuture<'static, CallResult> + }); + + { + let mut registrations = ops.unregisters.lock().unwrap(); + + if registrations + .iter() + .any(|(k, id, _)| *k == RegistrationKind::TriggerType && *id == type_id) + { + return Ok(()); + } + + if registrations.len() + ops.pending_registrations >= MAX_REGISTRATIONS_PER_RUNTIME { + return Err(registration_cap_exceeded()); + } + + // Claim before touching the bus — same reasoning as `op_iii_register`: + // nothing here proves `IIIClient::register_trigger_type` cannot be + // given the same duplicate-id guard treatment later, and claiming + // costs nothing when it already isn't needed for a crash. + if !ops.ids.claim(&type_id, &ops.runtime_id) { + return Err(JsErrorBox::generic( + NodeEngineError::IdTaken(type_id).message(), + )); + } + + let description = (!description.is_empty()).then_some(description); + let unregister = ops + .engine + .register_trigger_type(type_id.clone(), description, handler); + registrations.push((RegistrationKind::TriggerType, type_id.clone(), unregister)); + } + // Echoed back as `RunResponse.registered`/`EvalOutcome.registered` — the + // same delta functions already report. With one-shot `run` the default, + // this is often the only record a caller gets of what its eval + // published; omitting trigger types here would silently under-report it. + ops.registered + .push((RegistrationKind::TriggerType, type_id)); + Ok(()) +} + +/// Remove a trigger type this runtime registered. `type_id` is tenant-chosen +/// (`iii.unregisterTriggerType` takes it directly, not from a closure the +/// way a `registerFunction`/`registerTriggerType` ref's own `unregister()` +/// does), so — unlike `op_iii_unregister_trigger` — the namespace check here +/// is load-bearing, not merely defense-in-depth: without it a tenant could +/// name another namespace's id and learn (via the refusal shape) whether it +/// exists, the exact thing `require_own_namespace`'s shared refusal exists to +/// prevent for functions. +#[op2(fast)] +fn op_iii_unregister_trigger_type( + state: &mut OpState, + #[string] type_id: String, +) -> Result<(), JsErrorBox> { + if type_id.len() > MAX_FUNCTION_ID_BYTES { + return Err(JsErrorBox::type_error(format!( + "trigger type id is {} bytes; the limit is {MAX_FUNCTION_ID_BYTES}", + type_id.len() + ))); + } + unregister_checked( + state.borrow_mut::(), + RegistrationKind::TriggerType, + type_id, + ) +} + +// --------------------------------------------------------------------------- +// iii.files — this runtime's private scratch directory +// --------------------------------------------------------------------------- + +/// Cap on the tenant-supplied file NAME. +/// +/// This is a `#[string]`, so deno_core byte-copies it into an owned Rust +/// `String` at dispatch, before the op body runs — the hazard documented at +/// `MAX_ACTION_BYTES`. The check is still the first statement in every body +/// that takes one, matching `op_iii_call` and `op_iii_register`. +/// +/// Honest accounting of what this cap buys, because the `op_iii_call` +/// argument does NOT transfer: these ops are SYNCHRONOUS, so at most one copy +/// is ever live and it is dropped at the end of the body — unlike +/// `op_iii_call`, where 32 un-awaited calls pin 32 copies for a whole timeout +/// window. What it actually buys is a STABLE refusal: 255 is `NAME_MAX` on +/// every filesystem this ships to, so a name that passes here cannot be +/// refused later by the OS with a platform-dependent `ENAMETOOLONG` the guest +/// cannot act on. +const MAX_SCRATCH_NAME_BYTES: usize = 255; + +/// Windows device names, which the OS resolves as devices regardless of any +/// extension — `CON.txt` is still `CON`. +/// +/// Checked UNCONDITIONALLY, not behind `cfg(windows)`. This worker ships +/// `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc`, but CI runs Linux: +/// a `cfg(windows)` rule would be untested code on the only platform it +/// protects. The cost is that a Linux tenant cannot name a file `con.txt`. +const WINDOWS_RESERVED: &[&str] = &[ + "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", + "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", +]; + +/// Turn a tenant-supplied name into a host path inside this runtime's +/// directory, or refuse. +/// +/// The containment argument is STRUCTURAL, not a denylist: an accepted name is +/// exactly ONE path component drawn from a closed charset, so `root.join(name)` +/// has exactly one component below `root` and there is no intermediate +/// component for a symlink to redirect through. That is what makes the +/// leaf-only `O_NOFOLLOW` / `symlink_metadata` check at each open COMPLETE +/// rather than partial — `O_NOFOLLOW` refuses only the FINAL component, which +/// would be nearly worthless if `a/b/c` were expressible. +/// +/// The sibling python sandbox's escape came from the opposite posture: +/// cap-primitives rejects only *rooted* symlink targets, i.e. a denylist with +/// a hole. Do not loosen the charset. +fn scratch_path(root: &std::path::Path, name: &str) -> Result { + if name.len() > MAX_SCRATCH_NAME_BYTES { + return Err(JsErrorBox::type_error(format!( + "file name is {} bytes; max {MAX_SCRATCH_NAME_BYTES}", + name.len() + ))); + } + if name.is_empty() { + return Err(JsErrorBox::type_error("file name must not be empty")); + } + // One rule refuses, simultaneously: `/` and `\` (traversal and Windows + // separators), `\0` (C-string truncation), `:` (Windows alternate data + // streams and drive letters), whitespace and control characters (log + // forging), and every non-ASCII byte (Unicode normalization — on APFS and + // NTFS two different byte sequences can be the SAME file, which is both an + // aliasing bug and a way to exceed the entry cap with names that look + // distinct). + if !name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-') + { + return Err(JsErrorBox::type_error(format!( + "file name {name:?} may only contain letters, digits, '.', '_' and '-' — \ + it names one file in this runtime's private directory, not a path" + ))); + } + // `.` and `..` are entirely within the charset above, so the rule before + // this one does not catch them. + // + // This DELIBERATELY overlaps the trailing-dot rule below, which also + // refuses both (they end in `.`). Verified by mutation: disabling either + // rule alone leaves `..` refused; only disabling BOTH accepts it, which is + // what `traversal_names_are_refused` actually pins. The overlap is kept + // because the two rules guard different things and could plausibly be + // edited apart — the trailing-dot rule reads as a Windows nicety somebody + // might one day put behind `cfg(windows)`, at which point this rule is the + // only thing standing between a tenant and `..`. + if name == "." || name == ".." { + return Err(JsErrorBox::type_error(format!( + "file name {name:?} is a directory reference, not a file" + ))); + } + // Windows silently strips a trailing dot or space, so `a.` and `a` alias. + if name.ends_with('.') || name.ends_with(' ') { + return Err(JsErrorBox::type_error(format!( + "file name {name:?} must not end with '.' or a space — on Windows those are \ + stripped, so two different names would be the same file" + ))); + } + let stem = name.split('.').next().unwrap_or(name).to_ascii_lowercase(); + if WINDOWS_RESERVED.contains(&stem.as_str()) { + return Err(JsErrorBox::type_error(format!( + "file name {name:?} is a reserved device name on Windows" + ))); + } + // `Path::join` REPLACES the base when its argument is absolute: + // `root.join("/etc/passwd")` is `/etc/passwd`. The charset rule makes that + // unreachable — which is exactly why anyone loosening it must read this. + Ok(root.join(name)) +} + +/// What this runtime's directory currently holds, plus the size of the file a +/// write is about to replace. +struct ScratchUsage { + bytes: u64, + files: usize, + /// `Some` when `target` already exists — its current size, so an overwrite + /// does not double-count. + target_bytes: Option, +} + +/// Measure the directory. Derived per call rather than cached on `OpsState`: +/// a stored counter has to be maintained across create, overwrite, remove, and +/// a `write_all` that fails halfway leaving a partial file — each of those a +/// place to leak budget, and a leaked counter refuses every later write for +/// the life of the runtime. Cheap here specifically because the directory is +/// flat and capped at `scratch_max_files`, so this is a bounded stat scan. +/// +/// `DirEntry::metadata` deliberately: it does NOT traverse symlinks, so a +/// planted link contributes its own size rather than its target's. +/// +/// ponytail: O(entries) stat scan per write; cache a counter on `OpsState` if +/// a write-heavy workload ever shows it hot. +fn scan_scratch(root: &std::path::Path, target: &str) -> Result { + let mut usage = ScratchUsage { + bytes: 0, + files: 0, + target_bytes: None, + }; + let entries = std::fs::read_dir(root) + .map_err(|e| JsErrorBox::generic(format!("scratch directory is unreadable: {e}")))?; + for entry in entries.flatten() { + let Ok(md) = entry.metadata() else { continue }; + let len = md.len(); + usage.bytes += len; + usage.files += 1; + if entry.file_name() == std::ffi::OsStr::new(target) { + usage.target_bytes = Some(len); + } + } + Ok(usage) +} + +/// The refusal every mutating op gives once this runtime's directory is at its +/// cap. One function so the call sites cannot drift into different wordings +/// for what is, to a tenant, one cap — the same rationale +/// `registration_cap_exceeded` gives. +/// +/// Names the guest's own file name and the caps; NEVER the host path, which +/// would leak the temp token and the host layout into tenant code. +fn scratch_quota_exceeded(name: &str, max_bytes: u64, max_files: usize) -> JsErrorBox { + JsErrorBox::generic(format!( + "writing {name:?} would exceed this runtime's scratch quota \ + ({max_bytes} bytes across at most {max_files} files); remove a file first" + )) +} + +/// Borrow the scratch root, or refuse when the feature is off. +/// +/// Defence in depth: with `scratch_mb: 0` the guest surface is removed +/// entirely (see `runtime.rs`), so this refusal should be unreachable. +fn scratch_root(ops: &OpsState) -> Result<&std::path::Path, JsErrorBox> { + ops.scratch + .as_ref() + .map(|d| d.path()) + .ok_or_else(|| JsErrorBox::generic("iii.files is disabled on this deployment")) +} + +/// Open a file for reading, refusing anything that is not a regular file. +/// +/// `std::fs::File::open` follows symlinks and `std::fs::metadata` resolves +/// them, so both are wrong here: `symlink_metadata` answers "what is AT this +/// path". Refusing a non-regular file is not tidiness — `File::open` on a FIFO +/// blocks forever, the watchdog terminates at JS boundaries and cannot +/// interrupt a blocking syscall, and a wedged isolate thread then wedges +/// `RuntimeThread::Drop`'s join and every teardown queued behind it. +fn open_regular(path: &std::path::Path) -> Result { + let md = std::fs::symlink_metadata(path) + .map_err(|_| JsErrorBox::type_error("no such file in this runtime's scratch directory"))?; + if !md.is_file() { + return Err(JsErrorBox::type_error( + "that scratch entry is not a regular file", + )); + } + let mut open = std::fs::OpenOptions::new(); + open.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + open.custom_flags(libc::O_NOFOLLOW); + } + open.open(path) + .map_err(|e| JsErrorBox::generic(format!("scratch read failed: {e}"))) +} + +/// Write (or overwrite) one file in this runtime's private directory. +/// +/// `contents` is `#[buffer] &[u8]`: a ZERO-COPY view of the `Uint8Array`'s +/// backing store, NOT an owned Rust copy. Those bytes were allocated by +/// `crate::allocator`'s capped `v8::Allocator` and are already charged against +/// `external_mb`, so there is no Rust-heap byte cap to add here — the quota +/// below is about DISK. Do NOT "simplify" this to `#[buffer(copy)] Vec` or +/// `#[string] String`: either reintroduces the exact off-heap copy +/// `MAX_CALL_PAYLOAD_BYTES` exists to bound, at a far larger size. +/// +/// Sync, and it must stay sync. An `.await` between the scan and the write is +/// precisely the TOCTOU that forced `pending_registrations` into existence: a +/// tenant firing 100 un-awaited writes would have all 100 observe the same +/// under-quota snapshot. Sync makes that unrepresentable rather than defended. +/// +/// ponytail: the watchdog's `terminate_execution` cannot interrupt a blocking +/// syscall, so a pathologically slow `$TMPDIR` extends a runtime past its +/// deadline by one write. Bounded because the write is size-capped and +/// `open_regular` refuses the two things that block unboundedly. Upgrade path +/// is `spawn_blocking` plus a reservation counter; not before a slow-storage +/// deployment actually appears. +#[op2(fast)] +fn op_iii_fs_write( + state: &mut OpState, + #[string] name: String, + #[buffer] contents: &[u8], +) -> Result<(), JsErrorBox> { + let ops = state.borrow_mut::(); + if name.len() > MAX_SCRATCH_NAME_BYTES { + return Err(JsErrorBox::type_error(format!( + "file name is {} bytes; max {MAX_SCRATCH_NAME_BYTES}", + name.len() + ))); + } + let max_bytes = ops.scratch_max_bytes; + let max_files = ops.scratch_max_files; + let root = scratch_root(ops)?.to_path_buf(); + let path = scratch_path(&root, &name)?; + + let usage = scan_scratch(&root, &name)?; + let projected_bytes = usage.bytes - usage.target_bytes.unwrap_or(0) + contents.len() as u64; + let projected_files = usage.files + usize::from(usage.target_bytes.is_none()); + // Checked BEFORE the truncating open, so a refusal is non-destructive: the + // previous contents are still there. + if projected_bytes > max_bytes || projected_files > max_files { + return Err(scratch_quota_exceeded(&name, max_bytes, max_files)); + } + + let mut open = std::fs::OpenOptions::new(); + open.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + open.custom_flags(libc::O_NOFOLLOW); + } + let mut f = open + .open(&path) + .map_err(|e| JsErrorBox::generic(format!("scratch write failed: {e}")))?; + std::io::Write::write_all(&mut f, contents) + .map_err(|e| JsErrorBox::generic(format!("scratch write failed: {e}"))) +} + +/// Read one file back. +/// +/// Plain `#[op2]`, not `(fast)`: a fastcall cannot allocate a return buffer. +/// `#[buffer] Vec` copies into a fresh `Uint8Array` through the capped +/// allocator, so the result is charged against `external_mb` like any other +/// guest buffer, and it is bounded by the total-bytes quota — nothing in the +/// directory can exceed it. +#[op2] +#[buffer] +fn op_iii_fs_read(state: &mut OpState, #[string] name: String) -> Result, JsErrorBox> { + let ops = state.borrow_mut::(); + if name.len() > MAX_SCRATCH_NAME_BYTES { + return Err(JsErrorBox::type_error(format!( + "file name is {} bytes; max {MAX_SCRATCH_NAME_BYTES}", + name.len() + ))); + } + let cap = ops.scratch_max_bytes; + let root = scratch_root(ops)?.to_path_buf(); + let path = scratch_path(&root, &name)?; + let f = open_regular(&path)?; + let mut buf = Vec::new(); + // Belt-and-braces against a file grown out-of-band between the stat and + // the open; the quota already bounds anything this runtime wrote. + std::io::Read::read_to_end(&mut std::io::Read::take(f, cap + 1), &mut buf) + .map_err(|e| JsErrorBox::generic(format!("scratch read failed: {e}")))?; + Ok(buf) +} + +/// Every file and its size, as JSON text — the same +/// one-representation-across-the-boundary rule `op_iii_call` states. Bounded +/// by construction: at most `scratch_max_files` entries of at most +/// `MAX_SCRATCH_NAME_BYTES` plus a number each. +/// +/// This is the one DISCRETIONARY op. `keep` works without it. It is here +/// because it is the only way for a guest to observe its own quota state, +/// which turns "write refused" from a mystery into something a tenant can +/// handle — and because it is the scan the write path already computes. +#[op2] +#[string] +fn op_iii_fs_list(state: &mut OpState) -> Result { + let ops = state.borrow_mut::(); + let root = scratch_root(ops)?.to_path_buf(); + let entries = std::fs::read_dir(&root) + .map_err(|e| JsErrorBox::generic(format!("scratch directory is unreadable: {e}")))?; + let mut out: Vec = Vec::new(); + for entry in entries.flatten() { + let Ok(md) = entry.metadata() else { continue }; + if !md.is_file() { + continue; + } + let Ok(name) = entry.file_name().into_string() else { + continue; + }; + out.push(serde_json::json!({ "name": name, "bytes": md.len() })); + } + out.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); + serde_json::to_string(&out) + .map_err(|e| JsErrorBox::generic(format!("scratch listing failed: {e}"))) +} + +/// Remove one file. Idempotent: removing a name that is not there is a quiet +/// success, the same shape `OpsState::unregister` chose. +/// +/// NOT optional. Without it a long-lived runtime — which is the entire point +/// of `keep` — can only ever approach its cap and never retreat from it. The +/// first tenant to fill the quota would have permanently bricked its own +/// runtime with no recovery short of teardown: a self-inflicted denial of +/// service shipped by omission. +#[op2(fast)] +fn op_iii_fs_remove(state: &mut OpState, #[string] name: String) -> Result<(), JsErrorBox> { + let ops = state.borrow_mut::(); + if name.len() > MAX_SCRATCH_NAME_BYTES { + return Err(JsErrorBox::type_error(format!( + "file name is {} bytes; max {MAX_SCRATCH_NAME_BYTES}", + name.len() + ))); + } + let root = scratch_root(ops)?.to_path_buf(); + let path = scratch_path(&root, &name)?; + match std::fs::remove_file(&path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(JsErrorBox::generic(format!("scratch remove failed: {e}"))), + } +} + +extension!( + node_engine_ext, + ops = [ + op_iii_log, + op_iii_call, + op_iii_register, + op_iii_unregister, + op_iii_register_trigger, + op_iii_unregister_trigger, + op_iii_register_trigger_type, + op_iii_unregister_trigger_type, + op_iii_fs_write, + op_iii_fs_read, + op_iii_fs_list, + op_iii_fs_remove, + ], + options = { state: OpsState }, + state = |op_state: &mut OpState, options| { + op_state.put::(options.state); + }, +); + +/// Reads the ops state out of a runtime's `OpState`. Used by the isolate loop +/// to take the per-eval log buffer and registration delta. +pub fn with_ops_state(op_state: &Rc>, f: impl FnOnce(&mut OpsState) -> R) -> R { + let mut borrowed = op_state.borrow_mut(); + f(borrowed.borrow_mut::()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::engine::FakeEngine; + + /// A minimal but real `OpsState` for one runtime — no isolate involved. + /// `unregisters`/`ids` are fresh per call, matching `RuntimeThread::spawn` + /// (see the module doc on `OpsState::unregister`): two calls with the + /// same `runtime_id` do NOT share state, exactly as two real runtimes + /// never do either. + fn test_ops(namespace: &str, runtime_id: &str, engine: Arc) -> OpsState { + let (tx, _rx) = mpsc::unbounded_channel(); + OpsState { + engine, + namespace: namespace.to_string(), + logs: Vec::new(), + log_bytes: 0, + log_truncated: false, + detached_log_bytes: 0, + capturing: false, + registered: Vec::new(), + unregisters: Arc::new(Mutex::new(Vec::new())), + pending_registrations: 0, + ids: crate::ids::IdRegistry::default(), + runtime_id: runtime_id.to_string(), + call_timeout_ms: 2_000, + max_timeout_ms: 10_000, + inflight_calls: 0, + command_tx: tx.downgrade(), + invoke_timeout_ms: 2_000, + last_activity: Arc::new(Mutex::new(Instant::now())), + scratch: None, + scratch_max_bytes: 0, + scratch_max_files: 0, + } + } + + fn noop_handler() -> ProxyHandler { + Arc::new(|_| Box::pin(async { Ok(serde_json::json!(null)) })) + } + + /// The mutation this guards against: deleting the `require_own_namespace` + /// call from `unregister_checked`. See that function's doc comment for + /// why a JS-level eval test cannot reach this line — the guest surface + /// never hands `op_iii_unregister` a foreign id, so only a direct call + /// can prove the check itself refuses one. + #[test] + fn a_runtime_cannot_unregister_another_runtimes_function() { + let fake = FakeEngine::new(); + // Stands in for "victim::" having registered it — going straight to + // `Engine::register` rather than through `op_iii_register`, since + // only the removal path is under test here. + let _ = fake.register( + "victim::secret".to_string(), + None, + None, + None, + noop_handler(), + ); + assert!(fake + .registered_ids() + .contains(&"victim::secret".to_string())); + + let mut attacker = test_ops("attacker::", "rt-attacker", fake.clone()); + let err = unregister_checked( + &mut attacker, + RegistrationKind::Function, + "victim::secret".to_string(), + ) + .unwrap_err(); + assert!( + err.to_string().contains("victim::secret"), + "expected a namespace refusal naming the id: {err}" + ); + assert!( + fake.registered_ids() + .contains(&"victim::secret".to_string()), + "the victim's function was removed by another runtime" + ); + + // "Not yours" and "not there" must be indistinguishable: an id that + // was never registered anywhere gets the identical refusal shape — + // derived independently here, not by editing the string above — so + // the op cannot be used to probe which ids are live elsewhere. + let missing = unregister_checked( + &mut attacker, + RegistrationKind::Function, + "victim::never-existed".to_string(), + ) + .unwrap_err(); + let expected = |id: &str| { + NodeEngineError::NamespaceDenied { + id: id.to_string(), + namespace: "attacker::".to_string(), + } + .message() + }; + assert_eq!(err.to_string(), expected("victim::secret")); + assert_eq!(missing.to_string(), expected("victim::never-existed")); + } + + /// A runtime unregistering its own, actually-live id succeeds and the + /// engine forgets it. + #[test] + fn unregister_checked_removes_a_registration_the_runtime_owns() { + let fake = FakeEngine::new(); + let mut ops = test_ops("app::", "rt-owner", fake.clone()); + let unregister = fake.register("app::mine".to_string(), None, None, None, noop_handler()); + ops.unregisters.lock().unwrap().push(( + RegistrationKind::Function, + "app::mine".to_string(), + unregister, + )); + ops.ids.claim("app::mine", "rt-owner"); + + unregister_checked( + &mut ops, + RegistrationKind::Function, + "app::mine".to_string(), + ) + .unwrap(); + + assert!(!fake.registered_ids().contains(&"app::mine".to_string())); + assert!( + ops.ids.claim("app::mine", "someone-else"), + "the id should be free again after unregister" + ); + } + + /// Unregistering an id inside your own namespace that was never + /// registered is a quiet no-op, not an error — the same idempotent shape + /// `op_iii_register` gives a re-registration. + #[test] + fn unregister_checked_is_a_no_op_for_an_unknown_id_in_your_own_namespace() { + let fake = FakeEngine::new(); + let mut ops = test_ops("app::", "rt-owner", fake.clone()); + unregister_checked( + &mut ops, + RegistrationKind::Function, + "app::never-registered".to_string(), + ) + .unwrap(); + } + + /// CRITICAL (Task 12 review, round 2): a cross-kind unregister — asking + /// to remove a TRIGGER TYPE at an id that is actually a live FUNCTION — + /// must leave that function's bus registration AND its worker-global + /// `ids` claim alone. Before this fix, `OpsState::unregister` found + /// nothing to remove from the bus (correct) but still released the + /// claim unconditionally (wrong): a second runtime could then claim the + /// same id and reach `Engine::register` on a duplicate, which aborts the + /// process (see `ids.rs`'s module doc). + #[test] + fn cross_kind_unregister_does_not_release_a_live_registrations_claim() { + let fake = FakeEngine::new(); + let mut ops = test_ops("app::", "rt-owner", fake.clone()); + let unregister = fake.register("app::x".to_string(), None, None, None, noop_handler()); + ops.unregisters.lock().unwrap().push(( + RegistrationKind::Function, + "app::x".to_string(), + unregister, + )); + ops.ids.claim("app::x", "rt-owner"); + + // No trigger type was ever registered at this id — this must be a + // pure no-op. + ops.unregister(RegistrationKind::TriggerType, "app::x"); + + assert!( + fake.registered_ids().contains(&"app::x".to_string()), + "the live function was removed from the bus by an unrelated unregister" + ); + assert!( + !ops.ids.claim("app::x", "rt-other"), + "a live registration's claim was released by an unrelated unregister" + ); + } + + /// A tenant CAN register a function and a trigger type under the + /// identical literal id — nothing stops them. Unregistering ONE must not + /// release the claim while the OTHER is still live; only once NOTHING + /// remains under that id does the claim actually free up. + #[test] + fn unregistering_one_kind_does_not_release_the_claim_while_another_kind_shares_the_id() { + let fake = FakeEngine::new(); + let mut ops = test_ops("app::", "rt-owner", fake.clone()); + let unregister_fn = fake.register("app::x".to_string(), None, None, None, noop_handler()); + let unregister_type = fake.register("app::x".to_string(), None, None, None, noop_handler()); + { + let mut regs = ops.unregisters.lock().unwrap(); + regs.push(( + RegistrationKind::Function, + "app::x".to_string(), + unregister_fn, + )); + regs.push(( + RegistrationKind::TriggerType, + "app::x".to_string(), + unregister_type, + )); + } + ops.ids.claim("app::x", "rt-owner"); + + ops.unregister(RegistrationKind::TriggerType, "app::x"); + assert!( + !ops.ids.claim("app::x", "rt-other"), + "the claim was released while the function under the same id is still live" + ); + + ops.unregister(RegistrationKind::Function, "app::x"); + assert!( + ops.ids.claim("app::x", "rt-other"), + "the claim should free once nothing remains registered under this id" + ); + } +} + +#[cfg(test)] +mod scratch_tests { + use super::*; + + fn root() -> tempfile::TempDir { + tempfile::Builder::new() + .prefix("node-core-test-") + .tempdir() + .expect("tempdir") + } + + /// Every accepted name must be exactly one component. + /// + /// Mutation, established by running it: deleting the `.`/`..` rule ALONE + /// leaves this green, because `.` and `..` both end in `.` and the + /// trailing-dot rule catches them too. The mutation this actually + /// discriminates is deleting BOTH — which is the honest claim, and the + /// reason the overlap is documented at the rule rather than left to look + /// accidental. The assertion on `root.parent()` is what proves a mutant + /// escapes rather than merely differing. + #[test] + fn traversal_names_are_refused() { + let d = root(); + for name in ["..", ".", "../etc/passwd", "a/../b"] { + assert!( + scratch_path(d.path(), name).is_err(), + "accepted traversal name {name:?}" + ); + } + assert!( + !d.path().parent().unwrap().join("etc").exists(), + "nothing may have been created outside the scratch root" + ); + } + + /// Mutation: replace the charset allowlist with `!name.contains("..")` — + /// the reasonable-looking rewrite. `foo/bar` then passes and `root.join` + /// yields a path one directory down. + #[test] + fn separators_are_refused() { + let d = root(); + for name in ["foo/bar", "foo\\bar", "a:b", "a\u{0}b", "a b", "a\nb"] { + assert!( + scratch_path(d.path(), name).is_err(), + "accepted name containing a separator or control char: {name:?}" + ); + } + } + + /// `Path::join` REPLACES the base when its argument is absolute, so a + /// mutant that allows `/` reads the host's passwd file rather than a file + /// in the scratch directory. Mutation: add `b'/'` to the charset. + #[test] + fn absolute_names_are_refused() { + let d = root(); + for name in ["/etc/passwd", "C:\\Windows", "\\\\server\\share"] { + assert!( + scratch_path(d.path(), name).is_err(), + "accepted absolute name {name:?}" + ); + } + } + + /// Unconditional, not `cfg(windows)`: CI runs Linux, and a + /// `cfg(windows)` rule would be untested code on the only platform it + /// protects. Mutation: delete the reserved-name rule. + #[test] + fn windows_device_names_are_refused() { + let d = root(); + for name in ["CON", "con.txt", "COM1", "nul", "LPT9.log", "a.", "a "] { + assert!( + scratch_path(d.path(), name).is_err(), + "accepted reserved or alias-prone name {name:?}" + ); + } + assert!(scratch_path(d.path(), "console.txt").is_ok()); + } + + /// Non-ASCII is refused because on APFS and NTFS two different byte + /// sequences can be the SAME file — an aliasing bug and a way to exceed + /// the entry cap with names that look distinct. Mutation: allow + /// `!b.is_ascii()`. + #[test] + fn non_ascii_names_are_refused() { + let d = root(); + assert!(scratch_path(d.path(), "café.txt").is_err()); + assert!(scratch_path(d.path(), "cafe.txt").is_ok()); + } + + /// Asserting only "it threw" would pass against a mutant with no length + /// check at all, because the OS answers `ENAMETOOLONG`. The message must + /// name the limit. Mutation: delete the length check. + #[test] + fn an_oversized_name_names_the_limit() { + let d = root(); + let long = "x".repeat(MAX_SCRATCH_NAME_BYTES + 1); + let err = scratch_path(d.path(), &long).unwrap_err().to_string(); + assert!( + err.contains(&MAX_SCRATCH_NAME_BYTES.to_string()), + "refusal must name the limit, got: {err}" + ); + } + + /// Host-side, because no guest op can plant a link — which is exactly why + /// the guard looks like dead code and gets deleted without this test. + /// Mutation: replace `open_regular`'s `symlink_metadata`/`is_file` guard + /// with a bare `File::open`; the host then reads the link's target. + #[cfg(unix)] + #[test] + fn a_planted_symlink_is_not_read_through() { + let d = root(); + let bait = d.path().parent().unwrap().join("node-core-bait.txt"); + std::fs::write(&bait, b"ESCAPED").expect("write bait"); + std::os::unix::fs::symlink(&bait, d.path().join("link.txt")).expect("plant link"); + + let err = open_regular(&d.path().join("link.txt")) + .expect_err("a symlink must be refused, not followed"); + assert!(!err.to_string().contains("ESCAPED")); + let _ = std::fs::remove_file(&bait); + } + + /// `File::open` on a FIFO blocks forever, the watchdog terminates only at + /// JS boundaries, and a wedged isolate thread then wedges every teardown + /// queued behind it. Run on its own thread with a bounded wait, because + /// the mutant HANGS rather than failing — and a hanging test is a bad + /// test. Mutation: weaken the guard to "not a symlink". + #[cfg(unix)] + #[test] + fn a_fifo_is_refused_rather_than_opened() { + let d = root(); + let fifo = d.path().join("pipe"); + let c = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0, "mkfifo"); + + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(open_regular(&fifo).is_err()); + }); + match rx.recv_timeout(std::time::Duration::from_secs(5)) { + Ok(refused) => assert!(refused, "a FIFO must be refused"), + Err(_) => panic!("open_regular blocked on a FIFO instead of refusing"), + } + } + + /// The `- target_bytes` term is the most easily-omitted line in the quota + /// projection. Mutation: drop it, and the second same-size overwrite of a + /// nearly-full directory is refused. + #[test] + fn scanning_reports_the_target_size_for_an_overwrite() { + let d = root(); + std::fs::write(d.path().join("a.txt"), b"0123456789").unwrap(); + std::fs::write(d.path().join("b.txt"), b"012").unwrap(); + + let u = scan_scratch(d.path(), "a.txt").unwrap(); + assert_eq!(u.bytes, 13); + assert_eq!(u.files, 2); + assert_eq!(u.target_bytes, Some(10)); + + let fresh = scan_scratch(d.path(), "new.txt").unwrap(); + assert_eq!(fresh.target_bytes, None, "an absent target has no size"); + } +} diff --git a/crates/node-core/src/prelude.js b/crates/node-core/src/prelude.js new file mode 100644 index 0000000000..c31fab4795 --- /dev/null +++ b/crates/node-core/src/prelude.js @@ -0,0 +1,552 @@ +"use strict"; +((globalThis) => { + const handlers = new Map(); + // Trigger-type handlers, keyed by the type id — the guest-side half of + // `iii.registerTriggerType`. Looked up FRESH on every `invoke()` call, the + // same as `handlers` is for functions, so a re-registration under the same + // id (prelude-side `.set()`, no new bus write — see `op_iii_register_trigger_type`) + // is picked up by whichever engine-side proxy is already routing there. + const triggerTypes = new Map(); + // The only two method names `invoke()` may ever look up on a trigger-type + // handler object. `target[method]` would otherwise be an unguarded + // property lookup on tenant-shaped data driven by an engine-supplied + // string — not reachable today (the adapter only ever sends one of these + // two literals), but "constructor"/"valueOf"/etc. would resolve through + // `Object.prototype` and pass the `typeof fn === "function"` gate below. + const TRIGGER_TYPE_METHODS = new Set(["registerTrigger", "unregisterTrigger"]); + + function formatError(e) { + if (e instanceof Error) { + return e.stack ? String(e.stack) : `${e.name}: ${e.message}`; + } + try { + return String(e); + } catch { + return "unstringifiable thrown value"; + } + } + + // `formatError` without the stack. A handler that fails at DEFINITION time + // has a stack made entirely of prelude internals — `Array.map`, the + // generated `[code-runner:eval]` wrapper, `toHandler` itself. None of it is + // the caller's code, none of it is actionable, and it buries the one line + // that is. Runtime errors keep their stack: that one points at tenant code. + function formatCause(e) { + if (e instanceof Error) { + return `${e.name}: ${e.message}`; + } + try { + return String(e); + } catch { + return "unstringifiable thrown value"; + } + } + + // A definition error carries its message and nothing else, for the same + // reason. Overwriting `stack` is what makes `settle`'s `formatError` — which + // prefers `e.stack` — report just the message. + function definitionError(message) { + const e = new Error(message); + e.stack = `Error: ${message}`; + return e; + } + + // The envelope builders, captured before any tenant code can run. + // + // `settle`'s return value IS the eval's result as Rust reads it, so anything + // it resolves off the global at call time is a way to forge that envelope. + // Overwriting `JSON.stringify` turned a thrown error into a reported + // success; replacing `globalThis.Promise` — or `Promise.prototype.then` — + // let `.then()` return a hand-written envelope string instead of a promise. + // `__iii` being frozen does not help: these are the primitives `settle` + // itself is built from. + const stringify = JSON.stringify; + const resolvePromise = Promise.resolve.bind(Promise); + const thenPromise = Function.prototype.call.bind(Promise.prototype.then); + + // Every value leaving the isolate goes through here: one promise in, one + // promise of `{"ok":...}` / `{"err":"..."}` JSON text out. + // + // Values JSON cannot represent come back as ok:null rather than turning a + // successful run into an error. Two different failures produce that: + // `stringify` THROWS on a cycle or a BigInt, but for a function, a symbol, + // or an object whose `toJSON` returns undefined it returns `undefined` + // instead — and stringifying `{ok: v}` in one step hides that, because a + // dropped property yields `{}`, an envelope carrying neither key. So + // stringify the VALUE alone, where unrepresentable is observable, and build + // the envelope around the text. + function settle(promise) { + return thenPromise( + resolvePromise(promise), + (v) => { + try { + const encoded = v === undefined ? "null" : stringify(v); + return encoded === undefined ? '{"ok":null}' : `{"ok":${encoded}}`; + } catch { + return '{"ok":null}'; + } + }, + (e) => `{"err":${stringify(formatError(e))}}`, + ); + } + + // `id` resolves against `handlers` for a plain function invocation, or + // against `triggerTypes` (picking one of its two methods by name) when + // `method` is given — the same envelope-producing path now serves both + // directions the engine calls INTO the isolate. + // + // Returns a promise/value for `wrap_invoke`'s OWN `settle(...)` to consume + // — it must NOT call `settle` itself. `wrap_invoke` always generates + // `globalThis.__iii.settle(globalThis.__iii.invoke(...))`; settling here + // too would hand that outer `settle` an already-encoded envelope STRING to + // re-stringify, corrupting every response (`{"ok":"{\"ok\":...}"}`). + // + // The missing-handler case is raised through a promise rejection, not a + // synchronous throw, so a handler that itself throws synchronously and a + // missing handler both fail identically for whichever caller is awaiting + // this — `wrap_invoke`'s bare (non-async-IIFE) call site would otherwise + // let a synchronous throw here escape `execute_script` before `settle` is + // ever reached. + // + // Uses the pre-captured `thenPromise`, NOT `.then()`/`Promise.prototype. + // then` directly: this is the ENGINE calling INTO the isolate through a + // path `settle` cannot see, so a tenant that overwrote `Promise.prototype. + // then` before this runs would otherwise have its replacement invoked + // here, forging whatever this resolves to (e.g. turning a handler that + // throws into a reported success) — the exact class of hijack `stringify`/ + // `resolvePromise`/`thenPromise` are captured above to prevent, and the + // reason those three are named specifically in that block's comment. + function invoke(id, payloadJson, method) { + const target = method ? triggerTypes.get(id) : handlers.get(id); + const fn = !method ? target : TRIGGER_TYPE_METHODS.has(method) ? target && target[method] : undefined; + if (typeof fn !== "function") { + return thenPromise(resolvePromise(undefined), () => { + throw definitionError(`no handler registered for ${id}${method ? `.${method}` : ""}`); + }); + } + return thenPromise(resolvePromise(JSON.parse(payloadJson)), (p) => fn(p)); + } + + const { + op_iii_log, + op_iii_call, + op_iii_register, + op_iii_unregister, + op_iii_register_trigger, + op_iii_unregister_trigger, + op_iii_register_trigger_type, + op_iii_unregister_trigger_type, + op_iii_fs_write, + op_iii_fs_read, + op_iii_fs_list, + op_iii_fs_remove, + } = Deno.core.ops; + + // V8's own UTF-8 codec, captured here for the same reason the ops are: + // `Deno` is deleted before tenant code runs. Hand-rolling a UTF-8 encoder + // in this file would be the flimsy-algorithm trap — surrogate pairs are + // exactly where it goes wrong. + const { encode: utf8Encode, decode: utf8Decode } = Deno.core; + + function formatArg(a) { + if (typeof a === "string") return a; + if (a instanceof Error) return a.stack ? String(a.stack) : String(a); + try { + const s = JSON.stringify(a); + return s === undefined ? String(a) : s; + } catch { + return String(a); + } + } + + function emit(level) { + return (...args) => op_iii_log(level, args.map(formatArg).join(" ")); + } + + // Replaces deno_core's console, which writes to the process stdout. Ours + // routes into the eval's response instead. + globalThis.console = { + log: emit("log"), + info: emit("log"), + debug: emit("log"), + warn: emit("warn"), + error: emit("error"), + trace: emit("warn"), + }; + + // The SDK's request-object form: `iii.trigger({function_id, payload})`. + // `action` routes the call (omit for request/response); `timeout` is a + // per-call millisecond budget clamped by the host. + async function trigger(request) { + if (request === null || typeof request !== "object") { + throw new TypeError("trigger(request): request must be an object"); + } + const { function_id, payload, action, timeout } = request; + if (typeof function_id !== "string" || function_id.length === 0) { + throw new TypeError("trigger(request): function_id must be a non-empty string"); + } + if (action !== undefined && typeof action !== "string") { + throw new TypeError("trigger(request): action must be a string when given"); + } + if (timeout !== undefined && typeof timeout !== "number") { + throw new TypeError("trigger(request): timeout must be a number when given"); + } + // `stringify` is the pre-captured `JSON.stringify` — see the block above + // where it is captured, before any tenant code can run. This value + // crosses into Rust, so the global (tenant-replaceable) one is never + // safe to use here. + const text = await op_iii_call( + function_id, + stringify(payload === undefined ? {} : payload), + action === undefined ? "" : action, + timeout === undefined ? 0 : timeout, + ); + return JSON.parse(text); + } + + // SDK signature: (functionId, handler, options?). `options.description` is + // what `engine::functions::info` shows a caller; omitted sends "", which + // Rust reads as "not supplied" and replaces with a generic default. + function registerFunction(functionId, handler, options) { + if (typeof functionId !== "string" || functionId.length === 0) { + throw new TypeError( + "registerFunction(functionId, handler, options?): functionId must be a non-empty string", + ); + } + if (typeof handler !== "function") { + throw new TypeError( + "registerFunction(functionId, handler, options?): handler must be a function — an " + + "HttpInvocationConfig object registers an engine-side HTTP binding with no isolate " + + "involved, which code-runner does not publish; call engine::functions::register for that", + ); + } + if (options !== undefined && (options === null || typeof options !== "object")) { + throw new TypeError( + "registerFunction(functionId, handler, options?): options must be an object when given", + ); + } + const description = options === undefined ? undefined : options.description; + if (description !== undefined && typeof description !== "string") { + throw new TypeError( + "registerFunction(functionId, handler, options?): options.description must be a string", + ); + } + // `request_format`/`response_format` are JSON Schemas for the catalog — + // engine::functions::info shows them to the next caller in place of + // "any". Checked here as plain objects for a good error early; the op + // re-validates either way (this check runs on tenant-replaceable + // builtins, the op's does not). + const formats = []; + for (const name of ["request_format", "response_format"]) { + const value = options === undefined ? undefined : options[name]; + if (value !== undefined && (value === null || typeof value !== "object" || Array.isArray(value))) { + throw new TypeError( + `registerFunction(functionId, handler, options?): options.${name} must be a plain object holding a JSON Schema`, + ); + } + const encoded = value === undefined ? "" : stringify(value); + if (typeof encoded !== "string") { + throw new TypeError( + `registerFunction(functionId, handler, options?): options.${name} did not survive JSON encoding`, + ); + } + formats.push(encoded); + } + op_iii_register(functionId, description === undefined ? "" : description, formats[0], formats[1]); + handlers.set(functionId, handler); + return { + unregister() { + op_iii_unregister(functionId); + handlers.delete(functionId); + }, + }; + } + + // Bind a trigger to a registered function. Returns a ref whose + // `unregister()` removes it — the SDK shape, mirroring `registerFunction`. + async function registerTrigger(input) { + if (input === null || typeof input !== "object") { + throw new TypeError("registerTrigger(input): input must be an object"); + } + if (typeof input.type !== "string" || input.type.length === 0) { + throw new TypeError("registerTrigger(input): input.type must be a non-empty string"); + } + if (typeof input.function_id !== "string" || input.function_id.length === 0) { + throw new TypeError("registerTrigger(input): input.function_id must be a non-empty string"); + } + // Pre-captured `stringify` — see the block above where it, `resolvePromise`, + // and `thenPromise` are captured before any tenant code can run. This + // value crosses into Rust, so the global (tenant-replaceable) one is + // never safe to use here. + const triggerId = await op_iii_register_trigger(stringify(input)); + return { + unregister() { + op_iii_unregister_trigger(triggerId); + }, + }; + } + + // Publish a trigger TYPE. `handler` is an object the ENGINE calls back + // into: `handler.registerTrigger(config)` / `handler.unregisterTrigger(config)` + // run whenever a trigger of this type is registered or removed anywhere on + // the bus. This is the one direction that isn't isolate -> host: the proxy + // built on the Rust side (`op_iii_register_trigger_type`) dispatches back + // in through `__iii.invoke`, the same path a registered function's handler + // already uses. + function registerTriggerType(triggerType, handler) { + if (triggerType === null || typeof triggerType !== "object") { + throw new TypeError("registerTriggerType(triggerType, handler): triggerType must be an object"); + } + if (typeof triggerType.id !== "string" || triggerType.id.length === 0) { + throw new TypeError("registerTriggerType(triggerType, handler): triggerType.id must be a non-empty string"); + } + if (handler === null || typeof handler !== "object") { + throw new TypeError("registerTriggerType(triggerType, handler): handler must be an object"); + } + if (typeof handler.registerTrigger !== "function" || typeof handler.unregisterTrigger !== "function") { + throw new TypeError( + "registerTriggerType(triggerType, handler): handler must have registerTrigger and unregisterTrigger methods", + ); + } + op_iii_register_trigger_type( + triggerType.id, + typeof triggerType.description === "string" ? triggerType.description : "", + ); + triggerTypes.set(triggerType.id, handler); + return { + unregister() { + op_iii_unregister_trigger_type(triggerType.id); + triggerTypes.delete(triggerType.id); + }, + }; + } + + function unregisterTriggerType(triggerType) { + const id = typeof triggerType === "string" ? triggerType : triggerType && triggerType.id; + if (typeof id !== "string" || id.length === 0) { + throw new TypeError("unregisterTriggerType(triggerType): pass the type id or the type object"); + } + op_iii_unregister_trigger_type(id); + triggerTypes.delete(id); + } + + // A real property, not a missing one: the iii-sdk client this shim mirrors + // owns the connection it closes, but here the connection belongs to the + // WORKER, shared by every namespace runtime on it — severing it would be a + // cross-tenant denial of service. Throwing names the actual way to dispose + // a runtime, instead of leaving tenant code to puzzle out + // "undefined is not a function". + function shutdown() { + throw new Error( + "iii.shutdown() is not available in a code-runner runtime — the engine " + + "connection belongs to the worker and is shared by every runtime. Use " + + "code-runner::teardown to dispose this runtime.", + ); + } + + // An agent's first move against an unknown global is printing it or + // listing its keys; an opaque `{}` there previously cost a live session + // (in the sibling sandbox-code-runner worker) six blind runs before anyone + // worked out what the global even was. `String(iii)` and Node's inspect + // both answer with this instead. + const HINT = + "[iii: code-runner host client. e.g. await iii.trigger({ function_id: 'worker::fn', " + + "payload: {} }); registerFunction(id, handler, opts?); iii.namespace is the prefix this " + + "runtime may register under. iii.files is a private scratch directory " + + "(write/read/readText/list/remove) that lives as long as this runtime. " + + "docs ]"; + + // This runtime's private scratch directory. Flat — a name is one file, never + // a path — and bounded by the operator's `scratch_mb`/`scratch_files`. The + // directory dies with the runtime, so it is what makes a kept runtime's + // files outlive a single eval and nothing more. + // + // Frozen HERE, separately from the `Object.freeze(globalThis.iii)` that + // runtime.rs applies: that freeze is SHALLOW, so it pins the `files` + // property but not the object behind it. Two freezes, two different jobs. + // + // Honest about the stakes, so nobody overclaims in review: unlike `settle`, + // nothing the HOST reads comes back through `iii.files`, so a tenant that + // forged a method here would only be lying to itself. This freeze is for + // consistency with the rule, not because it stops an exploit. + function requireName(name, fn) { + if (typeof name !== "string") { + throw new TypeError(`iii.files.${fn}: name must be a string`); + } + return name; + } + + const files = Object.freeze({ + write(name, contents) { + requireName(name, "write"); + let bytes; + if (typeof contents === "string") bytes = utf8Encode(contents); + else if (contents instanceof Uint8Array) bytes = contents; + else throw new TypeError("iii.files.write: contents must be a string or Uint8Array"); + op_iii_fs_write(name, bytes); + }, + read(name) { + return op_iii_fs_read(requireName(name, "read")); + }, + readText(name) { + return utf8Decode(op_iii_fs_read(requireName(name, "readText"))); + }, + list() { + return JSON.parse(op_iii_fs_list()); + }, + remove(name) { + op_iii_fs_remove(requireName(name, "remove")); + }, + }); + + globalThis.iii = { trigger, registerFunction, registerTrigger, registerTriggerType, unregisterTriggerType, shutdown, files }; + + // Non-enumerable: a `toString` STRING key set via an object literal or a + // bare `defineProperty` call defaults to enumerable and would show up in + // `Object.keys(iii)` — the pinned golden counts six SDK methods plus + // `namespace`, not this hint, as the guest-visible surface. The Symbol key + // is never enumerable regardless (`Object.keys`/`for...in` only ever see + // string keys), so this only matters for `toString`. + Object.defineProperties(globalThis.iii, { + toString: { value: () => HINT, enumerable: false }, + [Symbol.for("nodejs.util.inspect.custom")]: { value: () => HINT, enumerable: false }, + }); + + // `namespace` (published by runtime.rs, see `[node-engine:namespace]`) and + // `Object.freeze` both apply once this script returns — see that call site + // for why freezing has to wait that long, and why waiting is still safe. + + // Resolve a caller-supplied handler string to a function. + // + // Expression first. The body fallback is gated on SyntaxError ALONE and + // that is load-bearing: almost any string is a valid function body, so an + // unconditional fallback can never fail — "payload.n * 2", the most natural + // short handler anyone would write, would become a live function returning + // undefined forever, which the envelope reports as a deliberate null. + // + // Returns `{ fn, form }`, not a bare function. `form` names which branch + // won — only this code knows, and re-deriving it in Rust would need a + // JavaScript parser. It was read by `node-engine::eject`, which wrote these + // handlers to disk and had to emit the shape the caller actually got; that + // function is gone, so `wrap_register` now just passes `form` back as part + // of its eval result and nothing consumes it. + function toHandler(id, src) { + // Construct and invoke as SEPARATE steps. Only construction can raise the + // SyntaxError that means "this is not an expression"; only invocation can + // raise a tenant error. Splitting them keeps the not-a-function throw + // below outside any catch, so it is never wrapped twice, and it keeps an + // invocation error from ever reaching the body-form fallback. + // + // Every message goes through `formatCause`: a handler is free to + // `throw null`, and reading `.message` off that would raise an unrelated + // TypeError that loses the handler id entirely. + let make; + try { + make = new Function("return (" + src + ")"); + } catch (exprErr) { + if (!(exprErr instanceof SyntaxError)) { + throw definitionError(`handler for ${id}: ${formatCause(exprErr)}`); + } + // Not an expression at all — try it as a function body. + try { + return { fn: new Function("payload", src), form: "body" }; + } catch (bodyErr) { + // Both parser messages quote tokens from the `new Function` + // wrappers, not from the caller's source, so neither is actionable on + // its own. Lead with the shape that actually works: `toHandler`'s + // only caller now is `wrap_register` (protocol.rs), so this is + // reached with a genuine syntax error in `register_function`'s + // `source` — the retired bare-expression/function-body forms this + // message used to recommend are exactly what that contract no + // longer accepts. + throw definitionError( + `handler for ${id} does not parse: source must define handler(payload) — write, ` + + `for example, "export function handler(p) { ... }" or ` + + `"const handler = (p) => { ... }". Note that "export" is only recognised as ` + + `the first token of source: a statement ahead of it, a second export further ` + + `down, or CommonJS "exports.handler = ..." all leave an export the evaluated ` + + `source cannot parse — drop the keyword, or put the handler first. ` + + `(as an expression: ${formatCause(exprErr)}; as a body: ${formatCause(bodyErr)})`, + ); + } + } + + let fn; + try { + fn = make(); + } catch (e) { + // NOT a fallback to the body form: an expression that parses but throws + // was meant as an expression, and "payload.n * 2" silently becoming a + // null-returning handler is the exact failure this gate prevents. + // + // A ReferenceError here is almost always the same confusion: the caller + // wrote a bare expression ("payload.n * 2") instead of DEFINING + // handler, so evaluating it looked up `payload` before any payload + // exists. Naming the contract is what keeps that from being a wall. + // + // `src` is deliberately NOT interpolated. This hint used to quote it, + // from when callers passed their handler text straight in; + // `toHandler`'s only caller is now `wrap_register` (protocol.rs), so + // `src` is the GENERATED wrapper — the hint dumped ~1,400 characters of + // machine-written code at the caller, and recommended the bare- + // expression and function-body forms this contract retired. (It also + // made an E2E assertion vacuous: the case checking this message names + // "source must define handler(payload)" was matching that phrase + // inside the dumped wrapper, not in any message.) + const hint = + e instanceof ReferenceError + ? `. source must define handler(payload) — write, for example, ` + + `"export function handler(p) { ... }" or "const handler = (p) => { ... }"` + : ""; + throw definitionError( + `handler for ${id} threw while being defined: ${formatCause(e)}${hint}`, + ); + } + if (typeof fn !== "function") { + const kind = typeof fn; + const article = "aeiou".includes(kind[0]) ? "an" : "a"; + throw definitionError( + `handler for ${id} evaluated to ${article} ${kind}, not a function; ` + + `write an expression such as "(p) => …", or a body containing "return"`, + ); + } + return { fn, form: "expression" }; + } + + // `handlers` is deliberately NOT exposed: `wrap_eval` and `wrap_invoke` + // resolve `__iii` by name at call time, so tenant code that can reach it + // could forge its own result envelope. + // + // `Object.freeze` alone is NOT enough — it protects the object, not the + // binding, so `globalThis.__iii = {...}` would replace it wholesale. + // `defineProperty` defaults to non-writable AND non-configurable, which + // closes both the property-assignment and the rebinding forms. + Object.defineProperty(globalThis, "__iii", { + value: Object.freeze({ settle, invoke, toHandler }), + }); + + // Remove deno_core's builtin surface. This is the containment boundary: + // `Deno.core.ops` carries `op_panic` — literally `panic!(...)`, which + // unwinds out of a V8 callback and kills this worker thread, i.e. one + // tenant can take down every other tenant's runtime — and `op_print`, + // which writes straight to the worker's stdout. Neither is reachable + // through the two `iii` ops that are supposed to be the entire escape + // surface. + // + // deno_core supports this: 01_core.js hands Rust a captured copy of + // `__bootstrap` specifically so extension scripts keep working "when the + // live `__bootstrap` has already been deleted (i.e. after runtime + // bootstrap)". Anything this prelude needs from `Deno.core` must be + // destructured into a local ABOVE, before these deletes. + delete globalThis.Deno; + delete globalThis.__bootstrap; + + // WebAssembly is not part of what this worker offers — the README promises + // "plain modern JavaScript plus the `iii` global" — and it is the one + // remaining way to take memory the capped ArrayBuffer allocator cannot see: + // V8 backs `WebAssembly.Memory` with its own reservation, not that + // allocator, so a tenant could hold hundreds of megabytes under a runtime + // configured for far less. Removing it also drops a JIT surface nothing + // here needs. + delete globalThis.WebAssembly; +})(globalThis); diff --git a/crates/node-core/src/protocol.rs b/crates/node-core/src/protocol.rs new file mode 100644 index 0000000000..197575e47a --- /dev/null +++ b/crates/node-core/src/protocol.rs @@ -0,0 +1,457 @@ +//! The JSON envelope every JS↔Rust value crosses in. +//! +//! Nothing depends on `serde_v8` conversion semantics: JavaScript stringifies +//! its own values with `JSON.stringify` and Rust parses the resulting string, +//! so a value means the same thing on both sides or it is not representable. + +use serde_json::Value; + +use crate::error::NodeEngineError; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Envelope { + Ok(Value), + Err(String), +} + +impl Envelope { + pub fn parse(s: &str) -> Result { + let v: Value = serde_json::from_str(s).map_err(|e| { + NodeEngineError::eval_failed(format!("runtime returned a non-JSON envelope: {e}")) + })?; + if let Some(err) = v.get("err") { + return Ok(Envelope::Err( + err.as_str().unwrap_or("unknown error").to_string(), + )); + } + match v.get("ok") { + Some(ok) => Ok(Envelope::Ok(ok.clone())), + None => Err(NodeEngineError::eval_failed(format!( + "runtime returned an envelope with neither ok nor err: {s}" + ))), + } + } +} + +/// JSON string literals are valid JavaScript string literals, so serde_json is +/// the escaper for anything interpolated into generated source. +fn js_string(s: &str) -> String { + serde_json::to_string(s).expect("string serializes") +} + +/// Wrap caller code in an async IIFE so top-level `await` works, and hand the +/// resulting promise to the prelude's `settle` so it comes back as an envelope. +pub fn wrap_eval(code: &str) -> String { + format!("globalThis.__iii.settle((async () => {{\n{code}\n}})())") +} + +/// Source that invokes a registered JS handler, or — when `method` is given — +/// one of a registered trigger TYPE's two callback methods. `fn_id`/`type_id` +/// and the payload are escaped as JS string literals; the payload crosses as +/// JSON text the prelude parses. `method` reaches `__iii.invoke` as a bare +/// JS argument (a quoted string literal, or the literal token `undefined`) +/// rather than JSON text, matching how the prelude's `invoke(id, payloadJson, +/// method)` reads it directly with no `JSON.parse`. +pub fn wrap_invoke(fn_id: &str, payload: &Value, method: Option<&str>) -> String { + let payload_json = serde_json::to_string(payload).expect("payload serializes"); + let method_arg = match method { + Some(m) => js_string(m), + None => "undefined".to_string(), + }; + format!( + "globalThis.__iii.settle(globalThis.__iii.invoke({}, {}, {}))", + js_string(fn_id), + js_string(&payload_json), + method_arg + ) +} + +/// Source that resolves `source` to a handler function, registers it, then +/// reports the form it resolved to. +/// +/// This is a STATEMENT BODY for [`wrap_eval`], not a standalone expression: +/// `wrap_eval` already supplies the async IIFE and `settle`, so a throw here +/// reaches the caller as `eval_failed`. Wrapping this in its own IIFE would +/// detach the promise and report success on every failure. The trailing +/// `return` is what `wrap_eval`'s IIFE turns into the eval's `result`. +/// +/// `source` must DEFINE `handler(payload)` — the documented shape is +/// `export function handler(p) { ... }`, and `const`/`let handler = ...` +/// are equally valid ways to define it. (`class handler {}` satisfies the +/// generated wrapper's `typeof handler === "function"` check and registers, +/// but a class constructor has no `[[Call]]`, so every invocation then +/// throws — see `a_class_named_handler_registers_but_can_never_be_invoked`. +/// It is not a supported form and no document recommends it.) `__iii. +/// toHandler` (prelude.js) still only resolves ONE JavaScript *expression* +/// to a function — that mechanism, and the error mapping built on it (no +/// internal stack), is unchanged and worth keeping exactly as +/// `register_function`'s old batch loop left it. So `source` is turned into +/// an expression here, in Rust, rather than by touching prelude.js: a +/// leading `export` is stripped (deno_core runs this as a plain script, and +/// `export` is a SyntaxError anywhere outside a module — see the runtime +/// comment on `execute_script`), and the whole thing is wrapped so the +/// expression resolves to whatever `source` bound `handler` to, or throws a +/// clean error if it bound nothing (or something that is not a function). +/// +/// The wrapper is two nested IIFEs, not one — this shape, and every claim +/// below, was checked against real V8 (`node -e`, deno_core embeds the same +/// engine), not derived by reasoning about the spec alone: +/// +/// ```js +/// (function(){var handler; +/// handler=(function(){ +/// +/// return typeof handler==="function"?handler:undefined; +/// })(); +/// if(typeof handler!=="function")throw new TypeError("source must define handler(payload)"); +/// return handler; +/// })() +/// ``` +/// +/// - **The inner IIFE, not `var handler;` alone, is what makes `const`/ +/// `let`/`class handler` legal.** An earlier version of this wrapper put +/// `var handler;` directly ahead of `` in ONE scope — +/// which works for `function handler(){}` and a bare `handler = ...` +/// assignment, but a `var` and a `let`/`const`/`class` of the SAME name in +/// the SAME scope is a `SyntaxError` ("Identifier 'handler' has already +/// been declared"), and `export const handler = async (p) => ...` is the +/// canonical ESM idiom — exactly what "defining `handler(payload)`" +/// invites an agent to write. Giving `` its OWN function +/// scope (the inner IIFE) means whatever declaration form it uses for +/// `handler` never collides with the OUTER `var handler;`, which exists +/// purely to receive the inner IIFE's result. +/// - **`typeof handler === "function"` in the OUTER scope, not a bare +/// `return handler` inside the inner one** — `typeof` is the one JS +/// operator that never throws on an unresolvable reference, so a `source` +/// that binds nothing fails this check with a message this function +/// writes, rather than raising a `ReferenceError` that `toHandler`'s own +/// handling (built for the OLD, now-retired bare-expression contract) +/// would catch and answer with a hint that quotes this whole generated +/// wrapper — newlines included — back at the caller. +/// - **The outer `var handler;` still matters** even with the source in its +/// own scope: the namespace runtime is ONE isolate shared by every +/// registration into it, and `new Function` runs in sloppy mode — a +/// PREVIOUS registration's `handler = ...` (undeclared, hence a global in +/// ITS inner IIFE, same as any sloppy-mode top-level assignment) must not +/// be visible to a LATER `source` that binds nothing. The outer `var +/// handler;` shadows any such stale global before the outer `typeof` +/// check ever runs, so "binds nothing" always means "sees its own +/// `undefined`", never "inherits a neighbour's leftover function". +/// - **The inner IIFE's `return` is what makes the "must define handler" +/// check unconditional.** A `source` containing its own top-level +/// `return` (mimicking the OLD body-form contract) still only returns +/// from the INNER function; the outer `typeof handler !== "function"` +/// check runs regardless, so a non-function early return (`"return 42"`) +/// is still refused — closing that case of the deferred "check is +/// bypassable" finding. (A `source` whose early return happens to BE a +/// function is still accepted, same as before: that is the retired +/// bare-expression contract smuggled back in through `return`, a +/// narrower, still-deferred gap, not something this wrapper newly opens.) +/// - **A `source`'s own `"use strict"` directive prologue survives** as a +/// side effect of the inner IIFE: the prologue must be the first +/// statement(s) of a function body to take effect, and with the source +/// now running as the FIRST content of the inner function (not preceded +/// by `var handler;`, which broke prologue position in the earlier, +/// single-scope version), a tenant that opts into strict mode to catch a +/// typo keeps that protection. +pub fn wrap_register( + id: &str, + source: &str, + description: Option<&str>, + request_format: Option<&serde_json::Value>, + response_format: Option<&serde_json::Value>, +) -> String { + let stripped = strip_leading_export(source); + let handler_expr = format!( + "(function(){{var handler;\n\ + handler=(function(){{\n{stripped}\n\ + return typeof handler===\"function\"?handler:undefined;\n\ + }})();\n\ + if(typeof handler!==\"function\")throw new TypeError(\"source must define handler(payload)\");\n\ + return handler;\n\ + }})()" + ); + // A missing description is an ABSENT property, not `null`: the prelude's + // third argument is optional and type-checked, so `null` would be a + // TypeError while `undefined` takes the default. + let desc = match description { + Some(text) => format!(",desc:{}", js_string(text)), + None => String::new(), + }; + // Formats embed as compact-JSON literals — JSON is a valid JS expression, + // and the `__def` literal evaluates before any tenant source runs. An + // absent format leaves its key out, so `__def.reqf` reads `undefined` — + // "not supplied" — through the same options plumbing as `desc`. + let reqf = match request_format { + Some(schema) => format!(",reqf:{schema}"), + None => String::new(), + }; + let resf = match response_format { + Some(schema) => format!(",resf:{schema}"), + None => String::new(), + }; + // `registerFunction`'s third argument is now an options OBJECT (the SDK + // shape — see `prelude.js`), not the raw description string: passing + // `__def.desc` positionally would hand a string where an object is + // required and every registration from source would throw. `desc` absent + // means `__def.desc` reads as `undefined`, so `{description:__def.desc}` + // still lands on `options.description === undefined` — "not supplied" — + // exactly like today. + format!( + "const __def={{id:{},src:{}{desc}{reqf}{resf}}};\ + const __h=__iii.toHandler(__def.id,__def.src);\ + iii.registerFunction(__def.id,__h.fn,{{description:__def.desc,\ + request_format:__def.reqf,response_format:__def.resf}});\ + return {{id:__def.id,form:__h.form}};", + js_string(id), + js_string(&handler_expr) + ) +} + +/// Strip a leading `export` keyword — only when it is a real word boundary, +/// and only when what follows is not `default`. Both are cases where +/// dropping just the word `export` would MANGLE the source into something +/// that still fails, but for a different, more confusing reason, rather +/// than leaving it to fail cleanly on the `export` token it actually +/// contains: +/// - `exports.handler = ...` (a plain identifier that happens to start with +/// the same five letters) would become `s.handler = ...` without a +/// boundary check. +/// - `export default function handler(){}` cannot become a bare declaration +/// by dropping only the keyword — `default function handler(){}` is +/// still not valid JavaScript on its own — so it is left untouched too. +fn strip_leading_export(source: &str) -> &str { + let trimmed = source.trim_start(); + let Some(rest) = trimmed.strip_prefix("export") else { + return trimmed; + }; + let Some(boundary) = rest.chars().next() else { + return trimmed; + }; + if !boundary.is_whitespace() { + return trimmed; + } + let rest = rest[boundary.len_utf8()..].trim_start(); + if rest.starts_with("default") { + return trimmed; + } + rest +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parses_ok_envelope() { + assert_eq!( + Envelope::parse(r#"{"ok":{"a":1}}"#).unwrap(), + Envelope::Ok(json!({"a": 1})) + ); + } + + #[test] + fn parses_null_ok_envelope() { + assert_eq!( + Envelope::parse(r#"{"ok":null}"#).unwrap(), + Envelope::Ok(Value::Null) + ); + } + + #[test] + fn parses_err_envelope() { + assert_eq!( + Envelope::parse(r#"{"err":"boom"}"#).unwrap(), + Envelope::Err("boom".into()) + ); + } + + #[test] + fn rejects_garbage() { + assert!(Envelope::parse("not json").is_err()); + assert!(Envelope::parse(r#"{"other":1}"#).is_err()); + } + + #[test] + fn wrap_eval_embeds_code_in_an_async_iife() { + let src = wrap_eval("return 1 + 1"); + assert!(src.contains("__iii.settle")); + assert!(src.contains("return 1 + 1")); + assert!(src.contains("async ()")); + } + + /// Code arrives from untrusted callers; the invoke wrapper must never let + /// a quote or backslash in the function id or payload break out of its + /// string literal. + #[test] + fn wrap_invoke_escapes_its_arguments() { + let src = wrap_invoke(r#"ns::a"b\c"#, &json!({ "s": "\"quoted\"" }), None); + assert!(src.contains(r#"ns::a\"b\\c"#)); + assert!(!src.contains("\n")); + } + + /// A plain function invocation (the pre-Task-12 shape) sends the literal + /// token `undefined` as the third argument, not a string — the prelude's + /// `invoke(id, payloadJson, method)` branches on `method` being falsy, + /// and `"undefined"` (a quoted string) is truthy. + #[test] + fn wrap_invoke_sends_the_bare_undefined_token_for_no_method() { + let src = wrap_invoke("test::x", &json!({}), None); + assert!( + src.contains(", undefined)"), + "method argument must be the bare token, not a quoted string: {src}" + ); + } + + /// A trigger-type callback carries its method name as a proper JS string + /// literal, escaped exactly like `fn_id` and the payload. + #[test] + fn wrap_invoke_escapes_a_method_name() { + let src = wrap_invoke("app::mytype", &json!({}), Some(r#"a"b"#)); + assert!(src.contains(r#""a\"b""#), "method not escaped: {src}"); + } + + /// Formats embed as JSON literals in `__def` and ride the options + /// object; absent formats leave the keys out entirely, so the prelude + /// reads `undefined` — "not supplied" — exactly like the description. + #[test] + fn wrap_register_carries_formats_only_when_given() { + let schema = serde_json::json!({"type": "object"}); + let with = wrap_register( + "ns::a", + "export function handler(p) { return p }", + None, + Some(&schema), + None, + ); + assert!(with.contains(r#"reqf:{"type":"object"}"#), "{with}"); + assert!(with.contains("request_format:__def.reqf"), "{with}"); + assert!(with.contains("response_format:__def.resf"), "{with}"); + + let without = wrap_register( + "ns::a", + "export function handler(p) { return p }", + None, + None, + None, + ); + assert!(!without.contains("reqf:"), "{without}"); + assert!(!without.contains("resf:"), "{without}"); + } + + #[test] + fn wrap_register_escapes_ids_and_source() { + let src = wrap_register( + r#"ns::a"b"#, + "export function handler(p) {\n return `x`\n}", + None, + None, + None, + ); + // Both interpolations are JSON string literals, so nothing can break + // out of them — including the newline, which would otherwise comment + // out the rest of the generated script. + assert!(src.contains(r#"ns::a\"b"#), "id not escaped: {src}"); + assert!(src.contains(r#"return `x`\n"#), "source not escaped: {src}"); + assert!(!src.contains('\n'), "generated source must be one line"); + assert!( + src.trim_end() + .ends_with("return {id:__def.id,form:__h.form};"), + "must end with the return that becomes the eval's result: {src}" + ); + } + + /// `wrap_eval` already supplies the async IIFE and `settle`. A second IIFE + /// here would detach the inner promise: the outer would resolve undefined, + /// the envelope would read `{"ok":null}`, and EVERY failure would be + /// reported to the caller as success. + #[test] + fn wrap_register_is_a_statement_body_not_an_iife() { + let src = wrap_register( + "ns::a", + "export function handler(p) { return p }", + None, + None, + None, + ); + assert!( + !src.trim_start().starts_with("(async"), + "double-wrapped: {src}" + ); + assert!(src.contains("__iii.toHandler")); + assert!(src.contains("iii.registerFunction")); + // The trailing `return` is what makes this a statement body rather + // than a dead expression: `wrap_eval`'s IIFE turns it into the + // eval's `result`. + assert!( + src.contains("return {id:__def.id,form:__h.form};"), + "missing the return that becomes the eval's result: {src}" + ); + } + + /// `source` defines `handler(payload)`, documented as + /// `export function handler(p) { ... }` — `export` is invalid anywhere + /// outside a module, including nested inside the generated IIFE, so it + /// must be stripped before the source is embedded. + #[test] + fn wrap_register_strips_a_leading_export() { + let src = wrap_register( + "ns::a", + "export function handler(p) { return 1 }", + None, + None, + None, + ); + assert!( + !src.contains("export"), + "a literal `export` would be a SyntaxError once embedded: {src}" + ); + } + + /// `exports.handler = ...` is a plain identifier that happens to start + /// with the same five letters as the keyword — stripping without a word + /// boundary would mangle it into `s.handler = ...`. `export default + /// function handler(){}` cannot become a bare declaration by dropping + /// only the keyword (`default function handler(){}` is still not valid + /// JavaScript on its own), so it is left untouched too, rather than + /// mangled into a different, more confusing failure. + #[test] + fn strip_leading_export_requires_a_real_word_boundary() { + assert_eq!( + strip_leading_export("export function handler(){}"), + "function handler(){}" + ); + assert_eq!( + strip_leading_export("exports.handler = 1"), + "exports.handler = 1", + "must not mangle a plain identifier into `s.handler`" + ); + assert_eq!( + strip_leading_export("export default function handler(){}"), + "export default function handler(){}", + "must not mangle `export default` into a bare `default ...`" + ); + assert_eq!( + strip_leading_export("function handler(){}"), + "function handler(){}" + ); + } + + /// A description is an ABSENT property when omitted, not `null` — the + /// prelude's third argument is type-checked and only `undefined` takes + /// its default. + #[test] + fn wrap_register_omits_absent_description() { + let with = wrap_register( + "ns::a", + "export function handler() {}", + Some("does a thing"), + None, + None, + ); + assert!(with.contains(r#"desc:"does a thing""#), "{with}"); + let without = wrap_register("ns::a", "export function handler() {}", None, None, None); + assert!(!without.contains("desc:"), "{without}"); + } +} diff --git a/crates/node-core/src/runtime.rs b/crates/node-core/src/runtime.rs new file mode 100644 index 0000000000..aa53a90b9e --- /dev/null +++ b/crates/node-core/src/runtime.rs @@ -0,0 +1,3208 @@ +//! One V8 isolate on one OS thread, driven by a multiplexed loop. +//! +//! Isolates are not `Send`, so each runtime owns a thread and is reached only +//! through [`Command`]s on an mpsc channel. The loop interleaves starting new +//! commands, polling in-flight promises, and pumping the deno_core event loop, +//! which is what lets one JS handler await another handler in the same isolate +//! instead of deadlocking behind it. + +use std::cell::RefCell; +use std::future::poll_fn; +use std::pin::Pin; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::task::Poll; +use std::time::Duration; + +use deno_core::error::JsError; +use deno_core::{v8, JsRuntime, OpState, PollEventLoopOptions, RuntimeOptions}; +use serde_json::Value; +use tokio::sync::{mpsc, oneshot}; +use tokio::time::Instant; + +use crate::engine::Engine; +use crate::error::NodeEngineError; +use crate::ops::{node_engine_ext, with_ops_state, OpsState}; +use crate::protocol::{wrap_eval, wrap_invoke, Envelope}; + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)] +pub struct LogLine { + pub level: String, + pub message: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct EvalOutcome { + pub result: Value, + pub logs: Vec, + pub registered: Vec, +} + +pub enum Command { + Eval { + code: String, + timeout: Duration, + reply: oneshot::Sender>, + }, + Invoke { + fn_id: String, + payload: Value, + timeout: Duration, + reply: oneshot::Sender>, + /// `None` for a plain function invocation; `Some("registerTrigger" | + /// "unregisterTrigger")` when this targets a trigger TYPE's callback + /// instead — see `wrap_invoke`. + method: Option, + }, +} + +#[derive(Clone)] +pub struct RuntimeOpts { + pub heap_mb: usize, + /// Ceiling on off-heap (ArrayBuffer) memory — see `crate::allocator`. + pub external_mb: usize, + /// Required prefix for ids the evaluated code may register. + pub namespace: String, + /// Budget for `iii.trigger`, for handler invocations arriving from + /// the bus, and for any single event-loop pump. + pub call_timeout_ms: u64, + /// Ceiling a guest-supplied `iii.trigger({..., timeout})` is clamped to. + /// Same value (`NodeEngineConfig::max_timeout_ms`) the RPC-level eval + /// timeout is clamped to via `clamp_timeout` in `manager.rs` — that + /// clamp only ever covered the eval's own deadline, not this op's + /// argument, which reached `Engine::call` unclamped before this field + /// existed. + pub max_timeout_ms: u64, + /// Shared with every other runtime; guards the duplicate-id abort. + pub ids: crate::ids::IdRegistry, + /// This runtime's own id, used as the ownership key in `ids`. + pub runtime_id: String, + /// The SAME `Arc` as `manager::Runtime::last_activity`. `run`/`register` + /// bump it from the manager's side; `op_iii_register`'s invoke proxy (see + /// `OpsState::last_activity`) bumps it from this thread's side, since an + /// INVOKE dispatched straight from the bus never reaches the manager at + /// all. + pub last_activity: Arc>, + /// Per-runtime scratch quota, bytes. 0 removes `iii.files` entirely. + pub scratch_mb: usize, + /// Per-runtime scratch quota, entry count. + pub scratch_files: usize, + /// Where the scratch directory is created; `None` uses the system temp + /// directory. + pub scratch_root: Option, +} + +// `runtime_id` is a capability — same rule as `RunRequest` and `IdRegistry`. +// `ids` already redacts itself (see `IdRegistry`'s own hand-rolled `Debug`, +// just above it in `crate::ids`), so only `runtime_id` needs guarding here. +impl std::fmt::Debug for RuntimeOpts { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RuntimeOpts") + .field("heap_mb", &self.heap_mb) + .field("external_mb", &self.external_mb) + .field("namespace", &self.namespace) + .field("call_timeout_ms", &self.call_timeout_ms) + .field("max_timeout_ms", &self.max_timeout_ms) + .field("ids", &self.ids) + .field("runtime_id", &"") + .field("last_activity", &self.last_activity) + .field("scratch_mb", &self.scratch_mb) + .field("scratch_files", &self.scratch_files) + .field("scratch_root", &self.scratch_root) + .finish() + } +} + +/// Create this runtime's private scratch directory, or `None` when the +/// feature is switched off. +/// +/// The directory name is NOT derived from `runtime_id`. `tempfile` mints its +/// own independent random suffix, so `ls $TMPDIR` does not enumerate live +/// runtime capabilities and the mapping is not derivable in either direction. +/// "Name the dir after the runtime, for debuggability" is the obvious future +/// improvement and it is exactly wrong: `runtime_id` is the capability to +/// eval into and tear down a runtime, and that leak has already been found +/// and fixed four separate times in this crate. An operator who genuinely +/// needs the correlation can add a `debug` tracing line — an explicit, +/// reviewable choice rather than a default. +/// +/// `tempfile::Builder` also gives O_EXCL creation (so no pre-planted +/// directory or symlink at the root) and mode 0700 on unix, in one call. +fn make_scratch(opts: &RuntimeOpts) -> std::io::Result> { + if opts.scratch_mb == 0 { + return Ok(None); + } + let mut builder = tempfile::Builder::new(); + builder.prefix("code-runner-"); + let dir = match &opts.scratch_root { + Some(root) => { + std::fs::create_dir_all(root)?; + builder.tempdir_in(root)? + } + None => builder.tempdir()?, + }; + Ok(Some(dir)) +} + +/// Initialise the V8 platform exactly once per process, before any isolate is +/// created. Safe to call from anywhere; later calls are no-ops. +pub fn init_v8_platform() { + static ONCE: once_cell::sync::OnceCell<()> = once_cell::sync::OnceCell::new(); + ONCE.get_or_init(|| JsRuntime::init_platform(None)); +} + +pub type Unregisters = Arc< + std::sync::Mutex< + Vec<( + crate::ops::RegistrationKind, + String, + crate::engine::UnregisterFn, + )>, + >, +>; + +pub struct RuntimeThread { + tx: mpsc::UnboundedSender, + unregisters: Unregisters, + join: Option>, +} + +impl RuntimeThread { + pub fn spawn(opts: RuntimeOpts, engine: Arc) -> RuntimeThread { + let (tx, rx) = mpsc::unbounded_channel(); + let weak_tx = tx.downgrade(); + let unregisters: Unregisters = Arc::new(std::sync::Mutex::new(Vec::new())); + let thread_unregisters = unregisters.clone(); + let join = std::thread::Builder::new() + .name("code-runner-isolate".to_string()) + .spawn(move || { + let tokio_rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current-thread runtime builds"); + tokio_rt.block_on(run_loop(rx, opts, engine, thread_unregisters, weak_tx)); + }) + .expect("isolate thread spawns"); + RuntimeThread { + tx, + unregisters, + join: Some(join), + } + } + + /// Every live registration this runtime made, so the manager can undo them + /// from its own thread at teardown. + pub fn unregisters(&self) -> Unregisters { + self.unregisters.clone() + } + + /// Queue a command. `Err` returns the command when the loop has exited. + /// + /// Boxed, not bare `Command`: `Invoke` grew a `method: Option` + /// field alongside `fn_id`/`payload`/`timeout`/`reply`, and clippy's + /// `result_large_err` flags a bare `Command` here as bloating every + /// caller's stack frame for the `Ok(())` case too. Every current caller + /// only checks `.is_err()`, so this costs nothing today; a future one + /// that wants the command back still can. + /// + /// There is deliberately no accessor handing out a strong sender clone: + /// the loop only sees its channel close when EVERY sender is gone, so a + /// clone parked in a registry or a long-lived task would make `Drop`'s + /// join below block forever. The registration proxy holds a + /// `WeakUnboundedSender` for the same reason. + pub fn send(&self, cmd: Command) -> Result<(), Box> { + self.tx.send(cmd).map_err(|e| Box::new(e.0)) + } + + /// Close the channel and join the isolate thread. + pub fn shutdown(self) { + drop(self); + } +} + +impl Drop for RuntimeThread { + fn drop(&mut self) { + // The sender MUST be dropped before the join: the loop only exits on + // `Poll::Ready(None)`, so joining first would hang forever. `Drop::drop` + // runs before the struct's own fields are dropped, hence the swap. + // + // ponytail: blocking join on the caller's thread. Teardown is rare and + // the loop exits as soon as the channel closes; move to a detached + // reaper task if teardown ever shows up on a hot path. + let (dead_tx, _) = mpsc::unbounded_channel(); + drop(std::mem::replace(&mut self.tx, dead_tx)); + if let Some(join) = self.join.take() { + let _ = join.join(); + } + } +} + +/// Data the heap-limit callback needs. V8 gives the callback a raw pointer, so +/// this lives in a `Box` whose ownership is described at the call site. +struct HeapGuard { + oom: Arc, + isolate: v8::IsolateHandle, +} + +/// # Safety +/// `data` must point at a live `HeapGuard`. The only caller is `run_loop`, +/// which owns it in a `Box` bound BEFORE its `JsRuntime` — locals drop in +/// reverse declaration order, so the isolate is always disposed (and can no +/// longer invoke this callback) before the `Box` is freed, on the unwind path +/// as well as the normal one. V8 calls this on the isolate's own thread while +/// JS is running. +unsafe extern "C" fn near_heap_limit( + data: *mut std::ffi::c_void, + current_limit: usize, + _initial_limit: usize, +) -> usize { + let guard = &*(data as *const HeapGuard); + guard.oom.store(true, Ordering::SeqCst); + guard.isolate.terminate_execution(); + // Hand V8 headroom so it can unwind instead of aborting the process. + current_limit * 2 +} + +enum Reply { + Eval(oneshot::Sender>), + Invoke(oneshot::Sender>), +} + +impl Reply { + fn fail(self, err: NodeEngineError) { + match self { + Reply::Eval(tx) => { + let _ = tx.send(Err(err)); + } + Reply::Invoke(tx) => { + let _ = tx.send(Err(err)); + } + } + } +} + +type SettleFuture = + Pin, Box>>>>; + +struct Pending { + fut: SettleFuture, + reply: Reply, + deadline: Instant, +} + +/// Why the loop is exiting, and who still needs answering. +/// +/// `reply` carries the caller whose own command killed the isolate. `start` +/// deliberately hands it back instead of sending it, because that caller may +/// re-send the instant it sees the error — and it must find a closed channel, +/// not queue work onto a dead runtime. Teardown closes `rx` first, then +/// answers. +struct FatalExit { + err: NodeEngineError, + reply: Option, +} + +/// Deadline the watchdog is currently enforcing. `None` = nothing in flight. +pub type DeadlineSlot = Arc>>; + +/// The only thing that can stop runaway synchronous JavaScript. +/// +/// While V8 executes a synchronous script the isolate thread is inside V8 and +/// never returns to tokio, so no timer *on that thread* can fire — a bare +/// `for(;;){}` would hang it forever. `v8::IsolateHandle` is `Send + Sync` +/// precisely so another thread can interrupt it, which is what this does. +fn spawn_watchdog( + isolate: v8::IsolateHandle, + deadline: DeadlineSlot, + terminated: Arc, + stop: Arc, +) -> std::thread::JoinHandle<()> { + std::thread::Builder::new() + .name("code-runner-watchdog".to_string()) + .spawn(move || { + // ponytail: 25ms poll rather than a condvar. Deadlines are in the + // seconds range, so finer wakeups buy nothing; switch to a condvar + // only if sub-tick precision ever matters. + const TICK: Duration = Duration::from_millis(25); + while !stop.load(Ordering::SeqCst) { + std::thread::sleep(TICK); + // Check and terminate under ONE lock acquisition. Releasing + // between them lets the isolate thread settle the command, + // answer its caller Ok, and republish — and then get killed + // anyway, handing the next unrelated caller a bogus timeout. + // `terminate_execution` is non-blocking and the isolate thread + // never holds this lock across anything slow, so holding it + // here cannot deadlock. + let mut slot = deadline.lock().unwrap(); + if slot.is_some_and(|d| std::time::Instant::now() >= d) { + terminated.store(true, Ordering::SeqCst); + isolate.terminate_execution(); + *slot = None; + } + } + }) + .expect("watchdog thread spawns") +} + +/// Why a V8 failure happened. A terminated isolate reports an ordinary script +/// error, so the flags — not the message — say whether this was a deadline, a +/// heap cap, or genuine bad JavaScript. +fn classify( + oom: &AtomicBool, + terminated: &AtomicBool, + e: &dyn std::fmt::Display, +) -> NodeEngineError { + if oom.load(Ordering::SeqCst) { + NodeEngineError::Oom + } else if terminated.load(Ordering::SeqCst) { + NodeEngineError::Timeout + } else { + NodeEngineError::eval_failed(e.to_string()) + } +} + +async fn run_loop( + mut rx: mpsc::UnboundedReceiver, + opts: RuntimeOpts, + engine: Arc, + unregisters: Unregisters, + command_tx: mpsc::WeakUnboundedSender, +) { + let heap_bytes = opts.heap_mb * 1024 * 1024; + // `heap_limits` bounds the object heap only; this bounds everything V8 + // allocates beside it. The handle is kept alive by the isolate. + let (_external, external_allocator) = crate::allocator::capped(opts.external_mb * 1024 * 1024); + + // Bound BEFORE `js`, initialised after it. Locals drop in reverse + // declaration order, so `js` disposes the isolate first and this `Box` + // is freed second — the ordering V8 requires, and unlike a trailing + // `drop(js); drop(heap_guard);` pair it still holds if the loop unwinds. + // + // `needless_late_init` is exactly wrong here, and its suggested fix is a + // silent memory-safety regression: collapsing this into a single + // `let heap_guard = Box::new(..)` below moves the binding AFTER `js`'s, + // which flips the drop order and leaves V8 holding a freed pointer + // through isolate disposal. Do not "clean this up". + #[allow(clippy::needless_late_init)] + let heap_guard: Box; + + // Before the isolate, because it has to go into the `OpsState` handed to + // `node_engine_ext::init`. Never `unwrap()`, and never degrade silently to + // "no filesystem": a runtime whose config promises a directory and quietly + // has none is worse than one that refuses to start. Returning here drops + // `rx`, so the manager's first send fails and it reaps — the same + // observable outcome as the prelude-failure path below, with less code. + let scratch = match make_scratch(&opts) { + Ok(s) => s, + Err(e) => { + tracing::error!(error = %e, "scratch directory could not be created; runtime is unusable"); + return; + } + }; + + let mut js = JsRuntime::new(RuntimeOptions { + create_params: Some( + v8::CreateParams::default() + .heap_limits(0, heap_bytes) + .array_buffer_allocator(external_allocator.make_shared()), + ), + extensions: vec![node_engine_ext::init(OpsState { + engine: engine.clone(), + namespace: opts.namespace.clone(), + logs: Vec::new(), + log_bytes: 0, + log_truncated: false, + detached_log_bytes: 0, + capturing: false, + registered: Vec::new(), + unregisters: unregisters.clone(), + pending_registrations: 0, + call_timeout_ms: opts.call_timeout_ms, + max_timeout_ms: opts.max_timeout_ms, + inflight_calls: 0, + command_tx, + invoke_timeout_ms: opts.call_timeout_ms, + ids: opts.ids.clone(), + runtime_id: opts.runtime_id.clone(), + last_activity: opts.last_activity.clone(), + scratch, + scratch_max_bytes: opts.scratch_mb as u64 * 1024 * 1024, + scratch_max_files: opts.scratch_files, + })], + ..Default::default() + }); + let op_state = js.op_state(); + + let oom = Arc::new(AtomicBool::new(false)); + let terminated = Arc::new(AtomicBool::new(false)); + let isolate_handle = js.v8_isolate().thread_safe_handle(); + heap_guard = Box::new(HeapGuard { + oom: oom.clone(), + isolate: isolate_handle.clone(), + }); + let heap_guard_ptr: *const HeapGuard = &*heap_guard; + js.v8_isolate() + .add_near_heap_limit_callback(near_heap_limit, heap_guard_ptr as *mut std::ffi::c_void); + + let deadline_slot: DeadlineSlot = Arc::new(std::sync::Mutex::new(None)); + let stop_watchdog = Arc::new(AtomicBool::new(false)); + let watchdog = spawn_watchdog( + isolate_handle, + deadline_slot.clone(), + terminated.clone(), + stop_watchdog.clone(), + ); + + // Ceiling on any single event-loop pump, including detached tenant work + // running with nothing in `pending`. Reuses the configured per-call budget + // — work outside a command that outlives a whole call timeout, with no + // caller waiting on it, is the pathological case, not a legitimate one. + let pump_budget = Duration::from_millis(opts.call_timeout_ms); + + let mut pending: Vec = Vec::new(); + let mut closed = false; + // Set once the isolate is unusable. V8 termination is sticky, so there is + // no recovering a runtime past this point — it dies and callers are told. + let mut fatal: Option = None; + + if let Err(e) = js.execute_script("[code-runner:prelude]", include_str!("prelude.js")) { + tracing::error!(error = %e, "prelude failed to evaluate; runtime is unusable"); + closed = true; + } + + // The prefix `op_iii_register` will hold this runtime to, published to the + // code that has to satisfy it. Without this, evaluated code that wants to + // register has to be told its own namespace out of band or guess, and a + // guess is a `namespace_denied` after the work is already done. Not a + // security boundary — the op re-checks every id against the same value — + // so it is read-only only to keep the isolate honest with itself. + // + // `include_str!("prelude.js")` above is a compile-time constant, so it + // cannot carry a per-runtime value — this per-runtime script is why + // `namespace` is published here rather than baked into the prelude's own + // object literal. `Object.freeze` rides the same script, right after: it + // has to wait for `namespace` to exist (freezing first would make this + // `defineProperty` throw, adding a property to a non-extensible object), + // and nothing runs between the prelude finishing and this script — both + // are plain synchronous `execute_script` calls, with no tenant code + // scheduled in between — so the object is never observably unfrozen from + // the outside. + // + // `scratch_mb: 0` also drops `iii.files` here rather than in the prelude: + // the prelude is a compile-time constant and cannot carry a per-runtime + // value, and this script already runs in the one window where `iii` exists + // but is not yet frozen. + let drop_files = if opts.scratch_mb == 0 { + "delete globalThis.iii.files;\n" + } else { + "" + }; + let publish_ns = format!( + r#"{}Object.defineProperty(globalThis.iii, "namespace", {{ value: {}, enumerable: true }}); +Object.freeze(globalThis.iii);"#, + drop_files, + serde_json::to_string(&opts.namespace).expect("namespace serializes") + ); + if let Err(e) = js.execute_script("[code-runner:namespace]", publish_ns) { + tracing::error!(error = %e, "namespace publish failed; runtime is unusable"); + closed = true; + } + + while fatal.is_none() && !(closed && pending.is_empty()) { + // Drain what is already queued BEFORE the tick, so every in-flight + // command's deadline is known to the `timeout_at` that wraps it. + loop { + match rx.try_recv() { + Ok(cmd) => { + fatal = start( + &mut js, + &mut pending, + cmd, + &oom, + &terminated, + &deadline_slot, + &op_state, + ); + if fatal.is_some() { + break; + } + } + Err(mpsc::error::TryRecvError::Empty) => break, + Err(mpsc::error::TryRecvError::Disconnected) => { + closed = true; + break; + } + } + } + if fatal.is_some() || (closed && pending.is_empty()) { + break; + } + + let next_deadline = pending.iter().map(|p| p.deadline).min(); + *deadline_slot.lock().unwrap() = next_deadline.map(|d| d.into_std()); + + let mut started_this_tick = false; + + // One tick: accept commands, poll settled promises, pump the event + // loop. Returns the indices that settled, newest-last. + let tick = poll_fn(|cx| { + while !closed { + match rx.poll_recv(cx) { + Poll::Ready(Some(cmd)) => { + started_this_tick = true; + if let Some(err) = start( + &mut js, + &mut pending, + cmd, + &oom, + &terminated, + &deadline_slot, + &op_state, + ) { + return Poll::Ready(Err(err)); + } + } + Poll::Ready(None) => closed = true, + Poll::Pending => break, + } + } + + let mut settled = Vec::new(); + for (i, p) in pending.iter_mut().enumerate() { + if let Poll::Ready(res) = p.fut.as_mut().poll(cx) { + settled.push((i, res)); + } + } + + // Drives ops and microtasks — which means TENANT JS RUNS INSIDE + // THIS CALL, including detached work with nothing in `pending`: + // `iii.trigger(...).catch(() => { for(;;){} })` settles its + // eval immediately and wedges the thread later, when the rejection + // handler runs. With `pending` empty the slot is `None`, so the + // watchdog never fires, and `next_deadline` is `None`, so no + // `timeout_at` wraps this tick — both mechanisms disarmed at once. + // Arm the watchdog for the pump itself so no `poll_event_loop` + // call can ever run unbounded. + { + let mut slot = deadline_slot.lock().unwrap(); + *slot = Some(match next_deadline { + // A pending command already bounds this pump with its own + // deadline. Do NOT also apply `pump_budget` here: it is + // `default_timeout_ms`, while an eval may legitimately + // request up to `max_timeout_ms`, so tightening it would + // kill a long-but-valid eval early — and only after its + // first `await`, since work before that runs under + // `execute_script`, which is asymmetric and surprising. + Some(d) => d.into_std(), + // Nothing pending: this is the detached-work window, and + // `pump_budget` is the only thing standing between a + // spinning microtask and a permanently wedged thread. + None => std::time::Instant::now() + pump_budget, + }); + } + let _ = js.poll_event_loop(cx, PollEventLoopOptions::default()); + *deadline_slot.lock().unwrap() = next_deadline.map(|d| d.into_std()); + + // Settled results first: a promise that genuinely resolved in this + // same poll must reach its caller even if the watchdog fired + // during the pump. Checking `terminated` above this would discard + // it and answer `Timeout` instead of the value it already had. + if !settled.is_empty() { + return Poll::Ready(Ok(settled)); + } + + // A terminated isolate cannot make progress. Surface it so the + // outer loop's dead-flag check tears the runtime down; returning + // `Pending` here would park forever when `next_deadline` is `None`. + if terminated.load(Ordering::SeqCst) || oom.load(Ordering::SeqCst) { + return Poll::Ready(Ok(Vec::new())); + } + // A command that arrived mid-tick is NOT covered by the + // `timeout_at` wrapping this tick — that wrapper was built from the + // deadlines known beforehand. Yield so the outer loop recomputes, + // or a never-settling first command would wait forever. + if started_this_tick || (closed && pending.is_empty()) { + return Poll::Ready(Ok(Vec::new())); + } + Poll::Pending + }); + + // Two complementary deadline mechanisms, both required: + // - the watchdog thread interrupts V8 spinning on synchronous JS, + // when this thread cannot run timers at all; + // - this `timeout_at` catches a runtime parked on a promise that + // never settles, where this thread is free but V8 is idle and has + // nothing to terminate. + let ticked = match next_deadline { + Some(deadline) => match tokio::time::timeout_at(deadline, tick).await { + Ok(t) => t, + Err(_) => Err(FatalExit { + err: if oom.load(Ordering::SeqCst) { + NodeEngineError::Oom + } else { + NodeEngineError::Timeout + }, + // Nobody to hand back — every affected caller is in + // `pending` and is answered during teardown. + reply: None, + }), + }, + None => tick.await, + }; + + match ticked { + Err(err) => fatal = Some(err), + // Settle back-to-front so indices stay valid as entries are removed. + Ok(settled) => { + // Blank the slot BEFORE answering anyone. A command that + // finished at or just after its own deadline would otherwise + // leave that expired deadline visible while we reply, and the + // watchdog would kill the runtime out from under the next + // command. The watchdog's single-lock check cannot help here + // — the slot's contents are genuinely stale, not raced. + *deadline_slot.lock().unwrap() = None; + for (i, res) in settled.into_iter().rev() { + let p = pending.remove(i); + complete(&mut js, &oom, &terminated, p.reply, res, &op_state); + } + *deadline_slot.lock().unwrap() = pending + .iter() + .map(|p| p.deadline) + .min() + .map(|d| d.into_std()); + } + } + + // Either terminator may have fired without this loop being the one to + // observe it — a heap trip inside a microtask, or a watchdog kill that + // `complete` classified and replied to. V8 termination is sticky, so + // the isolate is unusable either way: tear down now rather than leave + // a zombie holding a capacity slot and handing later callers spurious + // timeouts. Both flags are set-once and only ever mean "isolate dead". + if fatal.is_none() && (oom.load(Ordering::SeqCst) || terminated.load(Ordering::SeqCst)) { + fatal = Some(FatalExit { + err: if oom.load(Ordering::SeqCst) { + NodeEngineError::Oom + } else { + NodeEngineError::Timeout + }, + reply: None, + }); + } + } + + // Close BEFORE anyone is answered — including the caller whose own command + // killed the isolate, which is why `start` handed its reply back rather + // than sending it. Any caller that re-sends the instant it sees its error + // must find a closed channel. Dropping each queued command resolves its + // awaiting proxy as `runtime_gone`. + if fatal.is_some() { + rx.close(); + while rx.try_recv().is_ok() {} + } + + stop_watchdog.store(true, Ordering::SeqCst); + *deadline_slot.lock().unwrap() = None; + let _ = watchdog.join(); + + if let Some(FatalExit { err, reply }) = fatal { + if let Some(reply) = reply { + reply.fail(err.clone()); + } + for p in pending.drain(..) { + p.reply.fail(err.clone()); + } + } + + // No explicit drops: `heap_guard` is bound before `js`, so scope exit + // disposes the isolate first and frees the callback data second — on the + // unwind path too. `heap_guard` is referenced here only to keep the + // binding alive to this point. + let _ = &heap_guard; +} + +/// Start one command. Returns `Some(FatalExit)` when the isolate died running +/// it: the runtime must tear down, and the caller is answered by teardown +/// AFTER the channel is closed — never here. +fn start( + js: &mut JsRuntime, + pending: &mut Vec, + cmd: Command, + oom: &AtomicBool, + terminated: &AtomicBool, + deadline_slot: &DeadlineSlot, + op_state: &Rc>, +) -> Option { + let now = Instant::now(); + let is_eval = matches!(cmd, Command::Eval { .. }); + let (name, source, deadline, reply) = match cmd { + Command::Eval { + code, + timeout, + reply, + } => { + // Evals are serialised per runtime by the manager, so the buffer + // and the registration delta belong to exactly one caller. + with_ops_state(op_state, |s| { + s.capturing = true; + s.logs.clear(); + s.log_bytes = 0; + s.log_truncated = false; + s.detached_log_bytes = 0; + s.registered.clear(); + }); + ( + "[code-runner:eval]", + wrap_eval(&code), + now + timeout, + Reply::Eval(reply), + ) + } + Command::Invoke { + fn_id, + payload, + timeout, + reply, + method, + } => ( + "[code-runner:invoke]", + wrap_invoke(&fn_id, &payload, method.as_deref()), + now + timeout, + Reply::Invoke(reply), + ), + }; + + // Publish BEFORE running. A synchronous script never returns control here, + // so the watchdog has to already know when to interrupt it. + { + let earliest = pending + .iter() + .map(|p| p.deadline) + .chain(std::iter::once(deadline)) + .min(); + *deadline_slot.lock().unwrap() = earliest.map(|d| d.into_std()); + } + + match js.execute_script(name, source) { + Ok(global) => { + pending.push(Pending { + fut: Box::pin(js.resolve(global)), + reply, + deadline, + }); + None + } + Err(e) => { + let logs = if is_eval { + with_ops_state(op_state, |s| { + s.capturing = false; + std::mem::take(&mut s.logs) + }) + } else { + Vec::new() + }; + match classify(oom, terminated, &e) { + err @ NodeEngineError::EvalFailed { .. } => { + reply.fail(err.with_logs(logs)); + None + } + err => Some(FatalExit { + err, + reply: Some(reply), + }), + } + } + } +} + +fn complete( + js: &mut JsRuntime, + oom: &AtomicBool, + terminated: &AtomicBool, + reply: Reply, + res: Result, Box>, + op_state: &Rc>, +) { + let is_eval = matches!(reply, Reply::Eval(_)); + + // Every eval exit path closes capture, so a later handler invocation with + // no eval in flight logs to tracing instead of a stale buffer. + let finish_eval = |op_state: &Rc>| { + with_ops_state(op_state, |s| { + s.capturing = false; + ( + std::mem::take(&mut s.logs), + // `OpsState::registered` is kind-tagged so a cross-kind + // unregister cannot drop the wrong entry (see ops.rs); the + // kind is internal bookkeeping and never leaves the worker. + std::mem::take(&mut s.registered) + .into_iter() + .map(|(_, id)| id) + .collect(), + ) + }) + }; + + let envelope = match res { + Err(e) => { + let logs = if is_eval { + finish_eval(op_state).0 + } else { + Vec::new() + }; + reply.fail(classify(oom, terminated, &e).with_logs(logs)); + return; + } + Ok(global) => { + let text = { + deno_core::scope!(scope, js); + let local = v8::Local::new(scope, global); + local.to_rust_string_lossy(scope) + }; + Envelope::parse(&text) + } + }; + + match envelope { + Err(e) => { + let logs = if is_eval { + finish_eval(op_state).0 + } else { + Vec::new() + }; + reply.fail(e.with_logs(logs)); + } + Ok(Envelope::Err(message)) => { + // The logs are the point: a tenant script that throws still + // produced whatever it printed first, and a host reporting this + // as a process-shaped response owes the caller that stdout. + let logs = if is_eval { + finish_eval(op_state).0 + } else { + Vec::new() + }; + reply.fail(NodeEngineError::EvalFailed { message, logs }); + } + Ok(Envelope::Ok(value)) => match reply { + Reply::Eval(tx) => { + let (logs, registered) = finish_eval(op_state); + let _ = tx.send(Ok(EvalOutcome { + result: value, + logs, + registered, + })); + } + // Deliberately does not clear `s.registered`: an id registered by + // a handler invoked outside an eval lingers there until the next + // eval clears it. Harmless — nothing reads `s.registered` between + // an INVOKE's own completion (this branch, which does not take + // it) and the next EVAL's start (`start`, which clears it before + // capturing begins), so a stale entry is invisible to any reader + // before it is wiped and can never contaminate a later eval's + // reported list. (`op_iii_register`'s dedup check used to read + // this list too, which is what the "more conservative, not + // wrong" framing here originally described — that check was + // removed once the kind-tagged `unregisters` lookup made it both + // redundant AND, for a cross-kind id collision, actively wrong.) + Reply::Invoke(tx) => { + let _ = tx.send(Ok(value)); + } + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::engine::FakeEngine; + use crate::engine::TriggerCallback; + use serde_json::json; + + /// Distinct from `call_timeout_ms` (2_000) so a test can tell "clamped to + /// the ceiling" apart from "fell back to the default". + const TEST_MAX_TIMEOUT_MS: u64 = 10_000; + + /// Small enough that a quota test can fill it without writing megabytes, + /// large enough that no ordinary test trips it by accident. + const TEST_SCRATCH_MB: usize = 1; + const TEST_SCRATCH_FILES: usize = 4; + + async fn eval( + rt: &RuntimeThread, + code: &str, + timeout_ms: u64, + ) -> Result { + let (reply, rx) = tokio::sync::oneshot::channel(); + rt.send(Command::Eval { + code: code.to_string(), + timeout: Duration::from_millis(timeout_ms), + reply, + }) + .map_err(|_| "runtime thread alive") + .expect("runtime thread alive"); + rx.await.expect("runtime thread replied") + } + + fn spawn_rt() -> RuntimeThread { + init_v8_platform(); + RuntimeThread::spawn( + RuntimeOpts { + heap_mb: 32, + external_mb: 8, + namespace: "test::".into(), + call_timeout_ms: 2_000, + max_timeout_ms: TEST_MAX_TIMEOUT_MS, + ids: crate::ids::IdRegistry::default(), + runtime_id: "rt-test".into(), + last_activity: Arc::new(std::sync::Mutex::new(std::time::Instant::now())), + scratch_mb: TEST_SCRATCH_MB, + scratch_files: TEST_SCRATCH_FILES, + scratch_root: None, + }, + FakeEngine::new(), + ) + } + + fn spawn_rt_with(engine: Arc) -> RuntimeThread { + spawn_rt_with_namespace(engine, "test::") + } + + /// Two runtimes on different namespaces — same shape as `spawn_rt_with`, + /// parameterised, for tests that need to prove one runtime cannot touch + /// another's ids. + fn spawn_rt_with_namespace(engine: Arc, namespace: &str) -> RuntimeThread { + spawn_rt_with_namespace_and_timeout(engine, namespace, 2_000) + } + + fn spawn_rt_with_namespace_and_timeout( + engine: Arc, + namespace: &str, + call_timeout_ms: u64, + ) -> RuntimeThread { + init_v8_platform(); + RuntimeThread::spawn( + RuntimeOpts { + heap_mb: 32, + external_mb: 8, + namespace: namespace.into(), + call_timeout_ms, + max_timeout_ms: TEST_MAX_TIMEOUT_MS, + ids: crate::ids::IdRegistry::default(), + runtime_id: format!("rt-test-{}", namespace.trim_end_matches(':')), + last_activity: Arc::new(std::sync::Mutex::new(std::time::Instant::now())), + scratch_mb: TEST_SCRATCH_MB, + scratch_files: TEST_SCRATCH_FILES, + scratch_root: None, + }, + engine, + ) + } + + /// The finding this guards: a derived `Debug` on `RuntimeOpts` would print + /// `runtime_id` — the capability to eval into or tear down this runtime — + /// the moment anything formats it with `{:?}`, e.g. a log line built from + /// the options on an error path. + #[test] + fn runtime_opts_debug_does_not_leak_the_runtime_id() { + let opts = RuntimeOpts { + heap_mb: 32, + external_mb: 8, + namespace: "test::".into(), + call_timeout_ms: 2_000, + max_timeout_ms: TEST_MAX_TIMEOUT_MS, + ids: crate::ids::IdRegistry::default(), + runtime_id: "rt-secret-capability".into(), + last_activity: Arc::new(std::sync::Mutex::new(std::time::Instant::now())), + scratch_mb: TEST_SCRATCH_MB, + scratch_files: TEST_SCRATCH_FILES, + scratch_root: None, + }; + let rendered = format!("{opts:?}"); + assert!( + !rendered.contains("rt-secret-capability"), + "leaked the runtime_id: {rendered}" + ); + assert!( + rendered.contains("test::"), + "non-secret fields should still show: {rendered}" + ); + } + + #[tokio::test] + async fn returns_the_completion_value() { + let rt = spawn_rt(); + let out = eval(&rt, "return 1 + 1", 2_000).await.unwrap(); + assert_eq!(out.result, json!(2)); + rt.shutdown(); + } + + #[tokio::test] + async fn supports_top_level_await() { + let rt = spawn_rt(); + let out = eval(&rt, "return await Promise.resolve({ a: 1 })", 2_000) + .await + .unwrap(); + assert_eq!(out.result, json!({ "a": 1 })); + rt.shutdown(); + } + + #[tokio::test] + async fn undefined_completion_is_null() { + let rt = spawn_rt(); + let out = eval(&rt, "const x = 1;", 2_000).await.unwrap(); + assert_eq!(out.result, json!(null)); + rt.shutdown(); + } + + #[tokio::test] + async fn globals_persist_across_evals_in_one_runtime() { + let rt = spawn_rt(); + eval(&rt, "globalThis.counter = 41", 2_000).await.unwrap(); + let out = eval(&rt, "return ++globalThis.counter", 2_000) + .await + .unwrap(); + assert_eq!(out.result, json!(42)); + rt.shutdown(); + } + + #[tokio::test] + async fn a_thrown_error_becomes_eval_failed_with_a_stack() { + let rt = spawn_rt(); + let err = eval(&rt, "throw new Error('boom')", 2_000) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + assert!(err.to_string().contains("boom")); + rt.shutdown(); + } + + #[tokio::test] + async fn a_syntax_error_becomes_eval_failed() { + let rt = spawn_rt(); + let err = eval(&rt, "this is not javascript", 2_000) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::eval_failed"); + rt.shutdown(); + } + + #[tokio::test] + async fn a_busy_loop_is_killed_at_the_deadline() { + let rt = spawn_rt(); + let err = eval(&rt, "for(;;){}", 300).await.unwrap_err(); + assert_eq!(err.code(), "node-engine::timeout"); + // The isolate is dead: the channel is closed, so a follow-up send + // fails. This is the invariant that forces teardown to close `rx` + // before answering the caller whose command did the killing. + let (reply, _rx) = tokio::sync::oneshot::channel(); + let send = rt.send(Command::Eval { + code: "return 1".into(), + timeout: Duration::from_millis(500), + reply, + }); + assert!( + send.is_err(), + "sender must be closed after the runtime dies" + ); + } + + /// Detached tenant work — a rejection handler on a promise the eval never + /// awaited — runs inside `poll_event_loop` AFTER the eval has replied, + /// when `pending` is empty and both deadline mechanisms would otherwise be + /// disarmed. Without the pump window this wedges the isolate thread + /// permanently, which in turn makes `teardown` and the idle sweeper block + /// forever on `RuntimeThread::Drop`'s join. + #[tokio::test] + async fn detached_work_cannot_wedge_the_isolate_after_the_eval_replies() { + let fake = FakeEngine::new(); + // The rejection MUST land in a later pump than the eval's own settle. + // A synchronous fake resolves the op and runs its `.catch` inside the + // same `poll_event_loop` call, while the eval is still pending and its + // deadline still covers everything — the detached window would be + // unreachable and this test would pass without proving anything. + fake.delay_calls(Duration::from_millis(300)); + let rt = spawn_rt_with(fake); + + // Nothing is awaited, so the eval settles at once. + let out = eval( + &rt, + "iii.trigger({ function_id: 'does::not::exist', payload: {} }).catch(() => { for(;;){} }); \ + return 'done'", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("done")); + + // `pending` is now empty and the slot is `None`. Wait for the delayed + // rejection to arrive and start spinning inside the pump — with no + // eval deadline and no `timeout_at`, only the pump window can stop it. + tokio::time::sleep(Duration::from_millis(600)).await; + + // Without the pump window this join never returns. `shutdown` blocks, + // so it has to run off the async runtime to be timeoutable at all. + let joined = tokio::task::spawn_blocking(move || rt.shutdown()); + tokio::time::timeout(Duration::from_secs(20), joined) + .await + .expect("isolate thread never exited — detached JS wedged the pump") + .expect("shutdown task joined"); + } + + #[tokio::test] + async fn a_never_settling_promise_is_killed_at_the_deadline() { + let rt = spawn_rt(); + let err = eval(&rt, "await new Promise(() => {})", 300) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::timeout"); + } + + /// The containment boundary. `Deno.core.ops.op_panic` is a literal + /// `panic!` that would kill this worker thread and with it every other + /// tenant's runtime, and `op_print` writes to the worker's stdout. + /// Neither may be reachable from tenant code. + #[tokio::test] + async fn deno_core_globals_are_removed_from_the_isolate() { + let rt = spawn_rt(); + let out = eval( + &rt, + "return [typeof Deno, typeof __bootstrap, typeof globalThis.Deno]", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(["undefined", "undefined", "undefined"])); + rt.shutdown(); + } + + #[tokio::test] + async fn op_panic_is_unreachable_from_tenant_code() { + let rt = spawn_rt(); + // Reaching it would panic the isolate thread, not fail this eval. + let out = eval( + &rt, + "try { Deno.core.ops.op_panic('pwned'); return 'REACHED' } \ + catch (e) { return 'blocked' }", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("blocked")); + // The runtime is still alive and serving. + assert_eq!(eval(&rt, "return 1", 2_000).await.unwrap().result, json!(1)); + rt.shutdown(); + } + + /// The tamper must be planted in one eval and observed in the NEXT. + /// + /// Within a single eval it is unobservable: `wrap_eval` emits + /// `globalThis.__iii.settle()`, and JS resolves the callee + /// before evaluating the argument, so code inside the IIFE cannot affect + /// the call carrying it. Globals persist across evals, so the real + /// exploit is cross-call. Two independent forms are planted here: + /// overwriting the `settle` property, and rebinding `__iii` itself to a + /// forged object — `Object.freeze` alone would only stop the former; + /// `defineProperty`'s non-writable, non-configurable binding stops both. + #[tokio::test] + async fn a_forged_settle_cannot_survive_into_the_next_eval() { + let rt = spawn_rt(); + eval( + &rt, + "try { globalThis.__iii.settle = () => '{\"ok\":\"forged\"}' } catch (e) {} \ + try { globalThis.__iii = { settle: () => '{\"ok\":\"forged\"}', invoke: () => {} } } \ + catch (e) {} \ + return 'planted'", + 2_000, + ) + .await + .unwrap(); + + // On a writable __iii, or one whose binding can be replaced wholesale, + // this eval's wrapper would resolve the forged `settle` and return + // "forged", so this assertion genuinely fails against unfixed code. + let after = eval(&rt, "return 'real'", 2_000).await.unwrap(); + assert_eq!(after.result, json!("real")); + rt.shutdown(); + } + + #[tokio::test] + async fn unbounded_allocation_is_killed_by_the_heap_cap() { + let rt = spawn_rt(); + let err = eval( + &rt, + "const a = []; for(;;) { a.push(new Array(100000).fill('x')); }", + 30_000, + ) + .await + .unwrap_err(); + assert_eq!(err.code(), "node-engine::oom"); + } + + #[tokio::test] + async fn console_lines_are_captured_in_order_with_levels() { + let rt = spawn_rt(); + let out = eval( + &rt, + "console.log('one'); console.warn('two'); console.error('three'); return 'done'", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("done")); + assert_eq!( + out.logs, + vec![ + LogLine { + level: "log".into(), + message: "one".into() + }, + LogLine { + level: "warn".into(), + message: "two".into() + }, + LogLine { + level: "error".into(), + message: "three".into() + }, + ] + ); + rt.shutdown(); + } + + #[tokio::test] + async fn console_formats_multiple_and_non_string_arguments() { + let rt = spawn_rt(); + let out = eval(&rt, "console.log('n =', 42, { a: 1 }); return null", 2_000) + .await + .unwrap(); + assert_eq!(out.logs.len(), 1); + assert_eq!(out.logs[0].message, r#"n = 42 {"a":1}"#); + rt.shutdown(); + } + + /// The log buffer is Rust-side, outside V8's heap cap, so a flood through + /// this sanctioned op must not become an unbounded process allocation. + #[tokio::test] + async fn a_console_flood_is_capped() { + let rt = spawn_rt(); + let out = eval( + &rt, + "for (let i = 0; i < 200000; i++) console.log('x'.repeat(64)); return 'done'", + 20_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("done")); + // 1000 lines plus at most one truncation marker. + assert!(out.logs.len() <= 1_001, "buffer grew to {}", out.logs.len()); + let last = out.logs.last().expect("some logs captured"); + assert!( + last.message.contains("truncated"), + "expected a truncation marker, got {:?}", + last + ); + rt.shutdown(); + } + + /// `a_console_flood_is_capped` uses 64-byte lines, so it trips + /// `MAX_LOG_LINES` (1000 * 64B = 64,000B, well under the 256KiB byte cap) + /// and never exercises `MAX_LOG_BYTES` at all. Fewer, larger messages — + /// 256KiB / 2048B ~= 128 lines — trip the byte cap on its own, proving + /// the byte accounting is real and not dead code shadowed by the line + /// check. + #[tokio::test] + async fn a_console_flood_of_large_messages_is_capped_by_bytes() { + let rt = spawn_rt(); + let out = eval( + &rt, + "for (let i = 0; i < 500; i++) console.log('x'.repeat(2048)); return 'done'", + 5_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("done")); + // Far short of the 1000-line cap: only the byte cap could have + // stopped this. + assert!( + out.logs.len() > 100 && out.logs.len() <= 130, + "expected ~128 lines plus a truncation marker, got {}", + out.logs.len() + ); + let last = out.logs.last().expect("some logs captured"); + assert!( + last.message.contains("truncated"), + "expected a truncation marker, got {:?}", + last + ); + rt.shutdown(); + } + + #[tokio::test] + async fn logs_do_not_leak_between_evals() { + let rt = spawn_rt(); + eval(&rt, "console.log('first'); return null", 2_000) + .await + .unwrap(); + let out = eval(&rt, "return null", 2_000).await.unwrap(); + assert!(out.logs.is_empty(), "second eval saw {:?}", out.logs); + rt.shutdown(); + } + + #[tokio::test] + async fn trigger_takes_the_sdk_request_object() { + let fake = FakeEngine::new(); + fake.with_response("test::double", Ok(json!(42))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "return await iii.trigger({ function_id: 'test::double', payload: { n: 21 } })", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(42)); + assert_eq!( + fake.calls(), + vec![("test::double".to_string(), json!({ "n": 21 }))] + ); + rt.shutdown(); + } + + #[tokio::test] + async fn call_function_no_longer_exists() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval(&rt, "return typeof iii.callFunction", 2_000) + .await + .unwrap(); + assert_eq!(out.result, json!("undefined")); + rt.shutdown(); + } + + #[tokio::test] + async fn trigger_rejects_a_request_without_a_function_id() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let err = eval(&rt, "return await iii.trigger({ payload: {} })", 2_000) + .await + .unwrap_err(); + assert!( + err.to_string() + .contains("function_id must be a non-empty string"), + "unhelpful message: {err}" + ); + rt.shutdown(); + } + + /// `trigger`'s other three validation branches — only `function_id`'s + /// had coverage. Each case's code is a separate eval so one failure + /// doesn't hide the rest; each asserts the message names what was wrong. + #[tokio::test] + async fn trigger_rejects_a_malformed_request_on_every_field() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + + let not_an_object = eval(&rt, "return await iii.trigger('nope')", 2_000) + .await + .unwrap_err(); + assert!( + not_an_object + .to_string() + .contains("request must be an object"), + "unhelpful message: {not_an_object}" + ); + + let bad_action = eval( + &rt, + "return await iii.trigger({ function_id: 'x::y', action: 3 })", + 2_000, + ) + .await + .unwrap_err(); + assert!( + bad_action.to_string().contains("action must be a string"), + "unhelpful message: {bad_action}" + ); + + let bad_timeout = eval( + &rt, + "return await iii.trigger({ function_id: 'x::y', timeout: '500' })", + 2_000, + ) + .await + .unwrap_err(); + assert!( + bad_timeout.to_string().contains("timeout must be a number"), + "unhelpful message: {bad_timeout}" + ); + + rt.shutdown(); + } + + #[tokio::test] + async fn trigger_resolves_with_the_engine_result() { + let fake = FakeEngine::new(); + fake.with_response("state::get", Ok(json!({ "value": 7 }))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "const r = await iii.trigger({ function_id: 'state::get', payload: { key: 'k' } }); \ + return r.value", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(7)); + assert_eq!( + fake.calls(), + vec![("state::get".to_string(), json!({ "key": "k" }))] + ); + rt.shutdown(); + } + + #[tokio::test] + async fn trigger_rejects_with_the_engine_error() { + let fake = FakeEngine::new(); + fake.with_response("thing::fail", Err("upstream exploded".into())); + let rt = spawn_rt_with(fake); + let out = eval( + &rt, + "try { await iii.trigger({ function_id: 'thing::fail', payload: {} }); \ + return 'no throw' } \ + catch (e) { return e.message }", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("upstream exploded")); + rt.shutdown(); + } + + /// `FakeEngine::call` ignores `action` (see its `calls()`, which only + /// records `fn_id`/`payload`), so this only proves an `action` field on + /// the request object reaches `op_iii_call` and `Engine::call` without + /// tripping any of `trigger`'s own validation. The string -> `TriggerAction` + /// decode `IIIEngine` does with that value (`parse_trigger_action`) is + /// covered directly in `src/engine.rs`'s test module — it had zero + /// coverage before this task, since nothing called `Engine::call` with + /// `Some(_)` until `trigger` did. + #[tokio::test] + async fn trigger_forwards_the_action_string_to_the_engine() { + let fake = FakeEngine::new(); + fake.with_response("app::react", Ok(json!(null))); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "return await iii.trigger({ function_id: 'app::react', payload: {}, action: 'void' })", + 2_000, + ) + .await + .unwrap(); + assert_eq!(fake.calls(), vec![("app::react".to_string(), json!({}))]); + rt.shutdown(); + } + + /// `trigger`'s payload crosses into Rust as JSON text built from the + /// pre-captured `stringify`, never the global `JSON.stringify` — see the + /// capture block near the top of `prelude.js`. Overwriting the global + /// once turned a thrown error into a reported success elsewhere in this + /// codebase; this proves `trigger` does not repeat that mistake. Unlike + /// the `settle`-forgery test, one eval is enough here: `stringify` is a + /// closure variable resolved once when the prelude loads, not a property + /// re-read at call time, so even tampering in the SAME eval that calls + /// `trigger` cannot reach it. + #[tokio::test] + async fn trigger_payload_survives_a_hijacked_json_stringify() { + let fake = FakeEngine::new(); + fake.with_response("test::echo", Ok(json!("ok"))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "JSON.stringify = () => { throw new Error('hijacked') }; \ + return await iii.trigger({ function_id: 'test::echo', payload: { n: 1 } })", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("ok")); + assert_eq!( + fake.calls(), + vec![("test::echo".to_string(), json!({ "n": 1 }))] + ); + rt.shutdown(); + } + + /// Everything `op_iii_call` holds lives on the Rust heap, outside V8's + /// cap, so both bounds have to hold or a tenant routes around its own + /// isolate's memory limit through a sanctioned op. + #[tokio::test] + async fn an_oversized_payload_is_rejected() { + let fake = FakeEngine::new(); + fake.with_response("thing::ping", Ok(json!("pong"))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "try { await iii.trigger({ function_id: 'thing::ping', \ + payload: { blob: 'x'.repeat(2 * 1024 * 1024) } }); \ + return 'accepted' } \ + catch (e) { return e.message }", + 10_000, + ) + .await + .unwrap(); + assert!( + out.result.as_str().unwrap().contains("limit"), + "expected a size-limit rejection, got {:?}", + out.result + ); + assert!( + fake.calls().is_empty(), + "oversized payload reached the engine" + ); + rt.shutdown(); + } + + /// `action`'s same hazard as `payload_json`: `#[string]` args are + /// byte-copied to the Rust heap at argument-dispatch time, before + /// `op_iii_call`'s body — and so before `MAX_CALL_PAYLOAD_BYTES` — ever + /// runs. Without its own cap this string is uncapped Rust-heap pinning + /// that `MAX_INFLIGHT_CALLS` does nothing to bound. + #[tokio::test] + async fn an_oversized_action_is_rejected() { + let fake = FakeEngine::new(); + fake.with_response("thing::ping", Ok(json!("pong"))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "try { await iii.trigger({ function_id: 'thing::ping', payload: {}, \ + action: 'x'.repeat(2000) }); \ + return 'accepted' } \ + catch (e) { return e.message }", + 10_000, + ) + .await + .unwrap(); + assert!( + out.result.as_str().unwrap().contains("limit"), + "expected a size-limit rejection, got {:?}", + out.result + ); + assert!( + fake.calls().is_empty(), + "oversized action reached the engine" + ); + rt.shutdown(); + } + + /// `function_id` is the third `#[string]` of the same shape, and was the + /// one left uncapped: measured at one eval firing 32 un-awaited calls + /// with an 8 MiB id, a single runtime went from 36 MiB to 316 MiB RSS + /// with 0 of the 32 refused — deno_core byte-copies the argument before + /// `op_iii_call`'s body runs, and it stays pinned across `engine.call`'s + /// await. At `heap_mb: 128` that is roughly 4 GiB from one runtime, + /// times `max_runtimes`. + #[tokio::test] + async fn an_oversized_function_id_is_rejected() { + let fake = FakeEngine::new(); + fake.with_response("thing::ping", Ok(json!("pong"))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "try { await iii.trigger({ function_id: 'thing::' + 'x'.repeat(1024), \ + payload: {} }); \ + return 'accepted' } \ + catch (e) { return e.message }", + 10_000, + ) + .await + .unwrap(); + assert!( + out.result.as_str().unwrap().contains("limit"), + "expected a size-limit rejection, got {:?}", + out.result + ); + assert!( + fake.calls().is_empty(), + "oversized function id reached the engine" + ); + rt.shutdown(); + } + + /// A guest-supplied `timeout` is a CEILING clamp, not passed through + /// verbatim: `iii.trigger({..., timeout: Number.MAX_SAFE_INTEGER})` + /// reaching `Engine::call` unclamped would, on the real `IIIEngine`, + /// become a `tokio::time::timeout` that effectively never expires, + /// holding an inflight slot and an entry in the SDK's process-wide + /// pending-invocation map far past the operator's configured + /// `max_timeout_ms`. A SHORT requested timeout must still pass through + /// unchanged — this is a ceiling, not a fixed override. + #[tokio::test] + async fn triggers_timeout_is_clamped_to_the_configured_ceiling() { + let fake = FakeEngine::new(); + fake.with_response("thing::ping", Ok(json!("pong"))); + let rt = spawn_rt_with(fake.clone()); + + eval( + &rt, + "return await iii.trigger({ function_id: 'thing::ping', payload: {}, timeout: 500 })", + 2_000, + ) + .await + .unwrap(); + eval( + &rt, + "return await iii.trigger({ function_id: 'thing::ping', payload: {}, \ + timeout: Number.MAX_SAFE_INTEGER })", + 2_000, + ) + .await + .unwrap(); + + assert_eq!(fake.call_timeouts(), vec![500, TEST_MAX_TIMEOUT_MS]); + rt.shutdown(); + } + + #[tokio::test] + async fn concurrent_calls_are_capped() { + let fake = FakeEngine::new(); + // A real engine call stays pending; the default fake resolves at once, + // which would drain the counter before the next call started. + fake.hang_calls(); + let rt = spawn_rt_with(fake); + let out = eval( + &rt, + // The 32 calls that win a slot hang forever, so the rejections + // cannot be awaited directly. Drain several microtask rounds + // instead: an op rejection takes a few hops to reach `.catch` + // (op promise -> trigger's async fn -> handler), and one + // round lands short. Rounds are deterministic, not timing-based, + // so this is a fixed count with margin, not a sleep. + "let rejected = 0; \ + for (let i = 0; i < 200; i++) { \ + iii.trigger({ function_id: 'x::y', payload: {} }).catch(() => { rejected++ }); \ + } \ + for (let i = 0; i < 10; i++) await Promise.resolve(); \ + return rejected", + 5_000, + ) + .await + .unwrap(); + // 200 fired, at most 32 may be in flight, so the rest must be refused. + assert!( + out.result.as_u64().unwrap() >= 168, + "expected the excess to be rejected, got {:?}", + out.result + ); + // Deliberately no shutdown(): the isolate still holds hung calls, and + // dropping it is exactly how a real torn-down runtime sheds them. + } + + /// `concurrent_calls_are_capped` only proves the cap trips; it does not + /// prove `release_inflight` ever runs. If the counter only ever grew, the + /// cap would degrade into a one-shot budget: the 33rd call ever made on a + /// long-lived runtime would fail forever after, not just while 32 calls + /// are genuinely outstanding. 40 sequential AWAITED calls — each one must + /// fully settle (and release its slot) before the next starts, since nothing + /// here is concurrent — crosses the 32-call cap entirely, so this fails if + /// the slot is never actually freed. + #[tokio::test] + async fn the_inflight_slot_is_released_after_each_call_so_later_calls_still_succeed() { + let fake = FakeEngine::new(); + fake.with_response("thing::ping", Ok(json!("pong"))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "for (let i = 0; i < 40; i++) { \ + await iii.trigger({ function_id: 'thing::ping', payload: {} }); \ + } \ + return 'done'", + 5_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("done")); + assert_eq!(fake.calls().len(), 40); + rt.shutdown(); + } + + /// A payload `JSON.stringify` cannot represent (a function) becomes + /// `undefined`, which the op receives as `""` and fails to parse. That + /// path has its own `release_inflight` call, so a leak there would slowly + /// exhaust the 32-slot cap and wedge the runtime. + #[tokio::test] + async fn an_unserializable_payload_rejects_without_leaking_a_slot() { + let fake = FakeEngine::new(); + fake.with_response("thing::ping", Ok(json!("pong"))); + let rt = spawn_rt_with(fake.clone()); + // NOTE: no `//` comments inside this JS string. Rust's `\`-newline + // continuation strips the newline, so the whole literal is ONE line + // and a `//` would comment out everything after it — including the + // `return`. Explanations go in Rust comments, out here. + // + // The trailing call is the actual assertion: if the rejected calls + // leaked their slots, 100 of them would have exhausted the 32-slot + // cap and this one would fail too. + let out = eval( + &rt, + "let refused = 0; \ + for (let i = 0; i < 100; i++) { \ + try { await iii.trigger({ function_id: 'thing::ping', payload: () => {} }) } \ + catch (e) { refused++ } \ + } \ + return [refused, await iii.trigger({ function_id: 'thing::ping', payload: {} })]", + 10_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!([100, "pong"])); + rt.shutdown(); + } + + #[tokio::test] + async fn trigger_defaults_a_missing_payload_to_an_empty_object() { + let fake = FakeEngine::new(); + fake.with_response("thing::ping", Ok(json!("pong"))); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "return await iii.trigger({ function_id: 'thing::ping' })", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("pong")); + assert_eq!(fake.calls(), vec![("thing::ping".to_string(), json!({}))]); + rt.shutdown(); + } + + #[tokio::test] + async fn register_then_invoke_round_trips_through_the_engine() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "iii.registerFunction('test::double', async (p) => ({ n: p.n * 2 })); return 'ok'", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.registered, vec!["test::double".to_string()]); + assert_eq!(fake.registered_ids(), vec!["test::double".to_string()]); + assert_eq!( + fake.invoke("test::double", json!({ "n": 21 })).await, + Ok(json!({ "n": 42 })) + ); + rt.shutdown(); + } + + #[tokio::test] + async fn a_synchronous_handler_works_too() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::inc', (p) => p.n + 1); return null", + 2_000, + ) + .await + .unwrap(); + assert_eq!( + fake.invoke("test::inc", json!({ "n": 1 })).await, + Ok(json!(2)) + ); + rt.shutdown(); + } + + #[tokio::test] + async fn a_throwing_handler_surfaces_its_message() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::boom', () => { throw new Error('nope') }); return null", + 2_000, + ) + .await + .unwrap(); + let err = fake.invoke("test::boom", json!({})).await.unwrap_err(); + assert!(err.contains("nope"), "got {err}"); + rt.shutdown(); + } + + #[tokio::test] + async fn ids_outside_the_namespace_are_rejected() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "try { iii.registerFunction('state::get', () => 1); return 'no throw' } \ + catch (e) { return e.message }", + 2_000, + ) + .await + .unwrap(); + assert!( + out.result.as_str().unwrap().contains("test::"), + "message should name the namespace, got {:?}", + out.result + ); + assert!(fake.registered_ids().is_empty()); + rt.shutdown(); + } + + /// Pins the SDK shape: `(functionId, handler, options?)` returning a ref + /// whose `unregister` is a function. + #[tokio::test] + async fn register_function_takes_an_options_object_and_returns_a_ref() { + let fake = FakeEngine::new(); + let out = eval( + &spawn_rt_with(fake.clone()), + "const ref = iii.registerFunction('test::x', () => 1, { description: 'd' }); + return typeof ref.unregister", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("function")); + } + + #[tokio::test] + async fn unregister_removes_the_function_from_the_engine() { + let fake = FakeEngine::new(); + eval( + &spawn_rt_with(fake.clone()), + "const ref = iii.registerFunction('test::x', () => 1); + ref.unregister(); + return 1", + 2_000, + ) + .await + .unwrap(); + assert!( + !fake.registered_ids().contains(&"test::x".to_string()), + "unregister() left the function published" + ); + } + + /// `unregister()` also drops the prelude's own `handlers` entry — not + /// just the engine-side registration — or an id the bus no longer routes + /// would still answer an INVOKE dispatched straight to this isolate. + #[tokio::test] + async fn unregister_removes_the_handlers_map_entry_too() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "const ref = iii.registerFunction('test::x', () => 1); + ref.unregister(); + return 1", + 2_000, + ) + .await + .unwrap(); + let out = eval(&rt, "return __iii.invoke('test::x', '{}')", 2_000) + .await + .unwrap_err(); + assert!( + out.to_string().contains("no handler registered"), + "got {out}" + ); + rt.shutdown(); + } + + /// `out.registered` is the eval's reported delta — `RunResponse.registered` + /// downstream, often the only record a one-shot `run` caller ever gets of + /// what its eval published. Unregistering inside the same eval that + /// registered must retract the id from that report too, or a caller is + /// told it published something that is not live. + #[tokio::test] + async fn unregister_in_the_same_eval_retracts_it_from_the_registered_report() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + + // Control: a plain registration must still be reported — proves the + // fix below did not simply stop reporting registrations at all. + let kept = eval( + &rt, + "iii.registerFunction('test::kept', () => 1); return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(kept.registered, vec!["test::kept".to_string()]); + + let unregistered = eval( + &rt, + "const ref = iii.registerFunction('test::x', () => 1); + ref.unregister(); + return 1", + 2_000, + ) + .await + .unwrap(); + assert!( + unregistered.registered.is_empty(), + "unregister() in the same eval should retract the id from the \ + response, got {:?}", + unregistered.registered + ); + rt.shutdown(); + } + + /// The SDK also accepts an `HttpInvocationConfig` object in the handler + /// position — an engine-side HTTP binding with no isolate involved. + /// node-engine cannot publish that; it must refuse, not silently accept + /// or coerce, and the refusal must name the real alternative. + #[tokio::test] + async fn a_non_function_handler_is_refused_naming_the_alternative() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "try { iii.registerFunction('test::http', { url: 'https://example.com' }); \ + return 'no throw' } \ + catch (e) { return e.message }", + 2_000, + ) + .await + .unwrap(); + let msg = out.result.as_str().unwrap(); + assert!( + msg.contains("HttpInvocationConfig") && msg.contains("engine::functions::register"), + "should name the alternative: {msg}" + ); + assert!(fake.registered_ids().is_empty()); + rt.shutdown(); + } + + /// End-to-end guest-surface proof that one runtime cannot touch another's + /// namespace at all — this is `op_iii_register`'s existing check, not + /// `op_iii_unregister`'s new one: the prelude's `registerFunction` only + /// ever hands `unregister()` an id that already passed ITS OWN + /// namespace check, so there is no JS-reachable way to hand a foreign id + /// to `op_iii_unregister` for this test to exercise. `op_iii_unregister`'s + /// own check is proven directly (with a hand-built `OpsState`, bypassing + /// that gate on purpose) by `ops::tests::a_runtime_cannot_unregister_another_runtimes_function`. + #[tokio::test] + async fn a_runtime_cannot_register_over_another_runtimes_namespace() { + let fake = FakeEngine::new(); + let victim = spawn_rt_with_namespace(fake.clone(), "victim::"); + eval( + &victim, + "iii.registerFunction('victim::secret', () => 1); return 1", + 2_000, + ) + .await + .unwrap(); + + let attacker = spawn_rt_with_namespace(fake.clone(), "attacker::"); + let err = eval( + &attacker, + "iii.registerFunction('victim::secret', () => 2); return 1", + 2_000, + ) + .await + .unwrap_err(); + assert!( + err.to_string().contains("victim::secret"), + "expected a namespace refusal naming the id: {err}" + ); + assert!( + fake.registered_ids() + .contains(&"victim::secret".to_string()), + "the victim's function was removed by another runtime" + ); + victim.shutdown(); + attacker.shutdown(); + } + + /// Registrations pin Rust-heap memory for the runtime's life AND write to + /// the trusted bus, so the count has to be bounded like every other + /// tenant-reachable allocation path. + #[tokio::test] + async fn registrations_are_capped_per_runtime() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "let ok = 0, refused = 0; \ + for (let i = 0; i < 400; i++) { \ + try { iii.registerFunction('test::f' + i, () => i); ok++ } \ + catch (e) { refused++ } \ + } \ + return [ok, refused]", + 20_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!([256, 144])); + assert_eq!( + fake.registered_ids().len(), + 256, + "the bus saw uncapped writes" + ); + rt.shutdown(); + } + + #[tokio::test] + async fn an_overlong_function_id_is_rejected() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "try { iii.registerFunction('test::' + 'x'.repeat(1024), () => 1); return 'accepted' } \ + catch (e) { return 'rejected' }", + 5_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!("rejected")); + assert!(fake.registered_ids().is_empty()); + rt.shutdown(); + } + + #[tokio::test] + async fn re_registering_an_id_replaces_the_handler() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::v', () => 1); return null", + 2_000, + ) + .await + .unwrap(); + eval( + &rt, + "iii.registerFunction('test::v', () => 2); return null", + 2_000, + ) + .await + .unwrap(); + assert_eq!(fake.invoke("test::v", json!({})).await, Ok(json!(2))); + rt.shutdown(); + } + + /// The reason the loop is multiplexed: a handler awaiting another handler + /// in the same isolate must interleave, not deadlock. + #[tokio::test] + async fn a_handler_can_await_another_handler_in_the_same_runtime() { + let fake = FakeEngine::new(); + // `iii.trigger` inside the isolate must come back in as a real + // dispatch, the way the engine would route it. + fake.route_calls_to_registrations(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::inner', (p) => p.n * 10); \ + iii.registerFunction('test::outer', async (p) => \ + await iii.trigger({ function_id: 'test::inner', payload: { n: p.n } })); \ + return null", + 2_000, + ) + .await + .unwrap(); + + let engine = fake.clone(); + let proxied = + tokio::spawn(async move { engine.invoke("test::outer", json!({ "n": 4 })).await }); + + let result = tokio::time::timeout(Duration::from_secs(5), proxied) + .await + .expect("outer/inner deadlocked") + .expect("task joined"); + assert_eq!(result, Ok(json!(40))); + rt.shutdown(); + } + + /// Console output from a handler invoked between evals belongs to no + /// caller's response; it must not surface in the next eval's logs. + #[tokio::test] + async fn handler_logs_outside_an_eval_do_not_leak_into_the_next_eval() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::noisy', () => { console.log('from handler'); return 1 }); \ + return null", + 2_000, + ) + .await + .unwrap(); + + assert_eq!(fake.invoke("test::noisy", json!({})).await, Ok(json!(1))); + + let out = eval(&rt, "return null", 2_000).await.unwrap(); + assert!(out.logs.is_empty(), "handler log leaked: {:?}", out.logs); + rt.shutdown(); + } + + /// Returns `":
"`, or `"ERR: …"` when `toHandler` throws. + /// Reaching through `.fn` on purpose: the return became `{ fn, form }` so + /// `eject` can emit the shape the caller actually got. + async fn to_handler(rt: &RuntimeThread, src: &str) -> serde_json::Value { + let code = format!( + "try {{ const h = __iii.toHandler('t::x', {}); return typeof h.fn + ':' + h.form }} \ + catch (e) {{ return 'ERR: ' + e.message }}", + serde_json::to_string(src).unwrap() + ); + eval(rt, &code, 2_000).await.unwrap().result + } + + #[tokio::test] + async fn to_handler_accepts_expression_forms() { + let rt = spawn_rt(); + for src in [ + "(p) => p.n * 2", + "async (p) => p.n", + "function (p) { return p.n * 2 }", + ] { + assert_eq!( + to_handler(&rt, src).await, + json!("function:expression"), + "src: {src}" + ); + } + assert_eq!( + to_handler(&rt, "return payload.n + 1").await, + json!("function:body"), + "a function body resolves to the body form" + ); + rt.shutdown(); + } + + #[tokio::test] + async fn to_handler_falls_back_to_a_body_only_on_a_syntax_error() { + let rt = spawn_rt(); + for src in ["return p.n * 2", "const x = 1; return x"] { + assert_eq!( + to_handler(&rt, src).await, + json!("function:body"), + "src: {src}" + ); + } + rt.shutdown(); + } + + /// The whole point of gating the fallback on `SyntaxError`. An + /// unconditional fallback would turn each of these into a live function + /// that returns null forever, which is indistinguishable on the wire from + /// a deliberate null. + #[tokio::test] + async fn to_handler_rejects_expressions_that_are_not_functions() { + let rt = spawn_rt(); + for src in ["42", "{ a: 1 }", "null", "payload.n * 2"] { + let out = to_handler(&rt, src).await; + let msg = out.as_str().unwrap(); + assert!(msg.starts_with("ERR: "), "src {src:?} produced {out:?}"); + assert!(msg.contains("t::x"), "message should name the id: {msg}"); + } + rt.shutdown(); + } + + /// A handler is free to `throw null`. Reading `.message` off that would + /// raise an unrelated TypeError and lose the id, so every path formats + /// through `formatError`. + #[tokio::test] + async fn to_handler_survives_a_handler_that_throws_a_non_error() { + let rt = spawn_rt(); + for src in ["(() => { throw null })()", "(() => { throw 7 })()"] { + let out = to_handler(&rt, src).await; + let msg = out.as_str().unwrap(); + assert!(msg.starts_with("ERR: "), "src {src:?} produced {out:?}"); + assert!(msg.contains("t::x"), "id lost for {src:?}: {msg}"); + assert!( + !msg.contains("Cannot read properties"), + "leaked an unrelated TypeError for {src:?}: {msg}" + ); + } + rt.shutdown(); + } + + /// `toHandler`'s own not-a-function error must not be caught and re-wrapped + /// by `toHandler` itself. + #[tokio::test] + async fn to_handler_does_not_double_wrap_its_own_error() { + let rt = spawn_rt(); + let out = to_handler(&rt, "42").await; + let msg = out.as_str().unwrap(); + assert_eq!( + msg.matches("handler for").count(), + 1, + "message wrapped twice: {msg}" + ); + rt.shutdown(); + } + + #[tokio::test] + async fn to_handler_rejects_text_that_parses_as_neither() { + let rt = spawn_rt(); + let out = to_handler(&rt, "@@@").await; + let msg = out.as_str().unwrap(); + assert!(msg.starts_with("ERR: "), "got {out:?}"); + // Without this the test passes before `toHandler` exists: the helper's + // catch turns "__iii.toHandler is not a function" into an "ERR: …" + // string, so it could never observe its own regression. + assert!(msg.contains("t::x"), "message should name the id: {msg}"); + rt.shutdown(); + } + + /// `iii.shutdown()` exists as a real property, not a missing one — the + /// SDK's `shutdown()` closes the client's connection, but a node-engine + /// runtime does not own one; the worker does, shared by every tenant. + /// Throwing here, by name, is what tells guest code the real way to + /// dispose a runtime instead of "undefined is not a function". + #[tokio::test] + async fn shutdown_throws_a_message_that_names_the_alternative() { + let fake = FakeEngine::new(); + let out = eval( + &spawn_rt_with(fake.clone()), + "try { iii.shutdown(); return 'no throw' } catch (e) { return e.message }", + 2_000, + ) + .await + .unwrap(); + let msg = out.result.as_str().unwrap(); + assert!(msg.contains("code-runner::teardown"), "unhelpful: {msg}"); + assert!(msg.contains("shared by every runtime"), "unhelpful: {msg}"); + } + + /// An agent's first move against an unknown global is printing it — an + /// opaque `{}` here previously cost a live session (in the sibling + /// sandbox-code-runner worker) six blind runs before anyone worked out + /// what the global even was. + #[tokio::test] + async fn the_iii_global_prints_a_usage_hint_rather_than_an_opaque_object() { + let fake = FakeEngine::new(); + let out = eval(&spawn_rt_with(fake.clone()), "return String(iii)", 2_000) + .await + .unwrap(); + let hint = out.result.as_str().unwrap(); + assert!( + hint.contains("iii.trigger"), + "hint does not name trigger: {hint}" + ); + assert!( + hint.contains("registerFunction"), + "hint does not name registerFunction: {hint}" + ); + } + + /// `settle`'s return value IS the eval's result as Rust reads it, so a + /// writable `iii` method would be a way for tenant code to forge this + /// runtime's results — the same reason `__iii` is frozen and + /// non-configurable. A no-op assignment under a silently-swallowed catch + /// (non-strict `iii.trigger = ...` on a frozen object) must leave the + /// original `trigger` untouched. + #[tokio::test] + async fn the_iii_global_is_frozen() { + let fake = FakeEngine::new(); + let out = eval( + &spawn_rt_with(fake.clone()), + "try { iii.trigger = () => 'forged'; } catch (_) {} + return typeof iii.trigger === 'function' && iii.trigger.name === 'trigger'", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!(true)); + } + + /// Pins the guest-visible API. The shim is hand-written against the SDK's + /// real signatures, so drift is invisible without a golden — this test is + /// what says "iii-sdk changed and we did not". + /// + /// Renders ARITY (`Function.length`) alongside the name and type, because + /// name-and-`typeof` alone is not a signature: `registerFunction` could + /// silently drop to one declared argument and still match a golden that + /// only says `function`. Arity is as much of the argument shape as JS + /// exposes reflectively — it counts parameters before the first default + /// or rest, which is exactly the SDK-shape drift worth catching. + /// + /// Read at RUNTIME rather than `include_str!` so `UPDATE_GOLDENS=1 + /// cargo test` regenerates this file the same way every other golden in + /// this crate is regenerated (see `tests/support/mod.rs`) — the golden is + /// never meant to be hand-edited into agreement. + #[tokio::test] + async fn the_iii_surface_matches_its_golden() { + let fake = FakeEngine::new(); + let out = eval( + &spawn_rt_with(fake.clone()), + "return Object.keys(iii).sort().flatMap(k => { \ + const v = iii[k]; \ + const sig = x => `${typeof x}` + (typeof x === 'function' ? `/${x.length}` : ''); \ + const line = `${k}:${sig(v)}`; \ + return (v && typeof v === 'object') \ + ? [line, ...Object.keys(v).sort().map(k2 => ` ${k2}:${sig(v[k2])}`)] \ + : [line]; \ + }).join('\\n')", + 2_000, + ) + .await + .unwrap(); + let rendered = out.result.as_str().unwrap(); + + let path = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden/iii-surface.txt"); + if std::env::var("UPDATE_GOLDENS").as_deref() == Ok("1") { + std::fs::write(&path, format!("{rendered}\n")).expect("write golden"); + return; + } + let golden = std::fs::read_to_string(&path).expect("read golden"); + assert_eq!( + rendered, + golden.trim_end(), + "the iii surface changed; review, then regenerate with `UPDATE_GOLDENS=1 cargo test`" + ); + } + + /// The property this exists for: a failing script still produced whatever + /// it printed before it threw, and a host reporting the failure as a + /// process-shaped response owes the caller that stdout. + /// + /// Mutation: restore `let _ = finish_eval(op_state);` at either failure + /// site in `complete` — the logs come back empty and both arms fail. + #[tokio::test] + async fn a_throwing_eval_still_reports_what_it_printed() { + let rt = spawn_rt(); + + // Synchronous throw. + let err = eval( + &rt, + "console.log('before'); console.error('bad'); throw new Error('boom')", + 2_000, + ) + .await + .unwrap_err(); + match err { + NodeEngineError::EvalFailed { message, logs } => { + assert!(message.contains("boom"), "message was {message}"); + let rendered: Vec<_> = logs + .iter() + .map(|l| format!("{}:{}", l.level, l.message)) + .collect(); + assert_eq!(rendered, vec!["log:before", "error:bad"]); + } + other => panic!("expected EvalFailed, got {other:?}"), + } + + // Rejected promise, which reaches `complete` by the other path. + let err = eval( + &rt, + "console.log('printed'); await Promise.reject(new Error('nope'))", + 2_000, + ) + .await + .unwrap_err(); + match err { + NodeEngineError::EvalFailed { message, logs } => { + assert!(message.contains("nope"), "message was {message}"); + assert_eq!(logs.len(), 1); + assert_eq!(logs[0].message, "printed"); + } + other => panic!("expected EvalFailed, got {other:?}"), + } + rt.shutdown(); + } + + // --- iii.files: this runtime's private scratch directory --- + + /// The property `keep` exists for. Mutation: move the `TempDir` creation + /// out of `run_loop` and into the op (a per-call directory); the second + /// eval then reads nothing. + #[tokio::test] + async fn files_written_in_one_eval_are_visible_in_the_next() { + let rt = spawn_rt(); + eval(&rt, "iii.files.write('a.txt', 'hello'); return 1", 2_000) + .await + .unwrap(); + let out = eval(&rt, "return iii.files.readText('a.txt')", 2_000) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!("hello")); + rt.shutdown(); + } + + /// Mutation: hoist the `TempDir` to a process-global `OnceCell`; runtime B + /// then sees runtime A's file. + #[tokio::test] + async fn two_runtimes_never_share_a_directory() { + let a = spawn_rt(); + let b = spawn_rt(); + eval(&a, "iii.files.write('secret.txt', 'A'); return 1", 2_000) + .await + .unwrap(); + let out = eval(&b, "return iii.files.list()", 2_000).await.unwrap(); + assert_eq!(out.result, serde_json::json!([])); + let missing = eval( + &b, + "try { iii.files.readText('secret.txt'); return 'read' } catch (e) { return 'refused' }", + 2_000, + ) + .await + .unwrap(); + assert_eq!(missing.result, serde_json::json!("refused")); + a.shutdown(); + b.shutdown(); + } + + /// Asserts the total NEVER exceeded the cap, not merely that a call threw + /// — a check-after mutant (`current > cap` instead of `projected > cap`) + /// also throws, just one write too late. Also pins refuse-don't-kill: the + /// runtime still answers afterwards. + #[tokio::test] + async fn the_byte_quota_refuses_a_breaching_write_and_the_runtime_survives() { + let rt = spawn_rt(); + let out = eval( + &rt, + "const big = 'x'.repeat(600 * 1024); + iii.files.write('a.txt', big); + let refused = false; + try { iii.files.write('b.txt', big) } catch (e) { refused = true } + const total = iii.files.list().reduce((n, f) => n + f.bytes, 0); + return [refused, total]", + 5_000, + ) + .await + .unwrap(); + let arr = out.result.as_array().unwrap(); + assert_eq!( + arr[0], + serde_json::json!(true), + "the second write must be refused" + ); + assert!( + arr[1].as_u64().unwrap() <= (TEST_SCRATCH_MB * 1024 * 1024) as u64, + "the directory total must never exceed the cap, got {}", + arr[1] + ); + + let alive = eval(&rt, "return 'alive'", 2_000).await.unwrap(); + assert_eq!(alive.result, serde_json::json!("alive")); + rt.shutdown(); + } + + /// The `- target_bytes` term, at the JS level. Mutation: drop it from the + /// projection and the second overwrite is refused. + #[tokio::test] + async fn overwriting_a_file_does_not_double_count() { + let rt = spawn_rt(); + let out = eval( + &rt, + "const big = 'x'.repeat(900 * 1024); + iii.files.write('a.txt', big); + iii.files.write('a.txt', big); + iii.files.write('a.txt', big); + return iii.files.list().length", + 5_000, + ) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!(1)); + rt.shutdown(); + } + + /// One-byte files, so the byte cap provably cannot be what stopped it. + /// Mutation: delete the entry check, or flip `>` to `>=`. + #[tokio::test] + async fn the_entry_quota_refuses_the_file_past_the_cap() { + let rt = spawn_rt(); + let out = eval( + &rt, + "let written = 0; + let refused = false; + for (let i = 0; i < 20; i++) { + try { iii.files.write(`f${i}.txt`, 'x'); written++ } catch (e) { refused = true; break } + } + return [written, refused]", + 5_000, + ) + .await + .unwrap(); + let arr = out.result.as_array().unwrap(); + assert_eq!(arr[0], serde_json::json!(TEST_SCRATCH_FILES)); + assert_eq!(arr[1], serde_json::json!(true)); + rt.shutdown(); + } + + /// Without `remove`, the first tenant to fill the quota has permanently + /// bricked its own runtime. Mutation: make `remove` a reporting no-op. + #[tokio::test] + async fn removing_a_file_returns_its_bytes_to_the_quota() { + let rt = spawn_rt(); + let out = eval( + &rt, + "for (let i = 0; i < 4; i++) iii.files.write(`f${i}.txt`, 'x'); + let blocked = false; + try { iii.files.write('extra.txt', 'x') } catch (e) { blocked = true } + iii.files.remove('f0.txt'); + iii.files.write('extra.txt', 'x'); + return [blocked, iii.files.list().length]", + 5_000, + ) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!([true, 4])); + rt.shutdown(); + } + + /// Mutation: move the quota check after the truncating open. The mutant + /// leaves an EMPTY file — `truncate(true)` already fired — so asserting + /// only "it threw" would miss it. + #[tokio::test] + async fn a_refused_write_leaves_the_previous_contents_intact() { + let rt = spawn_rt(); + let out = eval( + &rt, + "iii.files.write('a.txt', 'keep me'); + try { iii.files.write('a.txt', 'x'.repeat(2 * 1024 * 1024)) } catch (e) {} + return iii.files.readText('a.txt')", + 5_000, + ) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!("keep me")); + rt.shutdown(); + } + + /// Both forms, because they are two different freezes: the inner + /// `Object.freeze(files)` in the prelude, and runtime.rs's shallow + /// `Object.freeze(globalThis.iii)`. Mutation: drop the inner freeze and + /// the first assertion fails. + #[tokio::test] + async fn iii_files_is_frozen() { + let rt = spawn_rt(); + let out = eval( + &rt, + "try { iii.files.write = () => 'forged' } catch (_) {} + try { iii.files = {} } catch (_) {} + return [typeof iii.files.write === 'function' && iii.files.write.length === 2, + typeof iii.files.list === 'function']", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!([true, true])); + rt.shutdown(); + } + + /// Uses V8's own codec on both sides. Mutation: hand-roll the encoder and + /// a surrogate pair comes back mangled. + #[tokio::test] + async fn text_round_trips_through_utf8() { + let rt = spawn_rt(); + let out = eval( + &rt, + "iii.files.write('u.txt', 'café 🎉'); + return [iii.files.readText('u.txt'), iii.files.read('u.txt') instanceof Uint8Array]", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, serde_json::json!(["café 🎉", true])); + rt.shutdown(); + } + + // --- Task 12: iii.registerTrigger / registerTriggerType / unregisterTriggerType --- + + /// The engine call for `iii.registerTrigger` — `Engine::register_trigger` + /// wired into the isolate for the first time. `t.unregister()` proves the + /// SDK-shaped ref this returns is really usable, not just shaped like + /// one: the brief's own test name promises "and can be removed", but its + /// given body never actually called `unregister()`. + #[tokio::test] + async fn register_trigger_reaches_the_engine_and_can_be_removed() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "const t = await iii.registerTrigger({ + type: 'state', function_id: 'app::react', config: { key: 'k' } + }); + globalThis.t = t; + return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(fake.registered_triggers().len(), 1); + + eval(&rt, "t.unregister(); return 1", 2_000).await.unwrap(); + assert_eq!( + fake.registered_triggers().len(), + 0, + "unregister() left the trigger live on the bus" + ); + rt.shutdown(); + } + + /// The engine calls INTO the isolate here. This is the same path a + /// registered function's handler uses; only the method name is new. + /// + /// Drives the callback with `fire_trigger_type_config` — the FULL + /// `TriggerConfig` shape the live engine actually sends, not + /// `fire_trigger_type`'s abbreviated `{method, config}` — and asserts on + /// `c.id`/`c.function_id` (which trigger instance, which function to + /// invoke — recoverable from nothing else) AND `c.config.key` (the + /// tenant's own opaque config), so this is evidence about the real wire + /// shape a `TriggerHandler` implementation receives, not about a test + /// double's narrower one. + #[tokio::test] + async fn a_trigger_type_handler_receives_engine_callbacks() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace(fake.clone(), "app::"); + eval( + &rt, + "globalThis.seen = []; + iii.registerTriggerType( + { id: 'app::mytype', description: 'test type' }, + { + registerTrigger: (c) => { globalThis.seen.push(['reg', c.id, c.function_id, c.config.key]) }, + unregisterTrigger: (c) => { globalThis.seen.push(['unreg', c.id, c.function_id, c.config.key]) }, + }, + ); + return 1", + 2_000, + ) + .await + .unwrap(); + + fake.fire_trigger_type_config( + "app::mytype", + "registerTrigger", + TriggerCallback { + id: "trig-1".to_string(), + function_id: "app::react".to_string(), + config: json!({ "key": "v" }), + metadata: None, + }, + ) + .await + .unwrap(); + let out = eval(&rt, "return globalThis.seen", 2_000).await.unwrap(); + assert_eq!(out.result, json!([["reg", "trig-1", "app::react", "v"]])); + rt.shutdown(); + } + + /// A tenant's trigger-type handler that hangs must not wedge the + /// engine's caller: the callback runs under `invoke_timeout_ms`, the + /// same budget a registered function's handler already uses + /// (`op_iii_register`'s proxy). + /// + /// This test discriminates by HANGING, not failing, if the timeout is + /// broken: `fire_trigger_type`'s future would simply never resolve. A + /// broken timeout should report a test failure, not wedge the whole + /// suite/CI run — wrapped in its own `tokio::time::timeout` so a + /// regression here fails fast with a clear message instead. + #[tokio::test] + async fn a_hanging_trigger_type_handler_times_out_instead_of_wedging() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace_and_timeout(fake.clone(), "app::", 50); + eval( + &rt, + "iii.registerTriggerType( + { id: 'app::slow' }, + { registerTrigger: () => new Promise(() => {}), unregisterTrigger: () => {} }, + ); + return 1", + 2_000, + ) + .await + .unwrap(); + let err = tokio::time::timeout( + Duration::from_secs(5), + fake.fire_trigger_type("app::slow", "registerTrigger", json!({ "id": "t1" })), + ) + .await + .expect("fire_trigger_type must resolve within 5s, not hang") + .unwrap_err(); + assert!(err.contains("timeout"), "expected a timeout, got: {err}"); + } + + /// Task 9's review flagged `IIIEngine::triggers` as unbounded and + /// guest-reachable the moment an op exists to reach it. Fills the shared + /// budget with function registrations, then proves BOTH new registration + /// kinds — not just functions — are refused once it is exhausted. + #[tokio::test] + async fn triggers_and_trigger_types_count_against_the_shared_registration_cap() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let fill = format!( + "for (let i = 0; i < {}; i++) {{ iii.registerFunction('test::f' + i, () => i) }} \ + return 1", + crate::ops::MAX_REGISTRATIONS_PER_RUNTIME, + ); + eval(&rt, &fill, 20_000).await.unwrap(); + + let trigger_err = eval( + &rt, + "await iii.registerTrigger({ type: 'state', function_id: 'test::f0', config: {} }); \ + return 1", + 2_000, + ) + .await + .unwrap_err(); + assert!( + trigger_err.to_string().contains("256"), + "must name the cap: {trigger_err}" + ); + assert!( + fake.registered_triggers().is_empty(), + "the bus saw an uncapped trigger write" + ); + + let type_err = eval( + &rt, + "iii.registerTriggerType({ id: 'test::overtype' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); \ + return 1", + 2_000, + ) + .await + .unwrap_err(); + assert!( + type_err.to_string().contains("256"), + "must name the cap: {type_err}" + ); + assert!( + fake.registered_trigger_types().is_empty(), + "the bus saw an uncapped trigger-type write" + ); + + rt.shutdown(); + } + + #[tokio::test] + async fn an_overlong_trigger_config_is_rejected() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let code = "try { await iii.registerTrigger({ type: 'state', function_id: 'test::f', \ + config: { big: 'x'.repeat(2 * 1024 * 1024) } }); return 'accepted' } \ + catch (e) { return 'rejected' }"; + let out = eval(&rt, code, 5_000).await.unwrap(); + assert_eq!(out.result, json!("rejected")); + assert!(fake.registered_triggers().is_empty()); + rt.shutdown(); + } + + #[tokio::test] + async fn an_overlong_trigger_type_id_is_rejected() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let code = "try { iii.registerTriggerType({ id: 'test::' + 'x'.repeat(1024) }, \ + { registerTrigger(){}, unregisterTrigger(){} }); return 'accepted' } \ + catch (e) { return 'rejected' }"; + let out = eval(&rt, code, 5_000).await.unwrap(); + assert_eq!(out.result, json!("rejected")); + assert!(fake.registered_trigger_types().is_empty()); + rt.shutdown(); + } + + #[tokio::test] + async fn trigger_type_ids_outside_the_namespace_are_rejected() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace(fake.clone(), "app::"); + let out = eval( + &rt, + "try { iii.registerTriggerType({ id: 'other::type' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); return 'no throw' } \ + catch (e) { return e.message }", + 2_000, + ) + .await + .unwrap(); + assert!( + out.result.as_str().unwrap().contains("app::"), + "message should name the namespace, got {:?}", + out.result + ); + assert!(fake.registered_trigger_types().is_empty()); + rt.shutdown(); + } + + #[tokio::test] + async fn unregister_trigger_type_removes_the_registration() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace(fake.clone(), "app::"); + eval( + &rt, + "const ref = iii.registerTriggerType({ id: 'app::mytype' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); \ + ref.unregister(); return 1", + 2_000, + ) + .await + .unwrap(); + assert!(fake.registered_trigger_types().is_empty()); + rt.shutdown(); + } + + /// The standalone `iii.unregisterTriggerType(id)` form — distinct from a + /// ref's own `unregister()` — accepts either a bare id string or the + /// original type object (reading its `.id`). + #[tokio::test] + async fn unregister_trigger_type_accepts_a_bare_id_or_the_type_object() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace(fake.clone(), "app::"); + eval( + &rt, + "iii.registerTriggerType({ id: 'app::a' }, { registerTrigger(){}, unregisterTrigger(){} }); \ + iii.registerTriggerType({ id: 'app::b' }, { registerTrigger(){}, unregisterTrigger(){} }); \ + iii.unregisterTriggerType('app::a'); \ + iii.unregisterTriggerType({ id: 'app::b' }); \ + return 1", + 2_000, + ) + .await + .unwrap(); + assert!(fake.registered_trigger_types().is_empty()); + rt.shutdown(); + } + + /// Re-registering under an id this runtime already holds is a no-op at + /// the engine layer (see `op_iii_register_trigger_type`'s doc comment for + /// why) — but the bus-level proxy is never rebuilt, so the invoke-time + /// lookup must still route to whichever handler was registered MOST + /// RECENTLY, not the first, or a re-registration would silently keep + /// firing stale JavaScript. + #[tokio::test] + async fn re_registering_a_trigger_type_routes_to_the_latest_handler() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace(fake.clone(), "app::"); + eval( + &rt, + "globalThis.seen = []; + iii.registerTriggerType({ id: 'app::mytype' }, { + registerTrigger: () => { globalThis.seen.push('first') }, + unregisterTrigger: () => {}, + }); + iii.registerTriggerType({ id: 'app::mytype' }, { + registerTrigger: () => { globalThis.seen.push('second') }, + unregisterTrigger: () => {}, + }); + return 1", + 2_000, + ) + .await + .unwrap(); + + fake.fire_trigger_type("app::mytype", "registerTrigger", json!({})) + .await + .unwrap(); + let out = eval(&rt, "return globalThis.seen", 2_000).await.unwrap(); + assert_eq!(out.result, json!(["second"])); + rt.shutdown(); + } + + /// A re-registration under an id this runtime already holds must not + /// spend a second slot from the shared cap. Fills to `MAX - 2` with + /// functions, registers ONE trigger type five times over (four of those + /// re-registrations), and proves exactly one more registration still + /// fits — it would already be refused if any of the five had counted. + #[tokio::test] + async fn re_registering_a_trigger_type_does_not_spend_a_second_cap_slot() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace(fake.clone(), "app::"); + let fill = format!( + "for (let i = 0; i < {}; i++) {{ iii.registerFunction('app::f' + i, () => i) }} \ + return 1", + crate::ops::MAX_REGISTRATIONS_PER_RUNTIME - 2, + ); + eval(&rt, &fill, 20_000).await.unwrap(); + + eval( + &rt, + "for (let i = 0; i < 5; i++) { \ + iii.registerTriggerType({ id: 'app::mytype' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); \ + } return 1", + 5_000, + ) + .await + .unwrap(); + + // `MAX - 2` functions + one logical trigger-type registration = `MAX + // - 1` held; exactly one more registration must still fit. + let out = eval( + &rt, + "iii.registerFunction('app::last', () => 1); return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(1)); + rt.shutdown(); + } + + // --- Task 12 fix round: kind-tagged registrations, full trigger-type + // payloads, the `.then` hijack, and the `registered` delta --- + + /// A function and a trigger type sharing the identical literal id must + /// not collide: before `RegistrationKind` tagged `unregisters` entries, + /// `op_iii_register_trigger_type`'s dedup check matched the FUNCTION + /// entry (id-only lookup) and treated the trigger type as "already + /// registered", so it silently never reached the bus while `eval` + /// reported success. + #[tokio::test] + async fn a_function_id_and_a_trigger_type_id_do_not_collide_on_registration() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::x', () => 1); return 1", + 2_000, + ) + .await + .unwrap(); + + let out = eval( + &rt, + "iii.registerTriggerType({ id: 'test::x' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(1)); + assert_eq!( + fake.registered_trigger_types(), + vec!["test::x".to_string()], + "the trigger type never reached the bus despite eval() reporting success" + ); + rt.shutdown(); + } + + /// Registering a function must not evict a same-named trigger type: + /// before the kind tag, `op_iii_register`'s dedup lookup matched the + /// TRIGGER TYPE'S entry, swap-removed it, and called ITS unregister — + /// silently un-publishing a live trigger type as a side effect of an + /// unrelated function registration. + #[tokio::test] + async fn registering_a_function_does_not_evict_a_same_named_trigger_type() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerTriggerType({ id: 'test::x', description: 'd' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(fake.registered_trigger_types(), vec!["test::x".to_string()]); + + eval( + &rt, + "iii.registerFunction('test::x', () => 1, { description: 'd' }); return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!( + fake.registered_trigger_types(), + vec!["test::x".to_string()], + "registering a function evicted the same-named trigger type from the bus" + ); + assert_eq!(fake.registered_ids(), vec!["test::x".to_string()]); + rt.shutdown(); + } + + /// `iii.unregisterTriggerType(id)` must not remove a same-named + /// FUNCTION: before the kind tag, `OpsState::unregister`'s lookup + /// matched on id alone, so unregistering a trigger type that was never + /// registered (but shares a string with a live function) silently + /// un-published the function instead. + #[tokio::test] + async fn unregistering_a_trigger_type_id_does_not_remove_a_same_named_function() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::x', () => 1); return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(fake.registered_ids(), vec!["test::x".to_string()]); + + eval(&rt, "iii.unregisterTriggerType('test::x'); return 1", 2_000) + .await + .unwrap(); + assert_eq!( + fake.registered_ids(), + vec!["test::x".to_string()], + "unregisterTriggerType removed a same-named FUNCTION" + ); + rt.shutdown(); + } + + /// `EvalOutcome.registered`/`RunResponse.registered` must report a + /// trigger-type id the eval just published — the same delta functions + /// already report, and with one-shot `run` the default, often the only + /// record a caller ever gets of what its eval published. + #[tokio::test] + async fn registering_a_trigger_type_is_reported_in_the_registered_delta() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with_namespace(fake.clone(), "app::"); + let out = eval( + &rt, + "iii.registerTriggerType({ id: 'app::mytype' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.registered, vec!["app::mytype".to_string()]); + rt.shutdown(); + } + + /// `invoke()` must not resolve the engine-calls-into-the-isolate path + /// through the tenant-replaceable `Promise.prototype.then`: a hijacked + /// `.then` sits between a handler and `settle`'s own (pre-captured) + /// `thenPromise`, and can forge whatever this call resolves to — turning + /// a handler that throws into a reported success, undetectable by the + /// engine. Exercises the SAME path `op_iii_register`'s function proxy + /// uses (`fake.invoke` re-enters through `Command::Invoke`/`wrap_invoke`, + /// not through `__iii.invoke` called directly inside an eval), which is + /// what makes this a real regression test rather than one only the + /// `wrap_eval`-wrapped path would catch. + #[tokio::test] + async fn a_hijacked_promise_then_cannot_forge_an_invoke_result() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + eval( + &rt, + "iii.registerFunction('test::boom', () => { throw new Error('handler blew up') }); \ + Promise.prototype.then = function () { return 'FORGED' }; \ + return 1", + 2_000, + ) + .await + .unwrap(); + let err = fake.invoke("test::boom", json!({})).await.unwrap_err(); + assert!(err.contains("handler blew up"), "got {err}"); + rt.shutdown(); + } + + // --- Task 12 fix round 2: the same three collision directions, but + // within ONE eval — `ops.registered` is eval-scoped (cleared at every + // `start`), so a bug gated on it can only ever show up here; the + // cross-eval versions above never exercised it at all. --- + + /// The primary same-eval probe: `op_iii_register`'s dedup check used to + /// also match `ops.registered.contains(&fn_id)` — kind-blind, and + /// populated by the trigger-type registration one line above — so the + /// function registration was treated as "already registered", silently + /// skipped the bus write, and the eval still reported success. + #[tokio::test] + async fn a_function_id_and_a_trigger_type_id_do_not_collide_on_registration_in_the_same_eval() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "iii.registerTriggerType({ id: 'test::x' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); \ + iii.registerFunction('test::x', () => 1); \ + return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(1)); + assert_eq!( + fake.registered_ids(), + vec!["test::x".to_string()], + "the function never reached the bus despite eval() reporting success" + ); + assert_eq!(fake.registered_trigger_types(), vec!["test::x".to_string()]); + assert_eq!( + out.registered, + vec!["test::x".to_string(), "test::x".to_string()], + "both registrations from this eval should be in the reported delta" + ); + rt.shutdown(); + } + + /// The removal half of the case above: `OpsState::unregister`'s trim of + /// `ops.registered` was kind-BLIND (`retain(|id| id != fn_id)`) while the + /// bus removal beside it was kind-tagged, so unregistering ONE of a + /// same-id function/trigger-type pair dropped BOTH from the reported + /// delta — the eval answered `registered: []` with a live function still + /// on the bus, understating exactly what the delta exists to report. + #[tokio::test] + async fn unregistering_one_kind_leaves_the_other_in_the_reported_delta() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "iii.registerFunction('test::x', () => 1); \ + iii.registerTriggerType({ id: 'test::x' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); \ + iii.unregisterTriggerType('test::x'); \ + return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!( + out.registered, + vec!["test::x".to_string()], + "the surviving function must still be reported as registered" + ); + assert_eq!( + fake.registered_ids(), + vec!["test::x".to_string()], + "the function is live on the bus" + ); + assert!(fake.registered_trigger_types().is_empty()); + rt.shutdown(); + } + + #[tokio::test] + async fn registering_a_function_does_not_evict_a_same_named_trigger_type_in_the_same_eval() { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "iii.registerTriggerType({ id: 'test::x', description: 'd' }, \ + { registerTrigger(){}, unregisterTrigger(){} }); \ + iii.registerFunction('test::x', () => 1, { description: 'd' }); \ + return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(1)); + assert_eq!( + fake.registered_trigger_types(), + vec!["test::x".to_string()], + "registering a function evicted the same-named trigger type from the bus" + ); + assert_eq!(fake.registered_ids(), vec!["test::x".to_string()]); + rt.shutdown(); + } + + #[tokio::test] + async fn unregistering_a_trigger_type_id_does_not_remove_a_same_named_function_in_the_same_eval( + ) { + let fake = FakeEngine::new(); + let rt = spawn_rt_with(fake.clone()); + let out = eval( + &rt, + "iii.registerFunction('test::x', () => 1); \ + iii.unregisterTriggerType('test::x'); \ + return 1", + 2_000, + ) + .await + .unwrap(); + assert_eq!(out.result, json!(1)); + assert_eq!( + fake.registered_ids(), + vec!["test::x".to_string()], + "unregisterTriggerType removed a same-named FUNCTION" + ); + rt.shutdown(); + } +} diff --git a/crates/node-core/src/wire/mod.rs b/crates/node-core/src/wire/mod.rs new file mode 100644 index 0000000000..0da413efd3 --- /dev/null +++ b/crates/node-core/src/wire/mod.rs @@ -0,0 +1,12 @@ +//! The request/response types for the three operations `RuntimeManager` +//! exposes. +//! +//! They live here rather than with the hosting worker because +//! `RuntimeManager`'s own methods take and return them. Nothing in this module +//! touches the bus — `serde` and `schemars` derives only — so the crate stays +//! SDK-free; the worker re-exports them under its `functions` module, which is +//! what registers them. + +pub mod register; +pub mod run; +pub mod teardown; diff --git a/crates/node-core/src/wire/register.rs b/crates/node-core/src/wire/register.rs new file mode 100644 index 0000000000..22c8c3a1fb --- /dev/null +++ b/crates/node-core/src/wire/register.rs @@ -0,0 +1,188 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, JsonSchema)] +pub struct RegisterRequest { + /// e.g. `my-app::greet`. The segment before the first `::` is the + /// namespace; the first registration claims it and later ids must share + /// it. code-runner keeps one node runtime per namespace as an + /// implementation detail you never see or manage. + pub function_id: String, + /// JavaScript defining `handler(payload)`: + /// `export function handler(p) { return p.n * 2 }`. The runtime loads + /// the source, calls `handler`, and JSON-serialises the return value. + pub source: String, + /// What `engine::functions::info` shows a caller — write one. + #[serde(default)] + pub description: Option, + /// Optional JSON Schema for the payload this function expects. + /// `engine::functions::info` shows it to the next caller in place of + /// "any". Must be a JSON object that actually constrains something — + /// see [`validate_format`]. + #[serde(default)] + pub request_format: Option, + /// Optional JSON Schema for the value the handler returns; same rules as + /// `request_format`. + #[serde(default)] + pub response_format: Option, +} + +/// Serialized-size ceiling for one caller-supplied format. Schemas are +/// registry metadata every `engine::functions::info` caller downloads, not a +/// place to store data. +pub const MAX_FORMAT_BYTES: usize = 16 * 1024; + +/// Top-level keywords at least one of which a supplied format must carry. A +/// JSON Schema without ANY of them (`{}`, `{"description": …}`) constrains +/// nothing — it is the "any" the caller is trying to replace — so refusing it +/// early beats publishing noise to the catalog. +const FORMAT_KEYWORDS: [&str; 10] = [ + "type", + "properties", + "$ref", + "enum", + "const", + "anyOf", + "oneOf", + "allOf", + "not", + "items", +]; + +/// Validate one caller-supplied `request_format`/`response_format` value. +/// Shared by the worker wire (both languages) and `op_iii_register` (the +/// guest path), so the two trust boundaries cannot drift into different +/// rules. +pub fn validate_format(field: &str, format: &serde_json::Value) -> Result<(), String> { + let Some(object) = format.as_object() else { + return Err(format!( + "{field} must be a JSON Schema OBJECT, e.g. {{\"type\": \"object\"}} — got {}", + kind_of(format) + )); + }; + if !FORMAT_KEYWORDS.iter().any(|k| object.contains_key(*k)) { + return Err(format!( + "{field} constrains nothing — a schema needs at least one of {FORMAT_KEYWORDS:?} at \ + its top level (an empty object is the \"any\" you already get by omitting the field)" + )); + } + let bytes = serde_json::to_string(format) + .map(|s| s.len()) + .unwrap_or(usize::MAX); + if bytes > MAX_FORMAT_BYTES { + return Err(format!( + "{field} is {bytes} bytes serialized; the limit is {MAX_FORMAT_BYTES}" + )); + } + Ok(()) +} + +fn kind_of(v: &serde_json::Value) -> &'static str { + match v { + serde_json::Value::Null => "null", + serde_json::Value::Bool(_) => "a boolean", + serde_json::Value::Number(_) => "a number", + serde_json::Value::String(_) => "a string", + serde_json::Value::Array(_) => "an array", + serde_json::Value::Object(_) => "an object", + } +} + +// `source` is tenant-authored code — a secret under the same rule the old +// `FunctionDef` hand-rolled Debug existed for. This is where it enters the +// crate, and nothing downstream retains a copy, so this is the only place it +// needs redacting. +impl std::fmt::Debug for RegisterRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RegisterRequest") + .field("function_id", &self.function_id) + .field("source", &"") + .field("description", &self.description) + .field("request_format", &self.request_format) + .field("response_format", &self.response_format) + .finish() + } +} + +// No secrets here — the id and namespace are public on the bus — so `Debug` +// derives. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RegisterResponse { + /// The id now answering on the bus. + pub function_id: String, + /// The namespace it was registered under, normalised to end in `::`. + pub namespace: String, +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The finding this guards: a derived `Debug` on any type carrying + /// tenant-authored source prints it the moment anything formats it with + /// `{:?}`. + #[test] + fn debug_redacts_source_only() { + let req = RegisterRequest { + function_id: "app::greet".into(), + source: "SECRET_TENANT_SOURCE_1234".into(), + description: Some("greets".into()), + request_format: None, + response_format: None, + }; + let rendered = format!("{req:?}"); + assert!( + !rendered.contains("SECRET_TENANT_SOURCE_1234"), + "leaked tenant source: {rendered}" + ); + assert!( + rendered.contains("app::greet"), + "non-secret fields should still show: {rendered}" + ); + assert!( + rendered.contains("greets"), + "non-secret fields should still show: {rendered}" + ); + } +} + +#[cfg(test)] +mod format_tests { + use super::*; + use serde_json::json; + + #[test] + fn formats_must_be_objects() { + for bad in [json!("s"), json!(1), json!(true), json!(null), json!([1])] { + let err = validate_format("request_format", &bad).unwrap_err(); + assert!(err.contains("OBJECT"), "{bad}: {err}"); + } + } + + #[test] + fn formats_must_constrain_something() { + for hollow in [json!({}), json!({"description": "hi"})] { + let err = validate_format("request_format", &hollow).unwrap_err(); + assert!(err.contains("constrains nothing"), "{hollow}: {err}"); + } + } + + #[test] + fn real_schema_shapes_pass() { + for good in [ + json!({"type": "object", "properties": {"n": {"type": "number"}}}), + json!({"$ref": "#/definitions/x"}), + json!({"enum": [1, 2]}), + json!({"anyOf": [{"type": "string"}, {"type": "number"}]}), + ] { + assert_eq!(validate_format("request_format", &good), Ok(()), "{good}"); + } + } + + #[test] + fn oversized_formats_are_refused() { + let big = json!({"type": "object", "description": "x".repeat(MAX_FORMAT_BYTES)}); + let err = validate_format("response_format", &big).unwrap_err(); + assert!(err.contains("the limit is"), "{err}"); + } +} diff --git a/crates/node-core/src/wire/run.rs b/crates/node-core/src/wire/run.rs new file mode 100644 index 0000000000..fce2db37e6 --- /dev/null +++ b/crates/node-core/src/wire/run.rs @@ -0,0 +1,161 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::runtime::LogLine; + +#[derive(Deserialize, JsonSchema)] +pub struct RunRequest { + /// JavaScript source. Wrapped in an async IIFE, so `return` sets the + /// result and top-level `await` works. + pub code: String, + /// Run in a SPECIFIC runtime, sharing its globals and registrations — + /// that runtime is NEVER disposed by this call, you own it. Omit this to + /// run one-shot (see `keep`). + #[serde(default)] + pub runtime_id: Option, + /// Required prefix for ids this runtime may register, normalized to end + /// in `::` — `app`, `app:`, and `app::` all mean `app::`. Must be one + /// worker name: lowercase letters, digits, `.`, `_` or `-`, at most 64 + /// bytes, and no inner `::`; ids may still nest below it, so + /// `myapp::v2::save` is fine under `myapp::`. Accepted only when creating + /// a runtime; defaults to `code-runner::::`, where + /// `runtime_id` is itself `rt-`. + #[serde(default)] + pub namespace: Option, + /// Only meaningful when `runtime_id` is omitted. `false` (the default): + /// one-shot — create a runtime, evaluate `code`, and dispose the + /// runtime; nothing persists, and the response carries no `runtime_id`. + /// `true`: create a runtime and leave it running; the response's + /// `runtime_id` addresses it for later calls and is the capability + /// `code-runner::teardown` needs to stop it. + #[serde(default)] + pub keep: bool, + /// Wall-clock budget in milliseconds, clamped to the configured maximum. + #[serde(default)] + pub timeout_ms: Option, +} + +// `code` is tenant-authored JavaScript — the same secret `FunctionDef::handler` +// hand-rolls `Debug` to keep out of `{:?}`. `runtime_id` — when present — is a +// capability, same rule as `RegisterRequest`'s identical optional field. +impl std::fmt::Debug for RunRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunRequest") + .field("code", &"") + .field( + "runtime_id", + &self.runtime_id.as_ref().map(|_| ""), + ) + .field("namespace", &self.namespace) + .field("keep", &self.keep) + .field("timeout_ms", &self.timeout_ms) + .finish() + } +} + +#[derive(Serialize, JsonSchema)] +pub struct RunResponse { + /// Present only when the runtime outlives this call (`keep: true`, or a + /// `runtime_id` you passed in). Treat as a secret: it is the capability + /// to run into or tear down that runtime. Absent — not null — on the + /// default one-shot path: the runtime is already disposed by the time + /// this response is sent, so there is nothing left to address. + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_id: Option, + /// The completion value, JSON-encoded. Null when the code returned + /// nothing or something JSON cannot represent. + pub result: serde_json::Value, + pub logs: Vec, + /// Engine function ids registered during this eval. + pub registered: Vec, +} + +// `runtime_id` is a capability — its own doc comment says so, and it is a +// direct sibling of `RegisterResponse`, which redacts the identical field. +// `.as_ref().map(...)` rather than a bare `""`: `None` must still +// print as `None`, or a one-shot response's debug output would lie about +// there being a secret to redact. +impl std::fmt::Debug for RunResponse { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunResponse") + .field( + "runtime_id", + &self.runtime_id.as_ref().map(|_| ""), + ) + .field("result", &self.result) + .field("logs", &self.logs) + .field("registered", &self.registered) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The finding this guards: a derived `Debug` on `RunRequest` would print + /// both tenant-authored `code` and, when present, the `runtime_id` + /// capability the moment anything formats it with `{:?}`. + #[test] + fn debug_does_not_leak_code_or_the_runtime_id() { + let req = RunRequest { + code: "SECRET_TENANT_SOURCE_1234".into(), + runtime_id: Some("rt-secret-capability".into()), + namespace: Some("app::".into()), + keep: false, + timeout_ms: None, + }; + let rendered = format!("{req:?}"); + assert!( + !rendered.contains("SECRET_TENANT_SOURCE_1234"), + "leaked tenant code: {rendered}" + ); + assert!( + !rendered.contains("rt-secret-capability"), + "leaked the runtime_id: {rendered}" + ); + assert!( + rendered.contains("app::"), + "non-secret fields should still show: {rendered}" + ); + } + + /// `RunResponse`'s own doc comment says to treat `runtime_id` as a + /// secret; a derived `Debug` would print it verbatim. + #[test] + fn debug_does_not_leak_the_runtime_id() { + let res = RunResponse { + runtime_id: Some("rt-secret-capability".into()), + result: serde_json::json!({ "a": 1 }), + logs: vec![], + registered: vec!["app::a".into()], + }; + let rendered = format!("{res:?}"); + assert!( + !rendered.contains("rt-secret-capability"), + "leaked the runtime_id: {rendered}" + ); + assert!( + rendered.contains("app::a"), + "non-secret fields should still show: {rendered}" + ); + } + + /// A one-shot response's `runtime_id` must be ABSENT on the wire, not + /// `null`: nothing survives the call to address, so the key itself must + /// not be there to imply otherwise (`skip_serializing_if`). + #[test] + fn response_omits_runtime_id_on_the_wire_when_absent() { + let res = RunResponse { + runtime_id: None, + result: serde_json::json!(1), + logs: vec![], + registered: vec![], + }; + let value = serde_json::to_value(&res).unwrap(); + assert!( + !value.as_object().unwrap().contains_key("runtime_id"), + "a one-shot response must not carry a null runtime_id key: {value}" + ); + } +} diff --git a/crates/node-core/src/wire/teardown.rs b/crates/node-core/src/wire/teardown.rs new file mode 100644 index 0000000000..b5e0747434 --- /dev/null +++ b/crates/node-core/src/wire/teardown.rs @@ -0,0 +1,72 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, JsonSchema)] +pub struct TeardownRequest { + /// The runtime to destroy. Unregisters its functions and kills the + /// isolate. Pass exactly one of this or `namespace`. + #[serde(default)] + pub runtime_id: Option, + /// Destroy the runtime backing this namespace's registered functions. + /// The only way to reclaim one: `register_function` never returns its + /// runtime id. + #[serde(default)] + pub namespace: Option, +} + +// `runtime_id` is a capability — same rule as `RunRequest` and `IdRegistry`. +// `namespace` is not: it is caller-chosen and already shown unredacted +// elsewhere (e.g. `register_function`'s response). Nothing formats this +// today; a derived `Debug` prints it in full the first time something does. +impl std::fmt::Debug for TeardownRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TeardownRequest") + .field( + "runtime_id", + &self.runtime_id.as_ref().map(|_| ""), + ) + .field("namespace", &self.namespace) + .finish() + } +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct TeardownResponse { + /// Engine function ids removed by this teardown. + pub unregistered: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_does_not_leak_the_runtime_id() { + let req = TeardownRequest { + runtime_id: Some("rt-secret-capability".into()), + namespace: None, + }; + let rendered = format!("{req:?}"); + assert!( + !rendered.contains("rt-secret-capability"), + "leaked the runtime_id: {rendered}" + ); + assert!( + rendered.contains("TeardownRequest"), + "should still name the type: {rendered}" + ); + } + + #[test] + fn debug_shows_the_namespace_unredacted() { + let req = TeardownRequest { + runtime_id: None, + namespace: Some("app::".into()), + }; + let rendered = format!("{req:?}"); + assert!( + rendered.contains("app::"), + "namespace is not a capability and should render plainly: {rendered}" + ); + } +} diff --git a/crates/node-core/tests/golden/iii-surface.txt b/crates/node-core/tests/golden/iii-surface.txt new file mode 100644 index 0000000000..e0e8fb8526 --- /dev/null +++ b/crates/node-core/tests/golden/iii-surface.txt @@ -0,0 +1,13 @@ +files:object + list:function/0 + read:function/1 + readText:function/1 + remove:function/1 + write:function/2 +namespace:string +registerFunction:function/3 +registerTrigger:function/1 +registerTriggerType:function/2 +shutdown:function/0 +trigger:function/1 +unregisterTriggerType:function/1 diff --git a/crates/python-core/Cargo.lock b/crates/python-core/Cargo.lock new file mode 100644 index 0000000000..aac1c97e61 --- /dev/null +++ b/crates/python-core/Cargo.lock @@ -0,0 +1,2793 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59317f77929f0e679d39364702289274de2f0f0b22cbf50b2b8cff2169a0b27a" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.0", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +dependencies = [ + "allocator-api2", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "bzip2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" +dependencies = [ + "libbz2-rs-sys", +] + +[[package]] +name = "cap-fs-ext" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78e5a3368ae89b7cb68186411452b4b9fac8b41be9c19bf3f47c2d2c8e36e6b" +dependencies = [ + "cap-primitives", + "cap-std", + "io-lifetimes 3.0.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "cap-primitives" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdadbd7c002d3a484b35243669abdae85a0ebaded5a61117169dc3400f9a7ff0" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + +[[package]] +name = "cap-std" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7281235d6e96d3544ca18bba9049be92f4190f8d923e3caef1b5f66cfa752608" +dependencies = [ + "cap-primitives", + "io-extras", + "io-lifetimes 3.0.1", + "rustix", +] + +[[package]] +name = "cc" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.20", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "cpp_demangle" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "cranelift-assembler-x64" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d552bd33b7a56dc70aeb1e1c960e51a218fa0db50f23873b500a310379450b2d" +dependencies = [ + "cranelift-assembler-x64-meta", +] + +[[package]] +name = "cranelift-assembler-x64-meta" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078e80e4c222279e3330f6aa1a256ca77ddf156d4453166a9f09defedc4594dd" +dependencies = [ + "cranelift-srcgen", +] + +[[package]] +name = "cranelift-bforest" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820ce15d4ad3562d613c31a67b6d0434d403e7091a68d1349903842f7d31737e" +dependencies = [ + "cranelift-entity", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-bitset" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61bca563d4b86d285928d9e27f97f27039bb33a0fc524fa130d7d0c106bf8ab3" +dependencies = [ + "serde", + "serde_derive", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709f4b7c0fb57d952658d5b5c07fbdc4149acd7b7f0de9678ae754b9c981949a" +dependencies = [ + "bumpalo", + "cranelift-assembler-x64", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-codegen-meta", + "cranelift-codegen-shared", + "cranelift-control", + "cranelift-entity", + "cranelift-isle", + "gimli", + "hashbrown 0.17.1", + "libm", + "log", + "postcard", + "pulley-interpreter", + "regalloc2", + "rustc-hash", + "serde", + "serde_derive", + "sha2 0.10.9", + "smallvec", + "target-lexicon", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen-meta" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "903dc8915af62aad1d9d0f39a5968d33fa80b9aa899ed6f56e47f40ca4512e1e" +dependencies = [ + "cranelift-assembler-x64-meta", + "cranelift-codegen-shared", + "cranelift-srcgen", + "heck", + "pulley-interpreter", +] + +[[package]] +name = "cranelift-codegen-shared" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0522d74c227e49f3fd49ab055311486ae4f09083262b66705bed676952491469" + +[[package]] +name = "cranelift-control" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66560ea1c5cef72e170b18e46d263dba2d3169c9d39e8cafdab2173c6362cc1a" +dependencies = [ + "arbitrary", +] + +[[package]] +name = "cranelift-entity" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62ef5b17cc814d27e96b66a5b46da0e4ce2b8ac55a6d478048bb99d04b05526" +dependencies = [ + "cranelift-bitset", + "serde", + "serde_derive", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-frontend" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a87e0aaa39dbf70693b348a221e45904111704ee8f9fef140498471005f9842d" +dependencies = [ + "cranelift-codegen", + "hashbrown 0.17.1", + "log", + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cranelift-isle" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf79003ebfa1eed5e87f3b84446ad5236f540268289960e14f387dc9b28e40b7" + +[[package]] +name = "cranelift-native" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05bf4f235743c81e67ee4db617c5a4a0b65d58d3f0cfc575ee0f1a4e0cd58273" +dependencies = [ + "cranelift-codegen", + "libc", + "target-lexicon", +] + +[[package]] +name = "cranelift-srcgen" +version = "0.134.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6977c2a71ab1e0d1e62f966b411a498aa04c4dce47d93d52f8a360a06058922" + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "uuid", +] + +[[package]] +name = "deflate64" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", + "zeroize", +] + +[[package]] +name = "directories-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339ee130d97a610ea5a5872d2bbb130fdf68884ff09d3028b81bec8a1ac23bbc" +dependencies = [ + "cfg-if", + "dirs-sys-next", +] + +[[package]] +name = "dirs-sys-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "either" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix", + "windows-sys 0.59.0", +] + +[[package]] +name = "futures" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" + +[[package]] +name = "futures-executor" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a" + +[[package]] +name = "futures-macro" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "futures-sink" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307" + +[[package]] +name = "futures-task" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109" + +[[package]] +name = "futures-util" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fxprof-processed-profile" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25234f20a3ec0a962a61770cfe39ecf03cb529a6e474ad8cff025ed497eda557" +dependencies = [ + "bitflags", + "debugid", + "rustc-hash", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "gimli" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" +dependencies = [ + "fnv", + "hashbrown 0.16.1", + "indexmap", + "stable_deref_trait", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", + "serde", + "serde_core", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "iii-python-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "bytes", + "futures", + "schemars", + "serde", + "serde_json", + "sha2 0.11.0", + "tempfile", + "tokio", + "tracing", + "uuid", + "wasmtime", + "wasmtime-wasi", + "which", + "zip", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.60.2", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "ittapi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b996fe614c41395cdaedf3cf408a9534851090959d90d54a535f675550b64b1" +dependencies = [ + "anyhow", + "ittapi-sys", + "log", +] + +[[package]] +name = "ittapi-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5385394064fa2c886205dba02598013ce83d3e92d33dbdc0c52fe0e7bf4fc" +dependencies = [ + "cc", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libbz2-rs-sys" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2026a5056764a10b2bf5d56488cba40da507f5493a6a429340e2004d9ed085fa" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "lzma-rust2" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca93e534d1142d1d0dcca6d25fe302508a5dfb40b302802904577725ea0b695b" +dependencies = [ + "sha2 0.11.0", +] + +[[package]] +name = "mach2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" + +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memfd" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad38eb12aea514a0466ea40a80fd8cc83637065948eb4a426e4aa46261175227" +dependencies = [ + "rustix", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "crc32fast", + "hashbrown 0.17.1", + "indexmap", + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppmd-rust" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efca4c95a19a79d1c98f791f10aebd5c1363b473244630bb7dbde1dc98455a24" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pulley-interpreter" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc5c8c21ea032e4efbdf2d067dc45171779dbe0c8ecf20ef4a57efa7474f2b0a" +dependencies = [ + "cranelift-bitset", + "log", + "pulley-macros", + "wasmtime-internal-core", +] + +[[package]] +name = "pulley-macros" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f10925455d5dde962e3604eade797ba5488644c8ee14a44191e2f2b58980574" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "regalloc2" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85" +dependencies = [ + "allocator-api2", + "bumpalo", + "hashbrown 0.17.1", + "log", + "rustc-hash", + "serde", + "smallvec", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "js-sys", + "num-conv", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-compose" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59b710751a35d54732a63851cdfacbfb2266b7160ce174faf269d3f4e84e31b" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "log", + "petgraph", + "smallvec", + "wasm-encoder 0.252.0", + "wasmparser 0.252.0", + "wat", +] + +[[package]] +name = "wasm-encoder" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8185ae345fa5687c054626ff9a50e7089797a343d9904d1dc9820eb4c4d3196f" +dependencies = [ + "leb128fmt", + "wasmparser 0.252.0", +] + +[[package]] +name = "wasm-encoder" +version = "0.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b524283fb5df62eec102ed0574838961bdd7ba5ac9c50d38e2756c51c971a42" +dependencies = [ + "leb128fmt", + "wasmparser 0.255.0", +] + +[[package]] +name = "wasmparser" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3eb099dcadcde5be9eef55e3a337128efd4e44b4c93122487e4d2e4e1c6627c" +dependencies = [ + "bitflags", + "hashbrown 0.17.1", + "indexmap", + "semver", + "serde", +] + +[[package]] +name = "wasmparser" +version = "0.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e329ef4b5d46e73b91d3ac6924417cad55a8cbbf869c199283383427c3320b" +dependencies = [ + "bitflags", + "indexmap", + "semver", +] + +[[package]] +name = "wasmprinter" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7142797de29b35ab8dbf15c00f55fda75d409da4c423a8ab8bd6b667a785824b" +dependencies = [ + "anyhow", + "termcolor", + "wasmparser 0.252.0", +] + +[[package]] +name = "wasmtime" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c80ca6098e0d4d06886d91d7f2cc3cb6623eb583c4c0ab3c89cbfb6098c8586c" +dependencies = [ + "addr2line", + "async-trait", + "bitflags", + "bumpalo", + "cc", + "cfg-if", + "encoding_rs", + "futures", + "fxprof-processed-profile", + "gimli", + "ittapi", + "libc", + "log", + "mach2", + "memfd", + "object", + "once_cell", + "postcard", + "pulley-interpreter", + "rayon", + "rustix", + "semver", + "serde", + "serde_derive", + "serde_json", + "smallvec", + "target-lexicon", + "tempfile", + "wasm-compose", + "wasm-encoder 0.252.0", + "wasmparser 0.252.0", + "wasmtime-environ", + "wasmtime-internal-cache", + "wasmtime-internal-component-macro", + "wasmtime-internal-component-util", + "wasmtime-internal-core", + "wasmtime-internal-cranelift", + "wasmtime-internal-fiber", + "wasmtime-internal-jit-debug", + "wasmtime-internal-jit-icache-coherence", + "wasmtime-internal-unwinder", + "wasmtime-internal-versioned-export-macros", + "wat", + "windows-sys 0.61.2", + "wit-parser", +] + +[[package]] +name = "wasmtime-environ" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "134f9d136d29c76f6c1b4c9b468e97a2efc38c7d49fd188e39b64870b2fea701" +dependencies = [ + "anyhow", + "cpp_demangle", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-entity", + "gimli", + "hashbrown 0.17.1", + "indexmap", + "log", + "object", + "postcard", + "rustc-demangle", + "semver", + "serde", + "serde_derive", + "sha2 0.10.9", + "smallvec", + "target-lexicon", + "wasm-encoder 0.252.0", + "wasmparser 0.252.0", + "wasmprinter", + "wasmtime-internal-component-util", + "wasmtime-internal-core", +] + +[[package]] +name = "wasmtime-internal-cache" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65db2eb1bfc5371a3b4107dbf539d0b93d05016fc29625b1648146b47db02071" +dependencies = [ + "base64", + "directories-next", + "log", + "postcard", + "rustix", + "serde", + "serde_derive", + "sha2 0.10.9", + "toml", + "wasmtime-environ", + "windows-sys 0.61.2", + "zstd", +] + +[[package]] +name = "wasmtime-internal-component-macro" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf7b91fed3fc34781d57f9c6654ea2513bf0a99f7b0b0523c00de1e6efebe1c" +dependencies = [ + "anyhow", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasmtime-internal-component-util", + "wasmtime-internal-wit-bindgen", + "wit-parser", +] + +[[package]] +name = "wasmtime-internal-component-util" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc8a678149885cae00289f806fbe74c7863084cf74cace0b8dc73602279400e1" + +[[package]] +name = "wasmtime-internal-core" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a0092c4b9d070ac5e278b6d0db10f5e71214190f0347ca57502b4692f796321" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "libm", + "serde", +] + +[[package]] +name = "wasmtime-internal-cranelift" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6851ebc9e03cab23d9821d2b2505d380bdfe38f35ccec945247b05274d85c98b" +dependencies = [ + "cfg-if", + "cranelift-codegen", + "cranelift-control", + "cranelift-entity", + "cranelift-frontend", + "cranelift-native", + "gimli", + "itertools", + "log", + "object", + "pulley-interpreter", + "smallvec", + "target-lexicon", + "thiserror 2.0.20", + "wasmparser 0.252.0", + "wasmtime-environ", + "wasmtime-internal-core", + "wasmtime-internal-unwinder", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-fiber" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b26da6d5f60d4c438da70bba3553fe810a840533a64156be287dca2081c6991" +dependencies = [ + "cc", + "cfg-if", + "libc", + "rustix", + "wasmtime-environ", + "wasmtime-internal-versioned-export-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmtime-internal-jit-debug" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed621ba25d7bf78b7edd7b4749abbb27c2e5cdba836c9504a424ee74b6c23149" +dependencies = [ + "cc", + "object", + "rustix", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-jit-icache-coherence" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5684ba160951baad06a725696f3c590e2fb0e8067c2aebee27bf7f9259058e85" +dependencies = [ + "cfg-if", + "libc", + "wasmtime-internal-core", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmtime-internal-unwinder" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112eead527bffa8ff0646a11fb4339a9d52ddd1da2b9a6fce4aff84c815dd94f" +dependencies = [ + "cfg-if", + "cranelift-codegen", + "log", + "object", + "wasmtime-environ", +] + +[[package]] +name = "wasmtime-internal-versioned-export-macros" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "153592e0bed824fc13c6696203fa1bd7bd20eb355316475e39a55f081ef80eca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "wasmtime-internal-wit-bindgen" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c456ad6e81e0f46abfeca43687d18ea15e289c395b262ea6e0023e2682e088be" +dependencies = [ + "anyhow", + "bitflags", + "heck", + "indexmap", + "wit-parser", +] + +[[package]] +name = "wasmtime-wasi" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c1cf60cd6a565213af7074b4aad7bb5e110e3c6c6aae54425aa0500a0e15e86" +dependencies = [ + "async-trait", + "bitflags", + "bytes", + "cap-fs-ext", + "cap-std", + "cfg-if", + "futures", + "io-lifetimes 3.0.1", + "rand", + "rustix", + "thiserror 2.0.20", + "tokio", + "tracing", + "url", + "wasmtime", + "wasmtime-wasi-io", + "wiggle", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmtime-wasi-io" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fb08e1d7755aaa467ce14080b7b01e33c914a920f6000696f1e42e40ea6387e" +dependencies = [ + "async-trait", + "bytes", + "futures", + "tracing", + "wasmtime", +] + +[[package]] +name = "wast" +version = "35.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef140f1b49946586078353a453a1d28ba90adfc54dde75710bc1931de204d68" +dependencies = [ + "leb128", +] + +[[package]] +name = "wast" +version = "255.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ffec530f199bd3d553ac442c13dd108353cad533cad8514bc41e1f1f0fe686" +dependencies = [ + "bumpalo", + "leb128fmt", + "memchr", + "unicode-width", + "wasm-encoder 0.255.0", +] + +[[package]] +name = "wat" +version = "1.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dda82c82e1486c7eed42a0465e544d80fff37abc3b39482e0d34dbaabe2fe5b1" +dependencies = [ + "wast 255.0.0", +] + +[[package]] +name = "which" +version = "8.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f3ef584124b911bcc3875c2f1472e80f24361ceb789bd1c62b3e9a3df9ff43c" +dependencies = [ + "libc", +] + +[[package]] +name = "wiggle" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89091642df051b84a7e00bdff75e985e507f2298384e477cc9310b0ddd79f004" +dependencies = [ + "bitflags", + "thiserror 2.0.20", + "tracing", + "wasmtime", + "wasmtime-environ", + "wiggle-macro", +] + +[[package]] +name = "wiggle-generate" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12247f46f31bb5e7593947f9bba07317d0c1978e0d02250b979dd08f56f46e9f" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasmtime-environ", + "witx", +] + +[[package]] +name = "wiggle-macro" +version = "47.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e556a0880c9506fdcc662b1e226c7ced692f4977fed5b1ed40a3f3f0a48356f2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "wiggle-generate", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags", + "windows-sys 0.59.0", +] + +[[package]] +name = "wit-parser" +version = "0.252.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4266bea110371c620ccf3201c5023676046bc4556e5c7cfb5d500bda5ebc162d" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser 0.252.0", +] + +[[package]] +name = "witx" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e366f27a5cabcddb2706a78296a40b8fcc451e1a6aba2fc1d94b4a01bdaaef4b" +dependencies = [ + "anyhow", + "log", + "thiserror 1.0.69", + "wast 35.0.2", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "aes", + "bzip2", + "constant_time_eq", + "crc32fast", + "deflate64", + "flate2", + "getrandom 0.4.3", + "hmac", + "indexmap", + "lzma-rust2", + "memchr", + "pbkdf2", + "ppmd-rust", + "sha1", + "time", + "typed-path", + "zeroize", + "zopfli", + "zstd", +] + +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/crates/python-core/Cargo.toml b/crates/python-core/Cargo.toml new file mode 100644 index 0000000000..c7c1cea288 --- /dev/null +++ b/crates/python-core/Cargo.toml @@ -0,0 +1,50 @@ +[workspace] + +[package] +name = "iii-python-core" +version = "0.1.0" +edition = "2021" +description = "Run untrusted one-shot Python in CPython-on-WebAssembly inside wasmtime — the runner, guest wrapper and manager, with no bus dependency" +license = "Apache-2.0" +repository = "https://github.com/iii-hq/workers" +# Deliberately unpublished: workers in this repo link it by path, the same way +# they link crates/console-ui. +publish = false + +# NO iii-sdk, and no feature to add one back — same posture as +# crates/node-core, for the same reason. Nothing in this crate ever names an +# SDK type: `Manager` and `Runner` are pure compute over `RunSpec`/`RunOutcome`, +# and the hosting worker owns every connection. A crate with no SDK dependency +# has no exact pin to collide with a worker's own. +[dependencies] +tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros", "sync", "time"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +# `BoxFuture` for the guest-bridge trait, the same shape node-core uses. +futures = "0.3" +# `RunRequest`/`RunResponse`/`LogLine` reach the wire through the hosting +# worker's registration, so their `JsonSchema` derives have to live with the +# structs. Must stay on the same schemars major as iii-sdk so the derived +# schema matches what `RegisterFunction` emits. +schemars = "0.8" +anyhow = "1" +tracing = "0.1" +# The sandbox. Pinned exact like deno_core in node-core: wasmtime majors churn +# monthly and the containment behaviour (epoch traps, limiter semantics) must +# not move under us. +wasmtime = "=47.0.3" +wasmtime-wasi = "=47.0.3" +# `OutputStream::write` takes `bytes::Bytes` and wasmtime-wasi does not +# re-export the crate, so the trait cannot be implemented without naming it. +bytes = "1" +# Runtime extraction of the embedded CPython-WASI bundle. +zip = "8" +tempfile = "3" +# Runtime ids. `rt-` matches every sibling worker's shape. +uuid = { version = "1", features = ["v4"] } + +[build-dependencies] +sha2 = "0.11" + +[dev-dependencies] +which = "8" diff --git a/crates/python-core/build.rs b/crates/python-core/build.rs new file mode 100644 index 0000000000..ce631f345a --- /dev/null +++ b/crates/python-core/build.rs @@ -0,0 +1,62 @@ +use std::env; +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +/// CPython 3.14.7 built for wasm32-wasip1 with WASI SDK 24, from the CPython +/// WASI platform maintainer. WASI SDK 26/27 are known-bad upstream (CPython +/// hang) — never bump the SDK half of this pin casually. +const URL: &str = "https://github.com/brettcannon/cpython-wasi-build/releases/download/v3.14.7/python-3.14.7-wasi_sdk-24.zip"; +const SHA256: &str = "2e064d3fb8172471d39d741348efa722349c40b96301f69968dff714999c584b"; + +fn sha256_hex(path: &PathBuf) -> Option { + use sha2::{Digest, Sha256}; + use std::fmt::Write; + let bytes = fs::read(path).ok()?; + // digest 0.11's `Output` is a `hybrid_array::Array`, which doesn't impl + // `LowerHex` — format byte-by-byte instead of `format!("{:x}", ..)`. + let digest = Sha256::digest(bytes); + let mut hex = String::with_capacity(digest.len() * 2); + for b in digest.iter() { + write!(hex, "{b:02x}").ok()?; + } + Some(hex) +} + +fn main() { + println!("cargo:rerun-if-env-changed=III_PYTHON_WASI_ZIP"); + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + let dest = out_dir.join("python-wasi.zip"); + // Sidecar digest file that artifact.rs embeds via include_str!. Writing + // it here (rather than duplicating the SHA256 literal in artifact.rs) + // means the cache key artifact.rs derives from ZIP_SHA256 can never + // drift from the value build.rs actually verified against. + let digest_path = out_dir.join("python-wasi.sha256"); + + if sha256_hex(&dest).as_deref() == Some(SHA256) { + // Already fetched and verified. Recreate the digest sidecar if it + // was removed independently of the zip (e.g. a manual `rm`) so a + // stale OUT_DIR can't leave artifact.rs's include_str! dangling. + if !digest_path.is_file() { + fs::write(&digest_path, SHA256).expect("writing digest sidecar file"); + } + return; + } + if let Ok(local) = env::var("III_PYTHON_WASI_ZIP") { + fs::copy(&local, &dest).unwrap_or_else(|e| panic!("copying {local}: {e}")); + } else { + let status = Command::new("curl") + .args(["-fsSL", "--retry", "3", "-o"]) + .arg(&dest) + .arg(URL) + .status() + .expect("curl must be on PATH (or set III_PYTHON_WASI_ZIP to a local copy)"); + assert!(status.success(), "downloading {URL} failed"); + } + let got = sha256_hex(&dest).unwrap_or_default(); + assert_eq!( + got, SHA256, + "python-wasi.zip digest mismatch — refusing to embed an unverified interpreter" + ); + fs::write(&digest_path, SHA256).expect("writing digest sidecar file"); +} diff --git a/crates/python-core/src/artifact.rs b/crates/python-core/src/artifact.rs new file mode 100644 index 0000000000..86f11305f1 --- /dev/null +++ b/crates/python-core/src/artifact.rs @@ -0,0 +1,124 @@ +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use wasmtime::{Config, Engine, Module}; + +/// The pinned CPython-WASI release zip, verified against ZIP_SHA256 by build.rs. +pub const PYTHON_WASI_ZIP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/python-wasi.zip")); +/// The digest build.rs verified the embedded zip against, embedded from the +/// sidecar file it wrote — so this can never drift from what was actually +/// checked at build time (see build.rs's `SHA256` pin). +pub const ZIP_SHA256: &str = include_str!(concat!(env!("OUT_DIR"), "/python-wasi.sha256")); +pub const WASMTIME_VERSION: &str = "47.0.3"; + +/// How often the epoch ticker fires; deadlines are expressed in these ticks. +pub const EPOCH_TICK_MS: u64 = 10; + +/// The Engine every runtime shares: epoch interruption on, everything else default. +pub fn sandbox_engine() -> Result { + let mut cfg = Config::new(); + cfg.epoch_interruption(true); + // wasmtime::Error deliberately doesn't impl std::error::Error (see its + // docs), so anyhow's `Context` trait doesn't apply directly; convert via + // the crate's own `From for anyhow::Error` first. + Engine::new(&cfg) + .map_err(anyhow::Error::from) + .context("building wasmtime engine") +} + +fn cache_root() -> PathBuf { + // Containers routinely run with neither XDG_CACHE_HOME nor HOME set; + // this sits on the worker boot path, so that case must degrade to the + // temp dir (losing cache reuse across restarts), not panic the process. + let base = std::env::var_os("XDG_CACHE_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) + .unwrap_or_else(std::env::temp_dir); + base.join("iii").join("python-engine").join(ZIP_SHA256) +} + +/// Extract the embedded bundle into the versioned cache dir if it isn't +/// there yet. Atomic against concurrent extractors — separate processes, or +/// separate threads in the same process (as `cargo test` uses by default): +/// extract into a `tempfile`-unique temp sibling, then rename; a loser of +/// the rename race drops its own temp dir and uses the winner's tree. +pub fn ensure_extracted() -> Result { + let root = cache_root(); + if root.join("python.wasm").is_file() { + return Ok(root); + } + let parent = root.parent().expect("cache root has a parent"); + fs::create_dir_all(parent)?; + // A pid-only tmp name would collide between threads of the same test + // binary; `tempfile` gives every call its own unique directory instead. + let tmp = tempfile::Builder::new() + .prefix("extract-tmp-") + .tempdir_in(parent) + .context("creating extraction tempdir")?; + + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(PYTHON_WASI_ZIP)) + .context("embedded zip is unreadable")?; + for i in 0..zip.len() { + let mut entry = zip.by_index(i)?; + let Some(rel) = entry.enclosed_name() else { + anyhow::bail!("zip entry {} has an unsafe path", entry.name()); + }; + let dest = tmp.path().join(rel); + if entry.is_dir() { + fs::create_dir_all(&dest)?; + } else { + if let Some(dir) = dest.parent() { + fs::create_dir_all(dir)?; + } + let mut bytes = Vec::with_capacity(entry.size() as usize); + entry.read_to_end(&mut bytes)?; + fs::write(&dest, bytes)?; + } + } + match fs::rename(tmp.path(), &root) { + Ok(()) => { + let _ = tmp.keep(); // renamed away; nothing left to clean up on drop + } + Err(_) if root.join("python.wasm").is_file() => { + // Another instance won the race; `tmp` still owns its (unrenamed) + // directory and removes it when dropped at the end of scope. + } + Err(e) => return Err(e).context("publishing extracted artifact"), + } + Ok(root) +} + +/// Compile python.wasm, caching the serialized module next to the artifact, +/// keyed by wasmtime version. Cold: ~0.3 s. Warm: mmap, milliseconds. +pub fn load_module(engine: &Engine, root: &Path) -> Result { + let cwasm = root.join(format!("python-wasmtime-{WASMTIME_VERSION}.cwasm")); + if cwasm.is_file() { + // SAFETY: we serialized this file ourselves into a digest-keyed + // directory; the version key prevents cross-wasmtime loading. + match unsafe { Module::deserialize_file(engine, &cwasm) } { + Ok(m) => return Ok(m), + Err(e) => tracing::warn!(error = %e, "stale cwasm; recompiling"), + } + } + let wasm = fs::read(root.join("python.wasm")).context("reading python.wasm")?; + let module = Module::new(engine, &wasm) + .map_err(anyhow::Error::from) + .context("compiling python.wasm")?; + // Same collision this function's sibling (`ensure_extracted`) had: a + // pid-only tmp name is shared by every thread of one process, so two + // concurrent cold compiles could tear each other's `fs::write` to the + // same path, and that file is only ever read back through `unsafe` + // deserialize below. `tempfile_in` gives each writer its own private + // file, so there's nothing to tear; the final `persist` rename either + // installs a complete cwasm or is atomically superseded by another one. + use std::io::Write as _; + let mut tmp = tempfile::Builder::new() + .prefix("cwasm-tmp-") + .tempfile_in(root) + .context("creating cwasm tempfile")?; + tmp.write_all(&module.serialize()?)?; + let _ = tmp.persist(&cwasm); // best-effort cache; a losing persist is harmless + Ok(module) +} diff --git a/crates/python-core/src/config.rs b/crates/python-core/src/config.rs new file mode 100644 index 0000000000..79f6972ce1 --- /dev/null +++ b/crates/python-core/src/config.rs @@ -0,0 +1,94 @@ +//! Runtime caps and operator-facing limits, plus the compile-time caps the +//! wrapper, runner and manager enforce against. Unlike `NodeEngineConfig`, +//! this rejects unknown keys: it's operator config, not a wire request, so a +//! typo like `max_runtimez: 3` should fail loudly rather than silently no-op. +//! +//! Deserialization lives here; READING a file does not. `load_config` stays +//! with the worker that owns a `config.yaml`, which is what keeps `serde_yaml` +//! out of this crate. +use serde::Deserialize; + +pub const MAX_CODE_BYTES: usize = 1_048_576; +pub const MAX_PAYLOAD_BYTES: usize = 1_048_576; +pub const MAX_RESULT_BYTES: usize = 1_048_576; +pub const MAX_LOG_LINES: usize = 1_000; +pub const MAX_LOG_BYTES: usize = 262_144; + +#[derive(Debug, Clone, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct PythonEngineConfig { + pub max_concurrent_runs: usize, + /// Live runtimes (each owning a persistent `/work`) allowed at once. + /// + /// Deliberately far below node's 32: a python runtime's directory budget + /// is `MAX_WORK_DIR_BYTES`, so the host ceiling here is + /// `max_runtimes * 256 MiB` — 2 GiB at this default, and on a tmpfs + /// `$TMPDIR` that is host RAM. + pub max_runtimes: usize, + /// Reap a runtime with no activity for this long. The only backstop for + /// a caller that never tears one down. + pub idle_ttl_secs: u64, + pub default_timeout_ms: u64, + pub max_timeout_ms: u64, + pub default_memory_mb: u64, + pub max_memory_mb: u64, +} + +impl Default for PythonEngineConfig { + fn default() -> Self { + Self { + max_concurrent_runs: 8, + max_runtimes: 8, + idle_ttl_secs: 900, + default_timeout_ms: 5_000, + max_timeout_ms: 30_000, + default_memory_mb: 128, + max_memory_mb: 512, + } + } +} + +impl PythonEngineConfig { + // Ceilings are floored to 1: `u64::clamp` PANICS when min > max, and a + // configured `max_timeout_ms: 0` / `max_memory_mb: 0` reaches here + // unvalidated — that must degrade to the tightest real ceiling, not + // abort every run. + pub fn clamp_timeout(&self, requested: Option) -> u64 { + requested + .unwrap_or(self.default_timeout_ms) + .clamp(1, self.max_timeout_ms.max(1)) + } + pub fn clamp_memory(&self, requested: Option) -> u64 { + requested + .unwrap_or(self.default_memory_mb) + .clamp(1, self.max_memory_mb.max(1)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clamps_apply_defaults_and_ceilings() { + let cfg = PythonEngineConfig::default(); + assert_eq!(cfg.clamp_timeout(None), 5_000); + assert_eq!(cfg.clamp_timeout(Some(120_000)), 30_000); + assert_eq!(cfg.clamp_timeout(Some(0)), 1); + assert_eq!(cfg.clamp_memory(None), 128); + assert_eq!(cfg.clamp_memory(Some(4_096)), 512); + } + + /// A zero ceiling is an operator mistake, not a licence to panic: + /// `clamp(1, 0)` aborts every run. Mutation: drop either `.max(1)`. + #[test] + fn a_zero_ceiling_degrades_instead_of_panicking() { + let cfg = PythonEngineConfig { + max_timeout_ms: 0, + max_memory_mb: 0, + ..PythonEngineConfig::default() + }; + assert_eq!(cfg.clamp_timeout(Some(5_000)), 1); + assert_eq!(cfg.clamp_memory(Some(256)), 1); + } +} diff --git a/crates/python-core/src/error.rs b/crates/python-core/src/error.rs new file mode 100644 index 0000000000..3dbb7350bd --- /dev/null +++ b/crates/python-core/src/error.rs @@ -0,0 +1,104 @@ +//! The worker's structured error taxonomy. Carries no capability and no +//! tenant source code — only the message/traceback a tenant's own execution +//! produced — so unlike `node-engine::error`, this can `#[derive(Debug)]` +//! freely instead of hand-rolling a redacting one. +use serde::Serialize; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorKind { + InvalidInput, + SyntaxError, + PythonException, + Timeout, + OutOfMemory, + ResultTooLarge, + DiskQuotaExceeded, + /// The `runtime_id` names nothing live — never created, already torn + /// down, or reaped for idleness. + RuntimeNotFound, + /// `max_runtimes` live runtimes already exist. An ADMISSION failure: + /// retrying later may succeed, unlike the mid-run caps above. + Capacity, + Internal, +} + +impl ErrorKind { + /// The bare snake_case wire code — the same spelling `#[serde(rename_all + /// = "snake_case")]` produces, but without the JSON string quotes, since + /// this feeds a `code` field directly rather than a JSON document. + pub fn as_str(&self) -> &'static str { + match self { + Self::InvalidInput => "invalid_input", + Self::SyntaxError => "syntax_error", + Self::PythonException => "python_exception", + Self::Timeout => "timeout", + Self::OutOfMemory => "out_of_memory", + Self::ResultTooLarge => "result_too_large", + Self::DiskQuotaExceeded => "disk_quota_exceeded", + Self::RuntimeNotFound => "runtime_not_found", + Self::Capacity => "capacity", + Self::Internal => "internal", + } + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct PythonEngineError { + pub kind: ErrorKind, + pub message: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub traceback: Option, +} + +impl PythonEngineError { + pub fn new(kind: ErrorKind, message: impl Into) -> Self { + Self { + kind, + message: message.into(), + traceback: None, + } + } +} + +impl std::fmt::Display for PythonEngineError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.kind.as_str(), self.message) + } +} +impl std::error::Error for PythonEngineError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kinds_serialize_snake_case() { + let e = PythonEngineError::new(ErrorKind::ResultTooLarge, "too big"); + let v = serde_json::to_value(&e).unwrap(); + assert_eq!(v["kind"], "result_too_large"); + assert!(v.get("traceback").is_none()); + } + + /// `ErrorKind::as_str` is hand-written (it feeds a bare wire `code` + /// field, so it can't reuse the JSON-quoted serde output) — pin it + /// against the serde spelling for every variant so the two can't drift. + #[test] + fn as_str_agrees_with_serde_rename_for_every_variant() { + for kind in [ + ErrorKind::InvalidInput, + ErrorKind::SyntaxError, + ErrorKind::PythonException, + ErrorKind::Timeout, + ErrorKind::OutOfMemory, + ErrorKind::ResultTooLarge, + ErrorKind::DiskQuotaExceeded, + ErrorKind::RuntimeNotFound, + ErrorKind::Capacity, + ErrorKind::Internal, + ] { + let serde_spelling = serde_json::to_value(kind).unwrap(); + assert_eq!(serde_spelling, kind.as_str(), "drift for {kind:?}"); + } + } +} diff --git a/crates/python-core/src/lib.rs b/crates/python-core/src/lib.rs new file mode 100644 index 0000000000..6d79d37768 --- /dev/null +++ b/crates/python-core/src/lib.rs @@ -0,0 +1,12 @@ +//! iii-python-core: run untrusted one-shot Python in CPython-on-WebAssembly. +//! +//! Everything here is bus-free. `Manager` and `Runner` take a `RunSpec` and +//! return a `RunOutcome`; nothing in this tree names an `iii-sdk` type, so +//! nothing in it pins an SDK version. The wire types, the function +//! registration and the error conversion live with the hosting worker. + +pub mod artifact; +pub mod config; +pub mod error; +pub mod manager; +pub mod runner; diff --git a/crates/python-core/src/manager.rs b/crates/python-core/src/manager.rs new file mode 100644 index 0000000000..a6b9309ba1 --- /dev/null +++ b/crates/python-core/src/manager.rs @@ -0,0 +1,562 @@ +//! The layer between the wire and the sandbox: validate a request against +//! the caps, take a concurrency permit, hand a `RunSpec` to the `Runner`, and +//! turn the raw `RunOutcome` back into a `RunResponse` or a structured +//! `PythonEngineError`. +//! +//! `classify` is the point of this module. Its ordering is load-bearing: host +//! signals (`timed_out`, `disk_exceeded`, `memory_denied`) are checked before +//! anything the guest wrote (the envelope, the exit status), because a tenant +//! controls every byte under `/out` and could otherwise forge its way past a kill — +//! see `timeout_wins_over_a_forged_success_envelope` in `tests/manager.rs`. +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use serde::Deserialize; + +use crate::config::{ + PythonEngineConfig, MAX_CODE_BYTES, MAX_LOG_BYTES, MAX_LOG_LINES, MAX_PAYLOAD_BYTES, +}; +use crate::error::{ErrorKind, PythonEngineError}; +use crate::runner::{ + ExitKind, PersistentRuntime, PersistentSpec, RunOutcome, RunSpec, Runner, MAX_OUT_DIR_BYTES, + MAX_OUT_DIR_ENTRIES, +}; + +#[derive(Deserialize, schemars::JsonSchema)] +pub struct RunRequest { + /// Python source. Runs top-level; assign to `result` to return a value. + pub code: String, + /// Visible to the code as the global `payload` (None when omitted). + #[serde(default)] + pub payload: Option, + /// Wall-clock budget, default 5000, clamped to the config ceiling. + #[serde(default)] + pub timeout_ms: Option, + /// Linear-memory cap in MiB, default 128, clamped to the config ceiling. + #[serde(default)] + pub memory_mb: Option, +} + +// `code` is tenant-authored source — never print it, same rule +// `error.rs`'s module doc states for why `PythonEngineError` may derive +// `Debug` freely (it carries none). `payload` isn't source, but it is +// caller-supplied data of unknown shape that can carry secrets or PII just +// as easily as `code` can carry a hazardous string, so it gets the same +// redaction; presence (`Some`/`None`) still shows, only the contents don't. +// `timeout_ms`/`memory_mb` are plain knobs and stay visible — exactly what a +// diagnostic would want. +impl std::fmt::Debug for RunRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunRequest") + .field("code", &"") + .field("payload", &self.payload.as_ref().map(|_| "")) + .field("timeout_ms", &self.timeout_ms) + .field("memory_mb", &self.memory_mb) + .finish() + } +} + +/// What a run produced, in the shape the sandbox actually captured it. +/// +/// Two streams, not one pre-flattened log list. A host that reports a run as +/// a process — `stdout`/`stderr`/`exit_code` — needs them separate, and a +/// host that wants a level-tagged list can split them itself. Deciding that +/// here would force one of the two to unpick the other's choice. +/// +/// Each stream is independently capped at `MAX_LOG_LINES` lines and +/// `MAX_LOG_BYTES` bytes; `truncated` says whether anything was dropped, +/// either at the pipe (the guest outran the buffer) or here. +#[derive(Debug)] +pub struct RunOutput { + pub result: serde_json::Value, + pub stdout: String, + pub stderr: String, + pub truncated: bool, +} + +#[derive(Deserialize)] +struct Envelope { + ok: bool, + #[serde(default)] + result: serde_json::Value, + #[serde(default)] + kind: Option, + #[serde(default)] + message: Option, + #[serde(default)] + traceback: Option, +} + +/// One live runtime: a durable working directory, and when it was last used. +/// +/// The interpreter is NOT here. `python.wasm` is a WASI command module — +/// exports `memory` and `_start`, nothing else — so nothing can be called back +/// into after `_start` returns. What persists is the directory, which is also +/// exactly what sandbox-code-runner's `keep` promises. +struct Runtime { + work_dir: tempfile::TempDir, + last_activity: Mutex, + /// Fixed when the runtime is created. Linear memory only ever grows, so a + /// per-call ceiling on a shared interpreter would be a promise the sandbox + /// cannot keep — the second caller inherits whatever the first grew to. + memory_mb: u64, + /// The warm interpreter, booted on first use and `None` again once it has + /// been poisoned. An async mutex because one interpreter serves one turn + /// at a time and the wait is a real await, not a spin. + interp: tokio::sync::Mutex>, + /// Exempt from the idle sweep. Set for a runtime that backs a REGISTERED + /// function: nothing bumps its activity between invocations, so a + /// registration that is merely unpopular would otherwise be reaped and its + /// next caller would get `RuntimeNotFound` for a function the catalog + /// still advertises. `teardown` is the only way to remove one. + pinned: AtomicBool, +} + +pub struct Manager { + cfg: Arc, + runner: Arc, + /// What the guest's `iii` global can reach. `None` on a bare `Manager`; + /// the hosting worker installs one with [`Manager::with_bridge`]. + bridge: Option>, + permits: Arc, + runtimes: Mutex>>, +} + +impl Manager { + pub fn new(cfg: Arc, runner: Arc) -> Arc { + // `.max(1)`: zero permits is not "no concurrency", it is every run + // parked forever on a semaphore nothing ever releases. + let permits = Arc::new(tokio::sync::Semaphore::new(cfg.max_concurrent_runs.max(1))); + Arc::new(Self { + cfg, + runner, + permits, + bridge: None, + runtimes: Mutex::new(HashMap::new()), + }) + } + + /// Give guest code an `iii` global backed by `bridge`. + /// + /// Separate from `new` so the bare constructor stays usable in tests and + /// in a host that deliberately offers no bus access — an absent global is + /// a clearer contract than one that always refuses. + pub fn with_bridge( + cfg: Arc, + runner: Arc, + bridge: Arc, + ) -> Arc { + let permits = Arc::new(tokio::sync::Semaphore::new(cfg.max_concurrent_runs.max(1))); + Arc::new(Self { + cfg, + runner, + permits, + bridge: Some(bridge), + runtimes: Mutex::new(HashMap::new()), + }) + } + + /// A one-shot run: nothing persists, and nothing is addressable + /// afterwards. + pub async fn run(&self, req: RunRequest) -> Result { + let (code, payload_json, timeout_ms) = self.validate(&req)?; + let memory_mb = self.cfg.clamp_memory(req.memory_mb); + + // Permits are taken only after validation: a request that fails its + // caps must never queue behind runs that are actually going to + // execute. + let _permit = + self.permits.clone().acquire_owned().await.map_err(|_| { + PythonEngineError::new(ErrorKind::Internal, "worker is shutting down") + })?; + + let spec = RunSpec { + code: code.into_bytes(), + payload_json, + timeout_ms, + memory_mb, + work_dir: None, + bridge: self.bridge.clone(), + namespace: None, + }; + // Awaited directly — NOT `spawn_blocking`. `Runner::run` drives the + // guest on a fiber under `call_async`; its internal awaits (the + // epoch-slice yield, the wall-clock backstop timeout) need a real + // reactor. Moving it to a blocking thread would starve that reactor + // and disarm the very backstop that kills a guest parked in a host + // call (`time.sleep(86400)`), which would then hold the thread and + // this permit forever. + let outcome = self + .runner + .run(&spec) + .await + .map_err(|e| PythonEngineError::new(ErrorKind::Internal, format!("{e:#}")))?; + + classify(outcome, timeout_ms) + } + + /// Run in an existing runtime: same `/work`, and the same interpreter. + /// + /// Globals bound by an earlier call are still bound, and modules imported + /// by an earlier call are still imported. That is a superset of what + /// sandbox-code-runner promises for its own `keep`, which persists files + /// and boots a fresh interpreter per call. + /// + /// A call that overruns its budget takes the interpreter with it — the + /// only kill that reaches a guest parked in a host call unwinds `_start`, + /// leaving nothing resumable. The directory survives, so the next call on + /// this id boots a fresh interpreter on the same files. + pub async fn run_in( + &self, + runtime_id: &str, + req: RunRequest, + ) -> Result { + if req.memory_mb.is_some() { + return Err(PythonEngineError::new( + ErrorKind::InvalidInput, + "memory_mb is fixed when a runtime is created and cannot be set per call — \ + wasm linear memory only grows, so a later caller would inherit whatever an \ + earlier one already grew to", + )); + } + let rt = self.lookup(runtime_id)?; + let (code, payload_json, timeout_ms) = self.validate(&req)?; + + *rt.last_activity.lock().unwrap() = Instant::now(); + let out = self.turn_in(&rt, code, payload_json, timeout_ms).await; + // Bumped again on the way out: a long call must not look idle to a + // sweep that fires while it is still running. + *rt.last_activity.lock().unwrap() = Instant::now(); + out + } + + /// One turn on `rt`'s interpreter, booting or rebooting it as needed. + async fn turn_in( + &self, + rt: &Runtime, + code: String, + payload_json: Option, + timeout_ms: u64, + ) -> Result { + // Held across the whole turn: one interpreter runs one turn at a time, + // and a second caller must queue rather than interleave into a shared + // address space. + let mut slot = rt.interp.lock().await; + + // Taken after validation and after the runtime lock, so a request that + // fails its caps never queues behind runs that will actually execute. + let _permit = + self.permits.clone().acquire_owned().await.map_err(|_| { + PythonEngineError::new(ErrorKind::Internal, "worker is shutting down") + })?; + + // `None` here is either "never used" or "the last call poisoned it". + // Both boot the same way, on the same directory. + if !slot.as_ref().is_some_and(|i| i.is_live()) { + let fresh = self + .runner + .spawn_persistent(PersistentSpec { + work_dir: rt.work_dir.path().to_path_buf(), + memory_mb: rt.memory_mb, + bridge: self.bridge.clone(), + namespace: None, + }) + .await + .map_err(|e| { + PythonEngineError::new( + if e.memory_denied { + ErrorKind::OutOfMemory + } else { + ErrorKind::Internal + }, + format!("starting the interpreter: {:#}", e.error), + ) + })?; + *slot = Some(fresh); + } + + let outcome = slot + .as_ref() + .expect("just booted") + .run(code, payload_json, timeout_ms) + .await; + // Drop a poisoned interpreter now rather than on the next call, so a + // sweep or a teardown is not holding a corpse. + if !slot.as_ref().is_some_and(|i| i.is_live()) { + *slot = None; + } + let outcome = + outcome.map_err(|e| PythonEngineError::new(ErrorKind::Internal, format!("{e:#}")))?; + classify(outcome, timeout_ms) + } + + /// Create a runtime and return the id that addresses it. + /// + /// The directory name is `tempfile`'s own random suffix, never derived + /// from the id: a `runtime_id` is a capability, and a path is enumerable + /// by anything on the box. + pub fn create_runtime(&self, memory_mb: Option) -> Result { + let mut runtimes = self.runtimes.lock().unwrap(); + if runtimes.len() >= self.cfg.max_runtimes { + return Err(PythonEngineError::new( + ErrorKind::Capacity, + format!("all {} runtime slots are in use", self.cfg.max_runtimes), + )); + } + let work_dir = tempfile::Builder::new() + .prefix("iii-python-work-") + .tempdir() + .map_err(|e| { + PythonEngineError::new( + ErrorKind::Internal, + format!("creating the runtime's working directory: {e}"), + ) + })?; + let id = format!("rt-{}", uuid::Uuid::new_v4()); + runtimes.insert( + id.clone(), + Arc::new(Runtime { + work_dir, + last_activity: Mutex::new(Instant::now()), + memory_mb: self.cfg.clamp_memory(memory_mb), + interp: tokio::sync::Mutex::new(None), + pinned: AtomicBool::new(false), + }), + ); + Ok(id) + } + + /// Destroy a runtime and its directory. Dropping the `TempDir` is what + /// removes the tree, so every exit path gets cleanup for free. + pub fn destroy_runtime(&self, runtime_id: &str) -> Result<(), PythonEngineError> { + self.runtimes + .lock() + .unwrap() + .remove(runtime_id) + .map(|_| ()) + .ok_or_else(|| { + PythonEngineError::new( + ErrorKind::RuntimeNotFound, + format!("unknown runtime_id {runtime_id}"), + ) + }) + } + + /// Reap runtimes idle past `idle_ttl_secs`. The only backstop for a + /// caller that never tears one down. + pub fn sweep_idle(&self) -> Vec { + let ttl = std::time::Duration::from_secs(self.cfg.idle_ttl_secs); + let mut runtimes = self.runtimes.lock().unwrap(); + let stale: Vec = runtimes + .iter() + .filter(|(_, rt)| !rt.pinned.load(Ordering::Relaxed)) + .filter(|(_, rt)| rt.last_activity.lock().unwrap().elapsed() >= ttl) + .map(|(id, _)| id.clone()) + .collect(); + for id in &stale { + runtimes.remove(id); + } + stale + } + + /// Exempt `runtime_id` from the idle sweep. + /// + /// For a runtime backing a registered function, whose lifetime is the + /// registration's and not the traffic's. Idempotent, and there is + /// deliberately no unpin: the only way out is `destroy_runtime`, so a + /// pinned runtime cannot be quietly returned to the sweep by anything but + /// the teardown that also unregisters its functions. + pub fn pin_runtime(&self, runtime_id: &str) -> Result<(), PythonEngineError> { + self.lookup(runtime_id)? + .pinned + .store(true, Ordering::Relaxed); + Ok(()) + } + + pub fn live_runtime_count(&self) -> usize { + self.runtimes.lock().unwrap().len() + } + + fn lookup(&self, runtime_id: &str) -> Result, PythonEngineError> { + self.runtimes + .lock() + .unwrap() + .get(runtime_id) + .cloned() + .ok_or_else(|| { + PythonEngineError::new( + ErrorKind::RuntimeNotFound, + format!("unknown runtime_id {runtime_id}"), + ) + }) + } + + /// The caps every request faces, whichever path runs it. One + /// implementation so a persistent turn cannot accept code or a payload a + /// one-shot run would have refused. + fn validate( + &self, + req: &RunRequest, + ) -> Result<(String, Option, u64), PythonEngineError> { + if req.code.len() > MAX_CODE_BYTES { + return Err(PythonEngineError::new( + ErrorKind::InvalidInput, + format!("code is {} bytes; max {MAX_CODE_BYTES}", req.code.len()), + )); + } + let payload_json = match &req.payload { + None => None, + Some(v) => { + let s = serde_json::to_string(v).map_err(|e| { + PythonEngineError::new(ErrorKind::InvalidInput, format!("payload: {e}")) + })?; + if s.len() > MAX_PAYLOAD_BYTES { + return Err(PythonEngineError::new( + ErrorKind::InvalidInput, + format!( + "payload serializes to {} bytes; max {MAX_PAYLOAD_BYTES}", + s.len() + ), + )); + } + Some(s) + } + }; + Ok(( + req.code.clone(), + payload_json, + self.cfg.clamp_timeout(req.timeout_ms), + )) + } +} + +/// Host-side signals first; guest-writable bytes only after. +fn classify(out: RunOutcome, timeout_ms: u64) -> Result { + let (stdout, stderr, truncated) = capture_streams(&out); + + if out.timed_out { + return Err(PythonEngineError::new( + ErrorKind::Timeout, + format!("run exceeded {timeout_ms} ms and was killed"), + )); + } + + // Also host-derived, and also unconditional: the guest is killed the + // moment `/out` goes over, so there is no envelope it could have written + // that deserves to win here. + if let Some(which) = out.disk_exceeded { + let (bytes, entries) = match which { + "/work" => ( + crate::runner::MAX_WORK_DIR_BYTES, + crate::runner::MAX_WORK_DIR_ENTRIES, + ), + _ => (MAX_OUT_DIR_BYTES, MAX_OUT_DIR_ENTRIES), + }; + return Err(PythonEngineError::new( + ErrorKind::DiskQuotaExceeded, + format!( + "run wrote more than {bytes} bytes (or more than {entries} files) under \ + {which} and was killed" + ), + )); + } + + let envelope: Option = out + .envelope + .as_deref() + .and_then(|b| serde_json::from_slice(b).ok()); + let clean_success = matches!(&envelope, Some(e) if e.ok); + + if out.memory_denied && !clean_success { + return Err(PythonEngineError::new( + ErrorKind::OutOfMemory, + "run exceeded its memory cap and was killed", + )); + } + + match envelope { + Some(e) if e.ok => Ok(RunOutput { + result: e.result, + stdout, + stderr, + truncated, + }), + Some(e) => { + let kind = match e.kind.as_deref() { + Some("syntax_error") => ErrorKind::SyntaxError, + Some("python_exception") => ErrorKind::PythonException, + Some("result_too_large") => ErrorKind::ResultTooLarge, + // An envelope with an unrecognised kind is guest-shaped + // noise, not infrastructure: attribute it to the tenant. + _ => ErrorKind::PythonException, + }; + let mut err = PythonEngineError::new( + kind, + e.message + .unwrap_or_else(|| "tenant code failed".to_string()), + ); + err.traceback = e.traceback; + Err(err) + } + None => match out.exit { + ExitKind::Clean(status) => Err(PythonEngineError::new( + ErrorKind::PythonException, + format!("code exited with status {status} before completing"), + )), + // A trap with no envelope is guest-shaped, not infrastructure: + // only tenant code reaches this arm. A genuine host-side failure + // (instantiation, WASI setup) never becomes a `RunOutcome` at + // all — `Runner::run` returns it as an `Err`, handled above as + // `Internal`. Two ways tenant code lands here: `os._exit(200)` + // (wasmtime-wasi's `proc_exit` only maps status 0..126 to a + // clean `I32Exit`; anything >= 126 comes back as a plain trap) + // and real wasm stack exhaustion from runaway recursion. Both + // are the tenant's own doing, so this is `python_exception`, not + // `internal` — an unattributable exit here would let hostile + // input page an operator. The raw trap text can be an unbounded + // wasm backtrace, so it is logged for an operator to see and + // never handed to the caller. + ExitKind::Trap(reason) => { + tracing::warn!( + trap = %reason, + "guest execution trapped without producing a result; classifying as a tenant exception" + ); + Err(PythonEngineError::new( + ErrorKind::PythonException, + "execution ended abnormally without producing a result", + )) + } + }, + } +} + +/// Cap each captured stream independently and report whether anything was +/// lost, either at the pipe (the guest outran the buffer, `CapturedStream:: +/// dropped`) or here. +/// +/// Per stream rather than across both: they are two fields on the way out, so +/// a noisy stderr must not be able to consume the budget a caller needed for +/// stdout. +fn capture_streams(out: &RunOutcome) -> (String, String, bool) { + let mut truncated = out.stdout.dropped > 0 || out.stderr.dropped > 0; + let mut cap = |stream: &crate::runner::CapturedStream| { + let text = String::from_utf8_lossy(&stream.bytes); + let mut kept = String::new(); + for (n, line) in text.lines().enumerate() { + // `+ 1` counts the newline appended below; without it a stream + // of short lines overruns MAX_LOG_BYTES by up to MAX_LOG_LINES. + if n >= MAX_LOG_LINES || kept.len() + line.len() + 1 > MAX_LOG_BYTES { + truncated = true; + break; + } + kept.push_str(line); + kept.push('\n'); + } + kept + }; + let stdout = cap(&out.stdout); + let stderr = cap(&out.stderr); + (stdout, stderr, truncated) +} diff --git a/crates/python-core/src/runner.rs b/crates/python-core/src/runner.rs new file mode 100644 index 0000000000..9f472836fe --- /dev/null +++ b/crates/python-core/src/runner.rs @@ -0,0 +1,1559 @@ +//! The sandbox proper: one wasmtime `Engine`/`Module`/`InstancePre` for the +//! process, one fresh `Store` per call. Everything this module returns is a +//! *raw* signal — `manager.rs` does the classifying. In particular the three +//! containment flags (`timed_out`, `memory_denied`, `disk_exceeded`) are +//! derived only from host-side observations, never from anything the guest +//! wrote, so a tenant forging `/out/result.json` cannot talk its way out of a +//! kill. +use std::io::Read as _; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::{Context as TaskContext, Poll}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use bytes::Bytes; +use tokio::io::AsyncWrite; +use wasmtime::{Engine, InstancePre, Linker, ResourceLimiter, Store, Trap}; +use wasmtime_wasi::cli::{IsTerminal, StdinStream, StdoutStream}; +use wasmtime_wasi::p1::{self, WasiP1Ctx}; +use wasmtime_wasi::p2::{InputStream, OutputStream, Pollable, StreamResult}; +use wasmtime_wasi::{DirPerms, FilePerms, I32Exit, WasiCtxBuilder}; + +use crate::artifact::{self, EPOCH_TICK_MS}; +use crate::config::{MAX_LOG_BYTES, MAX_PAYLOAD_BYTES, MAX_RESULT_BYTES}; + +/// The interpreter's memory section declares a 640-page (40 MiB) minimum, so +/// wasmtime asks the limiter for that much before a single instruction runs. +/// A `memory_mb` below this can never host a run. +pub const MIN_MEMORY_MB: u64 = 40; + +/// Total bytes the guest may hold under `/out`. +/// +/// `/out` is the only resource wasmtime does not bound for us, and it is not +/// free disk: `tempfile::tempdir()` resolves under `$TMPDIR`, which on most +/// Linux hosts is tmpfs — i.e. host RAM, spent entirely outside `memory_mb`. +/// Four MiB costs a legitimate tenant nothing, since the only file that +/// matters is refused past `MAX_RESULT_BYTES` (1 MiB) on read. +pub const MAX_OUT_DIR_BYTES: u64 = 4 * 1024 * 1024; + +/// Directory entries the scan will visit before calling it a violation. +/// +/// The scan has to be bounded as well as the total: a guest that creates a +/// million small files would otherwise make the *walk* the attack. A +/// legitimate run leaves exactly one entry, so this is 64x headroom. +/// Byte budget for a runtime's `/work`, which unlike `/out` accumulates +/// across every call on that runtime. +/// +/// Far larger than `/out`'s, and affordable for the same reason the entry cap +/// is: the walk only runs while a call is in flight, and a parked runtime +/// writes nothing. The host ceiling is `max_runtimes * MAX_WORK_DIR_BYTES`, +/// which belongs in the operator docs — on a tmpfs `$TMPDIR` that is host RAM. +pub const MAX_WORK_DIR_BYTES: u64 = 256 * 1024 * 1024; +/// Entry budget for `/work`. Also the bound on its walk. +pub const MAX_WORK_DIR_ENTRIES: usize = 20_000; + +pub const MAX_OUT_DIR_ENTRIES: usize = 64; + +/// How often `/out` is measured while the guest runs. +/// +/// The bound is therefore soft by one interval's worth of writes (tens of MB +/// at WASI write speeds, not the tens of GB an unbounded run reaches). Buying +/// a tighter bound means paying a `read_dir` more often for every run, +/// including the honest ones. +const OUT_DIR_POLL: Duration = Duration::from_millis(250); + +/// How long the guest may hold the worker thread before it must hand it back. +/// +/// One tick, i.e. ~`EPOCH_TICK_MS`. The epoch deadline is re-armed this far +/// ahead over and over; each expiry yields to the executor and extends. This +/// is what stops a spinning guest from owning a tokio worker for its whole +/// budget — which would also stall the time driver, and with it the very +/// backstop a *parked* guest depends on. +const EPOCH_SLICE_TICKS: u64 = 1; + +// Both kills are armed at the same budget and still do not race, even though +// slicing now makes the fiber yield regularly. `tokio::time::timeout` polls +// the inner future first and only consults its delay on `Pending`, and the +// only `Pending` a guest can produce after the budget is spent comes from a +// host call — once `elapsed >= budget` the slice callback returns `Interrupt`, +// which is `Ready`, not a yield. So executing wasm always exits by the epoch +// (precise, and it names itself `Trap::Interrupt`) and the backstop only ever +// reaches a guest that has parked. I added a grace constant here to separate +// them and then deleted it: a mutation run at zero grace kept taking the epoch +// path 3/3, which is the same answer as the previous round for a related +// reason, so the constant was inert. + +pub struct RunSpec { + pub code: Vec, + pub payload_json: Option, + pub timeout_ms: u64, + pub memory_mb: u64, + /// A durable directory to preopen at `/work`, shared by every call on one + /// runtime. `None` for a one-shot run, which gets nothing. + /// + /// A one-shot run that is handed a `work_dir` sees the files a persistent + /// runtime left there, but brings none of its interpreter state — see + /// `PersistentRuntime` for the half that does survive. + pub work_dir: Option, + /// What the guest's `iii` global can do. `None` removes the global + /// entirely rather than leaving one that refuses — a guest surface that + /// exists and always fails is worse than an absent one. + pub bridge: Option>, + /// Published to the guest as `iii.namespace`. + pub namespace: Option, +} + +pub struct CapturedStream { + pub bytes: Vec, + pub dropped: u64, +} + +#[derive(Debug)] +pub enum ExitKind { + Clean(i32), + Trap(String), +} + +pub struct RunOutcome { + pub exit: ExitKind, + pub envelope: Option>, + pub stdout: CapturedStream, + pub stderr: CapturedStream, + /// The run exceeded its wall-clock budget. Host-derived, and true whichever + /// of the two kills fired — the epoch trap for executing wasm, or the + /// wall-clock backstop for a guest parked in a host call. + pub timed_out: bool, + pub memory_denied: bool, + /// Which guest-writable directory blew its budget, if either did — + /// `"/out"` or `"/work"`. Host-derived like the other two: measured by the + /// host walking its own directories, never reported by the guest. + /// + /// Names the directory rather than being a bare bool so the caller can be + /// told which budget to shrink; the two have very different sizes and very + /// different fixes. + pub disk_exceeded: Option<&'static str>, +} + +/// ResourceLimiter that records denial instead of erroring: growth beyond +/// the cap returns Ok(false), which CPython sees as allocation failure +/// (MemoryError) — the worker never trusts the guest to report it. +struct TrackedLimiter { + max_memory_bytes: usize, + denied: Arc, +} + +impl ResourceLimiter for TrackedLimiter { + fn memory_growing( + &mut self, + _current: usize, + desired: usize, + _max: Option, + ) -> wasmtime::Result { + if desired > self.max_memory_bytes { + self.denied.store(true, Ordering::Relaxed); + Ok(false) + } else { + Ok(true) + } + } + fn table_growing( + &mut self, + _current: usize, + _desired: usize, + _max: Option, + ) -> wasmtime::Result { + Ok(true) + } +} + +/// What `check_write` advertises. Matching wasmtime-wasi's own stdio impl: +/// large enough that the guest never sees back-pressure, since this sink +/// never blocks and never refuses. +const WRITE_BUDGET: usize = 1024 * 1024; + +/// Capped in-memory sink for guest stdout/stderr. Writes past the cap are +/// COUNTED AND DISCARDED, never refused: a tenant printing gigabytes must +/// neither buffer gigabytes on the host heap nor see print() start raising. +/// +/// The clones share one buffer and one counter, which is what lets the caller +/// keep a handle after handing one to `WasiCtxBuilder`. +#[derive(Clone)] +struct CappedPipe { + state: Arc>>, + dropped: Arc, + cap: usize, +} + +impl CappedPipe { + fn new(cap: usize) -> Self { + Self { + state: Arc::new(Mutex::new(Vec::new())), + dropped: Arc::new(AtomicU64::new(0)), + cap, + } + } + fn write_bytes(&self, buf: &[u8]) { + let mut b = self.state.lock().unwrap(); + let room = self.cap.saturating_sub(b.len()); + let take = room.min(buf.len()); + b.extend_from_slice(&buf[..take]); + let overflow = (buf.len() - take) as u64; + if overflow > 0 { + self.dropped.fetch_add(overflow, Ordering::Relaxed); + } + } + /// Drain what has been captured so far and reset the cap. + /// + /// A persistent runtime calls this at every turn boundary, which is what + /// makes `MAX_LOG_BYTES` a per-turn ceiling there rather than a per- + /// interpreter one — otherwise the tenth caller on a chatty runtime would + /// get no logs at all because the first nine filled the buffer. + fn take_captured(&self) -> CapturedStream { + CapturedStream { + bytes: std::mem::take(&mut *self.state.lock().unwrap()), + dropped: self.dropped.swap(0, Ordering::Relaxed), + } + } + fn into_captured(self) -> CapturedStream { + self.take_captured() + } +} + +// wasmtime-wasi 47.0.3 asks for two layers here. `StdoutStream` is what +// `WasiCtxBuilder::stdout`/`stderr` accept; it is a *factory* that hands out a +// fresh stream per `get-stdout` call, so the capping state has to live behind +// the Arc rather than in the stream itself. `p2_stream` has a default impl +// that wraps `async_stream` in an `AsyncWriteStream` — which spawns a tokio +// task and applies back-pressure — so we override it, exactly as every +// in-tree impl (`StdioOutputStream`, `MemoryOutputPipe`) does. The preview1 +// path we use reaches stdio only through `p2_stream`. +impl IsTerminal for CappedPipe { + fn is_terminal(&self) -> bool { + false + } +} + +impl StdoutStream for CappedPipe { + fn p2_stream(&self) -> Box { + Box::new(self.clone()) + } + fn async_stream(&self) -> Box { + Box::new(self.clone()) + } +} + +impl OutputStream for CappedPipe { + fn write(&mut self, bytes: Bytes) -> StreamResult<()> { + self.write_bytes(&bytes); + Ok(()) + } + fn flush(&mut self) -> StreamResult<()> { + Ok(()) // nothing is buffered anywhere else + } + fn check_write(&mut self) -> StreamResult { + Ok(WRITE_BUDGET) + } +} + +#[wasmtime_wasi::async_trait] +impl Pollable for CappedPipe { + async fn ready(&mut self) {} // always writable +} + +impl AsyncWrite for CappedPipe { + fn poll_write( + self: Pin<&mut Self>, + _cx: &mut TaskContext<'_>, + buf: &[u8], + ) -> Poll> { + self.write_bytes(buf); + // Report a full write: the overflow was accounted for in `dropped`, + // and a short write here would surface to the guest as a failed + // `print()`. + Poll::Ready(Ok(buf.len())) + } + fn poll_flush(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll> { + Poll::Ready(Ok(())) + } +} + +/// Read `/out/result.json`, refusing anything over `MAX_RESULT_BYTES`. +/// +/// `wrapper.py` enforces that cap, but only cooperating code goes through +/// `wrapper.py`: tenant code shares the interpreter and can write the file +/// itself, so the host must never size an allocation from a guest-chosen +/// number. `take()` bounds the read at cap+1 bytes — enough to tell "at the +/// cap" from "over it" without reading the rest. An over-cap file is reported +/// as *absent* rather than truncated: a truncated prefix could still parse +/// into a plausible-looking envelope. +/// +/// `/out` has `DirPerms::MUTATE`, which is all `path_symlink` is gated on +/// (`wasmtime-wasi/src/filesystem.rs`), and cap-primitives rejects only +/// *rooted* symlink targets — so `os.symlink("../../../../etc/passwd", +/// "/out/result.json")` is a link the guest can create. `File::open` is the +/// host's unsandboxed opener and would follow it, making the host read a +/// guest-chosen path with the worker's full authority (and block outright on +/// a FIFO). Refuse anything that is not a regular file. No TOCTOU: the guest +/// is dead by the time this runs. +fn read_envelope(path: &Path) -> Option> { + if !std::fs::symlink_metadata(path).ok()?.is_file() { + return None; + } + let mut buf = Vec::new(); + std::fs::File::open(path) + .ok()? + .take(MAX_RESULT_BYTES as u64 + 1) + .read_to_end(&mut buf) + .ok()?; + (buf.len() <= MAX_RESULT_BYTES).then_some(buf) +} + +/// A wasm backtrace has no bound the guest doesn't choose: +/// `sys.setrecursionlimit(10**9)` plus recursion renders thousands of frames, +/// hundreds of KB, repeatably. It is already kept out of the caller's error — +/// but it is *stored* here and warn-logged by `manager.rs`, and an operator's +/// log is a resource too. Counted in chars so the cut always lands on a +/// boundary. +const MAX_TRAP_CHARS: usize = 4096; + +fn trap_text(e: impl std::fmt::Display) -> String { + let s = format!("{e:#}"); + match s.char_indices().nth(MAX_TRAP_CHARS) { + Some((i, _)) => format!("{}... (trap text truncated)", &s[..i]), + None => s, + } +} + +/// True once `/out` is over either bound. Walks the tree — the guest has +/// `MUTATE`, so it can `mkdir` and hide bytes a level down — but stops the +/// instant either budget is blown, so the walk can never cost more than +/// `MAX_OUT_DIR_ENTRIES` stats. +/// +/// `DirEntry::metadata` does not traverse symlinks, which is what we want: a +/// link's target is somebody else's bytes, and following one would both +/// mis-account the total and hand the guest a way to make the host stat an +/// arbitrary path. +fn dir_over_budget(dir: &Path, max_bytes: u64, max_entries: usize) -> bool { + let mut stack = vec![dir.to_path_buf()]; + let mut bytes = 0u64; + let mut entries = 0usize; + while let Some(d) = stack.pop() { + let Ok(read) = std::fs::read_dir(&d) else { + continue; + }; + for entry in read.flatten() { + entries += 1; + if entries > max_entries { + return true; + } + let Ok(md) = entry.metadata() else { continue }; + if md.is_dir() { + stack.push(entry.path()); + } else { + bytes += md.len(); + if bytes > max_bytes { + return true; + } + } + } + } + false +} + +/// Resolves the first time either guest-writable directory is over budget, +/// naming which — and never otherwise, so it is only ever useful as the losing +/// side of a `select!`. +/// +/// One watchdog rather than two so the two budgets cannot race to report +/// different answers for the same kill. +async fn disk_watchdog(out_dir: PathBuf, work_dir: Option) -> &'static str { + loop { + tokio::time::sleep(OUT_DIR_POLL).await; + if dir_over_budget(&out_dir, MAX_OUT_DIR_BYTES, MAX_OUT_DIR_ENTRIES) { + return "/out"; + } + if let Some(w) = &work_dir { + if dir_over_budget(w, MAX_WORK_DIR_BYTES, MAX_WORK_DIR_ENTRIES) { + return "/work"; + } + } + } +} + +// --------------------------------------------------------------------------- +// The guest `iii` bridge +// --------------------------------------------------------------------------- + +/// Cap on one guest-written `iii` request frame. +/// +/// Enforced DURING accumulation, not after: the host owns the sink, so unlike +/// the V8 sibling — where `#[string]` op args are byte-copied onto the Rust +/// heap before any check in the op body runs — there is no window in which an +/// oversized payload is fully resident. Past the cap the buffer stops growing +/// and the frame is answered with an error rather than truncated-and-parsed, +/// because a truncated prefix can still parse into something plausible (the +/// same argument `read_envelope` makes about the result envelope). +pub const MAX_III_REQUEST_BYTES: usize = MAX_PAYLOAD_BYTES; + +/// Cap on a guest-supplied `function_id`, matching the V8 sibling's. +pub const MAX_FUNCTION_ID_BYTES: usize = 512; + +/// What the host can do on the guest's behalf. +/// +/// One method, deliberately. This crate is bus-free and must stay so; the +/// hosting worker implements this against its own connection, exactly as +/// node-core's `Engine` trait works. Registration, triggers and shutdown are +/// NOT here — see the README for why. +pub trait GuestBridge: Send + Sync + 'static { + fn call( + &self, + fn_id: String, + payload: serde_json::Value, + timeout_ms: u64, + ) -> futures::future::BoxFuture<'static, Result>; +} + +/// Bytes queued for the guest's stdin, with a park that costs nothing. +/// +/// The contract `wasmtime-wasi` enforces is sharp: `blocking_read` loops +/// `ready()`-then-`read()` and TRAPS with "max blocking attempts exceeded" +/// after ten empty reads. So `ready()` must resolve only when there is +/// something to read, and `read()` after that must never come back empty. +#[derive(Clone)] +struct FrameQueue { + bytes: Arc>>, + /// `notify_one` rather than `notify_waiters`: it stores a permit when + /// nobody is waiting yet, so a push that lands before the guest parks is + /// not lost. `notify_waiters` would drop it and the guest would hang. + notify: Arc, +} + +impl FrameQueue { + fn new() -> Self { + Self { + bytes: Arc::new(Mutex::new(std::collections::VecDeque::new())), + notify: Arc::new(tokio::sync::Notify::new()), + } + } + + /// Queue a length-prefixed frame: `\n`. + /// + /// Length-prefixed rather than delimited so the body needs no escaping and + /// the guest's read is exact. + fn push_frame(&self, body: &[u8]) { + let mut q = self.bytes.lock().unwrap(); + q.extend(format!("{}\n", body.len()).as_bytes()); + q.extend(body); + drop(q); + self.notify.notify_one(); + } +} + +impl IsTerminal for FrameQueue { + fn is_terminal(&self) -> bool { + false + } +} + +impl StdinStream for FrameQueue { + fn p2_stream(&self) -> Box { + Box::new(self.clone()) + } + // Never taken: preview1 reaches stdio only through `p2_stream`, which is + // overridden above. The default `p2_stream` wraps this in an + // `AsyncReadStream`, which is exactly the adapter we are avoiding. + fn async_stream(&self) -> Box { + Box::new(tokio::io::empty()) + } +} + +#[wasmtime_wasi::async_trait] +impl Pollable for FrameQueue { + async fn ready(&mut self) { + loop { + if !self.bytes.lock().unwrap().is_empty() { + return; + } + self.notify.notified().await; + } + } +} + +impl InputStream for FrameQueue { + fn read(&mut self, size: usize) -> StreamResult { + let mut q = self.bytes.lock().unwrap(); + // `ready()` only resolves when there is something here, so this is the + // spurious-wakeup path. Empty is correct and safe: `blocking_read` + // tolerates it, and its ten-attempt trap cannot be reached because + // `ready()` will not resolve again until a push. + if q.is_empty() { + return Ok(Bytes::new()); + } + let take = size.min(q.len()); + let out: Vec = q.drain(..take).collect(); + Ok(Bytes::from(out)) + } +} + +/// Where the scanner is between guest writes. +#[derive(PartialEq, Eq)] +enum SinkMode { + /// Looking for the frame marker; everything else is tenant output. + Scanning, + /// Inside a frame, accumulating until the terminating newline. + InFrame, + /// Inside a frame that already blew its cap: still looking for the + /// terminating newline, but no longer keeping any of it. + Overflowed, +} + +/// Splits a guest's stdout into tenant output and `iii` request frames. +/// +/// The guest marks a request with `\n\n\n`. Everything else is +/// the tenant's own output and goes to the capped log pipe. +/// +/// The sentinel is NOT a security boundary and nothing here pretends +/// otherwise: tenant code shares the interpreter, so it can reassign +/// `sys.stdout.write` or walk the frames to recover the sentinel and forge a +/// request. That costs it nothing, because every check is host-side — the +/// function id, the payload size and the timeout are all validated here, and a +/// forged frame gets exactly the same treatment as a real one. +struct FramingSink { + logs: CappedPipe, + marker: Vec, + pending: Vec, + mode: SinkMode, + tx: tokio::sync::mpsc::UnboundedSender, ()>>, +} + +impl FramingSink { + fn new( + logs: CappedPipe, + sentinel: &str, + tx: tokio::sync::mpsc::UnboundedSender, ()>>, + ) -> Self { + Self { + logs, + marker: format!("\n{sentinel}\n").into_bytes(), + pending: Vec::new(), + mode: SinkMode::Scanning, + tx, + } + } + + /// Flush whatever the rolling tail is still holding. + /// + /// The tail exists so a marker split across two writes is still found, but + /// it also means the LAST bytes a guest writes are held back waiting for a + /// write that never comes. Without this, a `print` after the guest's final + /// `iii.trigger` vanishes — which is exactly what + /// `tenant_output_and_request_frames_do_not_contaminate_each_other` + /// caught. + /// + /// A partial frame is discarded rather than logged: it was never a + /// complete request, and emitting half of one as tenant output would put + /// the sentinel into the caller's stdout. + fn finish(&mut self) { + if self.mode == SinkMode::Scanning { + let rest: Vec = std::mem::take(&mut self.pending); + self.logs.write_bytes(&rest); + } else { + self.pending.clear(); + } + } + + fn feed(&mut self, buf: &[u8]) { + self.pending.extend_from_slice(buf); + loop { + match self.mode { + SinkMode::Scanning => { + match find(&self.pending, &self.marker) { + Some(i) => { + let head: Vec = self.pending.drain(..i).collect(); + self.logs.write_bytes(&head); + self.pending.drain(..self.marker.len()); + self.mode = SinkMode::InFrame; + } + None => { + // Hold back enough that a marker split across two + // writes is still found. Without this the frame is + // silently logged as tenant output and the guest + // waits forever for an answer. + let keep = (self.marker.len() - 1).min(self.pending.len()); + let flush = self.pending.len() - keep; + let head: Vec = self.pending.drain(..flush).collect(); + self.logs.write_bytes(&head); + return; + } + } + } + SinkMode::InFrame | SinkMode::Overflowed => { + match self.pending.iter().position(|b| *b == b'\n') { + Some(i) => { + let body: Vec = self.pending.drain(..i).collect(); + self.pending.drain(..1); + let overflowed = self.mode == SinkMode::Overflowed; + self.mode = SinkMode::Scanning; + let _ = self.tx.send(if overflowed { Err(()) } else { Ok(body) }); + } + None => { + if self.pending.len() > MAX_III_REQUEST_BYTES { + // Stop growing. The bytes already held are + // dropped rather than kept-and-truncated. + self.pending.clear(); + self.mode = SinkMode::Overflowed; + } + return; + } + } + } + } + } + } +} + +/// The `StdoutStream` face of [`FramingSink`]. +/// +/// `StdoutStream` is a factory — it hands out a fresh stream per `get-stdout` +/// — so the scanner state has to live behind the `Arc`, exactly as +/// `CappedPipe`'s capping state does. +#[derive(Clone)] +struct FramingStdout { + inner: Arc>, +} + +impl IsTerminal for FramingStdout { + fn is_terminal(&self) -> bool { + false + } +} + +impl StdoutStream for FramingStdout { + fn p2_stream(&self) -> Box { + Box::new(self.clone()) + } + fn async_stream(&self) -> Box { + Box::new(self.clone()) + } +} + +impl OutputStream for FramingStdout { + fn write(&mut self, bytes: Bytes) -> StreamResult<()> { + self.inner.lock().unwrap().feed(&bytes); + Ok(()) + } + fn flush(&mut self) -> StreamResult<()> { + Ok(()) + } + fn check_write(&mut self) -> StreamResult { + Ok(WRITE_BUDGET) + } +} + +#[wasmtime_wasi::async_trait] +impl Pollable for FramingStdout { + async fn ready(&mut self) {} +} + +impl AsyncWrite for FramingStdout { + fn poll_write( + self: Pin<&mut Self>, + _: &mut TaskContext<'_>, + buf: &[u8], + ) -> Poll> { + self.inner.lock().unwrap().feed(buf); + Poll::Ready(Ok(buf.len())) + } + fn poll_flush(self: Pin<&mut Self>, _: &mut TaskContext<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + fn poll_shutdown(self: Pin<&mut Self>, _: &mut TaskContext<'_>) -> Poll> { + Poll::Ready(Ok(())) + } +} + +/// One guest request, as the guest writes it. +#[derive(serde::Deserialize)] +struct GuestCall { + function_id: String, + #[serde(default)] + payload: serde_json::Value, + #[serde(default)] + timeout_ms: Option, +} + +/// Answer one guest request. Every check is host-side, which is what makes a +/// forged frame harmless. +async fn answer_guest_call( + frame: Result, ()>, + bridge: &Arc, + remaining: Duration, +) -> Vec { + let reply = |ok: bool, v: serde_json::Value| { + serde_json::to_vec(&serde_json::json!({ "ok": ok, "value": v })) + .unwrap_or_else(|_| b"{\"ok\":false,\"value\":\"reply encoding failed\"}".to_vec()) + }; + let Ok(body) = frame else { + return reply( + false, + serde_json::json!(format!( + "iii request exceeded {MAX_III_REQUEST_BYTES} bytes and was refused" + )), + ); + }; + let call: GuestCall = match serde_json::from_slice(&body) { + Ok(c) => c, + Err(e) => { + return reply( + false, + serde_json::json!(format!("malformed iii request: {e}")), + ) + } + }; + if call.function_id.len() > MAX_FUNCTION_ID_BYTES { + return reply( + false, + serde_json::json!(format!( + "function_id is {} bytes; max {MAX_FUNCTION_ID_BYTES}", + call.function_id.len() + )), + ); + } + // Clamped to what is LEFT of this run's budget, not just to a ceiling. + // Unclamped, an `iii.trigger(timeout=30000)` inside a 5s run would blow + // the run's own deadline every time and the tenant would never see the + // bus error it could have handled. The margin is what leaves room for + // that error to surface as a Python exception. + let headroom = remaining.saturating_sub(Duration::from_millis(200)); + let asked = call.timeout_ms.unwrap_or(u64::MAX); + let timeout_ms = asked.min(headroom.as_millis() as u64).max(1); + + match bridge + .call(call.function_id, call.payload, timeout_ms) + .await + { + Ok(v) => reply(true, v), + Err(e) => reply(false, serde_json::json!(e)), + } +} + +fn find(haystack: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() || haystack.len() < needle.len() { + return None; + } + haystack.windows(needle.len()).position(|w| w == needle) +} + +struct Host { + wasi: WasiP1Ctx, + limiter: TrackedLimiter, +} + +pub struct Runner { + engine: Engine, + instance_pre: InstancePre, + stdlib_root: PathBuf, +} + +/// Everything `build_store` needs that is not the `Runner` itself. A struct +/// rather than ten positional arguments because both callers construct it and +/// a silently swapped pair of paths would be a sandbox escape. +struct StoreParts { + run_dir: PathBuf, + out_dir: PathBuf, + work_dir: Option, + memory_mb: u64, + stdout: CappedPipe, + stderr: CappedPipe, + denied: Arc, + framing: Option, + stdin_q: FrameQueue, + /// When the running turn must die. Shared with the epoch callback. + deadline: Arc>>, +} + +impl Runner { + /// Build the sandbox. One implementation so a one-shot run and a + /// persistent runtime cannot drift apart on a preopen or a permission. + fn build_store(&self, p: StoreParts) -> Result> { + // No environment is passed: with the artifact root preopened at `/`, + // CPython finds its own stdlib, and inheriting host env into an + // untrusted guest would be a leak. The longer `/run` and `/out` + // preopens shadow the paths they'd otherwise inherit from `/`. + let mut builder = WasiCtxBuilder::new(); + builder + .args(&["python", "-I", "-B", "/run/main.py", "/run", "/out"]) + .preopened_dir(&self.stdlib_root, "/", DirPerms::READ, FilePerms::READ)? + .preopened_dir(&p.run_dir, "/run", DirPerms::READ, FilePerms::READ)? + .preopened_dir(&p.out_dir, "/out", DirPerms::all(), FilePerms::all())? + .stderr(p.stderr.clone()); + match &p.framing { + // With a bridge, stdout is scanned for request frames and the + // tenant's own output is forwarded to the same capped pipe it + // would otherwise have written to directly. + Some(f) => { + builder.stdout(f.clone()).stdin(p.stdin_q.clone()); + } + None => { + builder.stdout(p.stdout.clone()); + } + } + // `/work` is deliberately NOT passed to the wrapper as an argv entry: + // it is the guest's own directory, addressed by absolute path, and the + // wrapper has no business in it. That keeps `wrapper.py` unchanged. + if let Some(w) = &p.work_dir { + builder.preopened_dir(w, "/work", DirPerms::all(), FilePerms::all())?; + } + let wasi = builder.build_p1(); + + let host = Host { + wasi, + limiter: TrackedLimiter { + max_memory_bytes: (p.memory_mb as usize) * 1024 * 1024, + denied: p.denied.clone(), + }, + }; + let mut store = Store::new(&self.engine, host); + store.limiter(|h| &mut h.limiter); + // Slice the budget rather than spending it in one epoch deadline. The + // callback runs on every slice expiry and is the *only* thing that can + // end the run by epoch, so `Trap::Interrupt` keeps meaning exactly + // "the wall-clock budget is spent" — a slice expiry yields instead. + // (`UpdateDeadline::Interrupt` from a callback raises the identical + // `Trap::Interrupt` as the no-callback default, so nothing downstream + // has to learn a second shape.) + store.set_epoch_deadline(EPOCH_SLICE_TICKS); + let deadline = p.deadline.clone(); + store.epoch_deadline_callback(move |_| { + // The cell is the whole of the per-turn arming contract: `Some(t)` + // means a turn is running and must die at `t`; `None` means no + // turn is running, so nothing can be over budget. A persistent + // runtime CLEARS it at turn end — leaving the previous turn's + // instant armed would trap the next turn's first instruction. + Ok( + if deadline + .lock() + .unwrap() + .is_some_and(|d| Instant::now() >= d) + { + wasmtime::UpdateDeadline::Interrupt + } else { + // `YieldCustom`, not `Yield`. Plain `Yield` uses wasmtime's + // runtime-agnostic yield — `wake_by_ref()` then `Pending` — + // an *immediate* self-wake, so the run queue is never empty. + // The current-thread scheduler this was measured on only + // reaches its driver poll once every `event_interval` (61) + // task polls, and each of those polls is a full ~10 ms epoch + // slice, so timers wait tens of slices for their turn. + // (On the multi-thread flavor production actually runs, the + // same self-wake also lands the task in the worker's LIFO + // slot and gets it polled straight back. Both reasons point + // the same way.) `tokio::task::yield_now()` instead defers the + // waker, so the queue drains and the driver runs every round — + // which is why `YieldCustom` exists and what its docs + // recommend. Measured with three spinning guests on one + // worker: plain `Yield` fired its slices (410 of them) and + // starved the runtime anyway, 1 s of unrelated timer work + // taking 3.01 s; `YieldCustom`, 1.07 s. + wasmtime::UpdateDeadline::YieldCustom( + EPOCH_SLICE_TICKS, + Box::pin(tokio::task::yield_now()), + ) + }, + ) + }); + + Ok(store) + } +} + +impl Runner { + /// Boot once per process: extract, compile/load, pre-instantiate, start ticker. + /// + /// Call this exactly once. Every call starts another epoch ticker on the + /// same-but-separate `Engine`; two runners in one process would be two + /// ~19 MB module images and two ticker threads, not a shared one. + pub fn boot() -> Result> { + let stdlib_root = artifact::ensure_extracted()?; + let engine = artifact::sandbox_engine()?; + let module = artifact::load_module(&engine, &stdlib_root)?; + let mut linker: Linker = Linker::new(&engine); + p1::add_to_linker_async(&mut linker, |h: &mut Host| &mut h.wasi)?; + let instance_pre = linker.instantiate_pre(&module)?; + + // One ticker for the process lifetime; every run's deadline is + // denominated in these ticks. Detached deliberately — it dies with + // the process. + let ticker_engine = engine.clone(); + std::thread::Builder::new() + .name("python-engine-epoch".into()) + .spawn(move || loop { + std::thread::sleep(Duration::from_millis(EPOCH_TICK_MS)); + ticker_engine.increment_epoch(); + }) + .context("spawning epoch ticker")?; + + Ok(Arc::new(Runner { + engine, + instance_pre, + stdlib_root, + })) + } + + /// Async because it is the only way to bound the run's wall clock. + /// + /// Epoch interruption is observed only at wasm loop back-edges and + /// function entries, so a guest parked in a host call — `time.sleep`, any + /// long `poll_oneoff` — is invisible to it and holds the thread for as + /// long as it likes. Under `call_async` the guest runs on a fiber, and + /// dropping the timed-out future makes wasmtime resume that fiber with an + /// error so it unwinds; the thread and the store come back. + pub async fn run(&self, spec: &RunSpec) -> Result { + // Per-run host dirs; RAII cleanup on every path. + let scratch = tempfile::tempdir().context("creating run scratch dir")?; + let run_dir = scratch.path().join("run"); + let out_dir = scratch.path().join("out"); + std::fs::create_dir_all(&run_dir)?; + std::fs::create_dir_all(&out_dir)?; + std::fs::write(run_dir.join("main.py"), include_str!("wrapper.py"))?; + std::fs::write(run_dir.join("code.py"), &spec.code)?; + if let Some(p) = &spec.payload_json { + std::fs::write(run_dir.join("payload.json"), p)?; + } + + let stdout = CappedPipe::new(MAX_LOG_BYTES); + let stderr = CappedPipe::new(MAX_LOG_BYTES); + let denied = Arc::new(AtomicBool::new(false)); + + // The bridge, when there is one. The sentinel is per-run and random: + // it is not a security boundary (tenant code shares the interpreter + // and can read it), but a fixed one would let tenant output collide + // with a frame by accident. + let sentinel = uuid::Uuid::new_v4().to_string(); + let (frame_tx, mut frame_rx) = tokio::sync::mpsc::unbounded_channel(); + let stdin_q = FrameQueue::new(); + let framing = spec.bridge.as_ref().map(|_| FramingStdout { + inner: Arc::new(Mutex::new(FramingSink::new( + stdout.clone(), + &sentinel, + frame_tx, + ))), + }); + if spec.bridge.is_some() { + // The guest learns the sentinel and its namespace from a file in + // its read-only `/run`, so the wrapper's two-argument contract is + // unchanged and the whole bridge stays optional: no file, no + // `iii` global. + std::fs::write( + run_dir.join("iii.json"), + serde_json::to_vec(&serde_json::json!({ + "sentinel": sentinel, + "namespace": spec.namespace.clone().unwrap_or_default(), + }))?, + )?; + } + + let budget = Duration::from_millis(spec.timeout_ms); + let started = Instant::now(); + let deadline = Arc::new(Mutex::new(Some(started + budget))); + let mut store = self.build_store(StoreParts { + run_dir: run_dir.clone(), + out_dir: out_dir.clone(), + work_dir: spec.work_dir.clone(), + memory_mb: spec.memory_mb, + stdout: stdout.clone(), + stderr: stderr.clone(), + denied: denied.clone(), + framing: framing.clone(), + stdin_q: stdin_q.clone(), + deadline, + })?; + + // Instantiation is outside the wall-clock backstop on purpose: it runs + // no guest code and makes no host calls, so it cannot park. Its only + // failure of interest is the limiter refusing the module's minimum + // memory, below. + let instance = match self.instance_pre.instantiate_async(&mut store).await { + Ok(i) => i, + // The interpreter's 40 MiB minimum memory (MIN_MEMORY_MB) is + // requested from the limiter before any code runs, so a + // `memory_mb` under that fails here rather than at a `memory.grow` + // — and `config.rs` clamps `memory_mb` to 1..=max, so ordinary + // tenant input reaches this. That is a resource condition, not an + // internal fault: report it as a denied run so the manager can + // classify it as such instead of as `internal`. + Err(e) if denied.load(Ordering::Relaxed) => { + return Ok(RunOutcome { + exit: ExitKind::Trap(trap_text(e)), + envelope: None, + stdout: stdout.into_captured(), + stderr: stderr.into_captured(), + timed_out: false, + memory_denied: true, + disk_exceeded: None, + }); + } + Err(e) => { + return Err(anyhow::Error::from(e).context("instantiating the interpreter")); + } + }; + let start = instance + .get_typed_func::<(), ()>(&mut store, "_start") + .map_err(anyhow::Error::from) + .context("locating _start")?; + // A normal CPython run does NOT return Ok(()): it calls proc_exit(0), + // which arrives here as an Err carrying I32Exit. Only a genuine trap + // (epoch kill, unreachable, a host-side error) takes the other branch. + // A denied memory growth is *not* a trap — it makes memory.grow return + // -1, which CPython reports to the tenant as MemoryError. + let call = start.call_async(&mut store, ()); + // The third kill. `/out` is guest-writable by necessity — the envelope + // arrives through it — and nothing in wasmtime bounds it, so the host + // measures it instead. Losing this `select!` drops `call`, which is the + // same unwind-the-fiber-and-hand-back-the-store path the wall-clock + // backstop already proves works; `store` is not touched afterwards on + // any arm. + // Answers guest requests for as long as the run lasts. Never + // resolves, so it only ever runs concurrently with the arms that do. + let bridge_pump = async { + if let Some(bridge) = spec.bridge.clone() { + while let Some(frame) = frame_rx.recv().await { + let remaining = budget.saturating_sub(started.elapsed()); + let reply = answer_guest_call(frame, &bridge, remaining).await; + stdin_q.push_frame(&reply); + } + } + std::future::pending::<()>().await + }; + + let (exit, killed, disk_exceeded) = tokio::select! { + timed = tokio::time::timeout(budget, call) => match timed { + // The backstop fired: the future has been dropped, wasmtime has + // unwound the fiber, and this thread is ours again. The guest was + // parked in a host call, so there is no wasm trap to report. + Err(_elapsed) => ( + ExitKind::Trap(format!( + "run exceeded its {}ms budget while parked in a host call", + spec.timeout_ms + )), + true, + None, + ), + Ok(Ok(())) => (ExitKind::Clean(0), false, None), + Ok(Err(e)) => match e.downcast_ref::() { + Some(code) => (ExitKind::Clean(code.0), false, None), + None => { + // `Trap::Interrupt` has exactly one producer: the epoch + // deadline. Exact, and not forgeable by the guest. + let by_epoch = matches!(e.downcast_ref::(), Some(Trap::Interrupt)); + (ExitKind::Trap(trap_text(e)), by_epoch, None) + } + }, + }, + () = bridge_pump => unreachable!("the bridge pump never resolves"), + which = disk_watchdog(out_dir.clone(), spec.work_dir.clone()) => ( + ExitKind::Trap(format!("run exceeded its {which} disk budget")), + false, + Some(which), + ), + }; + + // Every term is host-side. `killed` is whichever kill fired; the + // elapsed check is belt-and-braces for a trap that lands on the + // deadline boundary before either mechanism names itself. A disk kill + // is excluded: it can land at any point in the budget, and calling it + // a timeout would tell the caller the wrong thing to fix. + let timed_out = disk_exceeded.is_none() + && (killed || (matches!(exit, ExitKind::Trap(_)) && started.elapsed() >= budget)); + // Drain the scanner's rolling tail before the streams are read. + if let Some(f) = &framing { + f.inner.lock().unwrap().finish(); + } + let envelope = read_envelope(&out_dir.join("result.json")); + + Ok(RunOutcome { + exit, + envelope, + stdout: stdout.into_captured(), + stderr: stderr.into_captured(), + timed_out, + memory_denied: denied.load(Ordering::Relaxed), + disk_exceeded, + }) + } +} + +// ------------------------------------------------------------- persistence + +/// What `spawn_persistent` needs to boot an interpreter that outlives a call. +/// +/// `memory_mb` is here and NOT on the turn on purpose: wasm linear memory only +/// ever grows, so a per-call ceiling on a shared interpreter would be a promise +/// the sandbox cannot keep — the second caller inherits whatever the first grew +/// to. Creation-time only, and callers must refuse a per-call `memory_mb` +/// against an existing runtime rather than silently ignoring it. +pub struct PersistentSpec { + pub work_dir: PathBuf, + pub memory_mb: u64, + pub bridge: Option>, + pub namespace: Option, +} + +/// Spawning failed. `memory_denied` separates "this host is out of memory for +/// the interpreter's 40 MiB floor" from an internal fault, because the two +/// reach the caller as very different errors. +pub struct SpawnFailed { + pub memory_denied: bool, + pub error: anyhow::Error, +} + +struct Turn { + code: String, + payload_json: Option, + timeout_ms: u64, + reply: tokio::sync::oneshot::Sender, +} + +/// A CPython interpreter parked on stdin between calls. +/// +/// Everything a turn leaves behind — imported modules, globals bound in a +/// previous `exec`, open handles — is still there for the next one. That is +/// the point, and it is also why a `runtime_id` is a capability: two callers +/// sharing one of these share an address space. +pub struct PersistentRuntime { + turns: tokio::sync::mpsc::Sender, +} + +impl PersistentRuntime { + /// Run one turn on this interpreter. + /// + /// `Err` means the interpreter is gone — poisoned by a previous timeout, + /// or dead of a trap. The working directory is untouched, so the caller's + /// recovery is to boot a fresh interpreter on it. + pub async fn run( + &self, + code: String, + payload_json: Option, + timeout_ms: u64, + ) -> Result { + let (reply, answer) = tokio::sync::oneshot::channel(); + self.turns + .send(Turn { + code, + payload_json, + timeout_ms, + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("the interpreter is no longer running"))?; + answer + .await + .map_err(|_| anyhow::anyhow!("the interpreter died mid-turn")) + } + + /// False once the interpreter's task has exited. Lets a manager evict a + /// poisoned runtime on sweep instead of only on the next call. + pub fn is_live(&self) -> bool { + !self.turns.is_closed() + } +} + +/// `_start` returning, in the two shapes that matter. Shared with the one-shot +/// path's reading of the same result: a clean CPython exit arrives as an +/// `I32Exit` error, not `Ok(())`. +fn exit_of(r: std::result::Result<(), wasmtime::Error>) -> (ExitKind, bool) { + match r { + Ok(()) => (ExitKind::Clean(0), false), + Err(e) => match e.downcast_ref::() { + Some(code) => (ExitKind::Clean(code.0), false), + None => { + // `Trap::Interrupt` has exactly one producer: the epoch + // deadline. Exact, and not forgeable by the guest. + let by_epoch = matches!(e.downcast_ref::(), Some(Trap::Interrupt)); + (ExitKind::Trap(trap_text(e)), by_epoch) + } + }, + } +} + +/// Empty a directory without removing it — the guest holds a preopen on it. +/// +/// `file_type()` does not follow symlinks, so a guest-planted symlink to a +/// directory takes the `remove_file` arm and unlinks the link rather than +/// recursing through it into the host. +fn wipe_dir(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false); + let _ = if is_dir { + std::fs::remove_dir_all(e.path()) + } else { + std::fs::remove_file(e.path()) + }; + } +} + +/// Sleep until `at`, or forever when there is nothing to wait for. +async fn sleep_until(at: Option) { + match at { + Some(t) => tokio::time::sleep_until(tokio::time::Instant::from_std(t)).await, + None => std::future::pending().await, + } +} + +/// Is this frame the wrapper saying "the turn is over"? +/// +/// Not a trust boundary — the guest writes it, and everything under `/out` was +/// already guest-written. A tenant that forges one early only makes the host +/// read an envelope the wrapper has not produced yet, which comes back as its +/// own failed run. The host-derived kills are still checked first, upstream. +fn is_turn_done(frame: &std::result::Result, ()>) -> bool { + let Ok(body) = frame else { return false }; + serde_json::from_slice::(body) + .ok() + .and_then(|v| v.get("kind")?.as_str().map(|s| s == "turn_done")) + .unwrap_or(false) +} + +impl Runner { + /// Boot an interpreter and park it on stdin, ready for turns. + /// + /// The store cannot be held across calls in a map: `call_async` borrows it + /// for the future's life, so a suspended `_start` future beside its own + /// store would be self-referential. Instead a task owns both and turns + /// arrive over a channel — the same shape node-core's runtimes use. + pub async fn spawn_persistent( + &self, + spec: PersistentSpec, + ) -> std::result::Result { + let plain = |e: anyhow::Error| SpawnFailed { + memory_denied: false, + error: e, + }; + let scratch = tempfile::tempdir() + .context("creating runtime scratch dir") + .map_err(plain)?; + let run_dir = scratch.path().join("run"); + let out_dir = scratch.path().join("out"); + let setup = || -> Result { + std::fs::create_dir_all(&run_dir)?; + std::fs::create_dir_all(&out_dir)?; + std::fs::write(run_dir.join("main.py"), include_str!("wrapper.py"))?; + // No `code.py` and no `payload.json`: a persistent interpreter is + // told what to run per turn, over stdin. + let sentinel = uuid::Uuid::new_v4().to_string(); + std::fs::write( + run_dir.join("iii.json"), + serde_json::to_vec(&serde_json::json!({ + "sentinel": sentinel, + "namespace": spec.namespace.clone().unwrap_or_default(), + "persistent": true, + }))?, + )?; + Ok(sentinel) + }; + let sentinel = setup() + .context("preparing the runtime dir") + .map_err(plain)?; + + let stdout = CappedPipe::new(MAX_LOG_BYTES); + let stderr = CappedPipe::new(MAX_LOG_BYTES); + let denied = Arc::new(AtomicBool::new(false)); + let (frame_tx, mut frame_rx) = tokio::sync::mpsc::unbounded_channel(); + let stdin_q = FrameQueue::new(); + // Always framed, bridge or not: the turn-done frame rides the same + // channel, so a persistent runtime is never unframed. + let framing = FramingStdout { + inner: Arc::new(Mutex::new(FramingSink::new( + stdout.clone(), + &sentinel, + frame_tx, + ))), + }; + // `None` = no turn running, so nothing can be over budget. The task + // arms it at turn start and clears it at turn end. + let deadline = Arc::new(Mutex::new(None)); + + let mut store = self + .build_store(StoreParts { + run_dir, + out_dir: out_dir.clone(), + work_dir: Some(spec.work_dir.clone()), + memory_mb: spec.memory_mb, + stdout: stdout.clone(), + stderr: stderr.clone(), + denied: denied.clone(), + framing: Some(framing.clone()), + stdin_q: stdin_q.clone(), + deadline: deadline.clone(), + }) + .map_err(plain)?; + let instance = self + .instance_pre + .instantiate_async(&mut store) + .await + .map_err(|e| SpawnFailed { + memory_denied: denied.load(Ordering::Relaxed), + error: anyhow::Error::from(e).context("instantiating the interpreter"), + })?; + let start = instance + .get_typed_func::<(), ()>(&mut store, "_start") + .map_err(|e| plain(anyhow::Error::from(e).context("locating _start")))?; + + // Depth 1: a caller whose turn is already queued waits in `send`, so + // back-pressure lands on the caller rather than in an unbounded queue. + let (turn_tx, mut turn_rx) = tokio::sync::mpsc::channel::(1); + let bridge = spec.bridge.clone(); + let work_dir = spec.work_dir.clone(); + tokio::spawn(async move { + // Owned by the task so the sandbox outlives every turn and is + // removed when the interpreter dies. + let _scratch = scratch; + let call = start.call_async(&mut store, ()); + tokio::pin!(call); + // Created once, not per loop iteration: a chatty guest would + // otherwise restart the watchdog's poll interval on every frame + // and push detection out indefinitely. + let watchdog = disk_watchdog(out_dir.clone(), Some(work_dir)); + tokio::pin!(watchdog); + + let envelope_path = out_dir.join("result.json"); + let mut current: Option<(Turn, Instant)> = None; + + // Every exit from this loop is terminal for the interpreter. The + // working directory is not ours to clean up — it outlives us, and + // keeping it is the whole recovery story for a poisoned runtime. + loop { + let at = current.as_ref().map(|(_, d)| *d); + tokio::select! { + // A running turn's deadline. Nothing else can preempt a + // guest parked in a host call, and dropping `call` is what + // unwinds the fiber — so this arm ends the interpreter. + () = sleep_until(at), if at.is_some() => { + let (turn, _) = current.take().expect("armed only with a turn"); + framing.inner.lock().unwrap().finish(); + let _ = turn.reply.send(RunOutcome { + exit: ExitKind::Trap(format!( + "run exceeded its {}ms budget", turn.timeout_ms + )), + envelope: None, + stdout: stdout.take_captured(), + stderr: stderr.take_captured(), + timed_out: true, + memory_denied: denied.load(Ordering::Relaxed), + disk_exceeded: None, + }); + break; + } + // The interpreter exited or trapped. Terminal either way: + // `_start` does not come back. + r = &mut call => { + let (exit, by_epoch) = exit_of(r); + if let Some((turn, _)) = current.take() { + framing.inner.lock().unwrap().finish(); + let _ = turn.reply.send(RunOutcome { + exit, + envelope: read_envelope(&envelope_path), + stdout: stdout.take_captured(), + stderr: stderr.take_captured(), + timed_out: by_epoch, + memory_denied: denied.load(Ordering::Relaxed), + disk_exceeded: None, + }); + } + break; + } + // A guest-writable directory blew its budget. + which = &mut watchdog => { + if let Some((turn, _)) = current.take() { + framing.inner.lock().unwrap().finish(); + let _ = turn.reply.send(RunOutcome { + exit: ExitKind::Trap(format!("run exceeded its {which} disk budget")), + envelope: None, + stdout: stdout.take_captured(), + stderr: stderr.take_captured(), + timed_out: false, + memory_denied: denied.load(Ordering::Relaxed), + disk_exceeded: Some(which), + }); + } + break; + } + Some(frame) = frame_rx.recv() => { + if is_turn_done(&frame) { + // Belt-and-braces. Turn start arms the cell BEFORE + // pushing the frame that resumes the guest, so a + // stale instant is already unreachable: between + // turns the guest is parked in `fd_read` and no + // wasm executes, so the epoch callback cannot run. + // The clear is what keeps that true if the two + // lines at turn start are ever reordered — which + // is why no test here claims to catch its removal. + *deadline.lock().unwrap() = None; + if let Some((turn, _)) = current.take() { + framing.inner.lock().unwrap().finish(); + let _ = turn.reply.send(RunOutcome { + exit: ExitKind::Clean(0), + envelope: read_envelope(&envelope_path), + stdout: stdout.take_captured(), + stderr: stderr.take_captured(), + timed_out: false, + memory_denied: denied.load(Ordering::Relaxed), + disk_exceeded: None, + }); + } + } else { + // An `iii.trigger`. Awaiting it inline stops + // polling `call`, which is exactly right: the + // guest is blocked on `fd_read` for this answer + // and has nothing to make progress on. + let remaining = at + .map(|d| d.saturating_duration_since(Instant::now())) + .unwrap_or(Duration::ZERO); + let reply = match &bridge { + Some(b) => answer_guest_call(frame, b, remaining).await, + None => br#"{"ok":false,"value":"this runtime has no host bridge"}"# + .to_vec(), + }; + stdin_q.push_frame(&reply); + } + } + // `recv` rather than `Some(turn) = recv`: a failed + // pattern only disables the branch for one `select!` call, + // so a torn-down runtime would leave this task parked on + // `call` forever, holding its store and its scratch dir. It + // is disabled while a turn is running, so a teardown + // mid-turn is noticed as soon as that turn finishes. + queued = turn_rx.recv(), if current.is_none() => { + let Some(turn) = queued else { break }; + // `/out` is per-call: its budget would otherwise be + // spent by whichever turn wrote first, while `/work` + // deliberately accumulates. + wipe_dir(&out_dir); + // Sticky otherwise — one recovered MemoryError would + // make every later turn classify as out-of-memory. + denied.store(false, Ordering::Relaxed); + let at = Instant::now() + Duration::from_millis(turn.timeout_ms); + *deadline.lock().unwrap() = Some(at); + let payload = turn + .payload_json + .as_deref() + .and_then(|p| serde_json::from_str::(p).ok()) + .unwrap_or(serde_json::Value::Null); + let body = serde_json::to_vec(&serde_json::json!({ + "code": turn.code, + "payload": payload, + })) + .expect("a string and a parsed value serialize"); + stdin_q.push_frame(&body); + current = Some((turn, at)); + } + } + } + }); + + Ok(PersistentRuntime { turns: turn_tx }) + } +} + +#[cfg(test)] +mod sink_tests { + use super::*; + + type Frames = tokio::sync::mpsc::UnboundedReceiver, ()>>; + + fn sink(sentinel: &str) -> (FramingSink, CappedPipe, Frames) { + let logs = CappedPipe::new(MAX_LOG_BYTES); + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + (FramingSink::new(logs.clone(), sentinel, tx), logs, rx) + } + + fn logged(p: CappedPipe) -> String { + String::from_utf8_lossy(&p.into_captured().bytes).into_owned() + } + + /// The straddle case, driven directly. + /// + /// A guest test cannot reach this: CPython buffers, so it emits the whole + /// frame in one `write` and the marker never splits — which is exactly why + /// removing the rolling tail left the end-to-end test green when it was + /// mutated. This is the test that actually pins it. + /// + /// Mutation: set `keep` to 0 in `feed`'s `None` arm. + #[test] + fn a_marker_split_across_two_writes_is_still_a_frame() { + let (mut s, logs, mut rx) = sink("SENTINEL"); + s.feed(b"before\n\nSENT"); + s.feed(b"INEL\n{\"function_id\":\"x::y\"}\nafter\n"); + s.finish(); + + let frame = rx.try_recv().expect("a frame must have been emitted"); + assert_eq!(frame.unwrap(), br#"{"function_id":"x::y"}"#.to_vec()); + assert_eq!(logged(logs), "before\nafter\n"); + } + + /// One byte at a time — the worst case for any scanner that assumes a + /// write boundary means something. + #[test] + fn a_frame_delivered_one_byte_at_a_time_is_still_a_frame() { + let (mut s, logs, mut rx) = sink("S"); + for b in b"hi\n\nS\n{\"function_id\":\"a::b\"}\nbye\n" { + s.feed(&[*b]); + } + s.finish(); + assert_eq!( + rx.try_recv().expect("a frame").unwrap(), + br#"{"function_id":"a::b"}"#.to_vec() + ); + assert_eq!(logged(logs), "hi\nbye\n"); + } + + /// Past the cap the buffer STOPS GROWING rather than accumulating and + /// being checked afterwards — the whole point of the host owning the sink. + /// The frame is refused, not truncated-and-parsed: a truncated prefix can + /// still parse into something plausible. + /// + /// The peak assertion is what discriminates. Asserting only that the frame + /// was refused passes against a mutant with no guard at all, because the + /// terminating newline still ends the frame — it just does so after the + /// guest chose how much host memory to spend. + #[test] + fn an_oversized_frame_is_refused_without_being_buffered() { + let (mut s, _logs, mut rx) = sink("S"); + s.feed(b"\nS\n"); + let chunk = vec![b'x'; 64 * 1024]; + let mut peak = 0usize; + for _ in 0..(MAX_III_REQUEST_BYTES / chunk.len() + 4) { + s.feed(&chunk); + peak = peak.max(s.pending.len()); + } + s.feed(b"\n"); + assert!( + rx.try_recv().expect("a verdict").is_err(), + "an over-cap frame must be refused" + ); + assert!( + peak <= MAX_III_REQUEST_BYTES + chunk.len(), + "peak buffer was {peak}; the cap must bound it to one write's overshoot" + ); + } + + /// Text that merely contains the sentinel mid-line is tenant output, not + /// a frame: the marker is newline-delimited on both sides. + #[test] + fn a_sentinel_inside_a_line_is_not_a_frame() { + let (mut s, logs, mut rx) = sink("S"); + s.feed(b"look at this S thing\n"); + s.finish(); + assert!(rx.try_recv().is_err(), "no frame should have been emitted"); + assert_eq!(logged(logs), "look at this S thing\n"); + } +} diff --git a/crates/python-core/src/wrapper.py b/crates/python-core/src/wrapper.py new file mode 100644 index 0000000000..0df5de90b5 --- /dev/null +++ b/crates/python-core/src/wrapper.py @@ -0,0 +1,245 @@ +# python-engine's guest wrapper — the host writes this file into /run for +# every call; tenant code never chooses its name or content. Its integrity +# is ORDERING, not secrecy: the envelope is written after tenant code +# finishes, and the host never classifies infrastructure failures from +# anything written under /out (see manager.rs). +import builtins +import json +import sys +import traceback + +MAX_RESULT_BYTES = 1048576 +MAX_TRACEBACK_CHARS = 16384 +# `str(e)` is tenant-controlled and unbounded — `raise RuntimeError("x" * +# 10_000_000)` would otherwise build an envelope the host refuses on read, +# losing the very error the tenant needs to see. Capped here rather than at +# each call site so no future caller can forget. +MAX_MESSAGE_CHARS = 4096 +TENANT_FILENAME = "" + + +def write_error(out_dir, kind, message, tb_text=None): + if len(message) > MAX_MESSAGE_CHARS: + message = message[:MAX_MESSAGE_CHARS] + "... message truncated" + if tb_text is not None and len(tb_text) > MAX_TRACEBACK_CHARS: + tb_text = tb_text[:MAX_TRACEBACK_CHARS] + "\n... traceback truncated" + with open(out_dir + "/result.json", "w") as f: + json.dump({"ok": False, "kind": kind, "message": message, "traceback": tb_text}, f) + + +def _install_iii(run_dir): + """Install the `iii` global when the host offered a bridge. + + Returns `(persistent, sentinel)` — the same config file carries both, + because the bridge and the persistent-turn loop share one channel. + + + Absent config file means no bridge, and then there is no `iii` at all — + a global that exists and always fails is worse than one that is missing, + because a tenant cannot tell the two apart from inside. + + Installed as a BUILTIN, not a module import: `-I` implies `-P`, so + `/run` is not on `sys.path` and there is nothing to import. As a builtin + it also resolves in every module's name lookup, so no amount of tenant + `sys.path` fiddling changes what `iii` means for code that does not + rebind it. (A tenant rebinding its own `iii` is shadowing its own name, + not crossing a boundary.) + """ + try: + with open(run_dir + "/iii.json", "rb") as f: + cfg = json.load(f) + sentinel = cfg["sentinel"] + except (OSError, ValueError, KeyError): + # The file is host-written, so truncation/garbage here is corruption + # (a partial write during a crash), not tenant reach. A malformed + # bridge config means NO bridge — not an exception that escapes main + # before any envelope exists. + return (False, None) + + namespace = cfg.get("namespace", "") + stdout = sys.stdout + + def trigger(request): + if not isinstance(request, dict): + raise TypeError("iii.trigger: request must be a dict") + fn = request.get("function_id") + if not isinstance(fn, str) or not fn: + raise TypeError("iii.trigger: function_id must be a non-empty string") + # allow_nan=False: the bare `NaN`/`Infinity` tokens the default emits + # are not JSON, and the host's strict parser would fail the FRAME — + # a broken bridge — instead of this call. The ValueError this raises + # is an ordinary tenant exception at the trigger call site. + frame = json.dumps( + { + "function_id": fn, + "payload": request.get("payload"), + "timeout_ms": request.get("timeout_ms"), + }, + allow_nan=False, + ) + # The host scans stdout for "\n\n\n". Flushed + # immediately: the answer cannot come back until the whole frame has. + stdout.write("\n" + sentinel + "\n" + frame + "\n") + stdout.flush() + + # Length-prefixed on the way back, so the body needs no escaping. + body = _read_frame() + if body is None: + raise OSError("iii.trigger: the host closed the bridge") + answer = json.loads(body) + if answer.get("ok"): + return answer.get("value") + raise RuntimeError("iii.trigger: " + str(answer.get("value"))) + + class _Iii: + """An agent's first move against an unknown global is printing it.""" + + def __init__(self, ns): + # NOT `namespace = namespace` in the class body: a class body does + # not participate in the enclosing function's closure, so the + # right-hand side would skip the local and raise NameError. + self.namespace = ns + + def trigger(self, request): + return trigger(request) + + def __repr__(self): + return ( + "" + ) + + builtins.iii = _Iii(namespace) + return (bool(cfg.get("persistent")), sentinel) + + +def run_once(source, payload, out_dir, ns): + """Execute one tenant program in namespace `ns` and write its envelope. + + Factored out of `main` so a persistent runtime can call it repeatedly with + the SAME `ns` — that dict is what makes a global bound in one turn still + bound in the next. Every exit path still writes exactly one envelope, and + still writes it LAST — the ordering the host's classifier depends on. + """ + try: + code = compile(source, TENANT_FILENAME, "exec") + except SyntaxError as e: + write_error(out_dir, "syntax_error", "%s (line %s)" % (e.msg, e.lineno)) + return + + ns["payload"] = payload + # `result` is this turn's output slot, not carried-over state. Without the + # pop, a turn that sets no result would silently return the previous + # turn's — the caller reading a stale answer as their own. + ns.pop("result", None) + try: + exec(code, ns) + except SystemExit: + # sys.exit() inside tenant code ends the run; whatever `result` + # held at that point stands. Documented behavior. + pass + except BaseException as e: + tb = e.__traceback__ + while tb is not None and tb.tb_frame.f_code.co_filename != TENANT_FILENAME: + tb = tb.tb_next + text = "".join(traceback.format_exception(type(e), e, tb)) + write_error(out_dir, "python_exception", "%s: %s" % (type(e).__name__, e), text) + return + + value = ns.get("result") + try: + # allow_nan=False so float("nan")/float("inf") raise ValueError and + # take the unrepresentable path below; the default emits bare `NaN` / + # `Infinity` tokens that are not JSON, and the host's envelope parse + # would report the whole run as a bare exit. + serialized = json.dumps(value, allow_nan=False) + except (TypeError, ValueError): + serialized = "null" # unrepresentable results come back as null (node-engine parity) + # Build the envelope FIRST, then measure it. Checking `serialized` alone + # under-counts by the 24 bytes of `{"ok": true, "result": ` + `}` that the + # write adds, so every result in the top 24 bytes of the range passed here + # and was then refused by the host's own MAX_RESULT_BYTES check on read — + # the caller getting neither the success nor `result_too_large`. Measuring + # what is actually written removes the window and the magic number with it. + # + # With json.dumps' default ensure_ascii=True all non-ASCII is escaped as + # \uXXXX, so MAX_RESULT_BYTES measures the *escaped* size: a result heavy + # in non-ASCII is charged ~6 bytes per character. Deliberate, and + # documented in README.md. The write is binary so it cannot fail on the + # sandbox's locale encoding, which we do not control under -I. + envelope = b'{"ok": true, "result": ' + serialized.encode("utf-8", errors="replace") + b"}" + if len(envelope) > MAX_RESULT_BYTES: + write_error( + out_dir, + "result_too_large", + "serialized result envelope is %d bytes; max %d" % (len(envelope), MAX_RESULT_BYTES), + ) + return + with open(out_dir + "/result.json", "wb") as f: + f.write(envelope) + + +def _read_frame(): + """Read one `\\n` frame from the host, or None at EOF. + + Reads the BINARY stream, never `sys.stdin`. The host's prefix counts + BYTES, while text-mode `read(n)` counts CHARACTERS and `len()` counts + them too — so a single non-ASCII character in the body made the loop ask + for bytes the host had already finished sending, and the guest blocked + until its deadline. Reading bytes and decoding once makes the two ends + measure the same thing. + """ + raw = sys.stdin.buffer + header = b"" + while True: + ch = raw.read(1) + if not ch: + return None + if ch == b"\n": + break + header += ch + want = int(header) + body = b"" + while len(body) < want: + chunk = raw.read(want - len(body)) + if not chunk: + return None + body += chunk + return body.decode("utf-8") + + +def main(): + run_dir, out_dir = sys.argv[1], sys.argv[2] + persistent, sentinel = _install_iii(run_dir) + + if not persistent: + # One-shot: the program and its payload are files the host wrote + # before starting us, and we exit when it is done. + with open(run_dir + "/code.py", "rb") as f: + source = f.read().decode("utf-8", errors="replace") + try: + with open(run_dir + "/payload.json", "rb") as f: + payload = json.load(f) + except OSError: + payload = None + run_once(source, payload, out_dir, {"__name__": "__main__"}) + return + + # Persistent: the interpreter outlives the call. Each turn arrives on + # stdin, and the frame we emit afterwards is what tells the host the turn + # is over — it is not a trust boundary, just a boundary. A tenant that + # forges one early only makes the host read an envelope it has not + # written yet, which is reported as its own failure. + ns = {"__name__": "__main__"} + while True: + frame = _read_frame() + if frame is None: + return + turn = json.loads(frame) + run_once(turn.get("code", ""), turn.get("payload"), out_dir, ns) + sys.stdout.write("\n" + sentinel + "\n" + json.dumps({"kind": "turn_done"}) + "\n") + sys.stdout.flush() + + +main() diff --git a/crates/python-core/tests/artifact.rs b/crates/python-core/tests/artifact.rs new file mode 100644 index 0000000000..2f0de8b77f --- /dev/null +++ b/crates/python-core/tests/artifact.rs @@ -0,0 +1,40 @@ +use iii_python_core::artifact; + +#[test] +fn embedded_zip_matches_pinned_size_and_digest_constant() { + // sha2 is a build-dependency only and unavailable here. build.rs + // verified the digest and wrote it to OUT_DIR/python-wasi.sha256, which + // ZIP_SHA256 embeds via include_str!; asserting it against the pinned + // literal proves the build-time verification ran and produced the + // bytes we embedded. + assert_eq!(artifact::PYTHON_WASI_ZIP.len(), 14_291_017); + assert_eq!( + artifact::ZIP_SHA256, + "2e064d3fb8172471d39d741348efa722349c40b96301f69968dff714999c584b" + ); +} + +#[test] +fn extraction_is_idempotent_and_yields_interpreter_and_stdlib() { + let root = artifact::ensure_extracted().expect("first extraction"); + assert!(root.join("python.wasm").is_file()); + assert!(root.join("lib/python3.14/os.py").is_file()); + let again = artifact::ensure_extracted().expect("second call"); + assert_eq!(root, again); +} + +#[test] +fn module_compiles_and_second_load_hits_cwasm_cache() { + let root = artifact::ensure_extracted().unwrap(); + let engine = artifact::sandbox_engine().unwrap(); + let _m = artifact::load_module(&engine, &root).expect("cold compile"); + let cwasm = root.join(format!( + "python-wasmtime-{}.cwasm", + artifact::WASMTIME_VERSION + )); + assert!( + cwasm.is_file(), + "compile must persist a cwasm next to the artifact" + ); + let _m2 = artifact::load_module(&engine, &root).expect("warm load"); +} diff --git a/crates/python-core/tests/manager.rs b/crates/python-core/tests/manager.rs new file mode 100644 index 0000000000..ac6e6fbdb4 --- /dev/null +++ b/crates/python-core/tests/manager.rs @@ -0,0 +1,661 @@ +use std::sync::{Arc, OnceLock}; + +use iii_python_core::config::PythonEngineConfig; +use iii_python_core::error::ErrorKind; +use iii_python_core::manager::{Manager, RunRequest}; +use iii_python_core::runner::Runner; + +/// One `Runner` for the whole binary. `Runner::boot` is NOT idempotent — each +/// call builds another ~19 MB module image and starts another epoch ticker — +/// so it is shared even where the `Manager` is not. +fn runner() -> Arc { + static R: OnceLock> = OnceLock::new(); + R.get_or_init(|| Runner::boot().unwrap()).clone() +} + +/// The shared manager, for tests that only ever run one-shot. +fn manager() -> Arc { + static M: OnceLock> = OnceLock::new(); + M.get_or_init(|| Manager::new(Arc::new(PythonEngineConfig::default()), runner())) + .clone() +} + +/// A manager of this test's own, for anything that creates runtimes: the +/// registry is shared state, and a test that fills it would otherwise make +/// its neighbours fail depending on scheduling. +fn own_manager(cfg: PythonEngineConfig) -> Arc { + Manager::new(Arc::new(cfg), runner()) +} + +fn req(code: &str) -> RunRequest { + RunRequest { + code: code.into(), + payload: None, + timeout_ms: None, + memory_mb: None, + } +} + +#[tokio::test] +async fn happy_path_returns_result_and_logs() { + let resp = manager() + .run(req("print(\"hi\")\nresult = [1, 2]")) + .await + .unwrap(); + assert_eq!(resp.result, serde_json::json!([1, 2])); + // Two streams, not one flattened list — the hosting worker decides how to + // present them. + assert_eq!(resp.stdout, "hi\n"); + assert_eq!(resp.stderr, ""); + assert!(!resp.truncated); +} + +#[tokio::test] +async fn oversized_code_is_rejected_before_any_instantiation() { + let mut r = req(""); + r.code = "#".repeat(1_048_577); + let err = manager().run(r).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::InvalidInput); + assert!( + err.message.contains("1048576"), + "the limit must be named: {}", + err.message + ); +} + +#[tokio::test] +async fn oversized_payload_is_rejected_with_the_limit_named() { + let mut r = req("result = 1"); + r.payload = Some(serde_json::Value::String("x".repeat(1_048_577))); + let err = manager().run(r).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::InvalidInput); + assert!(err.message.contains("1048576")); +} + +#[tokio::test] +async fn timeout_wins_over_a_forged_success_envelope() { + // The tenant writes a forged ok-envelope, then spins into the epoch + // kill. Classification must report timeout: host signals precede + // guest-writable bytes. + let mut r = req( + "with open(\"/out/result.json\", \"w\") as f:\n f.write('{\"ok\": true, \"result\": \"forged\"}')\nwhile True:\n pass", + ); + r.timeout_ms = Some(500); + let err = manager().run(r).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::Timeout); + assert!(err.message.contains("500")); +} + +#[tokio::test] +async fn early_exit_is_a_python_exception_never_internal() { + let err = manager() + .run(req("import os\nos._exit(3)")) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::PythonException); + assert!(err.message.contains("status 3")); +} + +/// Correction 3: any exit status >= 126 comes back from wasmtime-wasi as a +/// plain trap (`I32Exit` only covers 0..126), not a `Clean` exit — see +/// `p1.rs`'s `proc_exit`. None of this suite's other cases reach the final +/// `ExitKind::Trap` arm in `classify` (timeout and memory-denied both +/// short-circuit before it, and every other trap here carries no envelope +/// but also no memory/timeout flag) — so without this test that arm's +/// mapping could silently regress back to `internal` and nothing would +/// catch it. Also pins that the raw trap text — which can be an unbounded +/// wasm backtrace for other trap causes — never reaches the caller. +#[tokio::test] +async fn hostile_exit_status_is_a_python_exception_never_internal() { + let err = manager() + .run(req("import os\nos._exit(200)")) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::PythonException); + assert!( + !err.message.to_lowercase().contains("wasm") + && !err.message.to_lowercase().contains("trap"), + "raw wasm trap text must stay out of the caller-facing message: {}", + err.message + ); +} + +/// Pins the `"syntax_error"` envelope-kind arm. Without this, a manager that +/// swapped it with `"result_too_large"`, or routed both through the default +/// `PythonException` arm, would still pass every other test in this suite. +#[tokio::test] +async fn syntax_error_in_code_maps_to_syntax_error_kind() { + let err = manager().run(req("def f(:\n pass")).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::SyntaxError); +} + +/// Pins the `"result_too_large"` envelope-kind arm — the sibling of the test +/// above, and the only place in the whole plan (through Task 7's e2e suite) +/// that exercises this specific kind end to end. +#[tokio::test] +async fn oversized_result_maps_to_result_too_large_kind() { + let err = manager() + .run(req("result = \"x\" * 2_000_000")) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::ResultTooLarge); +} + +/// The guest's cap and the host's cap must measure the same bytes. `"x" * N` +/// writes N+26 bytes, so 1_048_551 lands one byte over the shared 1 MiB cap — +/// and inside the 24-byte window where the guest used to say yes and the host +/// then said no, leaving the caller with `python_exception: code exited with +/// status 0 before completing` instead of an actionable `result_too_large`. +#[tokio::test] +async fn a_result_just_over_the_cap_is_result_too_large_not_a_bare_exit() { + let err = manager() + .run(req("result = \"x\" * 1_048_551")) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::ResultTooLarge); +} + +/// ...and the byte below it still round-trips, so the fix is a boundary, not +/// a blanket tightening. +#[tokio::test] +async fn a_result_exactly_at_the_cap_still_round_trips() { + let resp = manager() + .run(req("result = \"x\" * 1_048_550")) + .await + .unwrap(); + assert_eq!(resp.result.as_str().unwrap().len(), 1_048_550); +} + +/// The `/out` kill has to reach the caller as its own actionable kind, not as +/// a timeout (it isn't one) and not as an unattributable exit. +#[tokio::test] +async fn filling_out_classifies_as_disk_quota_exceeded() { + let mut r = req( + "with open(\"/out/flood\", \"wb\") as f:\n while True:\n f.write(b\"x\" * 1_000_000)\n f.flush()\n", + ); + r.timeout_ms = Some(30_000); + let err = manager().run(r).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::DiskQuotaExceeded); + assert!( + err.message.contains("/out"), + "the message should name what the tenant filled: {}", + err.message + ); +} + +#[tokio::test] +async fn oom_kill_classifies_out_of_memory() { + let mut r = req("xs = []\nwhile True:\n xs.append(\"a\" * 1_000_000)"); + r.memory_mb = Some(64); + let err = manager().run(r).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::OutOfMemory); +} + +#[tokio::test] +async fn recovered_memory_error_is_still_a_success() { + let mut r = req( + "xs = []\ntry:\n while True:\n xs.append(\"a\" * 1_000_000)\nexcept MemoryError:\n xs = None\nresult = \"recovered\"", + ); + r.memory_mb = Some(64); + let resp = manager().run(r).await.unwrap(); + assert_eq!(resp.result, "recovered"); +} + +#[tokio::test] +async fn tenant_exception_maps_kind_message_and_traceback() { + let err = manager() + .run(req("raise RuntimeError(\"boom\")")) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::PythonException); + assert_eq!(err.message, "RuntimeError: boom"); + let tb = err.traceback.unwrap(); + assert!(tb.contains("")); + assert!(!tb.contains("main.py")); +} + +#[tokio::test] +async fn a_log_flood_is_capped_per_stream_and_reported_as_truncated() { + let resp = manager() + .run(req("for i in range(5000):\n print(i)\nresult = None")) + .await + .unwrap(); + // Equality, not an upper bound: 5000 lines is well under MAX_LOG_BYTES, so + // MAX_LOG_LINES is the binding cap. An upper bound alone would still pass + // an off-by-one at 999 or a grosser bug that stopped at 500. The + // truncation MARKER is the hosting worker's business now — python-engine + // still appends it, and its own test pins that. + assert_eq!( + resp.stdout.lines().count(), + iii_python_core::config::MAX_LOG_LINES + ); + assert!(resp.truncated, "the flood must be reported as truncated"); +} + +#[tokio::test] +async fn concurrent_runs_complete_independently() { + let m = manager(); + let futs: Vec<_> = (0..4) + .map(|i| { + let m = m.clone(); + tokio::spawn(async move { m.run(req(&format!("result = {i} * {i}"))).await }) + }) + .collect(); + for (i, f) in futs.into_iter().enumerate() { + let resp = f.await.unwrap().unwrap(); + assert_eq!(resp.result, serde_json::json!(i * i)); + } +} + +/// `RunRequest::code` is tenant source and `payload` is arbitrary +/// caller-supplied data; neither may leak through an incidental +/// `tracing::debug!(?req)` or `panic!("{req:?}")`. `timeout_ms`/`memory_mb` +/// are plain knobs and must stay visible — a blanket redaction would be +/// just as wrong as none at all. +#[test] +fn run_request_debug_redacts_code_and_payload() { + let mut r = req("print(\"a secret print\")\nresult = 1"); + r.payload = Some(serde_json::json!({"token": "sk-supersecret"})); + r.timeout_ms = Some(1234); + let debug = format!("{r:?}"); + assert!( + !debug.contains("a secret print"), + "tenant source leaked into Debug: {debug}" + ); + assert!( + !debug.contains("sk-supersecret"), + "payload leaked into Debug: {debug}" + ); + assert!( + debug.contains("1234"), + "non-sensitive fields must stay visible: {debug}" + ); +} + +// --- persistent working directories --- + +/// The property `keep` exists for, and the one thing a WASI command module +/// CAN persist. Mutation: pass `work_dir: None` in `run_in`, or mint a fresh +/// directory per call — the second run then reads nothing. +#[tokio::test] +async fn files_written_in_one_call_are_visible_to_the_next() { + let m = own_manager(PythonEngineConfig::default()); + let id = m.create_runtime(None).expect("a runtime slot"); + + m.run_in( + &id, + req("open('/work/a.txt', 'w').write('hello')\nresult = None"), + ) + .await + .unwrap(); + let resp = m + .run_in(&id, req("result = open('/work/a.txt').read()")) + .await + .unwrap(); + assert_eq!(resp.result, serde_json::json!("hello")); + + m.destroy_runtime(&id).unwrap(); +} + +/// Both halves of what a `runtime_id` buys: the files in `/work` AND the +/// interpreter state that produced them. +/// +/// This inverts what this test asserted before park-and-loop landed, when +/// `_start` was the only way in and globals could not survive. Callers that +/// relied on a clean namespace per call must now clear it themselves — the +/// only thing still reset per turn is `result`. +#[tokio::test] +async fn globals_and_files_both_survive_between_calls() { + let m = own_manager(PythonEngineConfig::default()); + let id = m.create_runtime(None).unwrap(); + + m.run_in( + &id, + req("leaked = 42\nopen('/work/f', 'w').write('kept')\nresult = None"), + ) + .await + .unwrap(); + let resp = m + .run_in( + &id, + req("result = ['leaked' in globals(), open('/work/f').read()]"), + ) + .await + .unwrap(); + assert_eq!(resp.result, serde_json::json!([true, "kept"])); + + m.destroy_runtime(&id).unwrap(); +} + +/// Mutation: share one directory across runtimes, or key it by anything but +/// the runtime. +#[tokio::test] +async fn one_runtimes_files_are_invisible_to_another() { + let m = own_manager(PythonEngineConfig::default()); + let a = m.create_runtime(None).unwrap(); + let b = m.create_runtime(None).unwrap(); + + m.run_in( + &a, + req("open('/work/secret', 'w').write('A')\nresult = None"), + ) + .await + .unwrap(); + let resp = m + .run_in(&b, req("import os\nresult = os.listdir('/work')")) + .await + .unwrap(); + assert_eq!(resp.result, serde_json::json!([])); + + m.destroy_runtime(&a).unwrap(); + m.destroy_runtime(&b).unwrap(); +} + +/// A one-shot run has no `/work` at all, so touching it must fail rather than +/// silently writing somewhere. Mutation: preopen a scratch `/work` even when +/// `RunSpec::work_dir` is `None`. +#[tokio::test] +async fn a_one_shot_run_has_no_work_directory() { + let resp = manager() + .run(req( + "import os\ntry:\n os.listdir('/work')\n result = 'present'\nexcept OSError:\n result = 'absent'", + )) + .await + .unwrap(); + assert_eq!(resp.result, serde_json::json!("absent")); +} + +/// Destroying a runtime must make its id stop resolving AND take its +/// directory with it. Mutation: `remove` the entry but leak the `TempDir`. +#[tokio::test] +async fn a_destroyed_runtime_stops_resolving() { + let m = own_manager(PythonEngineConfig::default()); + let id = m.create_runtime(None).unwrap(); + assert_eq!(m.live_runtime_count(), 1); + + m.destroy_runtime(&id).unwrap(); + assert_eq!(m.live_runtime_count(), 0); + + let err = m + .run_in(&id, req("result = 1")) + .await + .expect_err("a destroyed id must not resolve"); + assert_eq!(err.kind, iii_python_core::error::ErrorKind::RuntimeNotFound); + assert_eq!( + m.destroy_runtime(&id).unwrap_err().kind, + iii_python_core::error::ErrorKind::RuntimeNotFound + ); +} + +/// Admission failure, distinct from the mid-run caps: retrying later can +/// succeed once a slot frees. Mutation: delete the cap check. +#[tokio::test] +async fn exceeding_max_runtimes_is_capacity_and_frees_on_teardown() { + let m = own_manager(PythonEngineConfig { + max_runtimes: 3, + ..PythonEngineConfig::default() + }); + let mut ids = Vec::new(); + while let Ok(id) = m.create_runtime(None) { + ids.push(id); + assert!(ids.len() < 100, "the cap must bite before this"); + } + assert_eq!(ids.len(), 3, "exactly max_runtimes slots, no more"); + let err = m.create_runtime(None).expect_err("the cap must refuse"); + assert_eq!(err.kind, iii_python_core::error::ErrorKind::Capacity); + + m.destroy_runtime(&ids.pop().unwrap()).unwrap(); + m.create_runtime(None) + .expect("a freed slot must be usable again"); +} + +/// The backstop for a caller that never tears a runtime down. Both +/// directions, because a sweeper that reaps everything passes a +/// reaps-the-idle-one test on its own. Mutation: drop the TTL comparison, +/// and the second half fails. +#[tokio::test] +async fn the_sweep_reaps_idle_runtimes_and_spares_fresh_ones() { + let eager = own_manager(PythonEngineConfig { + idle_ttl_secs: 0, + ..PythonEngineConfig::default() + }); + let id = eager.create_runtime(None).unwrap(); + assert_eq!(eager.sweep_idle(), vec![id]); + assert_eq!(eager.live_runtime_count(), 0); + + let patient = own_manager(PythonEngineConfig { + idle_ttl_secs: 3600, + ..PythonEngineConfig::default() + }); + patient.create_runtime(None).unwrap(); + assert!( + patient.sweep_idle().is_empty(), + "a runtime inside its TTL must survive the sweep" + ); + assert_eq!(patient.live_runtime_count(), 1); +} + +// --- the guest iii bridge --- + +use futures::future::BoxFuture; +use iii_python_core::runner::GuestBridge; + +/// Records what the guest asked for and answers from a script. +struct StubBridge { + calls: std::sync::Mutex>, + answer: Result, +} + +impl GuestBridge for StubBridge { + fn call( + &self, + fn_id: String, + payload: serde_json::Value, + timeout_ms: u64, + ) -> BoxFuture<'static, Result> { + self.calls + .lock() + .unwrap() + .push((fn_id, payload, timeout_ms)); + let answer = self.answer.clone(); + Box::pin(async move { answer }) + } +} + +fn bridged(answer: Result) -> (Arc, Arc) { + let bridge = Arc::new(StubBridge { + calls: std::sync::Mutex::new(Vec::new()), + answer, + }); + let m = Manager::with_bridge( + Arc::new(PythonEngineConfig::default()), + runner(), + bridge.clone(), + ); + (m, bridge) +} + +/// The round trip: guest calls out, host answers, guest gets the value back +/// as an ordinary Python object. Mutation: drop the `bridge_pump` arm from +/// the `select!` and the guest blocks until its budget expires. +#[tokio::test] +async fn guest_code_can_call_the_bus_and_use_the_answer() { + let (m, bridge) = bridged(Ok(serde_json::json!({ "n": 7 }))); + let resp = m + .run(req( + "answer = iii.trigger({'function_id': 'state::get', 'payload': {'key': 'k'}})\nresult = answer['n'] * 2", + )) + .await + .expect("the bridged run must succeed"); + assert_eq!(resp.result, serde_json::json!(14)); + + let calls = bridge.calls.lock().unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].0, "state::get"); + assert_eq!(calls[0].1, serde_json::json!({ "key": "k" })); +} + +/// A bus error must surface as a catchable Python exception, not kill the +/// run — the tenant may well have a fallback. +#[tokio::test] +async fn a_bus_error_is_a_catchable_python_exception() { + let (m, _) = bridged(Err("state::get: not found".into())); + let resp = m + .run(req( + "try:\n iii.trigger({'function_id': 'state::get'})\n result = 'no raise'\nexcept RuntimeError as e:\n result = str(e)", + )) + .await + .unwrap(); + assert!( + resp.result.as_str().unwrap().contains("not found"), + "got {:?}", + resp.result + ); +} + +/// Without a bridge there is no global at all, rather than one that always +/// refuses — a tenant cannot tell those apart from inside. Mutation: install +/// `iii` unconditionally in `wrapper.py`. +#[tokio::test] +async fn there_is_no_iii_global_without_a_bridge() { + let resp = manager() + // Reference the name and catch NameError. `'iii' in dir(__builtins__)` + // looks equivalent and is not: in an exec'd namespace `__builtins__` + // is often the dict, and `dir(a_dict)` lists dict METHODS, not keys — + // so that form answers `false` whether or not the global exists, and a + // mutation that installed `iii` unconditionally went undetected. + .run(req( + "try:\n iii\n result = 'present'\nexcept NameError:\n result = 'absent'", + )) + .await + .unwrap(); + assert_eq!(resp.result, serde_json::json!("absent")); +} + +/// The guest's own timeout must be clamped to what is LEFT of the run's +/// budget. Unclamped, this would blow the run's deadline every time and the +/// tenant would never see the bus error it could have handled. Mutation: +/// clamp only to a fixed ceiling. +#[tokio::test] +async fn a_guest_timeout_is_clamped_to_the_runs_remaining_budget() { + let (m, bridge) = bridged(Ok(serde_json::Value::Null)); + let mut r = req("iii.trigger({'function_id': 'x::y', 'timeout_ms': 600000})\nresult = None"); + r.timeout_ms = Some(3_000); + m.run(r).await.unwrap(); + + let asked = bridge.calls.lock().unwrap()[0].2; + assert!( + asked <= 3_000, + "the guest asked for 600000ms inside a 3000ms run; host passed {asked}" + ); + assert!(asked > 0, "a clamped timeout must still be usable: {asked}"); +} + +/// Tenant output and request frames share one pipe, so they must not be able +/// to become each other. Mutation: drop the rolling tail in `FramingSink` +/// and a marker split across two writes is silently logged as output. +#[tokio::test] +async fn tenant_output_and_request_frames_do_not_contaminate_each_other() { + let (m, bridge) = bridged(Ok(serde_json::json!("answered"))); + let resp = m + .run(req( + "print('before')\nresult = iii.trigger({'function_id': 'x::y'})\nprint('after')", + )) + .await + .unwrap(); + assert_eq!(resp.result, serde_json::json!("answered")); + assert_eq!( + resp.stdout, "before\nafter\n", + "the frame must not appear in tenant output" + ); + assert_eq!(bridge.calls.lock().unwrap().len(), 1); +} + +/// `memory_mb` binds a runtime for its whole life, so a per-call value against +/// an existing runtime is refused rather than silently ignored. +/// +/// Mutation: drop the guard in `run_in` and let the field through. Wasm linear +/// memory only ever grows, so the second caller would inherit whatever the +/// first grew to — the number they asked for would be a promise the sandbox +/// cannot keep, and silently ignoring it is how a caller learns that too late. +#[tokio::test] +async fn a_per_call_memory_mb_against_a_runtime_is_refused() { + let m = own_manager(PythonEngineConfig::default()); + let id = m.create_runtime(None).unwrap(); + + let mut r = req("result = 1"); + r.memory_mb = Some(256); + let err = m.run_in(&id, r).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::InvalidInput, "{}", err.message); + assert!(err.message.contains("memory_mb"), "{}", err.message); + + // The same request without the field runs. + assert_eq!( + m.run_in(&id, req("result = 1")).await.unwrap().result, + serde_json::json!(1) + ); + m.destroy_runtime(&id).unwrap(); +} + +/// A runtime backing a registered function outlives its own idleness. +/// +/// Mutation: drop the `pinned` filter from `sweep_idle`. Nothing bumps a +/// registration's activity between invocations, so an unpopular registered +/// function would be reaped and its next caller would get `RuntimeNotFound` +/// for a function the catalog still advertises. +#[tokio::test] +async fn a_pinned_runtime_is_never_swept() { + let m = own_manager(PythonEngineConfig { + idle_ttl_secs: 0, + ..PythonEngineConfig::default() + }); + let pinned = m.create_runtime(None).unwrap(); + let ordinary = m.create_runtime(None).unwrap(); + m.pin_runtime(&pinned).unwrap(); + + let reaped = m.sweep_idle(); + assert_eq!(reaped, vec![ordinary.clone()], "swept the wrong runtimes"); + assert_eq!(m.live_runtime_count(), 1); + + // Still usable, and still the same interpreter. + m.run_in(&pinned, req("kept = 7")).await.unwrap(); + assert_eq!( + m.run_in(&pinned, req("result = kept")) + .await + .unwrap() + .result, + serde_json::json!(7) + ); + + // Teardown is the only way out. + m.destroy_runtime(&pinned).unwrap(); + assert_eq!(m.live_runtime_count(), 0); +} + +/// Pinning something that is not there is an error, not a silent no-op — a +/// caller that pins a stale id must learn its registration has no runtime. +#[tokio::test] +async fn pinning_an_unknown_runtime_is_an_error() { + let m = own_manager(PythonEngineConfig::default()); + let err = m.pin_runtime("rt-nope").unwrap_err(); + assert_eq!(err.kind, ErrorKind::RuntimeNotFound); +} + +/// The host's ANSWER to `iii.trigger` is length-prefixed the same way a turn +/// frame is, so it carries the same hazard. +/// +/// Mutation: read `sys.stdin` instead of `sys.stdin.buffer` in `_read_frame`. +/// The prefix counts bytes and text-mode `read`/`len` count characters, so a +/// host function returning any non-ASCII value blocks the guest until its +/// deadline — a hang that only ever shows up in production data. +#[tokio::test] +async fn a_non_ascii_bridge_answer_does_not_hang_the_guest() { + let (m, _b) = bridged(Ok(serde_json::json!({"city": "東京", "note": "±3°"}))); + let out = m + .run(req( + "a = iii.trigger({'function_id': 'geo::lookup'})\nresult = a['city'] + a['note']", + )) + .await + .expect("the bridge answer must arrive intact"); + assert_eq!(out.result, serde_json::json!("東京±3°")); +} diff --git a/crates/python-core/tests/persistence.rs b/crates/python-core/tests/persistence.rs new file mode 100644 index 0000000000..2b10179ae8 --- /dev/null +++ b/crates/python-core/tests/persistence.rs @@ -0,0 +1,426 @@ +//! Park-and-loop interpreter persistence. +//! +//! Every containment test here names the mutation that makes it fail. A test +//! whose named mutation still passes is worthless and gets deleted — this +//! crate has deleted two already. + +use std::sync::{Arc, OnceLock}; + +use iii_python_core::runner::{ExitKind, PersistentSpec, Runner}; + +fn boot() -> Arc { + static R: OnceLock> = OnceLock::new(); + R.get_or_init(|| Runner::boot().expect("runner boots")) + .clone() +} + +/// A runtime plus the working directory it owns, kept alive together. +struct Live { + rt: iii_python_core::runner::PersistentRuntime, + _work: tempfile::TempDir, +} + +async fn spawn(memory_mb: u64) -> Live { + let work = tempfile::tempdir().unwrap(); + let rt = boot() + .spawn_persistent(PersistentSpec { + work_dir: work.path().to_path_buf(), + memory_mb, + bridge: None, + namespace: None, + }) + .await + .unwrap_or_else(|e| panic!("spawn: {}", e.error)); + Live { rt, _work: work } +} + +fn result_of(out: &iii_python_core::runner::RunOutcome) -> serde_json::Value { + let bytes = out.envelope.as_ref().unwrap_or_else(|| { + panic!( + "no envelope; stderr={}", + String::from_utf8_lossy(&out.stderr.bytes) + ) + }); + serde_json::from_slice(bytes).unwrap() +} + +/// The whole point: a name bound in one turn is still bound in the next. +#[tokio::test] +async fn globals_survive_between_turns() { + let live = spawn(128).await; + let first = live + .rt + .run("counter = 41".into(), None, 10_000) + .await + .unwrap(); + assert!(matches!(first.exit, ExitKind::Clean(0)), "{:?}", first.exit); + + let second = live + .rt + .run("counter += 1\nresult = counter".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(result_of(&second)["result"], 42); +} + +/// Imports are the expensive half of interpreter startup and the reason to +/// keep one warm at all. +#[tokio::test] +async fn imported_modules_survive_between_turns() { + let live = spawn(128).await; + live.rt + .run("import json as _j".into(), None, 10_000) + .await + .unwrap(); + let out = live + .rt + .run("result = _j.dumps([1, 2])".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(result_of(&out)["result"], "[1, 2]"); +} + +/// Files written to `/work` outlive the turn that wrote them — this is the +/// parity feature with sandbox-code-runner, which persists files and not +/// interpreters. +#[tokio::test] +async fn work_directory_survives_between_turns() { + let live = spawn(128).await; + live.rt + .run( + "open('/work/note.txt', 'w').write('hello')".into(), + None, + 10_000, + ) + .await + .unwrap(); + let out = live + .rt + .run( + "result = open('/work/note.txt').read()".into(), + None, + 10_000, + ) + .await + .unwrap(); + assert_eq!(result_of(&out)["result"], "hello"); +} + +/// Each turn is budgeted on its own `timeout_ms`, not on whatever the runtime +/// was created with or the previous caller asked for. +/// +/// **Mutation: cache the first turn's budget and reuse it** (arm the deadline +/// from a value captured at spawn rather than from `turn.timeout_ms`). The +/// second turn is then killed at 3 s despite asking for ten seconds. +/// +/// The margins are load-tolerant on purpose: the first turn's budget (3 s) +/// must comfortably hold a trivial turn on a slow shared CI runner — 600 ms +/// did not — while staying under the second turn's sleep (4 s), which is what +/// makes a leaked first-turn budget observable. +/// +/// Note on what is NOT claimed here: a turn has two independent kills — the +/// epoch deadline for executing wasm and the host-side `sleep_until` arm for a +/// guest parked in a host call — and they are armed to the same instant. Either +/// one alone produces `timed_out`, so no test through this API can show which +/// fired. That redundancy is deliberate; it is not something a test can pin. +#[tokio::test] +async fn each_turn_is_budgeted_on_its_own_timeout() { + let live = spawn(128).await; + let first = live.rt.run("result = 1".into(), None, 3_000).await.unwrap(); + assert!(!first.timed_out); + + let second = live + .rt + .run( + "import time\ntime.sleep(4)\nresult = 2".into(), + None, + 10_000, + ) + .await + .unwrap(); + assert!( + !second.timed_out, + "a 10s turn was killed on the previous turn's 3s budget" + ); + assert_eq!(result_of(&second)["result"], 2); +} + +/// **Mutation: drop the `denied.store(false, ...)` at turn start.** A +/// `MemoryError` the tenant caught and recovered from sets the limiter's flag, +/// and without the reset every later turn on this interpreter reports +/// `memory_denied` — classifying a perfectly good run as out-of-memory. +#[tokio::test] +async fn a_recovered_memory_error_does_not_poison_later_turns() { + let live = spawn(64).await; + let first = live + .rt + .run( + "try:\n b = bytearray(200 * 1024 * 1024)\nexcept MemoryError:\n pass\nresult = 'survived'" + .into(), + None, + 20_000, + ) + .await + .unwrap(); + assert!( + first.memory_denied, + "the allocation should have been refused: {:?}", + first.exit + ); + + let second = live + .rt + .run("result = 'clean'".into(), None, 10_000) + .await + .unwrap(); + assert!( + !second.memory_denied, + "the limiter's denied flag leaked across the turn boundary" + ); + assert_eq!(result_of(&second)["result"], "clean"); +} + +/// **Mutation: drop the `wipe_dir(&out_dir)` at turn start.** The previous +/// turn's envelope is then still on disk when a turn that writes none — one +/// killed by its deadline — is read, and the caller is handed the *previous* +/// turn's result as this turn's. +#[tokio::test] +async fn a_turn_never_inherits_the_previous_turns_envelope() { + let live = spawn(128).await; + let first = live + .rt + .run("result = 'first'".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(result_of(&first)["result"], "first"); + + // A turn that cannot write an envelope: it is killed mid-spin. + let second = live + .rt + .run("while True:\n pass".into(), None, 700) + .await + .unwrap(); + assert!(second.timed_out, "{:?}", second.exit); + assert!( + second.envelope.is_none(), + "read a stale envelope: {}", + String::from_utf8_lossy(second.envelope.as_deref().unwrap_or(b"")) + ); +} + +/// A timed-out turn poisons the interpreter but keeps the directory. +/// +/// The only kill that reaches a guest parked in a host call unwinds `_start`, +/// so there is no resumable state left; resuming at a tenant-chosen point +/// would hand half-written state to the next caller. The recovery is a fresh +/// interpreter on the same directory, which is why the directory must outlive +/// the interpreter that was using it. +/// +/// **Mutation: let the task clean up `work_dir` on exit** (treat it as the +/// runtime's own scratch, the way `/run` and `/out` are). The respawned +/// interpreter then cannot read the file the first one wrote, and the tenant +/// silently loses everything a timed-out call had produced. +#[tokio::test] +async fn a_timed_out_turn_kills_the_interpreter_but_not_the_directory() { + let work = tempfile::tempdir().unwrap(); + let rt = boot() + .spawn_persistent(PersistentSpec { + work_dir: work.path().to_path_buf(), + memory_mb: 128, + bridge: None, + namespace: None, + }) + .await + .unwrap_or_else(|e| panic!("spawn: {}", e.error)); + + rt.run( + "open('/work/kept.txt','w').write('yes')".into(), + None, + 10_000, + ) + .await + .unwrap(); + + let killed = rt + .run("while True:\n pass".into(), None, 700) + .await + .unwrap(); + assert!(killed.timed_out); + + // The interpreter is gone... + assert!(!rt.is_live(), "the interpreter survived its own timeout"); + assert!( + rt.run("result = 1".into(), None, 5_000).await.is_err(), + "a poisoned interpreter accepted another turn" + ); + + // ...but the directory it was working in is untouched, so a fresh + // interpreter on the same directory picks up where the tenant left off. + let fresh = boot() + .spawn_persistent(PersistentSpec { + work_dir: work.path().to_path_buf(), + memory_mb: 128, + bridge: None, + namespace: None, + }) + .await + .unwrap_or_else(|e| panic!("respawn: {}", e.error)); + let out = fresh + .run( + "result = open('/work/kept.txt').read()".into(), + None, + 10_000, + ) + .await + .unwrap(); + assert_eq!(result_of(&out)["result"], "yes"); +} + +/// A tenant exception ends its turn without ending the interpreter — a failing +/// script is a response, not an infrastructure failure, and the next caller on +/// this runtime must still be served. +#[tokio::test] +async fn a_tenant_exception_leaves_the_interpreter_usable() { + let live = spawn(128).await; + let boom = live + .rt + .run("raise ValueError('nope')".into(), None, 10_000) + .await + .unwrap(); + let env = result_of(&boom); + assert_eq!(env["ok"], false); + assert_eq!(env["kind"], "python_exception"); + assert!(env["message"].as_str().unwrap().contains("nope")); + assert!(live.rt.is_live()); + + let after = live + .rt + .run("result = 'still here'".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(result_of(&after)["result"], "still here"); +} + +/// **Mutation: drop the `take_captured` reset** (go back to reading the pipe +/// without draining it). Turn two then reports turn one's output as its own. +#[tokio::test] +async fn each_turn_reports_only_its_own_output() { + let live = spawn(128).await; + let first = live + .rt + .run("print('from-one')".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(String::from_utf8_lossy(&first.stdout.bytes), "from-one\n"); + + let second = live + .rt + .run("print('from-two')".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(String::from_utf8_lossy(&second.stdout.bytes), "from-two\n"); +} + +/// `sys.exit()` inside tenant code is the wrapper's documented "end this run, +/// keep whatever `result` held" — on a persistent interpreter it must not take +/// the interpreter down with it. +#[tokio::test] +async fn tenant_sys_exit_ends_the_turn_not_the_interpreter() { + let live = spawn(128).await; + let out = live + .rt + .run( + "import sys\nresult = 'before'\nsys.exit()".into(), + None, + 10_000, + ) + .await + .unwrap(); + assert_eq!(result_of(&out)["result"], "before"); + assert!(live.rt.is_live()); + let after = live.rt.run("result = 'after'".into(), None, 10_000).await; + assert_eq!(result_of(&after.unwrap())["result"], "after"); +} + +/// The payload reaches the turn that asked for it, not a later one. +#[tokio::test] +async fn each_turn_gets_its_own_payload() { + let live = spawn(128).await; + let a = live + .rt + .run( + "result = payload['n']".into(), + Some(r#"{"n":1}"#.into()), + 10_000, + ) + .await + .unwrap(); + assert_eq!(result_of(&a)["result"], 1); + let b = live + .rt + .run( + "result = payload['n']".into(), + Some(r#"{"n":2}"#.into()), + 10_000, + ) + .await + .unwrap(); + assert_eq!(result_of(&b)["result"], 2); +} + +/// **Mutation: drop the `ns.pop("result", None)` in `run_once`.** The shared +/// namespace is what makes globals survive, and `result` lives in it — so a +/// turn that sets no result would return the *previous* turn's value, and the +/// caller would read a stale answer as their own. +#[tokio::test] +async fn a_turn_that_sets_no_result_returns_null_not_the_last_one() { + let live = spawn(128).await; + let first = live + .rt + .run("result = 'mine'".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(result_of(&first)["result"], "mine"); + + let second = live + .rt + .run("x = 1 # sets no result".into(), None, 10_000) + .await + .unwrap(); + assert_eq!( + result_of(&second)["result"], + serde_json::Value::Null, + "inherited the previous turn's result" + ); +} + +/// A non-ASCII byte anywhere in a turn frame must not desynchronise the guest. +/// +/// **Mutation: read `sys.stdin` instead of `sys.stdin.buffer`** in +/// `_read_frame`. The host's length prefix counts BYTES; text-mode `read(n)` +/// counts CHARACTERS and so does `len()`, so the guest asks for bytes the host +/// has already finished sending and blocks until its deadline. Every character +/// below is multi-byte in UTF-8, in the code and in the payload. +#[tokio::test] +async fn a_turn_frame_carrying_non_ascii_is_framed_by_bytes() { + let live = spawn(128).await; + let out = live + .rt + .run( + "# — em dash, ± sign, 日本語\nresult = payload['greeting'] + ' — ok'".into(), + Some(r#"{"greeting":"こんにちは"}"#.into()), + 10_000, + ) + .await + .unwrap(); + assert!(!out.timed_out, "the guest desynchronised: {:?}", out.exit); + assert_eq!(result_of(&out)["result"], "こんにちは — ok"); + + // Still in sync for the next turn. + let after = live + .rt + .run("result = 'after'".into(), None, 10_000) + .await + .unwrap(); + assert_eq!(result_of(&after)["result"], "after"); +} diff --git a/crates/python-core/tests/runner.rs b/crates/python-core/tests/runner.rs new file mode 100644 index 0000000000..73be4afc1f --- /dev/null +++ b/crates/python-core/tests/runner.rs @@ -0,0 +1,439 @@ +use std::sync::{Arc, OnceLock}; + +use iii_python_core::runner::{ExitKind, RunSpec, Runner}; + +fn spec(code: &str) -> RunSpec { + RunSpec { + work_dir: None, + bridge: None, + namespace: None, + code: code.as_bytes().to_vec(), + payload_json: None, + timeout_ms: 10_000, + memory_mb: 128, + } +} + +/// One process-wide runner, matching production (`main.rs` boots exactly one) +/// and Task 5's tests. Every per-run knob lives on `RunSpec`, so no test needs +/// its own `Engine`, `InstancePre`, or epoch ticker thread. +fn boot() -> Arc { + static R: OnceLock> = OnceLock::new(); + R.get_or_init(|| Runner::boot().expect("runner boots")) + .clone() +} + +#[tokio::test] +async fn happy_path_produces_ok_envelope_and_captures_stdout() { + let r = boot(); + let out = r + .run(&spec("print(\"working\")\nresult = 2 + 2")) + .await + .unwrap(); + assert!(matches!(out.exit, ExitKind::Clean(0))); + let env: serde_json::Value = serde_json::from_slice(&out.envelope.unwrap()).unwrap(); + assert_eq!(env["result"], 4); + assert_eq!(String::from_utf8_lossy(&out.stdout.bytes), "working\n"); + assert!(!out.timed_out); + assert!(!out.memory_denied); +} + +#[tokio::test] +async fn payload_json_reaches_the_guest() { + let r = boot(); + let mut s = spec("result = payload[\"n\"] * 3"); + s.payload_json = Some("{\"n\": 14}".to_string()); + let out = r.run(&s).await.unwrap(); + let env: serde_json::Value = serde_json::from_slice(&out.envelope.unwrap()).unwrap(); + assert_eq!(env["result"], 42); +} + +#[tokio::test] +async fn tight_loop_hits_the_epoch_deadline_and_the_runner_survives() { + let r = boot(); + let mut s = spec("while True:\n pass"); + // 2000, not 500. A guest spends its first ~250 ms in CPython startup, + // *parked* in filesystem calls where the epoch cannot see it — so under + // parallel-suite contention a 500 ms budget could expire while it was + // still parked, the backstop would fire instead, and the assertion below + // (which is this test's whole job) would fail for a scheduling reason. + // Observed once. 2000 ms lands the deadline deep in the pure-spin phase. + s.timeout_ms = 2_000; + let started = std::time::Instant::now(); + let out = r.run(&s).await.unwrap(); + assert!(out.timed_out, "epoch flag must be set"); + // Spinning wasm must be caught by the epoch, not by the wall-clock + // backstop: a fiber that never returns `Pending` never lets the timeout be + // polled, so this is structural rather than a race. Without the assertion + // the epoch path could rot unnoticed behind the backstop. + match &out.exit { + ExitKind::Trap(msg) => assert!( + msg.contains("wasm trap: interrupt"), + "expected an epoch trap, got: {msg}" + ), + other => panic!("expected a trap, got {other:?}"), + } + assert!(started.elapsed().as_millis() < 5_000, "kill must be prompt"); + assert!(out.envelope.is_none(), "a killed run leaves no envelope"); + + // The shared Engine/Module must be unharmed. + let again = r.run(&spec("result = 1")).await.unwrap(); + assert!(matches!(again.exit, ExitKind::Clean(0))); +} + +/// A spinning guest must hand the worker back on every epoch slice, not hold +/// it for the whole budget. This runs on the default current-thread flavor on +/// purpose: with one worker, a guest that fails to yield starves the runtime +/// outright, so the test is strictly more demanding than a multi-thread one +/// where spare workers would mask the bug. +#[tokio::test] +async fn spinning_guests_do_not_starve_the_runtime() { + let r = boot(); + let spins: Vec<_> = (0..3) + .map(|_| { + let r = r.clone(); + tokio::spawn(async move { + let mut s = spec("while True:\n pass"); + s.timeout_ms = 3_000; + r.run(&s).await.unwrap() + }) + }) + .collect(); + + // Unrelated timer work on the same runtime must keep its schedule while + // those three spin. A single short sleep would prove nothing: for its + // first ~250 ms each guest is still in CPython startup, whose filesystem + // calls suspend the fiber anyway. So run a full second of timer work, + // which necessarily extends into the pure-spin phase. Held hostage, it + // does not finish until the guests' budget expires. + let started = std::time::Instant::now(); + for _ in 0..10 { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + let slept = started.elapsed(); + // 3s, not 2s. The fixed path measures 1.07 s and the unfixed one 2.76 s, + // so 3 s still discriminates — but 0.93 s of headroom is not enough for a + // 2-core CI runner with three guests each burning a core. + assert!( + slept < std::time::Duration::from_millis(3_000), + "1s of timer work took {slept:?} — spinning guests are starving the runtime" + ); + + for h in spins { + assert!(h.await.unwrap().timed_out); + } +} + +/// `run()`'s future must be `Send` so the manager can hold it across a spawn. +/// `TypedFunc::call_async` requires `Data: Send`, but nothing compiled that +/// proof until now, and `#[tokio::test]` defaults to current-thread — Task 5 +/// would otherwise have been the first to find out. +#[tokio::test] +async fn run_future_is_send() { + fn assert_send(_: T) {} + let r = boot(); + assert_send(r.run(&spec("result = 1"))); +} + +/// Epoch interruption is only observed at wasm back-edges and function +/// entries, so a guest parked in a host call is invisible to it. Before the +/// async rewrite this run held its thread for the full 5 s (measured), i.e. +/// `timeout_ms` bounded nothing that mattered. +#[tokio::test] +async fn guest_parked_in_a_host_call_is_still_killed_on_time() { + let r = boot(); + let mut s = spec("import time\ntime.sleep(30)\nresult = 'escaped'"); + s.timeout_ms = 500; + let started = std::time::Instant::now(); + let out = r.run(&s).await.unwrap(); + let elapsed = started.elapsed(); + assert!( + elapsed < std::time::Duration::from_secs(3), + "a sleeping guest must not outlive its budget; took {elapsed:?}" + ); + assert!(out.timed_out, "the kill must be reported as a timeout"); + assert!(matches!(out.exit, ExitKind::Trap(_))); + assert!(out.envelope.is_none()); + + // The point is not that the caller got an answer — it is that the thread + // and the store came back. A fix that reported the timeout while leaking + // the blocked fiber would pass every assertion above and still be the DoS. + let again = r.run(&spec("result = 'alive'")).await.unwrap(); + assert!(matches!(again.exit, ExitKind::Clean(0))); + let env: serde_json::Value = serde_json::from_slice(&again.envelope.unwrap()).unwrap(); + assert_eq!(env["result"], "alive"); +} + +#[tokio::test] +async fn allocation_loop_trips_the_limiter_and_the_runner_survives() { + let r = boot(); + let mut s = spec("xs = []\nwhile True:\n xs.append(\"a\" * 1_000_000)"); + s.memory_mb = 64; + let out = r.run(&s).await.unwrap(); + assert!(out.memory_denied, "limiter flag must be set"); + // Either CPython surfaced MemoryError and died with a traceback envelope, + // or growth failure trapped — both acceptable; the flag is the signal. + let again = r.run(&spec("result = 1")).await.unwrap(); + assert!(matches!(again.exit, ExitKind::Clean(0))); +} + +#[tokio::test] +async fn tenant_catching_memory_error_completes_with_flag_set() { + let r = boot(); + let mut s = spec( + "xs = []\ntry:\n while True:\n xs.append(\"a\" * 1_000_000)\nexcept MemoryError:\n xs = None\nresult = \"recovered\"", + ); + s.memory_mb = 64; + let out = r.run(&s).await.unwrap(); + let env: serde_json::Value = serde_json::from_slice(&out.envelope.unwrap()).unwrap(); + assert_eq!(env["result"], "recovered"); + assert!( + out.memory_denied, + "flag stays true even though the tenant recovered" + ); +} + +#[tokio::test] +async fn stdout_flood_is_capped_without_erroring_the_guest() { + let r = boot(); + let out = r + .run(&spec( + "for _ in range(200_000):\n print(\"x\" * 100)\nresult = \"done\"", + )) + .await + .unwrap(); + let env: serde_json::Value = serde_json::from_slice(&out.envelope.unwrap()).unwrap(); + assert_eq!( + env["result"], "done", + "prints beyond the cap must not raise in the guest" + ); + assert!(out.stdout.bytes.len() <= iii_python_core::config::MAX_LOG_BYTES); + assert!(out.stdout.dropped > 0); +} + +/// The brief's `RunOutcome` gives stderr its own cap and its own dropped +/// counter; nothing else in this suite would notice a runner that merged the +/// two streams into one pipe or dropped stderr on the floor. +#[tokio::test] +async fn stderr_is_captured_independently_of_stdout() { + let r = boot(); + let out = r + .run(&spec( + "import sys\nprint(\"to-out\")\nprint(\"to-err\", file=sys.stderr)\nresult = 1", + )) + .await + .unwrap(); + assert_eq!(String::from_utf8_lossy(&out.stdout.bytes), "to-out\n"); + assert_eq!(String::from_utf8_lossy(&out.stderr.bytes), "to-err\n"); + assert_eq!(out.stdout.dropped, 0); + assert_eq!(out.stderr.dropped, 0); +} + +#[tokio::test] +async fn runs_are_isolated_from_each_other() { + let r = boot(); + let a = r.run(&spec("import os\nopen(\"/out/marker\", \"w\").write(\"a\")\nresult = os.path.exists(\"/out/result.json\")")).await.unwrap(); + let env: serde_json::Value = serde_json::from_slice(&a.envelope.unwrap()).unwrap(); + assert_eq!( + env["result"], false, + "a fresh /out must be empty at exec time" + ); + let b = r + .run(&spec("import os\nresult = os.path.exists(\"/out/marker\")")) + .await + .unwrap(); + let env: serde_json::Value = serde_json::from_slice(&b.envelope.unwrap()).unwrap(); + assert_eq!( + env["result"], false, + "one run's /out must be invisible to the next" + ); + + // /out being writable is only half the property: `/` and `/run` must not + // be. That holds by construction today and is one `DirPerms::all()` typo + // away from silently inverting, so pin it here. + let c = r + .run(&spec(concat!( + "checks = []\n", + "for p in (\"/run/code.py\", \"/lib/probe\", \"/probe\"):\n", + " try:\n", + " open(p, \"w\")\n", + " checks.append(\"WRITABLE \" + p)\n", + " except OSError:\n", + " checks.append(\"ro\")\n", + "result = checks", + ))) + .await + .unwrap(); + let env: serde_json::Value = serde_json::from_slice(&c.envelope.unwrap()).unwrap(); + assert_eq!( + env["result"], + serde_json::json!(["ro", "ro", "ro"]), + "/run and / must be read-only to the guest" + ); +} + +/// The host must not size an allocation from a number the tenant picked. +/// `wrapper.py`'s MAX_RESULT_BYTES only binds cooperating code — tenant code +/// shares the interpreter and can write /out/result.json itself. +#[tokio::test] +async fn oversized_guest_written_envelope_is_refused_not_read() { + let r = boot(); + let out = r + .run(&spec( + "import os\nopen(\"/out/result.json\", \"w\").write(\"x\" * 8_000_000)\nos._exit(0)", + )) + .await + .unwrap(); + assert!(matches!(out.exit, ExitKind::Clean(0))); + assert!( + out.envelope.is_none(), + "an over-cap envelope must be refused, not truncated into something that parses" + ); + + // ...and the refusal must be a cap, not a blanket rejection of anything + // the guest wrote directly. + let ok = r + .run(&spec(concat!( + "import json, os\n", + "open(\"/out/result.json\", \"w\").write(json.dumps({\"ok\": True, \"result\": \"y\" * 1000}))\n", + "os._exit(0)", + ))).await + .unwrap(); + let env: serde_json::Value = serde_json::from_slice(&ok.envelope.unwrap()).unwrap(); + assert_eq!(env["result"], "y".repeat(1000)); +} + +/// `python.wasm` declares a 40 MiB minimum memory, which the limiter is asked +/// for before any code runs — and `config.rs` clamps `memory_mb` to 1..=max, +/// so a caller can legitimately ask for less. That must surface as a denied +/// run, not as an `Err` the manager would report as `internal`. +#[tokio::test] +async fn memory_below_the_interpreter_minimum_is_denied_not_an_error() { + let r = boot(); + let mut s = spec("result = 1"); + s.memory_mb = 8; + let out = r + .run(&s) + .await + .expect("a too-small cap is a run outcome, not an Err"); + assert!(out.memory_denied); + assert!(matches!(out.exit, ExitKind::Trap(_))); + assert!(out.envelope.is_none()); + + let again = r.run(&spec("result = 1")).await.unwrap(); + assert!(matches!(again.exit, ExitKind::Clean(0))); +} + +/// `/out` is the one resource wasmtime does not bound for us: memory has the +/// limiter, CPU the epoch, logs the capped pipes, inputs and the envelope +/// their byte caps — guest-writable disk had nothing. `$TMPDIR` is tmpfs on +/// most Linux hosts, so this is host RAM spent outside `memory_mb`. +#[tokio::test] +async fn filling_the_out_dir_is_killed_and_the_runner_survives() { + let r = boot(); + let mut s = spec(concat!( + "with open(\"/out/flood\", \"wb\") as f:\n", + " while True:\n", + " f.write(b\"x\" * 1_000_000)\n", + " f.flush()\n", + )); + // Long enough that finishing on the clock instead would be the bug. + s.timeout_ms = 30_000; + let started = std::time::Instant::now(); + let out = r.run(&s).await.unwrap(); + assert_eq!( + out.disk_exceeded, + Some("/out"), + "the /out budget must be what killed it, named as such" + ); + assert!(!out.timed_out, "a disk kill is not a timeout"); + assert!( + started.elapsed() < std::time::Duration::from_secs(15), + "the kill must be prompt, not the wall-clock budget expiring" + ); + assert!(out.envelope.is_none()); + + let again = r.run(&spec("result = 'alive'")).await.unwrap(); + assert!(matches!(again.exit, ExitKind::Clean(0))); + let env: serde_json::Value = serde_json::from_slice(&again.envelope.unwrap()).unwrap(); + assert_eq!(env["result"], "alive"); +} + +/// The scan is the other half of the bound: a guest that makes a million tiny +/// files makes the *walk* the attack, so entries are capped too. +#[tokio::test] +async fn flooding_out_with_tiny_files_is_killed_on_the_entry_cap() { + let r = boot(); + let mut s = spec(concat!( + "i = 0\n", + "while True:\n", + " open(\"/out/f%d\" % i, \"w\").write(\"x\")\n", + " i += 1\n", + )); + s.timeout_ms = 30_000; + let out = r.run(&s).await.unwrap(); + assert_eq!( + out.disk_exceeded, + Some("/out"), + "the entry cap must kill it too" + ); + assert!(!out.timed_out); + + let again = r.run(&spec("result = 1")).await.unwrap(); + assert!(matches!(again.exit, ExitKind::Clean(0))); +} + +/// An ordinary run must not trip the /out budget: one small file, one +/// directory entry, nowhere near either bound. +#[tokio::test] +async fn an_honest_run_never_trips_the_out_budget() { + let r = boot(); + let mut s = spec("import time\ntime.sleep(1.5)\nresult = 'fine'"); + s.timeout_ms = 10_000; + let out = r.run(&s).await.unwrap(); + assert!( + out.disk_exceeded.is_none(), + "1.5s of honest work must survive" + ); + let env: serde_json::Value = serde_json::from_slice(&out.envelope.unwrap()).unwrap(); + assert_eq!(env["result"], "fine"); +} + +/// `/out` has `DirPerms::MUTATE`, which is all `path_symlink` is gated on, and +/// only *rooted* link targets are refused — so the guest can point +/// `result.json` at an arbitrary relative path and, with a plain +/// `File::open`, make the host read it with the worker's own authority. +#[tokio::test] +async fn a_symlinked_envelope_is_not_read_through() { + let r = boot(); + // The link target is a real file with real envelope-shaped bytes, so a + // host that follows the link succeeds loudly rather than failing quietly. + let bait = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(bait.path(), br#"{"ok": true, "result": "ESCAPED"}"#).unwrap(); + let depth = bait.path().components().count(); + let code = format!( + concat!( + "import os\n", + "os.symlink(\"{}\", \"/out/result.json\")\n", + "os._exit(0)\n", + ), + // A relative traversal: cap-primitives refuses a rooted target, but + // not this. + "../".repeat(depth) + bait.path().to_str().unwrap().trim_start_matches('/') + ); + let out = r.run(&spec(&code)).await.unwrap(); + assert!(matches!(out.exit, ExitKind::Clean(0))); + assert!( + out.envelope.is_none(), + "the host must refuse a non-regular-file envelope, got {:?}", + out.envelope.as_deref().map(String::from_utf8_lossy) + ); +} + +#[tokio::test] +async fn guest_early_exit_yields_clean_nonzero_status_and_no_envelope() { + let r = boot(); + let out = r.run(&spec("import os\nos._exit(3)")).await.unwrap(); + assert!(matches!(out.exit, ExitKind::Clean(3))); + assert!(out.envelope.is_none()); +} diff --git a/crates/python-core/tests/wrapper.rs b/crates/python-core/tests/wrapper.rs new file mode 100644 index 0000000000..ee48067ace --- /dev/null +++ b/crates/python-core/tests/wrapper.rs @@ -0,0 +1,228 @@ +use std::fs; +use std::process::Command; + +const WRAPPER: &str = include_str!("../src/wrapper.py"); + +struct Run { + envelope: Option, + /// Size of the bytes actually written to `/out/result.json`. The host caps + /// *this*, so the boundary tests have to see it rather than the parsed + /// value. + written_len: Option, + stdout: String, + stderr: String, + status: std::process::ExitStatus, +} + +fn run_wrapper(code: &str, payload: Option<&str>) -> Run { + let dir = tempfile::tempdir().unwrap(); + let run_dir = dir.path().join("run"); + let out_dir = dir.path().join("out"); + fs::create_dir_all(&run_dir).unwrap(); + fs::create_dir_all(&out_dir).unwrap(); + fs::write(run_dir.join("main.py"), WRAPPER).unwrap(); + fs::write(run_dir.join("code.py"), code).unwrap(); + if let Some(p) = payload { + fs::write(run_dir.join("payload.json"), p).unwrap(); + } + let python = which::which("python3").expect("host python3 required for wrapper tests"); + let out = Command::new(python) + .arg("-I") + .arg("-B") + .arg(run_dir.join("main.py")) + .arg(&run_dir) + .arg(&out_dir) + .output() + .unwrap(); + let written = fs::read(out_dir.join("result.json")).ok(); + let envelope = written + .as_deref() + .and_then(|b| serde_json::from_slice(b).ok()); + Run { + envelope, + written_len: written.as_ref().map(Vec::len), + stdout: String::from_utf8_lossy(&out.stdout).into_owned(), + stderr: String::from_utf8_lossy(&out.stderr).into_owned(), + status: out.status, + } +} + +#[test] +fn assigned_result_and_payload_round_trip() { + let r = run_wrapper( + "result = {\"sum\": sum(payload[\"xs\"])}", + Some("{\"xs\": [1,2,3]}"), + ); + let env = r.envelope.unwrap(); + assert_eq!(env["ok"], true); + assert_eq!(env["result"]["sum"], 3 + 2 + 1); + assert!(r.status.success()); +} + +#[test] +fn missing_payload_is_none_and_unassigned_result_is_null() { + let r = run_wrapper("assert payload is None", None); + let env = r.envelope.unwrap(); + assert_eq!(env["ok"], true); + assert_eq!(env["result"], serde_json::Value::Null); +} + +#[test] +fn unrepresentable_result_becomes_null() { + // `object()` has no JSON form at all; NaN and Infinity have a json.dumps + // form (`NaN`, `Infinity`) that is NOT valid JSON — without + // allow_nan=False they poison the envelope and the host reports a bare + // exit instead of a result. + for code in [ + "result = object()", + "result = float(\"nan\")", + "result = float(\"inf\")", + ] { + let r = run_wrapper(code, None); + let env = r.envelope.unwrap(); + assert_eq!(env["ok"], true, "{code}"); + assert_eq!(env["result"], serde_json::Value::Null, "{code}"); + } +} + +#[test] +fn syntax_error_names_the_line_and_never_execs() { + let r = run_wrapper("def broken(:\n pass", None); + let env = r.envelope.unwrap(); + assert_eq!(env["ok"], false); + assert_eq!(env["kind"], "syntax_error"); + assert!(env["message"].as_str().unwrap().contains("line 1")); + assert!( + r.status.success(), + "wrapper itself must exit 0 on tenant syntax errors" + ); +} + +#[test] +fn exception_traceback_shows_tenant_frames_only() { + let r = run_wrapper( + "def inner():\n raise ValueError(\"boom\")\ninner()", + None, + ); + let env = r.envelope.unwrap(); + assert_eq!(env["kind"], "python_exception"); + assert_eq!(env["message"], "ValueError: boom"); + let tb = env["traceback"].as_str().unwrap(); + assert!(tb.contains(""), "tenant frames must be present: {tb}"); + assert!( + !tb.contains("main.py"), + "wrapper frames must be stripped: {tb}" + ); +} + +#[test] +fn system_exit_is_completion_not_error() { + let r = run_wrapper("result = 41\nimport sys\nsys.exit(0)\nresult = 42", None); + let env = r.envelope.unwrap(); + assert_eq!(env["ok"], true); + assert_eq!(env["result"], 41); +} + +#[test] +fn oversized_result_reports_result_too_large() { + let r = run_wrapper("result = \"x\" * 2_000_000", None); + let env = r.envelope.unwrap(); + assert_eq!(env["ok"], false); + assert_eq!(env["kind"], "result_too_large"); + assert!(env["message"].as_str().unwrap().contains("1048576")); +} + +/// The guest and the host must agree on what "1 MiB" measures. The guest used +/// to check the *serialized value* while writing the value wrapped in 24 bytes +/// of envelope, so every result in the top 24 bytes of the range passed here +/// and was then refused by the host — the caller getting a bare "code exited +/// with status 0" instead of either answer. +/// +/// `"x" * N` serializes to N+2 bytes and writes N+26. These two cases sit on +/// either side of the boundary and 1_048_551 is inside the old window. +#[test] +fn a_result_whose_envelope_is_exactly_the_cap_is_written_whole() { + let r = run_wrapper("result = \"x\" * 1_048_550", None); + assert_eq!(r.envelope.unwrap()["ok"], true); + assert_eq!( + r.written_len, + Some(iii_python_core::config::MAX_RESULT_BYTES), + "the write must land exactly on the cap the host enforces" + ); +} + +#[test] +fn a_result_one_byte_of_envelope_over_the_cap_is_refused_by_the_guest() { + let r = run_wrapper("result = \"x\" * 1_048_551", None); + let env = r.envelope.unwrap(); + assert_eq!(env["ok"], false); + assert_eq!( + env["kind"], "result_too_large", + "this length passed the old value-only check and was then silently refused by the host" + ); +} + +/// `MAX_TRACEBACK_CHARS` bounded the traceback but nothing bounded the +/// message, and `str(e)` is entirely tenant-controlled — so a big enough +/// exception text produced an envelope the host refuses, losing the error the +/// tenant actually needed. +#[test] +fn a_huge_exception_message_is_capped_not_lost() { + let r = run_wrapper("raise RuntimeError(\"x\" * 10_000_000)", None); + let env = r.envelope.unwrap(); + assert_eq!(env["kind"], "python_exception"); + assert!( + r.written_len.unwrap() <= iii_python_core::config::MAX_RESULT_BYTES, + "the error envelope must stay inside the cap the host enforces, was {:?}", + r.written_len + ); + let msg = env["message"].as_str().unwrap(); + assert!( + msg.starts_with("RuntimeError: xxx") && msg.ends_with("truncated"), + "the message must be truncated, not replaced" + ); +} + +#[test] +fn envelope_is_written_after_tenant_code_finishes() { + // Tenant pre-writes a forged envelope; the wrapper's final write must win. + let code = r#" +with open("OUT/result.json", "w") as f: + f.write('{"ok": true, "result": "forged"}') +result = "genuine" +"#; + // The wrapper receives out_dir as argv[2]; tenant code can find it the + // same way. Substitute the real path for OUT before running. + let dir = tempfile::tempdir().unwrap(); + let run_dir = dir.path().join("run"); + let out_dir = dir.path().join("out"); + std::fs::create_dir_all(&run_dir).unwrap(); + std::fs::create_dir_all(&out_dir).unwrap(); + std::fs::write(run_dir.join("main.py"), WRAPPER).unwrap(); + std::fs::write( + run_dir.join("code.py"), + code.replace("OUT", out_dir.to_str().unwrap()), + ) + .unwrap(); + let python = which::which("python3").unwrap(); + let out = std::process::Command::new(python) + .arg("-I") + .arg("-B") + .arg(run_dir.join("main.py")) + .arg(&run_dir) + .arg(&out_dir) + .output() + .unwrap(); + assert!(out.status.success()); + let env: serde_json::Value = + serde_json::from_slice(&std::fs::read(out_dir.join("result.json")).unwrap()).unwrap(); + assert_eq!(env["result"], "genuine"); +} + +#[test] +fn prints_reach_stdout_not_the_envelope() { + let r = run_wrapper("print(\"working\")\nresult = 1", None); + assert_eq!(r.stdout, "working\n"); + assert!(r.stderr.is_empty()); + assert_eq!(r.envelope.unwrap()["result"], 1); +} diff --git a/iii-permissions.yaml b/iii-permissions.yaml index dd7864e2e4..690f32126a 100644 --- a/iii-permissions.yaml +++ b/iii-permissions.yaml @@ -195,6 +195,10 @@ rules: # other on-config-change denies. - '!pdf::on-config-change' + # code-runner: internal hot-reload hook, same pattern as the other + # on-config-change denies. + - '!code-runner::on-config-change' + # Read-only / introspection (extend below for your tools). - state::get - state::list diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 55c13f7d6b..fdefaa72e7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,6 +27,34 @@ importers: specifier: ^5.9.2 version: 5.9.3 + code-runner/ui: + dependencies: + '@iii-dev/console-ui': + specifier: workspace:* + version: link:../../packages/console-ui + devDependencies: + '@types/react': + specifier: ^19.2.14 + version: 19.2.17 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.17) + esbuild: + specifier: ^0.25.0 + version: 0.25.12 + react: + specifier: ^19.2.6 + version: 19.2.7 + react-dom: + specifier: ^19.2.6 + version: 19.2.7(react@19.2.7) + typescript: + specifier: ^5.9.2 + version: 5.9.3 + vitest: + specifier: ^4.1.6 + version: 4.1.10(@opentelemetry/api@1.9.1)(@types/node@25.9.5)(@vitest/coverage-v8@4.1.10)(vite@8.1.5(@types/node@25.9.5)(jiti@2.7.0)) + computer/ui: dependencies: '@iii-dev/console-ui': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 41164c993a..1d8e858e93 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -11,6 +11,7 @@ packages: - console/ui - browser/ui - sandbox-code-runner/ui + - code-runner/ui - computer/ui - database/ui - editor/ui