diff --git a/Cargo.lock b/Cargo.lock index c831327..fcb80d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -368,8 +368,8 @@ checksum = "8e0bf07d379916947be6c4a07f43684153d710a2896c31f9e97781362895596c" dependencies = [ "ambient-authority", "fs-set-times", - "io-extras 0.18.4", - "io-lifetimes 2.0.4", + "io-extras", + "io-lifetimes", "ipnet", "maybe-owned", "rustix", @@ -378,33 +378,15 @@ dependencies = [ "winx", ] -[[package]] -name = "cap-primitives" -version = "4.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" -dependencies = [ - "ambient-authority", - "fs-set-times", - "io-extras 0.19.0", - "io-lifetimes 3.0.1", - "ipnet", - "maybe-owned", - "rustix", - "rustix-linux-procfs", - "windows-sys 0.61.2", - "winx", -] - [[package]] name = "cap-std" version = "3.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a59e59fa26472d29680ece6a9f8ee8b0551a719a33df2f5240bde065ecbddfd7" dependencies = [ - "cap-primitives 3.4.6", - "io-extras 0.18.4", - "io-lifetimes 2.0.4", + "cap-primitives", + "io-extras", + "io-lifetimes", "rustix", ] @@ -574,6 +556,7 @@ dependencies = [ "reqwest 0.12.28", "semver", "serde", + "serde_json", "sha2 0.10.9", "tar", "tempfile", @@ -711,27 +694,27 @@ dependencies = [ [[package]] name = "cranelift-assembler-x64" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6071a4f1df4837aa03d1e4d53067784acafe270ffc7dad66a7f39832204da3f" +checksum = "80aafbfb0490c28f23bdb6183acfd470d48244745d6bb70e66121f7751a9a7ca" dependencies = [ "cranelift-assembler-x64-meta", ] [[package]] name = "cranelift-assembler-x64-meta" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e3b92a9cc90388fe70e63640af30b734387449445aef0176ab2028e9892d70e" +checksum = "d2e5ea46889c5bf3c0eb5882a8d6ed755e26f6efab8b3f0b441a7e781f56b03e" dependencies = [ "cranelift-srcgen", ] [[package]] name = "cranelift-bforest" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f45c85646c4425cc85b868effaf20c302b437a3fb79bb27a64513dd522f07411" +checksum = "8a65274b952dba816b143b20df6976dbbfc1f2830907f6be262cf0370c061231" dependencies = [ "cranelift-entity", "wasmtime-internal-core", @@ -739,9 +722,9 @@ dependencies = [ [[package]] name = "cranelift-bitset" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94f56b5c7d564cfa03aa269a6b98c916cab4d545196a391d31403a23ef39333a" +checksum = "fc739cedf56f9ad87c94bc3473908d6b0149221526905a2871c33cfed7f2c8d9" dependencies = [ "serde", "serde_derive", @@ -750,9 +733,9 @@ dependencies = [ [[package]] name = "cranelift-codegen" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c073641ce6e382814a8220331cc1ea2c782a9ea5d5da6d0f7f7c0541192693e" +checksum = "d91eb4435f140b0b05bb053ef6267e22a8c858beed43a560749e90991d7b7a63" dependencies = [ "bumpalo", "cranelift-assembler-x64", @@ -781,9 +764,9 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db226fafea5194921de10dccf35ac2863500313990f770cbe8b26c51eebec4d4" +checksum = "b9e0194c51a53670724fec307f9bbd8dc18f9b0bb3c7728efd5a45475f8641de" dependencies = [ "cranelift-assembler-x64-meta", "cranelift-codegen-shared", @@ -794,24 +777,24 @@ dependencies = [ [[package]] name = "cranelift-codegen-shared" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8ac46b2c8e328ca979810426ea635ef90ecc8c54fd3296bde31ab470a48a1d" +checksum = "73c10abe5c89741cb15008c8a3d9fd177c7d7a1b9af22b7eff1eb3f9e9f2ed61" [[package]] name = "cranelift-control" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6754e0ab97915209ea6ce6549f6443b018e1338142ada4c856cec213ee82e4b8" +checksum = "d15be56b0f8c45eb15d60164f31f5ec89b277fde2a05283cc66722c2b57a7980" dependencies = [ "arbitrary", ] [[package]] name = "cranelift-entity" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "774d25e36df18696f63a284e9c4ea43455e2ebcca6308e0e02301f18c8e777e2" +checksum = "f1384afac57ecc364ced64eb8526da8d883233157f1b5e37353bc6d172a71427" dependencies = [ "cranelift-bitset", "serde", @@ -821,9 +804,9 @@ dependencies = [ [[package]] name = "cranelift-frontend" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cfcb31405e2de2a48e5a6de8e07a3d8b77f35caa3e944d627780734b36c138" +checksum = "c491acfa0f5056cf573c36f04d495d991b644ec9df893d132ea9415fb347c44e" dependencies = [ "cranelift-codegen", "hashbrown 0.17.1", @@ -834,26 +817,27 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f5a26df22db546ab92be6feaf21835ae91082af0a32bbb398b277df3765412f" +checksum = "851ff79666f0af6288aa0d652f7315ae9b027eef00113a819d2dd12f5395a4db" [[package]] name = "cranelift-native" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f258c08e590f90dcaf9904d25ba142ee2980c3aaeac4bb45f1452b1a407c2a" +checksum = "a8c4069cb5d92c95655b3bc610295de7be9c989d5cf007ba2d3dcb1834b10e26" dependencies = [ "cranelift-codegen", "libc", + "mach2", "target-lexicon", ] [[package]] name = "cranelift-srcgen" -version = "0.135.7" +version = "0.137.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67055b4f315e8f6af3e8eccec74ad38f7407f0fd854adbd49b4b3b27bdb2e3be" +checksum = "1c4cad638d567f380c02aeb025a4a930e97ca5c044299c5deb07c53679a027b1" [[package]] name = "crc32fast" @@ -1217,7 +1201,7 @@ version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ - "io-lifetimes 2.0.4", + "io-lifetimes", "rustix", "windows-sys 0.59.0", ] @@ -1749,32 +1733,16 @@ version = "0.18.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2285ddfe3054097ef4b2fe909ef8c3bcd1ea52a8f0d274416caebeef39f04a65" dependencies = [ - "io-lifetimes 2.0.4", + "io-lifetimes", "windows-sys 0.59.0", ] -[[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.2" @@ -2102,9 +2070,9 @@ dependencies = [ [[package]] name = "object" -version = "0.39.1" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" dependencies = [ "crc32fast", "hashbrown 0.17.1", @@ -2359,9 +2327,9 @@ dependencies = [ [[package]] name = "pulley-interpreter" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b8187c8e7db87d085865fc106502e7b34d5c25f8ce4c272945b21503371f6a0" +checksum = "ac335d6104773cb78791143cba33fb2148766dc43dc1e9c6907ff2046882d953" dependencies = [ "cranelift-bitset", "log", @@ -2371,13 +2339,13 @@ dependencies = [ [[package]] name = "pulley-macros" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f98ce0e381d9e45e63ea1d20bba3cf131797086077f43af9203f1fb7de0ed6b" +checksum = "ecc5c33f912277d2c57155ff8c599b3ab9cc6fc59526d2baba22f5cd411ffd68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -3390,21 +3358,6 @@ dependencies = [ "toml_edit 0.22.27", ] -[[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 1.1.2", - "toml_datetime 0.7.5+spec-1.1.0", - "toml_parser", - "toml_writer", - "winnow 0.7.15", -] - [[package]] name = "toml" version = "1.1.8+spec-1.1.0" @@ -3429,15 +3382,6 @@ dependencies = [ "serde", ] -[[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_datetime" version = "1.1.2+spec-1.1.0" @@ -3792,18 +3736,17 @@ dependencies = [ [[package]] name = "wasm-compose" -version = "0.254.2" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c0c1033c10d23d96f40e761ae66cc30c70cea3323a8edfe9159dac42108873f" +checksum = "df7deb87d659b1df555d3195e3df56d1f03b73d165c5a1bc3a0bad24274ea147" dependencies = [ "anyhow", - "heck", "indexmap", "log", "petgraph 0.6.5", "smallvec", - "wasm-encoder 0.254.2", - "wasmparser 0.254.2", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wat", ] @@ -3847,6 +3790,16 @@ dependencies = [ "wasmparser 0.258.3", ] +[[package]] +name = "wasm-encoder" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" +dependencies = [ + "leb128fmt", + "wasmparser 0.261.0", +] + [[package]] name = "wasm-encoder" version = "0.262.0" @@ -3919,6 +3872,18 @@ dependencies = [ "wasmparser 0.258.3", ] +[[package]] +name = "wasm-metadata" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b88de21560ecd49deb8d8f1616b9b695f66fc312c5eca503f43accdc5795339e" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", +] + [[package]] name = "wasm-pkg-client" version = "0.16.1" @@ -4011,7 +3976,6 @@ dependencies = [ "hashbrown 0.17.1", "indexmap", "semver", - "serde", ] [[package]] @@ -4040,6 +4004,19 @@ dependencies = [ "serde", ] +[[package]] +name = "wasmparser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" +dependencies = [ + "bitflags", + "hashbrown 0.17.1", + "indexmap", + "semver", + "serde", +] + [[package]] name = "wasmparser" version = "0.262.0" @@ -4053,20 +4030,20 @@ dependencies = [ [[package]] name = "wasmprinter" -version = "0.254.2" +version = "0.261.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b03c8f270f3f384f70f42869b5ff7f6253fe4f0aa8590f7edd332c1943e5f51" +checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" dependencies = [ "anyhow", "termcolor", - "wasmparser 0.254.2", + "wasmparser 0.261.0", ] [[package]] name = "wasmtime" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12300d040e8bea7e7ccde75b9919d27ebba47a217a64b09ba058ae8d3b4290b6" +checksum = "9e32e3ce9a15d2ddedfeae38437a4fe52ed9c59ac878e3131e5a840068faf44e" dependencies = [ "addr2line", "async-trait", @@ -4097,8 +4074,8 @@ dependencies = [ "target-lexicon", "tempfile", "wasm-compose", - "wasm-encoder 0.254.2", - "wasmparser 0.254.2", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmtime-environ", "wasmtime-internal-cache", "wasmtime-internal-component-macro", @@ -4112,14 +4089,14 @@ dependencies = [ "wasmtime-internal-versioned-export-macros", "wat", "windows-sys 0.61.2", - "wit-parser 0.254.2", + "wit-parser 0.261.0", ] [[package]] name = "wasmtime-environ" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "805d6554eb6dd6e62891061a31383a89d69fd891f785e5ae68f0835a554b7a2a" +checksum = "2b204a74048032e778bf04348dd80c906e749cd0a61e5447e55129d803b2303e" dependencies = [ "anyhow", "cpp_demangle", @@ -4136,11 +4113,10 @@ dependencies = [ "semver", "serde", "serde_derive", - "sha2 0.10.9", "smallvec", "target-lexicon", - "wasm-encoder 0.254.2", - "wasmparser 0.254.2", + "wasm-encoder 0.261.0", + "wasmparser 0.261.0", "wasmprinter", "wasmtime-internal-component-util", "wasmtime-internal-core", @@ -4148,9 +4124,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-cache" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b11ca8945aa341f944558622db59845dffa1435971f318d5fce2f2d9765a69b0" +checksum = "96e9b0120eaa3448f11673000e5c970fda5d78f3a3f35a08fd00fa9462453322" dependencies = [ "base64 0.22.1", "directories-next", @@ -4160,7 +4136,7 @@ dependencies = [ "serde", "serde_derive", "sha2 0.10.9", - "toml 0.9.12+spec-1.1.0", + "toml 1.1.8+spec-1.1.0", "wasmtime-environ", "windows-sys 0.61.2", "zstd 0.13.3", @@ -4168,30 +4144,30 @@ dependencies = [ [[package]] name = "wasmtime-internal-component-macro" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b832b80853365d9d3a741681044554be291a4f977aae074b318b55c7a4835f83" +checksum = "bc9b1c3975c5ed4ad404ecde0a4b2ed2a94b7dfc8b5c6b03e759831744a452c0" dependencies = [ "anyhow", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "wasmtime-internal-component-util", "wasmtime-internal-wit-bindgen", - "wit-parser 0.254.2", + "wit-parser 0.261.0", ] [[package]] name = "wasmtime-internal-component-util" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c8a11aaf68d8945991429d45950f32490a30ddcdcdb56629816cb41a255d8fe" +checksum = "86e3ec719916f972b40b5d02a9d0c072fbed65927ae777d67e4776226d9d0072" [[package]] name = "wasmtime-internal-core" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea266d6cfb31c324c075c8432386654bcbb1559aa8d29be9d47eacf7dcc41012" +checksum = "0188c3e530af2407cb868818701df371ddd7061e2d73182d6d0cdc5b7e1a7a5f" dependencies = [ "anyhow", "hashbrown 0.17.1", @@ -4201,9 +4177,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-cranelift" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d427759553b07c296c8ed7bff8ac930a94b9ba99e6a79243ea79bcc51aa58d96" +checksum = "6dfcfa2173aee3184c2c66c850a740c5b11565485f3ea36da2c405c9a21fd7fc" dependencies = [ "cranelift-codegen", "cranelift-control", @@ -4218,7 +4194,7 @@ dependencies = [ "smallvec", "target-lexicon", "thiserror 2.0.21", - "wasmparser 0.254.2", + "wasmparser 0.261.0", "wasmtime-environ", "wasmtime-internal-core", "wasmtime-internal-unwinder", @@ -4227,9 +4203,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-fiber" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b54c8c5b02ea985149a90f917e1761af99734c6c27e6d7fdd5b6f69fc1db3950" +checksum = "8ef75fc7dd6ac3e02239cb6e840d9ff400b8d33be948bd94553c51d978e2a77b" dependencies = [ "cc", "libc", @@ -4241,9 +4217,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-debug" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72bb10c94724f072b6eca515085033e61da9efae65d054545126df37a15530c3" +checksum = "1a3029a2f03287e5ba6162f43e717cfa9a4f92babc8b53f56e4bc1680687f684" dependencies = [ "cc", "object", @@ -4253,9 +4229,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-icache-coherence" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b781a27e8958fd07fd3135c0be216f77301efecd15cbf4f14ff210cdad5f169" +checksum = "42dcd30201c6eff398ed264a8633f381242ab0eae1e6702eb0c4721b8c5d498d" dependencies = [ "libc", "wasmtime-internal-core", @@ -4264,9 +4240,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-unwinder" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121188de1b2741b8e35530a9b0c8adf525b3aa5913a2ca3d4522509cfbc0494a" +checksum = "40bfc597fc389f058e0f3151b4063b12133f5999d68c751bb48fc36352f21dff" dependencies = [ "cranelift-codegen", "log", @@ -4276,39 +4252,38 @@ dependencies = [ [[package]] name = "wasmtime-internal-versioned-export-macros" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "933f1990e4e5177547a4abd51dcfa5cb7616fe42b9fb6f0f2b7423627758223c" +checksum = "9ea83140ce7e7e6c4357b43988974a761dd9f74d51ea674e5c822a5022bcc9f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "wasmtime-internal-wit-bindgen" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "417ebd61d2581d86d65413517f3a41294a9ad105da26f0dc7039912a0d97e1ed" +checksum = "61ef2d7c6d52219718083aba0f6b05afa245ff5e76aa75b95fcae7671e0bdbb5" dependencies = [ "anyhow", "bitflags", "heck", "indexmap", - "wit-component 0.254.2", - "wit-parser 0.254.2", + "wit-component 0.261.0", + "wit-parser 0.261.0", ] [[package]] name = "wasmtime-wasi" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ef0d3ec88f9406bc5e498848489c49ff515577500acc9f03fa93d0883dce435" +checksum = "a08c772131a8cbfc3a2c116b637c1c36609012738db949723df53fd9f88bb4e0" dependencies = [ "async-trait", "bitflags", "bytes", - "cap-primitives 4.0.3", "futures", "rand", "rustix", @@ -4321,14 +4296,13 @@ dependencies = [ "wasmtime-wasi-io", "wiggle", "windows-sys 0.61.2", - "winx", ] [[package]] name = "wasmtime-wasi-io" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe7dfc924e222e15455bd6d445ff7065a4595fffc7698c7bbc01acc0ed6c0421" +checksum = "bb4241148712c8604662377b440f93af7615f61a997f03bc28ea61450a545445" dependencies = [ "async-trait", "bytes", @@ -4408,9 +4382,9 @@ dependencies = [ [[package]] name = "wiggle" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f25221922f042ed78c7857a29f2e54d45d02a73891bcc3a046f2c3c0400cfd3" +checksum = "1de475da34b9904405df36a7f76037a29a06b5def3d57130bbcd1a31a79dff2e" dependencies = [ "bitflags", "thiserror 2.0.21", @@ -4422,27 +4396,27 @@ dependencies = [ [[package]] name = "wiggle-generate" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9ad83cd72263fd94189bdbf3bf37dc131f6a293ff639cebfbb00ed3f21f05f2" +checksum = "1b77277488ed90b907324d5b155b514c65e9fdba70a792e32d344a10b3c8f21b" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "wasmtime-environ", "witx", ] [[package]] name = "wiggle-macro" -version = "48.0.7" +version = "50.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96820f65b0f61bad3e6dd073f670db9a6da537dc71f848fee715f692b19dfd9a" +checksum = "d038b7871fd025d3d436f71c16bf107ff7fee91386f92bf133588e96b39468ae" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "wiggle-generate", ] @@ -4542,7 +4516,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -4551,16 +4525,7 @@ 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", + "windows-targets", ] [[package]] @@ -4578,31 +4543,14 @@ 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", + "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]] @@ -4611,96 +4559,48 @@ 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" @@ -4837,6 +4737,25 @@ dependencies = [ "wit-parser 0.258.3", ] +[[package]] +name = "wit-component" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2818766842bd2321074c348fb5c15d8fdb105a9eb78374e6d77c7d4127e1f2f9" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder 0.261.0", + "wasm-metadata 0.261.0", + "wasmparser 0.261.0", + "wit-parser 0.261.0", +] + [[package]] name = "wit-dylib" version = "0.258.3" @@ -4911,6 +4830,25 @@ dependencies = [ "wasmparser 0.258.3", ] +[[package]] +name = "wit-parser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "962e43c4db2da607b50839a531e5b63473268b40efdf8028d5c54b572ca4f6f6" +dependencies = [ + "anyhow", + "hashbrown 0.17.1", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser 0.261.0", +] + [[package]] name = "witx" version = "0.9.1" diff --git a/Cargo.toml b/Cargo.toml index 01bf135..3850c6c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,28 +10,54 @@ description = "Tool for targeting the WebAssembly Component Model using Python" name = "componentize_py" crate-type = ["cdylib", "rlib"] +[[bin]] +name = "componentize-py" +required-features = ["embedded-runtime"] + +[features] +default = ["embedded-runtime"] +# Builds CPython and the runtime into the crate. Preparing assets and +# `componentize` need it; reading and assembling prepared assets do not. +embedded-runtime = [ + "dep:bincode", + "dep:cap-std", + "dep:clap", + "dep:heck", + "dep:im-rc", + "dep:once_cell", + "dep:pretty_env_logger", + "dep:semver", + "dep:tokio", + "dep:wasm-pkg-client", + "dep:wasmtime-wasi", + "dep:wit-bindgen-core", + "dep:wit-dylib", + "dep:wit-parser", +] +pyo3 = ["dep:pyo3", "embedded-runtime"] + [dependencies] anyhow = { version = "1.0.91", features = ["backtrace"] } -clap = { version = "4.5.20", features = ["derive"] } +clap = { version = "4.5.20", features = ["derive"], optional = true } tar = "0.4.42" tempfile = "3.13.0" zstd = "0.13.2" wasm-encoder = { version = "0.258.0", features = ["wasmparser"] } -wit-dylib = "0.258.0" -wit-parser = "0.258.0" +wit-dylib = { version = "0.258.0", optional = true } +wit-parser = { version = "0.258.0", optional = true } wit-component = "0.258.0" wasmparser = "0.258.0" indexmap = "2.6.0" -bincode = "1.3.3" -heck = "0.5.0" +bincode = { version = "1.3.3", optional = true } +heck = { version = "0.5.0", optional = true } pyo3 = { version = "0.28.3", features = [ "abi3-py39", "extension-module", ], optional = true } -wasmtime = "48.0.0" -wasmtime-wasi = { version = "48.0.0", features = [ "p3" ] } -wasm-pkg-client = "0.16.1" -once_cell = "1.20.2" +wasmtime = "50.0.1" +wasmtime-wasi = { version = "50.0.1", features = [ "p3" ], optional = true } +wasm-pkg-client = { version = "0.16.1", optional = true } +once_cell = { version = "1.20.2", optional = true } component-init-transform = "0.3.1" async-trait = "0.1.83" futures = "0.3.31" @@ -40,15 +66,16 @@ tokio = { version = "1.41.0", features = [ "rt", "rt-multi-thread", "fs", -] } +], optional = true } bytes = "1.8.0" -pretty_env_logger = "0.5.0" -cap-std = "3.3.0" -im-rc = "15.1.0" +pretty_env_logger = { version = "0.5.0", optional = true } +cap-std = { version = "3.3.0", optional = true } +im-rc = { version = "15.1.0", optional = true } serde = { version = "1.0.213", features = ["derive"] } +serde_json = "1.0" toml = "0.8.19" -semver = "1.0.23" -wit-bindgen-core = "0.61.0" +semver = { version = "1.0.23", optional = true } +wit-bindgen-core = { version = "0.61.0", optional = true } sha2 = "0.10.9" filetime = "0.2.29" diff --git a/build.rs b/build.rs index e95716d..2535ffd 100644 --- a/build.rs +++ b/build.rs @@ -64,6 +64,13 @@ fn main() -> Result<()> { || env::var("CLIPPY_ARGS").is_ok() || env::var("CARGO_EXPAND_NO_RUN_NIGHTLY").is_ok() { + println!( + "cargo:warning=using stubbed runtime, core library, and adapter for static analysis purposes..." + ); + stubs_for_clippy(&out_dir) + } else if env::var_os("CARGO_FEATURE_EMBEDDED_RUNTIME").is_none() { + // Without the embedded runtime, the crate only reads and assembles + // prepared assets, which carry their own runtime. stubs_for_clippy(&out_dir) } else { package_all_the_things(&out_dir) @@ -75,10 +82,6 @@ fn main() -> Result<()> { } fn stubs_for_clippy(out_dir: &Path) -> Result<()> { - println!( - "cargo:warning=using stubbed runtime, core library, and adapter for static analysis purposes..." - ); - let files = [ "libcomponentize_py_runtime_sync.so.zst", "libcomponentize_py_runtime_async.so.zst", diff --git a/src/command.rs b/src/command.rs index 9a78995..275da74 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,6 +1,9 @@ use { - crate::{BindingsGenerator, ComponentGenerator}, - anyhow::{Context, Result}, + crate::{ + BindingsGenerator, ComponentGenerator, + prepared::{Assembler, BindingsPreparer, Prepared}, + }, + anyhow::{Context, Result, bail}, clap::Parser as _, std::{ env, @@ -130,6 +133,63 @@ pub enum Command { /// bindings generated by this command need not and should not be used by an /// actual component produced using the `componentize` command. Bindings(Bindings), + + /// Prepare the bindings, runtime and metadata for a WIT world, for + /// assembly with any number of applications. + /// + /// Prints the identity of the prepared assets. + Prepare(Prepare), + + /// Link prepared assets with a Python app and its native extensions, then + /// pre-initialize the result. + /// + /// The WIT world comes from the prepared assets; `--wit-path`, `--world` + /// and the other WIT options do not apply. + Assemble(Assemble), +} + +#[derive(clap::Args, Debug)] +pub struct Prepare { + /// Directory to which the prepared assets should be written. It must not + /// exist or must be empty. + pub output_dir: PathBuf, + + /// Specify a world to intersect with the target world. See + /// `componentize --intersect-world`. + #[arg(short = 'i', long)] + pub intersect_world: Option, +} + +#[derive(clap::Args, Debug)] +pub struct Assemble { + /// The name of a Python module containing the app to wrap. + pub app_name: String, + + /// Directory containing prepared assets. + #[arg(long)] + pub prepared: PathBuf, + + /// Fail unless the prepared assets have this identity. + #[arg(long)] + pub expect_identity: Option, + + /// Specify a directory containing the app and/or its dependencies, as + /// `[NAME=]DIRECTORY`. May be specified more than once. + /// + /// The directory is visible at `/NAME` during pre-initialization, and the + /// library names of native extensions under it start with `/NAME`. NAME + /// defaults to the position of the option, starting at 0. + #[arg(short = 'p', long, default_value = ".")] + pub python_path: Vec, + + /// Output file to which to write the resulting component + #[arg(short = 'o', long, default_value = "index.wasm")] + pub output: PathBuf, + + /// Size in bytes of the linear-memory stack used by C code. See + /// `componentize --stack-size`. + #[arg(long)] + pub stack_size: Option, } #[derive(clap::Args, Debug)] @@ -256,7 +316,103 @@ pub fn run + Clone, I: IntoIterator>(args: I) -> Res match command { Command::Componentize(opts) => componentize(common, opts), Command::Bindings(opts) => generate_bindings(common, opts), + Command::Prepare(opts) => prepare(common, opts), + Command::Assemble(opts) => assemble(common, opts), + } +} + +fn prepare(common: Common, prepare: Prepare) -> Result<()> { + let prepared = Runtime::new()?.block_on( + BindingsPreparer { + wit_paths: &common + .wit_path + .iter() + .map(|v| v.as_path()) + .collect::>(), + worlds: &common.world.iter().map(|v| v.as_str()).collect::>(), + features: &common + .features + .iter() + .map(|v| v.as_str()) + .collect::>(), + all_features: common.all_features, + bindings_module: common.bindings_module.as_deref(), + import_interface_names: &common + .import_interface_name + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect(), + export_interface_names: &common + .export_interface_name + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect(), + intersect_world: prepare.intersect_world.as_deref(), + registry_config: common.registry_config.as_deref(), + default_registries: !common.no_default_registries, + } + .prepare(), + )?; + prepared.write(&prepare.output_dir)?; + println!("{}", prepared.identity()); + Ok(()) +} + +fn assemble(common: Common, assemble: Assemble) -> Result<()> { + if !common.wit_path.is_empty() + || !common.world.is_empty() + || !common.features.is_empty() + || common.all_features + || !common.import_interface_name.is_empty() + || !common.export_interface_name.is_empty() + || common.bindings_module.is_some() + { + bail!("`assemble` takes the WIT world from the prepared assets; remove the WIT options"); + } + + let prepared = Prepared::read(&assemble.prepared)?; + if let Some(expected) = &assemble.expect_identity + && prepared.identity() != *expected + { + bail!( + "prepared assets at {} have identity {}, not {expected}", + assemble.prepared.display(), + prepared.identity() + ); + } + + let python_path = assemble + .python_path + .iter() + .enumerate() + .map(|(index, entry)| match entry.split_once('=') { + Some((name, path)) => (name.to_owned(), PathBuf::from(path)), + None => (index.to_string(), PathBuf::from(entry)), + }) + .collect::>(); + + let assembly = Assembler { + prepared: &prepared, + app_name: &assemble.app_name, + python_path: &python_path + .iter() + .map(|(name, path)| (name.as_str(), path.as_path())) + .collect::>(), + stack_size: assemble.stack_size, + } + .assemble()?; + let component = Runtime::new()?.block_on(assembly.initialize_default())?; + + if let Some(parent) = assemble.output.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&assemble.output, component)?; + + if !common.quiet { + println!("Component built successfully"); } + + Ok(()) } fn generate_bindings(common: Common, bindings: Bindings) -> Result<()> { diff --git a/src/lib.rs b/src/lib.rs index 2cee563..acfb445 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,13 +1,15 @@ #![deny(warnings)] +// Without the embedded runtime the crate only reads and assembles prepared +// assets, so the code that prepares them is unused. +#![cfg_attr(not(feature = "embedded-runtime"), allow(dead_code, unused_imports))] use { anyhow::{Context, Error, Result, anyhow, bail, ensure}, async_trait::async_trait, bytes::Bytes, - component_init_transform::Invoker, futures::future::FutureExt, indexmap::{IndexMap, IndexSet}, - serde::Deserialize, + serde::{Deserialize, Serialize}, sha2::{Digest as _, Sha256}, std::{ borrow::Cow, @@ -19,36 +21,48 @@ use { path::{Path, PathBuf}, str, }, - summary::{Locations, Summary}, tar::Archive, - wasm_encoder::{CustomSection, Section as _}, wasmtime::{ Config, Engine, Store, component::{Component, Instance, Linker, ResourceTable, ResourceType}, }, - wasmtime_wasi::{ - Deterministic, FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, - p2::pipe::{MemoryInputPipe, MemoryOutputPipe}, - }, + zstd::Decoder, +}; + +#[cfg(feature = "embedded-runtime")] +use { + summary::{Locations, Summary}, + wasm_encoder::{CustomSection, Section as _}, wit_component::metadata, wit_dylib::DylibOpts, wit_parser::{ CloneMaps, FunctionKind, Package, PackageId, PackageName, Resolve, Stability, TypeDefKind, World, WorldId, WorldItem, WorldKey, }, - zstd::Decoder, }; +#[cfg(feature = "embedded-runtime")] +use wasmtime_wasi::{ + Deterministic, FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, + p2::pipe::{MemoryInputPipe, MemoryOutputPipe}, +}; + +#[cfg(feature = "embedded-runtime")] pub mod command; mod link; mod prelink; -#[cfg(feature = "pyo3")] +pub mod prepared; +#[cfg(all(feature = "pyo3", feature = "embedded-runtime"))] mod python; +#[cfg(feature = "embedded-runtime")] mod registry; +#[cfg(feature = "embedded-runtime")] mod stubwasi; +#[cfg(feature = "embedded-runtime")] mod summary; -#[cfg(test)] +#[cfg(all(test, feature = "embedded-runtime"))] mod test; +#[cfg(feature = "embedded-runtime")] mod util; const DEBUG_PYTHON_BINDINGS: bool = false; @@ -60,13 +74,18 @@ wasmtime::component::bindgen!({ path: "wit", world: "init", exports: { default: async }, + additional_derives: [serde::Serialize, serde::Deserialize], }); +pub use {component_init_transform::Invoker, exports::exports::Symbols}; + +#[cfg(feature = "embedded-runtime")] pub struct Ctx { wasi: WasiCtx, table: ResourceTable, } +#[cfg(feature = "embedded-runtime")] impl WasiView for Ctx { fn ctx(&mut self) -> WasiCtxView<'_> { WasiCtxView { @@ -80,15 +99,18 @@ impl WasiView for Ctx { /// advances one microsecond each time it is read, so nothing the application /// saves depends on when it was built, and code waiting for time to pass still /// finishes. +#[cfg(feature = "embedded-runtime")] #[derive(Default)] struct BuildClock(std::sync::atomic::AtomicU64); +#[cfg(feature = "embedded-runtime")] impl BuildClock { fn tick(&self) -> u64 { self.0.fetch_add(1000, std::sync::atomic::Ordering::Relaxed) } } +#[cfg(feature = "embedded-runtime")] impl wasmtime_wasi::HostWallClock for BuildClock { fn resolution(&self) -> std::time::Duration { std::time::Duration::from_micros(1) @@ -99,6 +121,7 @@ impl wasmtime_wasi::HostWallClock for BuildClock { } } +#[cfg(feature = "embedded-runtime")] impl wasmtime_wasi::HostMonotonicClock for BuildClock { fn resolution(&self) -> u64 { 1000 @@ -119,9 +142,13 @@ fn set_build_mtimes(path: &Path) -> Result<()> { } // `FileTime::zero` is the platform epoch, which Windows cannot set. let epoch = filetime::FileTime::from_unix_time(0, 0); + // Newer `filetime` releases deprecate this in favor of `std::fs::set_times`, + // which does not set the times of directories on every platform. + #[allow(deprecated)] filetime::set_file_times(path, epoch, epoch).with_context(|| path.display().to_string()) } +#[derive(Clone)] pub struct Library { name: String, module: Vec, @@ -179,13 +206,13 @@ pub struct ConfigContext { config: T, } -struct MyInvoker { - store: Store, +struct MyInvoker { + store: Store, instance: Instance, } #[async_trait] -impl Invoker for MyInvoker { +impl Invoker for MyInvoker { async fn call_s32(&mut self, function: &str) -> Result { let func = self .instance @@ -222,6 +249,7 @@ impl Invoker for MyInvoker { } } +#[cfg(feature = "embedded-runtime")] pub struct BindingsGenerator<'a> { pub wit_paths: &'a [&'a Path], pub worlds: &'a [&'a str], @@ -237,6 +265,7 @@ pub struct BindingsGenerator<'a> { pub allow_existing: bool, } +#[cfg(feature = "embedded-runtime")] impl BindingsGenerator<'_> { pub async fn generate(&self) -> Result<()> { // Here we parse the specified WIT paths and resolve the specified @@ -364,6 +393,7 @@ pub(crate) fn warn_full_names_deprecated(full_names: Option, source: Optio } } +#[cfg(feature = "embedded-runtime")] /// Resolve the deprecated `world_module` spelling of `bindings_module`, warning /// about it and about `full_names`. pub(crate) fn resolve_deprecated( @@ -386,6 +416,7 @@ pub(crate) fn resolve_deprecated( Ok(bindings_module.or(world_module)) } +#[cfg(feature = "embedded-runtime")] /// Reject `--bindings-module` values which are not importable Python paths. fn validate_bindings_module(module: &str) -> Result<()> { if module @@ -398,6 +429,7 @@ fn validate_bindings_module(module: &str) -> Result<()> { } } +#[cfg(feature = "embedded-runtime")] /// Make each ancestor of a dotted bindings module a regular package. fn create_module_ancestors(root: &Path, module: &str) -> Result<()> { let components = module.split('.').collect::>(); @@ -414,6 +446,7 @@ fn create_module_ancestors(root: &Path, module: &str) -> Result<()> { Ok(()) } +#[cfg(feature = "embedded-runtime")] /// Replace each helper placeholder with the module path generated for it; an /// unimported interface has no entry and keeps its placeholder. fn resolve_helper_placeholders(path: &Path, replacements: &[(&str, String)]) -> Result<()> { @@ -443,8 +476,10 @@ fn resolve_helper_placeholders(path: &Path, replacements: &[(&str, String)]) -> Ok(()) } +#[cfg(feature = "embedded-runtime")] pub type AddToLinker<'a> = Option<&'a dyn Fn(&mut Linker) -> Result<()>>; +#[cfg(feature = "embedded-runtime")] pub struct ComponentGenerator<'a> { pub wit_paths: &'a [&'a Path], pub worlds: &'a [&'a str], @@ -467,8 +502,92 @@ pub struct ComponentGenerator<'a> { pub default_registries: bool, } +#[cfg(feature = "embedded-runtime")] impl ComponentGenerator<'_> { pub async fn generate(&self) -> Result<()> { + let bound = self.bind().await?; + + let component = link::link_libraries( + &bound.libraries, + &prelink::embedded_adapter()?, + self.stack_size, + )?; + + let stubbed_component = if self.stub_wasi { + stubwasi::link_stub_modules(bound.libraries)? + } else { + None + }; + + let mut preopens = vec![ + Preopen::new(bound.standard_library.path(), "python"), + Preopen::new(bound.helper_utils.path(), "bundled"), + ]; + let mut python_path = Vec::new(); + for (index, path) in bound.python_path.iter().enumerate() { + preopens.push(Preopen::new(Path::new(path), &index.to_string())); + python_path.push(format!("/{index}")); + } + for (mounts, world_dir) in &bound.world_dir_mounts { + for mount in mounts { + if DEBUG_PYTHON_BINDINGS { + eprintln!( + "world dir path: {}; mount: {mount}", + world_dir.path().display() + ); + } + preopens.push(Preopen::new(world_dir.path(), mount)); + } + } + + let plan = InitPlan::new( + self.app_name, + bound.symbols, + bound.stubs, + self.stub_wasi, + preopens, + &python_path, + BuildEntropy::for_inputs( + &component, + self.app_name, + &bound.python_path.iter().map(Path::new).collect::>(), + )?, + ); + + let component = initialize( + &component, + stubbed_component + .as_ref() + .map(|(component, map)| (component.deref(), map as &dyn Fn(u32) -> u32)), + &plan, + &default_engine()?, + self.add_to_linker, + ) + .await?; + + if DEBUG_PYTHON_BINDINGS { + // Prevent temporary directories from being deleted: + std::mem::forget(bound.world_dir_mounts); + } + + // Checks if the output directory exists, and creates it if it doesn't. + if let Some(parent) = self.output_path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(self.output_path, component)?; + + Ok(()) + } + + /// Resolves the WIT inputs, generates the Wasm and Python bindings, and + /// collects the libraries to link, without linking or initializing. + async fn bind(&self) -> Result { + ensure!( + cfg!(feature = "embedded-runtime"), + "componentize-py was built without the `embedded-runtime` feature, so it can \ + only assemble prepared assets" + ); + // This is a _big_ function. Here's an overview of what it does. // // Our goal here is to collect one or more WIT paths, parse them, and @@ -866,70 +985,6 @@ impl ComponentGenerator<'_> { dl_openable: false, }); - let component = link::link_libraries(&libraries, self.stack_size)?; - - let stubbed_component = if self.stub_wasi { - stubwasi::link_stub_modules(libraries)? - } else { - None - }; - - // Pre-initialize the component by running it through - // `component_init_transform::initialize`. Currently, this is the - // application's first and only chance to load any standard or third-party - // modules since we do not yet include a virtual filesystem in the component - // to make those modules available at runtime. - - let stdout = MemoryOutputPipe::new(10000); - let stderr = MemoryOutputPipe::new(10000); - - // Pre-initialization saves everything the application computes into - // the component, so derive its hash seed and random bytes from the - // linked component and the application's sources instead of from host - // entropy. Identical inputs then produce identical components, and - // applications that share the same libraries still get different - // values. The runtime reseeds `random` from the host before the first - // export call. - let digest = build_digest(&component, self.app_name, python_path)?; - let random_bytes = (0u32..1024) - .flat_map(|counter| { - Sha256::new() - .chain_update(digest) - .chain_update(counter.to_le_bytes()) - .finalize() - }) - .collect::>(); - - let mut wasi = WasiCtxBuilder::new(); - wasi.secure_random(Deterministic::new(random_bytes.clone())) - .insecure_random(Deterministic::new(random_bytes)) - .insecure_random_seed(u128::from_le_bytes(digest[..16].try_into().unwrap())) - .env( - "PYTHONHASHSEED", - u32::from_le_bytes(digest[..4].try_into().unwrap()).to_string(), - ) - .wall_clock(BuildClock::default()) - .monotonic_clock(BuildClock::default()) - // Writing bytecode would change the source directories during the - // build and record the time of the write. - .env("PYTHONDONTWRITEBYTECODE", "1"); - wasi.stdin(MemoryInputPipe::new(Bytes::new())) - .stdout(stdout.clone()) - .stderr(stderr.clone()) - .env("PYTHONUNBUFFERED", "1") - .env("PYTHONHOME", "/python") - .preopened_dir( - embedded_python_standard_lib.path(), - "python", - FsPerms::ReadWrite, - )? - .preopened_dir(embedded_helper_utils.path(), "bundled", FsPerms::ReadWrite)?; - - // Generate guest mounts for each host directory in `python_path`. - for (index, path) in python_path.iter().enumerate() { - wasi.preopened_dir(path, index.to_string(), FsPerms::ReadWrite)?; - } - // For each Python module with a `componentize-py.toml` file that // specifies where generated bindings for that package should be placed, // generate the bindings and place them as indicated. @@ -1001,18 +1056,6 @@ impl ComponentGenerator<'_> { &summary.helper_module_paths(&locations), )?; - for (mounts, world_dir) in world_dir_mounts.iter() { - for mount in mounts { - if DEBUG_PYTHON_BINDINGS { - eprintln!( - "world dir path: {}; mount: {mount}", - world_dir.path().display() - ); - } - wasi.preopened_dir(world_dir.path(), mount, FsPerms::ReadWrite)?; - } - } - // The guest's import system records directory modification times, so // give the directories created for this build a fixed time. for dir in [ @@ -1025,77 +1068,333 @@ impl ComponentGenerator<'_> { set_build_mtimes(dir)?; } - if DEBUG_PYTHON_BINDINGS { - // Prevent temporary directories from being deleted: - std::mem::forget(world_dir_mounts); - } - // Generate a `Symbols` object containing metadata to be passed to the // pre-init function. The runtime library will use this to look up types // and functions that will later be referenced by the generated Wasm code. let symbols = summary.collect_symbols(&locations, &metadata, &clone_maps); - // Finally, pre-initialize the component, writing the result to - // `self.output_path`. + Ok(Bound { + python_path: python_path.iter().map(|&path| path.to_owned()).collect(), + standard_library: embedded_python_standard_lib, + helper_utils: embedded_helper_utils, + world_dir_mounts, + libraries, + symbols, + stubs: import_stubs(&resolve, &all_worlds), + }) + } +} - let python_path = (0..python_path.len()) - .map(|index| format!("/{index}")) - .collect::>() - .join(":"); +#[cfg(feature = "embedded-runtime")] +/// The owned result of processing the WIT inputs for one build. +struct Bound { + python_path: Vec, + standard_library: tempfile::TempDir, + helper_utils: tempfile::TempDir, + world_dir_mounts: Vec<(Vec, tempfile::TempDir)>, + libraries: Vec, + symbols: Symbols, + stubs: Vec, +} - let table = ResourceTable::new(); - let wasi = wasi - .env( - "PYTHONPATH", - format!("/python:/world:{python_path}:/bundled"), - ) - .build(); +/// An import of the target world that pre-initialization satisfies with a +/// trapping stub. Imports of WASIp2 CLI interfaces are not stubbed; the +/// initializer supplies them. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ImportStub { + /// The interface name, or `None` for a world-level import. + pub interface: Option, + pub name: String, + pub kind: ImportStubKind, +} - let mut config = Config::new(); - config.wasm_component_model(true); - config.wasm_component_model_async(true); - config.wasm_component_model_map(true); +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ImportStubKind { + Function { is_async: bool }, + Resource, +} - let engine = Engine::new(&config)?; +#[cfg(feature = "embedded-runtime")] +fn import_stubs(resolve: &Resolve, worlds: &IndexSet) -> Vec { + let function = |interface: Option<&String>, name: &String, kind: &FunctionKind| ImportStub { + interface: interface.cloned(), + name: name.clone(), + kind: ImportStubKind::Function { + is_async: kind.is_async(), + }, + }; + let resource = |interface: Option<&String>, name: &str| ImportStub { + interface: interface.cloned(), + name: name.to_owned(), + kind: ImportStubKind::Resource, + }; - let mut linker = Linker::new(&engine); - let added_to_linker = if let Some(add_to_linker) = self.add_to_linker { - add_to_linker(&mut linker)?; - true - } else { - false - }; + let mut stubs = Vec::new(); + for &world in worlds { + for (key, item) in &resolve.worlds[world].imports { + match item { + WorldItem::Interface { id, .. } => { + let interface_name = match key { + WorldKey::Name(name) => name.clone(), + WorldKey::Interface(interface) => resolve.id_of(*interface).unwrap(), + }; + if is_wasip2_cli(&interface_name) { + continue; + } - let mut store = Store::new(&engine, Ctx { wasi, table }); + let interface = &resolve.interfaces[*id]; + for (function_name, f) in &interface.functions { + stubs.push(function(Some(&interface_name), function_name, &f.kind)); + } - let stub_wasi = self.stub_wasi; - let app_name = self.app_name.to_owned(); - let component = component_init_transform::initialize_staged( - &component, - stubbed_component - .as_ref() - .map(|(component, map)| (component.deref(), map as &dyn Fn(u32) -> u32)), - move |instrumented| { - async move { - let component = &Component::new(&engine, instrumented)?; - if !added_to_linker { - add_wasi_and_stubs(&resolve, &all_worlds, &mut linker)?; + for (type_name, id) in interface.types.iter() { + if let TypeDefKind::Resource = &resolve.types[*id].kind { + stubs.push(resource(Some(&interface_name), type_name)); + } } + } + WorldItem::Function(f) => stubs.push(function(None, &f.name, &f.kind)), + WorldItem::Type { id, .. } => { + let ty = &resolve.types[*id]; + if let TypeDefKind::Resource = &ty.kind { + stubs.push(resource(None, ty.name.as_ref().unwrap())); + } + } + } + } + } + stubs +} + +/// A host directory that pre-initialization makes visible to the guest. +#[derive(Clone, Debug)] +pub struct Preopen { + pub host: PathBuf, + /// The guest path, without a leading `/`. + pub guest: String, +} - let pre = InitPre::new(linker.instantiate_pre(component)?)?; - let instance = pre.instance_pre.instantiate_async(&mut store).await?; - let guest = pre.indices.interface0.load(&mut store, &instance)?; +impl Preopen { + fn new(host: &Path, guest: &str) -> Self { + Self { + host: host.to_owned(), + guest: guest.to_owned(), + } + } +} + +/// Entropy for pre-initialization, derived from the build inputs so that +/// identical inputs produce identical output. +/// +/// Pre-initialization saves everything the application computes into the +/// component, so it must not read host entropy. The runtime reseeds `random` +/// from the host before the first export call. +#[derive(Clone, Debug)] +pub struct BuildEntropy { + /// The value of `PYTHONHASHSEED`. + pub hash_seed: u32, + /// The bytes that `wasi:random` returns, in order, for both the secure and + /// insecure sources. + pub random_bytes: Vec, + /// The value of `wasi:random/insecure-seed`. + pub insecure_seed: u128, +} + +impl BuildEntropy { + /// Derives the entropy from the linked component, the application name + /// and the files of the application's Python path entries, so that + /// applications built from the same prepared assets get different values. + pub fn for_inputs( + component: &[u8], + app_name: &str, + python_path: &[impl AsRef], + ) -> Result { + let digest = build_digest(component, app_name, python_path)?; + Ok(Self { + hash_seed: u32::from_le_bytes(digest[..4].try_into().unwrap()), + random_bytes: (0u32..1024) + .flat_map(|counter| { + Sha256::new() + .chain_update(digest) + .chain_update(counter.to_le_bytes()) + .finalize() + }) + .collect(), + insecure_seed: u128::from_le_bytes(digest[..16].try_into().unwrap()), + }) + } +} + +/// Everything an initializer needs to pre-initialize a linked component. +/// +/// An initializer instantiates the instrumented component with WASIp2, these +/// environment variables and preopens, the entropy in `entropy`, wall and +/// monotonic clocks that start at zero and advance one microsecond per read, +/// an empty stdin, and a trapping stub for each entry of `stubs`. It then +/// calls `componentize-py:init/exports#init` with `app_name`, `symbols` and +/// `stub_wasi`. +#[derive(Clone, Debug)] +pub struct InitPlan { + pub app_name: String, + pub symbols: Symbols, + pub stubs: Vec, + pub stub_wasi: bool, + pub env: Vec<(String, String)>, + pub preopens: Vec, + pub entropy: BuildEntropy, +} + +/// The WIT world of the runtime's initialization export. +const INIT_WIT: &str = include_str!("../wit/init.wit"); + +impl InitPlan { + fn new( + app_name: &str, + symbols: Symbols, + stubs: Vec, + stub_wasi: bool, + preopens: Vec, + python_path: &[String], + entropy: BuildEntropy, + ) -> Self { + let python_path = iter::once("/python") + .chain(iter::once("/world")) + .chain(python_path.iter().map(String::as_str)) + .chain(iter::once("/bundled")) + .collect::>() + .join(":"); + let env = [ + ("PYTHONHASHSEED", entropy.hash_seed.to_string()), + // Writing bytecode would change the source directories during the + // build and record the time of the write. + ("PYTHONDONTWRITEBYTECODE", "1".to_owned()), + ("PYTHONUNBUFFERED", "1".to_owned()), + ("PYTHONHOME", "/python".to_owned()), + ("PYTHONPATH", python_path), + ] + .into_iter() + .map(|(key, value)| (key.to_owned(), value)) + .collect(); + + Self { + app_name: app_name.to_owned(), + symbols, + stubs, + stub_wasi, + env, + preopens, + entropy, + } + } +} - guest - .call_init(&mut store, &app_name, &symbols, stub_wasi) - .await? - .map_err(|e| anyhow!("{e}"))?; +/// Adds a trapping stub to `linker` for each import in `stubs`. +/// +/// An initializer adds WASIp2 first, then these stubs. +pub fn add_trapping_stubs(linker: &mut Linker, stubs: &[ImportStub]) -> Result<()> { + let mut by_interface = IndexMap::<_, Vec<_>>::new(); + for stub in stubs { + by_interface + .entry(stub.interface.as_deref()) + .or_default() + .push(stub); + } - Ok(Box::new(MyInvoker { store, instance }) as Box) + for (interface_name, stubs) in by_interface { + let mut instance = if let Some(interface_name) = interface_name { + match linker.instance(interface_name) { + Ok(instance) => instance, + Err(_) => continue, + } + } else { + linker.root() + }; + let qualified = |name: &str| match interface_name { + Some(interface_name) => format!("{interface_name}#{name}"), + None => name.to_owned(), + }; + for stub in stubs { + let message = format!("called trapping stub: {}", qualified(&stub.name)); + match stub.kind { + ImportStubKind::Function { is_async: true } => { + instance.func_new_concurrent(&stub.name, move |_, _, _, _| { + let message = message.clone(); + Box::pin(async move { Err(wasmtime::format_err!("{message}")) }) + }) } - .boxed() - }, - ) + ImportStubKind::Function { is_async: false } => instance + .func_new(&stub.name, move |_, _, _, _| { + Err(wasmtime::format_err!("{message}")) + }), + ImportStubKind::Resource => instance + .resource(&stub.name, ResourceType::host::<()>(), move |_, _| { + Err(wasmtime::format_err!("{message}")) + }) + .map(drop), + }?; + } + } + + Ok(()) +} + +/// The engine that `componentize` and `assemble` use. +pub fn default_engine() -> Result { + let mut config = Config::new(); + config.wasm_component_model(true); + config.wasm_component_model_async(true); + config.wasm_component_model_map(true); + Ok(Engine::new(&config)?) +} + +/// Pre-initializes `component` according to `plan`, with this crate's WASI +/// implementation on `engine`. +#[cfg(feature = "embedded-runtime")] +async fn initialize( + component: &[u8], + stubbed_component: component_init_transform::Stage2Map<'_>, + plan: &InitPlan, + engine: &Engine, + add_to_linker: AddToLinker<'_>, +) -> Result> { + let stdout = MemoryOutputPipe::new(10000); + let stderr = MemoryOutputPipe::new(10000); + + let mut wasi = WasiCtxBuilder::new(); + wasi.secure_random(Deterministic::new(plan.entropy.random_bytes.clone())) + .insecure_random(Deterministic::new(plan.entropy.random_bytes.clone())) + .insecure_random_seed(plan.entropy.insecure_seed) + .wall_clock(BuildClock::default()) + .monotonic_clock(BuildClock::default()) + .stdin(MemoryInputPipe::new(Bytes::new())) + .stdout(stdout.clone()) + .stderr(stderr.clone()); + for (key, value) in &plan.env { + wasi.env(key, value); + } + for preopen in &plan.preopens { + wasi.preopened_dir(&preopen.host, &preopen.guest, FsPerms::ReadWrite)?; + } + let wasi = wasi.build(); + + let mut linker = Linker::new(engine); + if let Some(add_to_linker) = add_to_linker { + add_to_linker(&mut linker)?; + } else { + wasmtime_wasi::p2::add_to_linker_async(&mut linker)?; + add_trapping_stubs(&mut linker, &plan.stubs)?; + } + + let store = Store::new( + engine, + Ctx { + wasi, + table: ResourceTable::new(), + }, + ); + + initialize_component(component, stubbed_component, plan, store, linker) .await .with_context(move || { format!( @@ -1103,18 +1402,47 @@ impl ComponentGenerator<'_> { String::from_utf8_lossy(&stdout.try_into_inner().unwrap()), String::from_utf8_lossy(&stderr.try_into_inner().unwrap()) ) - })?; + }) +} - // Checks if the output directory exists, and creates it if it doesn't. - if let Some(parent) = self.output_path.parent() { - fs::create_dir_all(parent)?; +/// Pre-initializes `component` according to `plan` with the caller's store +/// and linker, and returns the initialized component. +/// +/// The store's engine must enable the component model and its async support. +/// The store must provide the WASI context that `plan` describes, and the +/// linker must provide WASIp2 and the plan's stubs; see [`InitPlan`] and +/// [`add_trapping_stubs`]. +pub async fn initialize_component( + component: &[u8], + stubbed_component: component_init_transform::Stage2Map<'_>, + plan: &InitPlan, + mut store: Store, + linker: Linker, +) -> Result> { + let app_name = plan.app_name.clone(); + let symbols = plan.symbols.clone(); + let stub_wasi = plan.stub_wasi; + component_init_transform::initialize_staged(component, stubbed_component, move |instrumented| { + async move { + let engine = store.engine().clone(); + let component = &Component::new(&engine, instrumented)?; + let pre = InitPre::new(linker.instantiate_pre(component)?)?; + let instance = pre.instance_pre.instantiate_async(&mut store).await?; + let guest = pre.indices.interface0.load(&mut store, &instance)?; + + guest + .call_init(&mut store, &app_name, &symbols, stub_wasi) + .await? + .map_err(|e| anyhow!("{e}"))?; + + Ok(Box::new(MyInvoker { store, instance }) as Box) } - fs::write(self.output_path, component)?; - - Ok(()) - } + .boxed() + }) + .await } +#[cfg(feature = "embedded-runtime")] fn parse_features(features: &[&str]) -> IndexSet { features .iter() @@ -1128,6 +1456,7 @@ fn parse_features(features: &[&str]) -> IndexSet { .collect() } +#[cfg(feature = "embedded-runtime")] fn available_worlds(resolve: &Resolve) -> Vec { resolve .worlds @@ -1151,6 +1480,7 @@ fn available_worlds(resolve: &Resolve) -> Vec { .collect() } +#[cfg(feature = "embedded-runtime")] fn select_world( resolve: &Resolve, world: Option<&str>, @@ -1178,6 +1508,7 @@ fn select_world( }) } +#[cfg(feature = "embedded-runtime")] fn union_world( resolve: &mut Resolve, name: &str, @@ -1217,6 +1548,7 @@ fn union_world( Ok(union_world) } +#[cfg(feature = "embedded-runtime")] fn intersect_world(resolve: &mut Resolve, intersector: WorldId, world: WorldId) { let (imports_to_remove, exports_to_remove) = { let intersector = &resolve.worlds[intersector]; @@ -1258,152 +1590,7 @@ fn intersect_world(resolve: &mut Resolve, intersector: WorldId, world: WorldId) world.exports.retain(|k, _| !exports_to_remove.contains(k)); } -fn add_wasi_and_stubs( - resolve: &Resolve, - worlds: &IndexSet, - linker: &mut Linker, -) -> Result<()> { - wasmtime_wasi::p2::add_to_linker_async(linker)?; - - enum Stub<'a> { - Function(&'a String, &'a FunctionKind), - Resource(&'a String), - } - - let mut stubs = HashMap::<_, Vec<_>>::new(); - for &world in worlds { - for (key, item) in &resolve.worlds[world].imports { - match item { - WorldItem::Interface { id, .. } => { - let interface_name = match key { - WorldKey::Name(name) => name.clone(), - WorldKey::Interface(interface) => resolve.id_of(*interface).unwrap(), - }; - - let interface = &resolve.interfaces[*id]; - for (function_name, function) in &interface.functions { - stubs - .entry(Some(interface_name.clone())) - .or_default() - .push(Stub::Function(function_name, &function.kind)); - } - - for (type_name, id) in interface.types.iter() { - if let TypeDefKind::Resource = &resolve.types[*id].kind { - stubs - .entry(Some(interface_name.clone())) - .or_default() - .push(Stub::Resource(type_name)); - } - } - } - WorldItem::Function(function) => { - stubs - .entry(None) - .or_default() - .push(Stub::Function(&function.name, &function.kind)); - } - WorldItem::Type { id, .. } => { - let ty = &resolve.types[*id]; - if let TypeDefKind::Resource = &ty.kind { - stubs - .entry(None) - .or_default() - .push(Stub::Resource(ty.name.as_ref().unwrap())); - } - } - } - } - } - - for (interface_name, stubs) in stubs { - if let Some(interface_name) = interface_name { - // Note that we do _not_ stub interfaces which appear to be part of - // WASIp2 since those should be provided by the - // `wasmtime_wasi::add_to_linker_async` call above, and adding stubs - // to those same interfaces would just cause trouble. - if !is_wasip2_cli(&interface_name) - && let Ok(mut instance) = linker.instance(&interface_name) - { - for stub in stubs { - let interface_name = interface_name.clone(); - match stub { - Stub::Function(name, kind) => { - if kind.is_async() { - instance.func_new_concurrent(name, { - let name = name.clone(); - move |_, _, _, _| { - let interface_name = interface_name.clone(); - let name = name.clone(); - Box::pin(async move { - Err(wasmtime::format_err!( - "called trapping stub: {interface_name}#{name}" - )) - }) - } - }) - } else { - instance.func_new(name, { - let name = name.clone(); - move |_, _, _, _| { - Err(wasmtime::format_err!( - "called trapping stub: {interface_name}#{name}" - )) - } - }) - } - } - Stub::Resource(name) => instance - .resource(name, ResourceType::host::<()>(), { - let name = name.clone(); - move |_, _| { - Err(wasmtime::format_err!( - "called trapping stub: {interface_name}#{name}" - )) - } - }) - .map(drop), - }?; - } - } - } else { - let mut instance = linker.root(); - for stub in stubs { - match stub { - Stub::Function(name, kind) => { - if kind.is_async() { - instance.func_new_concurrent(name, { - let name = name.clone(); - move |_, _, _, _| { - let name = name.clone(); - Box::pin(async move { - Err(wasmtime::format_err!("called trapping stub: {name}")) - }) - } - }) - } else { - instance.func_new(name, { - let name = name.clone(); - move |_, _, _, _| { - Err(wasmtime::format_err!("called trapping stub: {name}")) - } - }) - } - } - Stub::Resource(name) => instance - .resource(name, ResourceType::host::<()>(), { - let name = name.clone(); - move |_, _| Err(wasmtime::format_err!("called trapping stub: {name}")) - }) - .map(drop), - }?; - } - } - } - - Ok(()) -} - +#[cfg(feature = "embedded-runtime")] fn is_wasip2_cli(interface_name: &str) -> bool { (interface_name.starts_with("wasi:cli/") || interface_name.starts_with("wasi:clocks/") @@ -1418,7 +1605,11 @@ fn is_wasip2_cli(interface_name: &str) -> bool { /// relative path and content of every file in each Python path entry, in /// sorted order. A symbolic link counts as its target path, not as the content /// it points to. -fn build_digest(component: &[u8], app_name: &str, python_path: &[&str]) -> Result<[u8; 32]> { +fn build_digest( + component: &[u8], + app_name: &str, + python_path: &[impl AsRef], +) -> Result<[u8; 32]> { fn update_tree(hasher: &mut Sha256, root: &Path, path: &Path) -> Result<()> { let relative = path .strip_prefix(root)? @@ -1455,7 +1646,7 @@ fn build_digest(component: &[u8], app_name: &str, python_path: &[&str]) -> Resul hasher.update([0]); for (index, entry) in python_path.iter().enumerate() { hasher.update((index as u64).to_le_bytes()); - let root = fs::canonicalize(entry)?; + let root = fs::canonicalize(entry.as_ref())?; update_tree(&mut hasher, &root, &root)?; } Ok(hasher.finalize().into()) diff --git a/src/link.rs b/src/link.rs index da7ae43..486c76a 100644 --- a/src/link.rs +++ b/src/link.rs @@ -1,10 +1,12 @@ -use std::io::Cursor; - use anyhow::Result; use crate::Library; -pub fn link_libraries(libraries: &[Library], stack_size: Option) -> Result> { +pub fn link_libraries( + libraries: &[Library], + adapter: &[u8], + stack_size: Option, +) -> Result> { let mut linker = wit_component::Linker::default(); linker.use_built_in_libdl(true).encoder().validate(true); if let Some(stack_size) = stack_size { @@ -20,13 +22,9 @@ pub fn link_libraries(libraries: &[Library], stack_size: Option) -> Result< linker.library(name, module, *dl_openable)?; } - linker.encoder().adapter( - "wasi_snapshot_preview1", - &zstd::decode_all(Cursor::new(include_bytes!(concat!( - env!("OUT_DIR"), - "/wasi_snapshot_preview1.reactor.wasm.zst" - ))))?, - )?; + linker + .encoder() + .adapter("wasi_snapshot_preview1", adapter)?; linker.encode().map_err(|e| anyhow::anyhow!(e)) } diff --git a/src/prelink.rs b/src/prelink.rs index d02b815..66541b0 100644 --- a/src/prelink.rs +++ b/src/prelink.rs @@ -33,10 +33,9 @@ pub fn embedded_python_standard_library() -> Result { // directory let stdlib = tempfile::tempdir()?; - Archive::new(Decoder::new(Cursor::new(include_bytes!(concat!( - env!("OUT_DIR"), - "/python-lib.tar.zst" - ))))?) + Archive::new(Decoder::new(Cursor::new( + embedded_python_standard_library_archive(), + ))?) .unpack(stdlib.path()) .unwrap(); @@ -57,11 +56,22 @@ pub fn embedded_helper_utils() -> Result { Ok(bundled) } +pub fn embedded_python_standard_library_archive() -> &'static [u8] { + include_bytes!(concat!(env!("OUT_DIR"), "/python-lib.tar.zst")) +} + +pub fn embedded_adapter() -> Result> { + Ok(zstd::decode_all(Cursor::new(include_bytes!(concat!( + env!("OUT_DIR"), + "/wasi_snapshot_preview1.reactor.wasm.zst" + ))))?) +} + /// Support libraries from the WASI SDK that extensions may depend on. Each is /// linked only when a linked library names it in its `dylink.0` needed list. -fn toolchain_support_libraries() -> Result)>> { +pub fn toolchain_support_libraries() -> Result)>> { Ok(vec![( - "libsetjmp.so", + "libsetjmp.so".to_owned(), zstd::decode_all(Cursor::new(include_bytes!(concat!( env!("OUT_DIR"), "/libsetjmp.so.zst" @@ -95,7 +105,11 @@ fn needed_libraries(module: &[u8]) -> Result> { /// `dlopen`. Support libraries that nothing needs are not linked, so they do /// not change the component. A needed name that remains unresolved is reported /// by the linker as a missing library. -fn add_support_libraries(libraries: &mut Vec, support: &[PathBuf]) -> Result<()> { +pub fn add_support_libraries( + libraries: &mut Vec, + support: &[PathBuf], + toolchain: &[(String, Vec)], +) -> Result<()> { let mut candidates: IndexMap)>> = IndexMap::new(); for path in support { let name = path @@ -109,8 +123,6 @@ fn add_support_libraries(libraries: &mut Vec, support: &[PathBuf]) -> R .or_default() .push((path.display().to_string(), module)); } - let toolchain = toolchain_support_libraries()?; - let mut index = 0; while index < libraries.len() { for needed in needed_libraries(&libraries[index].module)? { @@ -249,7 +261,7 @@ pub fn bundle_libraries( } } - add_support_libraries(&mut libraries, support)?; + add_support_libraries(&mut libraries, support, &toolchain_support_libraries()?)?; Ok(libraries) } @@ -333,15 +345,15 @@ fn search_directory( modules_seen: &mut HashSet, ) -> Result<()> { if path.is_dir() { - for entry in fs::read_dir(path).with_context(|| path.display().to_string())? { - search_directory( - root, - &entry?.path(), - libraries, - support, - configs, - modules_seen, - )?; + // Sort the entries so that the order of the libraries found, and so + // the linked component, does not depend on the file system. + let mut entries = fs::read_dir(path) + .with_context(|| path.display().to_string())? + .map(|entry| Ok(entry?.path())) + .collect::>>()?; + entries.sort(); + for entry in entries { + search_directory(root, &entry, libraries, support, configs, modules_seen)?; } } else if let Some(name) = path.file_name().and_then(|name| name.to_str()) { if NATIVE_EXTENSION_SUFFIXES @@ -425,3 +437,52 @@ fn module_name(root: &Path, path: &Path) -> Option { None } } + +/// Finds the native extensions and support libraries in an application's +/// Python path, for assembly with prepared bindings. +/// +/// Each entry is mounted at `/{name}`, so the library name of an extension is +/// `/{name}/{path relative to the entry}`. The names, and the order of the +/// returned libraries, do not depend on the order of the entries. A +/// `componentize-py.toml` file is an error, because it changes the WIT +/// bindings, which prepared bindings fix. +pub fn application_libraries( + python_path: &[(&str, &Path)], +) -> Result<(Vec, Vec)> { + let mut libraries = Vec::new(); + let mut support = Vec::new(); + for &(name, root) in python_path { + let mut found = Vec::new(); + let mut configs = Vec::new(); + search_directory( + root, + root, + &mut found, + &mut support, + &mut configs, + &mut HashSet::new(), + )?; + if let Some(config) = configs.first() { + bail!( + "{} configures WIT bindings, but prepared bindings cannot change; \ + prepare bindings that include this WIT instead", + config.path.join("componentize-py.toml").display() + ); + } + for library in found { + let path = library + .strip_prefix(root)? + .to_str() + .context("non-UTF-8 path")? + .replace('\\', "/"); + libraries.push(Library { + name: format!("/{name}/{path}"), + module: fs::read(&library).with_context(|| library.display().to_string())?, + dl_openable: true, + }); + } + } + libraries.sort_by(|a, b| a.name.cmp(&b.name)); + support.sort(); + Ok((libraries, support)) +} diff --git a/src/prepared.rs b/src/prepared.rs new file mode 100644 index 0000000..5353ad6 --- /dev/null +++ b/src/prepared.rs @@ -0,0 +1,549 @@ +//! Prepared bindings: the part of a build that depends only on the WIT world. +//! +//! [`BindingsPreparer`] resolves the WIT world once and produces [`Prepared`] +//! assets: the Wasm bindings module, the generated Python bindings, the +//! runtime libraries, the Python standard library, and the owned metadata that +//! initialization needs. [`Prepared::write`] persists them to a directory and +//! [`Prepared::read`] loads and verifies them in another process. +//! [`Assembler`] then links the prepared assets with an application and its +//! native extensions, without WIT processing or code generation, and +//! [`Assembly::initialize`] pre-initializes the result with the caller's store +//! and linker. +//! +//! Reading and assembling prepared assets does not need the `embedded-runtime` +//! feature; preparing them does. + +use { + crate::{ + BuildEntropy, ImportStub, InitPlan, Library, Preopen, Symbols, initialize_component, link, + prelink, set_build_mtimes, + }, + anyhow::{Context, Result, bail, ensure}, + serde::{Deserialize, Serialize}, + sha2::{Digest as _, Sha256}, + std::{ + collections::{BTreeMap, HashMap, HashSet}, + fs, + io::{Cursor, Read}, + path::{Path, PathBuf}, + }, + tar::{Archive, Builder, HeaderMode}, + tempfile::TempDir, + wasmtime::{Store, component::Linker}, + zstd::Decoder, +}; + +const FORMAT: u32 = 1; +const MANIFEST: &str = "manifest.json"; +const BLOBS: &str = "blobs"; + +/// Guest mount names that prepared assets use. Application mounts must not +/// use them. +const RESERVED_MOUNTS: &[&str] = &["python", "bundled", "world"]; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct Manifest { + format: u32, + /// The tool that prepared the assets. Recorded, not checked. + generator: String, + /// The SHA-256 of the initialization WIT that `symbols` conforms to. + init_wit: String, + adapter: String, + standard_library: String, + helper_utils: String, + world: Option, + libraries: Vec, + toolchain_support: Vec, + symbols: Symbols, + stubs: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct ManifestLibrary { + name: String, + dl_openable: bool, + blob: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct ManifestFile { + name: String, + blob: String, +} + +/// Prepared assets for one WIT world. +/// +/// Every file is a blob named by its SHA-256, and the manifest names the blobs +/// it uses. The identity of the assets is the SHA-256 of the manifest, so it +/// changes when any part of the assets changes. +pub struct Prepared { + manifest: Manifest, + blobs: BTreeMap>, +} + +fn digest(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// Line endings are normalized, because a checkout can convert them. +fn init_wit_digest() -> String { + digest(crate::INIT_WIT.replace("\r\n", "\n").as_bytes()) +} + +impl Prepared { + /// The SHA-256 of the manifest, in lowercase hexadecimal. + pub fn identity(&self) -> String { + digest(&self.manifest_bytes()) + } + + fn manifest_bytes(&self) -> Vec { + serde_json::to_vec_pretty(&self.manifest).unwrap() + } + + fn blob(&self, name: &str) -> &[u8] { + &self.blobs[name] + } + + fn add_blob(blobs: &mut BTreeMap>, bytes: Vec) -> String { + let name = digest(&bytes); + blobs.insert(name.clone(), bytes); + name + } + + /// Writes the assets to `dir`, which must not exist or must be empty. + pub fn write(&self, dir: &Path) -> Result<()> { + if dir.exists() { + ensure!( + fs::read_dir(dir)?.next().is_none(), + "{} is not empty", + dir.display() + ); + } + let blobs = dir.join(BLOBS); + fs::create_dir_all(&blobs)?; + for (name, bytes) in &self.blobs { + fs::write(blobs.join(name), bytes)?; + } + fs::write(dir.join(MANIFEST), self.manifest_bytes())?; + Ok(()) + } + + /// Reads assets that [`Prepared::write`] wrote, and verifies them. + /// + /// The directory must contain exactly the manifest and the blobs it names, + /// each blob must match its digest, the manifest must be in the form that + /// [`Prepared::write`] writes, and its format and initialization WIT must + /// be the ones this crate uses. + pub fn read(dir: &Path) -> Result { + let context = || format!("prepared assets at {}", dir.display()); + Self::read_inner(dir).with_context(context) + } + + fn read_inner(dir: &Path) -> Result { + for entry in fs::read_dir(dir)? { + let name = entry?.file_name(); + ensure!( + name == MANIFEST || name == BLOBS, + "unexpected entry `{}`", + name.to_string_lossy() + ); + } + + let bytes = fs::read(dir.join(MANIFEST)).context("cannot read the manifest")?; + let value = serde_json::from_slice::(&bytes) + .context("the manifest is not JSON")?; + let format = value.get("format").and_then(|format| format.as_u64()); + ensure!( + format == Some(u64::from(FORMAT)), + "the manifest has format {}, but this assembler reads format {FORMAT}", + format.map_or("unknown".to_owned(), |format| format.to_string()) + ); + let manifest = + serde_json::from_value::(value).context("the manifest is not valid")?; + ensure!( + manifest.init_wit == init_wit_digest(), + "the assets were prepared for initialization WIT {}, but this assembler uses {}; \ + prepare them again with this version", + manifest.init_wit, + init_wit_digest() + ); + + let referenced = manifest_blobs(&manifest); + let mut blobs = BTreeMap::new(); + for entry in fs::read_dir(dir.join(BLOBS))? { + let entry = entry?; + let name = entry.file_name().to_string_lossy().into_owned(); + ensure!( + referenced.contains(&name), + "blob `{name}` is not named by the manifest" + ); + let bytes = fs::read(entry.path())?; + ensure!( + digest(&bytes) == name, + "blob `{name}` does not match its digest" + ); + blobs.insert(name, bytes); + } + for name in &referenced { + ensure!(blobs.contains_key(name), "blob `{name}` is missing"); + } + + let prepared = Self { manifest, blobs }; + ensure!( + prepared.manifest_bytes() == bytes, + "the manifest is not in canonical form" + ); + Ok(prepared) + } +} + +fn manifest_blobs(manifest: &Manifest) -> HashSet { + [ + &manifest.adapter, + &manifest.standard_library, + &manifest.helper_utils, + ] + .into_iter() + .chain(&manifest.world) + .chain(manifest.libraries.iter().map(|library| &library.blob)) + .chain(manifest.toolchain_support.iter().map(|file| &file.blob)) + .cloned() + .collect() +} + +/// Packs a directory into a tar archive whose bytes depend only on the names +/// and contents of its files. +fn pack(dir: &Path) -> Result> { + fn walk(root: &Path, path: &Path, paths: &mut Vec) -> Result<()> { + for entry in fs::read_dir(path)? { + let path = entry?.path(); + paths.push(path.strip_prefix(root)?.to_owned()); + if path.is_dir() { + walk(root, &path, paths)?; + } + } + Ok(()) + } + + let mut paths = Vec::new(); + walk(dir, dir, &mut paths)?; + paths.sort(); + + let mut builder = Builder::new(Vec::new()); + builder.mode(HeaderMode::Deterministic); + builder.follow_symlinks(false); + for path in paths { + builder.append_path_with_name(dir.join(&path), &path)?; + } + Ok(builder.into_inner()?) +} + +fn unpack(archive: &[u8], compressed: bool) -> Result { + let dir = tempfile::tempdir()?; + if compressed { + unpack_entries( + Archive::new(Decoder::new(Cursor::new(archive))?), + dir.path(), + )?; + } else { + unpack_entries(Archive::new(Cursor::new(archive)), dir.path())?; + } + set_build_mtimes(dir.path())?; + Ok(dir) +} + +/// Unpacks only regular files and directories. Preparation writes no other +/// entries, and a link could point the build-time updates outside `dir`. +fn unpack_entries(mut archive: Archive, dir: &Path) -> Result<()> { + for entry in archive.entries()? { + let mut entry = entry?; + let kind = entry.header().entry_type(); + ensure!( + kind.is_file() || kind.is_dir(), + "prepared asset entry {} is neither a file nor a directory", + entry.path()?.display() + ); + entry.unpack_in(dir)?; + } + Ok(()) +} + +#[cfg(feature = "embedded-runtime")] +use crate::ComponentGenerator; + +/// Prepares the assets for a WIT world. +/// +/// The fields have the same meaning as in [`ComponentGenerator`]. Per-module +/// `componentize-py.toml` configuration does not apply, because preparation +/// does not search a Python path. +#[cfg(feature = "embedded-runtime")] +pub struct BindingsPreparer<'a> { + pub wit_paths: &'a [&'a Path], + pub worlds: &'a [&'a str], + pub features: &'a [&'a str], + pub all_features: bool, + pub bindings_module: Option<&'a str>, + pub import_interface_names: &'a HashMap<&'a str, &'a str>, + pub export_interface_names: &'a HashMap<&'a str, &'a str>, + pub intersect_world: Option<&'a str>, + pub registry_config: Option<&'a Path>, + pub default_registries: bool, +} + +#[cfg(feature = "embedded-runtime")] +impl BindingsPreparer<'_> { + pub async fn prepare(&self) -> Result { + let bound = ComponentGenerator { + wit_paths: self.wit_paths, + worlds: self.worlds, + features: self.features, + all_features: self.all_features, + bindings_module: self.bindings_module, + python_path: &[], + module_worlds: &[], + app_name: "", + output_path: Path::new(""), + add_to_linker: None, + stub_wasi: false, + stack_size: None, + import_interface_names: self.import_interface_names, + export_interface_names: self.export_interface_names, + intersect_world: self.intersect_world, + registry_config: self.registry_config, + default_registries: self.default_registries, + } + .bind() + .await?; + + let mut blobs = BTreeMap::new(); + let world = match &bound.world_dir_mounts[..] { + [] => None, + [(mounts, dir)] if mounts == &["world"] => { + Some(Prepared::add_blob(&mut blobs, pack(dir.path())?)) + } + _ => bail!("prepared bindings support only one generated bindings module"), + }; + + let manifest = Manifest { + format: FORMAT, + generator: format!("componentize-py {}", env!("CARGO_PKG_VERSION")), + init_wit: init_wit_digest(), + adapter: Prepared::add_blob(&mut blobs, prelink::embedded_adapter()?), + standard_library: Prepared::add_blob( + &mut blobs, + prelink::embedded_python_standard_library_archive().to_vec(), + ), + helper_utils: Prepared::add_blob(&mut blobs, pack(bound.helper_utils.path())?), + world, + libraries: bound + .libraries + .into_iter() + .map(|library| ManifestLibrary { + name: library.name, + dl_openable: library.dl_openable, + blob: Prepared::add_blob(&mut blobs, library.module), + }) + .collect(), + toolchain_support: prelink::toolchain_support_libraries()? + .into_iter() + .map(|(name, module)| ManifestFile { + name, + blob: Prepared::add_blob(&mut blobs, module), + }) + .collect(), + symbols: bound.symbols, + stubs: bound.stubs, + }; + + Ok(Prepared { manifest, blobs }) + } +} + +/// Links prepared assets with an application. +pub struct Assembler<'a> { + pub prepared: &'a Prepared, + /// The module that initialization imports. + pub app_name: &'a str, + /// The application's Python path. Each entry is a guest mount name and a + /// host directory; the directory is visible at `/{name}` during + /// initialization, and native extensions under it get library names + /// below `/{name}`. + pub python_path: &'a [(&'a str, &'a Path)], + /// See [`ComponentGenerator::stack_size`]. + pub stack_size: Option, +} + +/// A linked component and the plan to initialize it. +pub struct Assembly { + pub component: Vec, + pub plan: InitPlan, + _dirs: Vec, +} + +impl Assembler<'_> { + pub fn assemble(&self) -> Result { + let mut names = HashSet::new(); + for &(name, _) in self.python_path { + ensure!( + !name.is_empty() + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c)) + && name != "." + && name != "..", + "invalid Python path mount name `{name}`" + ); + ensure!( + !RESERVED_MOUNTS.contains(&name), + "the Python path mount name `{name}` is reserved" + ); + ensure!( + names.insert(name), + "duplicate Python path mount name `{name}`" + ); + } + + let manifest = &self.prepared.manifest; + let (application_libraries, support) = prelink::application_libraries(self.python_path)?; + let mut libraries = manifest + .libraries + .iter() + .map(|library| Library { + name: library.name.clone(), + module: self.prepared.blob(&library.blob).to_vec(), + dl_openable: library.dl_openable, + }) + .chain(application_libraries) + .collect::>(); + let toolchain = manifest + .toolchain_support + .iter() + .map(|file| (file.name.clone(), self.prepared.blob(&file.blob).to_vec())) + .collect::>(); + prelink::add_support_libraries(&mut libraries, &support, &toolchain)?; + + let component = link::link_libraries( + &libraries, + self.prepared.blob(&manifest.adapter), + self.stack_size, + )?; + + let standard_library = unpack(self.prepared.blob(&manifest.standard_library), true)?; + let helper_utils = unpack(self.prepared.blob(&manifest.helper_utils), false)?; + let world = manifest + .world + .as_ref() + .map(|world| unpack(self.prepared.blob(world), false)) + .transpose()?; + + let mut preopens = vec![ + Preopen::new(standard_library.path(), "python"), + Preopen::new(helper_utils.path(), "bundled"), + ]; + let mut python_path = Vec::new(); + for &(name, path) in self.python_path { + preopens.push(Preopen::new(path, name)); + python_path.push(format!("/{name}")); + } + if let Some(world) = &world { + preopens.push(Preopen::new(world.path(), "world")); + } + + let plan = InitPlan::new( + self.app_name, + manifest.symbols.clone(), + manifest.stubs.clone(), + false, + preopens, + &python_path, + BuildEntropy::for_inputs( + &component, + self.app_name, + &self + .python_path + .iter() + .map(|&(_, path)| path) + .collect::>(), + )?, + ); + + Ok(Assembly { + component, + plan, + _dirs: [standard_library, helper_utils] + .into_iter() + .chain(world) + .collect(), + }) + } +} + +impl Assembly { + /// Pre-initializes the component with the caller's store and linker; see + /// [`initialize_component`]. + pub async fn initialize( + &self, + store: Store, + linker: Linker, + ) -> Result> { + initialize_component(&self.component, None, &self.plan, store, linker).await + } + + /// Pre-initializes the component with this crate's WASI implementation and + /// [`default_engine`]. + #[cfg(feature = "embedded-runtime")] + pub async fn initialize_default(&self) -> Result> { + crate::initialize( + &self.component, + None, + &self.plan, + &crate::default_engine()?, + None, + ) + .await + } +} + +#[cfg(test)] +mod tests { + use { + super::unpack, + tar::{Builder, EntryType, Header}, + }; + + fn archive(kind: EntryType, link: Option<&str>) -> Vec { + let mut builder = Builder::new(Vec::new()); + let mut header = Header::new_gnu(); + header.set_entry_type(kind); + header.set_mode(0o644); + header.set_size(0); + if let Some(link) = link { + header.set_link_name(link).unwrap(); + } + builder.append_data(&mut header, "entry", &[][..]).unwrap(); + builder.into_inner().unwrap() + } + + #[test] + fn unpack_rejects_links() { + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().to_str().unwrap(); + for kind in [EntryType::Symlink, EntryType::Link] { + let error = unpack(&archive(kind, Some(target)), false).unwrap_err(); + assert!( + error + .to_string() + .contains("entry entry is neither a file nor a directory"), + "{error}" + ); + } + let unpacked = unpack(&archive(EntryType::Regular, None), false).unwrap(); + assert!(unpacked.path().join("entry").is_file()); + } +} diff --git a/tests/componentize.rs b/tests/componentize.rs index 22d792f..4d63c76 100644 --- a/tests/componentize.rs +++ b/tests/componentize.rs @@ -450,3 +450,159 @@ fn install_numpy(path: &Path) -> anyhow::Result<()> { Ok(()) } + +fn prepare_cli_world(dir: &Path, output: &str) -> anyhow::Result { + if !dir.join("wit").exists() { + fs_extra::copy_items(&["./wit"], dir, &CopyOptions::new())?; + } + let assert = cargo::cargo_bin_cmd!("componentize-py") + .current_dir(dir) + .args([ + "-d", + "wit", + "-w", + "wasi:cli/command@0.2.0", + "prepare", + output, + ]) + .assert() + .success(); + Ok(String::from_utf8(assert.get_output().stdout.clone())? + .trim() + .to_owned()) +} + +fn write_cli_app(dir: &Path, module: &str, prelude: &str, text: &str) -> anyhow::Result { + let app = dir.join(module); + fs::create_dir_all(&app)?; + fs::write( + app.join(format!("{module}.py")), + format!( + "{prelude}from wit.exports.wasi.cli_v0_2 import run, Run\n\n\ + @run.guest\nclass Cli(Run):\n def run(self) -> None:\n print({text:?})\n" + ), + )?; + Ok(app) +} + +fn assemble_cmd(dir: &Path, module: &str, app: &Path, extra: &[&str]) -> Command { + let mut command = cargo::cargo_bin_cmd!("componentize-py"); + command + .current_dir(dir) + .args(["assemble", "--prepared", "prepared"]) + .args(extra) + .args([module, "-p"]) + .arg(format!("app={}", app.display())) + .args(["-o", &format!("{module}.wasm")]); + command +} + +fn tree(dir: &Path) -> anyhow::Result)>> { + let mut files = Vec::new(); + for entry in fs::read_dir(dir)? { + let path = entry?.path(); + if path.is_dir() { + files.extend(tree(&path)?); + } else { + files.push((path.clone(), fs::read(&path)?)); + } + } + files.sort(); + Ok(files) +} + +#[test] +fn prepared_assets_assemble_unrelated_apps() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let identity = prepare_cli_world(dir.path(), "prepared")?; + assert_eq!( + prepare_cli_world(dir.path(), "prepared-again")?, + identity, + "preparing the same WIT twice gives the same identity" + ); + let before = tree(&dir.path().join("prepared"))?; + + for (module, text) in [("first", "first app"), ("second", "the second app")] { + let app = write_cli_app(dir.path(), module, "", text)?; + assemble_cmd(dir.path(), module, &app, &["--expect-identity", &identity]) + .assert() + .success(); + + Command::new("wasmtime") + .current_dir(dir.path()) + .args(["run", &format!("{module}.wasm")]) + .assert() + .success() + .stdout(format!("{text}\n")); + } + + assert!( + before == tree(&dir.path().join("prepared"))?, + "assembly does not change the prepared assets" + ); + Ok(()) +} + +#[test] +fn assemble_rejects_mismatched_assets_before_imports() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + prepare_cli_world(dir.path(), "prepared")?; + // Importing the app writes a marker into its own directory. + let app = write_cli_app( + dir.path(), + "marker", + "open('/app/imported', 'w').close()\n", + "ok", + )?; + let marker = app.join("imported"); + + assemble_cmd(dir.path(), "marker", &app, &[]) + .assert() + .success(); + assert!(marker.exists(), "intact assets import the app"); + fs::remove_file(&marker)?; + + let blob = fs::read_dir(dir.path().join("prepared/blobs"))? + .next() + .unwrap()? + .path(); + let original = fs::read(&blob)?; + let mut changed = original.clone(); + changed[0] ^= 1; + fs::write(&blob, &changed)?; + assemble_cmd(dir.path(), "marker", &app, &[]) + .assert() + .failure() + .stderr(predicate::str::contains("does not match its digest")); + fs::write(&blob, &original)?; + + fs::write(dir.path().join("prepared/extra"), "")?; + assemble_cmd(dir.path(), "marker", &app, &[]) + .assert() + .failure() + .stderr(predicate::str::contains("unexpected entry `extra`")); + fs::remove_file(dir.path().join("prepared/extra"))?; + + assemble_cmd(dir.path(), "marker", &app, &["--expect-identity", "0"]) + .assert() + .failure() + .stderr(predicate::str::contains("not 0")); + + assert!(!marker.exists(), "rejected assets do not import the app"); + Ok(()) +} + +#[test] +fn assemble_rejects_apps_that_configure_wit() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + prepare_cli_world(dir.path(), "prepared")?; + let app = write_cli_app(dir.path(), "configured", "", "ok")?; + fs::create_dir(app.join("sdk"))?; + fs::write(app.join("sdk/componentize-py.toml"), "")?; + + assemble_cmd(dir.path(), "configured", &app, &[]) + .assert() + .failure() + .stderr(predicate::str::contains("configures WIT bindings")); + Ok(()) +}