diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index de509fdda..a5d09d581 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,7 +36,7 @@ jobs: - name: Install Rust toolchain and the ALSA and udev headers the client links against run: | sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev - rustup toolchain install stable --profile minimal --component rustfmt --component clippy + rustup toolchain install stable --profile minimal --component rustfmt --component clippy --target wasm32-unknown-unknown # Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache). - uses: Swatinem/rust-cache@v2 with: diff --git a/Cargo.lock b/Cargo.lock index bcb050717..760e25457 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,6 +18,15 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" +[[package]] +name = "addr2line" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +dependencies = [ + "gimli", +] + [[package]] name = "adler2" version = "2.0.1" @@ -255,6 +264,9 @@ name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +dependencies = [ + "allocator-api2", +] [[package]] name = "bytemuck" @@ -393,6 +405,15 @@ dependencies = [ "error-code", ] +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -523,6 +544,144 @@ dependencies = [ "libc", ] +[[package]] +name = "cranelift-assembler-x64" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e92993516bcc43fd4e511b31d2e0c0c24f6b7ac18bb39e32cac2bfc05ea378e" +dependencies = [ + "cranelift-assembler-x64-meta", +] + +[[package]] +name = "cranelift-assembler-x64-meta" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97eeeb61b08ec484f274119faf3a8a1b80dd300b0208c0247d16d05982fc89fe" +dependencies = [ + "cranelift-srcgen", +] + +[[package]] +name = "cranelift-bforest" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "782eb44158681a105d157cb0ce63e3dc83f78ef5674266c12234f49da3f5c6e8" +dependencies = [ + "cranelift-entity", +] + +[[package]] +name = "cranelift-bitset" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd59af193204c4f025fb2c2d9ee0aeb1f60929edf000b0dfa3d45543a62f264" +dependencies = [ + "serde", + "serde_derive", +] + +[[package]] +name = "cranelift-codegen" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c29bd985057d790db25f6bc60b369b311aa2d75c2f496a7e9993585bfc7d60" +dependencies = [ + "bumpalo", + "cranelift-assembler-x64", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-codegen-meta", + "cranelift-codegen-shared", + "cranelift-control", + "cranelift-entity", + "cranelift-isle", + "gimli", + "hashbrown 0.15.5", + "log", + "pulley-interpreter", + "regalloc2", + "rustc-hash 2.1.3", + "serde", + "smallvec", + "target-lexicon", + "wasmtime-internal-math", +] + +[[package]] +name = "cranelift-codegen-meta" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9ef8a8495f19212f92db8425f768ffc67000c5cb417a0664475a8d09596700f" +dependencies = [ + "cranelift-assembler-x64-meta", + "cranelift-codegen-shared", + "cranelift-srcgen", + "heck", + "pulley-interpreter", +] + +[[package]] +name = "cranelift-codegen-shared" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3aa5099097666baf45bd68ef036327c8f29d8785fffaaa7db3b3b6b7e94bcc6" + +[[package]] +name = "cranelift-control" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f67f4f4e92c2934f40c2ff4574400bd27326932aad937a438b7fb459f60a63" +dependencies = [ + "arbitrary", +] + +[[package]] +name = "cranelift-entity" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8393d09f0abaa504896069e79f4eb6f15eb1853e5645732b082dac1ed292aaa8" +dependencies = [ + "cranelift-bitset", + "serde", + "serde_derive", +] + +[[package]] +name = "cranelift-frontend" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580cfaecbd11476dd82f6a393123dcbd9dfe583467df8d0c8441c641444d4985" +dependencies = [ + "cranelift-codegen", + "log", + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cranelift-isle" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c044843adb7d94b1facebaad846c0a762f79a77953417e3f0182093bcbbdc38" + +[[package]] +name = "cranelift-native" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d4c1707214e53f2040e4d13430069ea22623287b2750ed6d62e40eba88d91a" +dependencies = [ + "cranelift-codegen", + "libc", + "target-lexicon", +] + +[[package]] +name = "cranelift-srcgen" +version = "0.123.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d355a35edc49f628db7b793f3527eed31b560e77c3e8ed0e5258aad8df8a5249" + [[package]] name = "crc32fast" version = "1.5.2" @@ -672,6 +831,24 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[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.42" @@ -708,6 +885,12 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + [[package]] name = "fdeflate" version = "0.3.7" @@ -912,6 +1095,17 @@ dependencies = [ "windows 0.62.2", ] +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +dependencies = [ + "fallible-iterator", + "indexmap", + "stable_deref_trait", +] + [[package]] name = "glam" version = "0.30.10" @@ -950,6 +1144,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "foldhash 0.1.5", + "serde", ] [[package]] @@ -1085,6 +1280,26 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "horizon-mods" +version = "0.1.0" +dependencies = [ + "horizon-mods", + "log", + "serde", + "toml", + "wasmtime", + "wit-component 0.239.0", + "zip", +] + +[[package]] +name = "horizon-mods-test-guest" +version = "0.1.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "horizon-prepare" version = "0.1.0" @@ -1327,6 +1542,15 @@ dependencies = [ "generic-array", ] +[[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" @@ -1544,6 +1768,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memfd" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" +dependencies = [ + "rustix 1.1.5", +] + [[package]] name = "memmap2" version = "0.9.11" @@ -1599,7 +1832,7 @@ dependencies = [ "naga-types", "num-traits", "once_cell", - "rustc-hash", + "rustc-hash 1.1.0", "spirv", "thiserror 2.0.21", "unicode-ident", @@ -1613,7 +1846,7 @@ checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" dependencies = [ "hashbrown 0.17.1", "indexmap", - "rustc-hash", + "rustc-hash 1.1.0", "thiserror 2.0.21", ] @@ -2055,6 +2288,18 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "object" +version = "0.37.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +dependencies = [ + "crc32fast", + "hashbrown 0.15.5", + "indexmap", + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2242,6 +2487,18 @@ dependencies = [ "portable-atomic", ] +[[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.6" @@ -2291,6 +2548,29 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "pulley-interpreter" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "334ae8982dcf354e5f28e79fc6f935601e028b729cc174d3937eeeaa859057b8" +dependencies = [ + "cranelift-bitset", + "log", + "pulley-macros", + "wasmtime-internal-math", +] + +[[package]] +name = "pulley-macros" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cd207bca4bc5e46cb4fcea87196dcbd78befc628c64c67d11dc99fce5cd5369" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "quick-xml" version = "0.41.0" @@ -2375,6 +2655,20 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regalloc2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5216b1837de2149f8bc8e6d5f88a9326b63b8c836ed58ce4a0a29ec736a59734" +dependencies = [ + "allocator-api2", + "bumpalo", + "hashbrown 0.15.5", + "log", + "rustc-hash 2.1.3", + "smallvec", +] + [[package]] name = "regex" version = "1.13.1" @@ -2430,6 +2724,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustc_version" version = "0.4.1" @@ -2554,6 +2854,10 @@ 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" @@ -2668,6 +2972,9 @@ name = "smallvec" version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +dependencies = [ + "serde", +] [[package]] name = "smithay-client-toolkit" @@ -2862,6 +3169,21 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[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" @@ -3222,6 +3544,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-encoder" +version = "0.236.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "724fccfd4f3c24b7e589d333fc0429c68042897a7e8a5f8694f31792471841e7" +dependencies = [ + "leb128fmt", + "wasmparser 0.236.1", +] + +[[package]] +name = "wasm-encoder" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be00faa2b4950c76fe618c409d2c3ea5a3c9422013e079482d78544bb2d184c" +dependencies = [ + "leb128fmt", + "wasmparser 0.239.0", +] + [[package]] name = "wasm-encoder" version = "0.247.0" @@ -3229,7 +3571,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30b6733b8b91d010a6ac5b0fb237dc46a19650bc4c67db66857e2e787d437204" dependencies = [ "leb128fmt", - "wasmparser", + "wasmparser 0.247.0", +] + +[[package]] +name = "wasm-metadata" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20b3ec880a9ac69ccd92fbdbcf46ee833071cf09f82bb005b2327c7ae6025ae2" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder 0.239.0", + "wasmparser 0.239.0", ] [[package]] @@ -3240,8 +3594,33 @@ checksum = "665fe59e56cc9b419ca6fcca56673e3421d1a5011e3b65caf6b726fd9e041d10" dependencies = [ "anyhow", "indexmap", - "wasm-encoder", - "wasmparser", + "wasm-encoder 0.247.0", + "wasmparser 0.247.0", +] + +[[package]] +name = "wasmparser" +version = "0.236.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9b1e81f3eb254cf7404a82cee6926a4a3ccc5aad80cc3d43608a070c67aa1d7" +dependencies = [ + "bitflags 2.13.2", + "hashbrown 0.15.5", + "indexmap", + "semver", + "serde", +] + +[[package]] +name = "wasmparser" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9d90bb93e764f6beabf1d02028c70a2156a6583e63ac4218dd07ef733368b0" +dependencies = [ + "bitflags 2.13.2", + "hashbrown 0.15.5", + "indexmap", + "semver", ] [[package]] @@ -3256,6 +3635,252 @@ dependencies = [ "semver", ] +[[package]] +name = "wasmprinter" +version = "0.236.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2df225df06a6df15b46e3f73ca066ff92c2e023670969f7d50ce7d5e695abbb1" +dependencies = [ + "anyhow", + "termcolor", + "wasmparser 0.236.1", +] + +[[package]] +name = "wasmtime" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70095b9fe63cc2a87ed206729e11544610decc184c62898c5d201ff1d666d82e" +dependencies = [ + "addr2line", + "anyhow", + "bitflags 2.13.2", + "bumpalo", + "cc", + "cfg-if", + "encoding_rs", + "hashbrown 0.15.5", + "indexmap", + "libc", + "log", + "mach2", + "memfd", + "object", + "once_cell", + "postcard", + "pulley-interpreter", + "rustix 1.1.5", + "semver", + "serde", + "serde_derive", + "smallvec", + "target-lexicon", + "wasmparser 0.236.1", + "wasmtime-environ", + "wasmtime-internal-asm-macros", + "wasmtime-internal-component-macro", + "wasmtime-internal-component-util", + "wasmtime-internal-cranelift", + "wasmtime-internal-fiber", + "wasmtime-internal-jit-debug", + "wasmtime-internal-jit-icache-coherence", + "wasmtime-internal-math", + "wasmtime-internal-slab", + "wasmtime-internal-unwinder", + "wasmtime-internal-versioned-export-macros", + "wasmtime-internal-winch", + "windows-sys 0.60.2", +] + +[[package]] +name = "wasmtime-environ" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a67ea8904b6e369e2218780bd1f9186f1980cb616445eb2c1f3c4e45c8397865" +dependencies = [ + "anyhow", + "cranelift-bitset", + "cranelift-entity", + "gimli", + "indexmap", + "log", + "object", + "postcard", + "semver", + "serde", + "serde_derive", + "smallvec", + "target-lexicon", + "wasm-encoder 0.236.1", + "wasmparser 0.236.1", + "wasmprinter", + "wasmtime-internal-component-util", +] + +[[package]] +name = "wasmtime-internal-asm-macros" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0488a52ae93e654baecb08ce04d15d478756eb2168c2bdab7915710109161ce" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "wasmtime-internal-component-macro" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "377e406c3f8e7bea64db3cb3ee0d406c331e8fc09d8cb2e7bf9ad74cb5d3b31a" +dependencies = [ + "anyhow", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasmtime-internal-component-util", + "wasmtime-internal-wit-bindgen", + "wit-parser 0.236.1", +] + +[[package]] +name = "wasmtime-internal-component-util" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97c24503bb712afe2c797dc291b96e57556ee62c35fd951f87e96088324de37c" + +[[package]] +name = "wasmtime-internal-cranelift" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63ea7ee133de9109a4a1fc63dae3afc9ea32e92b8dada824fa4595dbf175f80" +dependencies = [ + "anyhow", + "cfg-if", + "cranelift-codegen", + "cranelift-control", + "cranelift-entity", + "cranelift-frontend", + "cranelift-native", + "gimli", + "itertools", + "log", + "object", + "pulley-interpreter", + "smallvec", + "target-lexicon", + "thiserror 2.0.21", + "wasmparser 0.236.1", + "wasmtime-environ", + "wasmtime-internal-math", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-fiber" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69662a0a4dbe9784d1e8add9e3c5d2db0ca348085c624c27a70992dbe2eff4a3" +dependencies = [ + "anyhow", + "cc", + "cfg-if", + "libc", + "rustix 1.1.5", + "wasmtime-internal-asm-macros", + "wasmtime-internal-versioned-export-macros", + "windows-sys 0.60.2", +] + +[[package]] +name = "wasmtime-internal-jit-debug" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00cb07d23903c0be359d6b920d94774ea322759c3f4d6721b61afa03602e4804" +dependencies = [ + "cc", + "wasmtime-internal-versioned-export-macros", +] + +[[package]] +name = "wasmtime-internal-jit-icache-coherence" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b47c37a6d026e2755fe2cf7ec5c1f4b0fba62e448ea910cdf6a07a4982c6a" +dependencies = [ + "anyhow", + "cfg-if", + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "wasmtime-internal-math" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b269f0ba44102c57fd5f94f1bf4395ccd4fc2b84698fc78f627a6f2a47131a62" +dependencies = [ + "libm", +] + +[[package]] +name = "wasmtime-internal-slab" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e35ac9d503d503703cd24d532e53e2e93c86109b451df40a9801500045aee25" + +[[package]] +name = "wasmtime-internal-unwinder" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83ce1d0930da44ed375701e6b4f187b46249f7efe2b1d8c1c77229a4adc82de9" +dependencies = [ + "anyhow", + "cfg-if", + "cranelift-codegen", + "log", + "object", +] + +[[package]] +name = "wasmtime-internal-versioned-export-macros" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6633be262400bd7abab4ff767a16e8b6a41ff117be54bf76dabecea9f96225" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "wasmtime-internal-winch" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "509d1e1cf8e3b3306f291407c92bca8381d9294f8c54ad74b692538f1f5b23c7" +dependencies = [ + "anyhow", + "cranelift-codegen", + "gimli", + "object", + "target-lexicon", + "wasmparser 0.236.1", + "wasmtime-environ", + "wasmtime-internal-cranelift", + "winch-codegen", +] + +[[package]] +name = "wasmtime-internal-wit-bindgen" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6d9a5b51b3400b4df1055724c4536ad5aa58fafe83cea5ca94f88cc9eb97563" +dependencies = [ + "anyhow", + "bitflags 2.13.2", + "heck", + "indexmap", + "wit-parser 0.236.1", +] + [[package]] name = "wayland-backend" version = "0.3.17" @@ -3455,7 +4080,7 @@ dependencies = [ "portable-atomic", "profiling", "raw-window-handle", - "rustc-hash", + "rustc-hash 1.1.0", "smallvec", "thiserror 2.0.21", "wgpu-core-deps-apple", @@ -3561,6 +4186,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winch-codegen" +version = "36.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e470d7e674c41ad32dddc02d8d8a94983e0a4c516028bda60747e6dd862a567" +dependencies = [ + "anyhow", + "cranelift-assembler-x64", + "cranelift-codegen", + "gimli", + "regalloc2", + "smallvec", + "target-lexicon", + "thiserror 2.0.21", + "wasmparser 0.236.1", + "wasmtime-environ", + "wasmtime-internal-cranelift", + "wasmtime-internal-math", +] + [[package]] name = "windows" version = "0.54.0" @@ -3718,6 +4363,15 @@ 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" @@ -3751,13 +4405,30 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "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-threading" version = "0.2.1" @@ -3779,6 +4450,12 @@ 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.42.2" @@ -3791,6 +4468,12 @@ 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.42.2" @@ -3803,12 +4486,24 @@ 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.42.2" @@ -3821,6 +4516,12 @@ 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.42.2" @@ -3833,6 +4534,12 @@ 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.42.2" @@ -3845,6 +4552,12 @@ 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.42.2" @@ -3857,6 +4570,12 @@ 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 = "winit" version = "0.30.13" @@ -3945,7 +4664,7 @@ checksum = "02dee27a2dc20d1008016c742ec9fc6ea498492994ba3750be7454cbc97ff04c" dependencies = [ "anyhow", "heck", - "wit-parser", + "wit-parser 0.247.0", ] [[package]] @@ -3959,9 +4678,9 @@ dependencies = [ "indexmap", "prettyplease", "syn 2.0.119", - "wasm-metadata", + "wasm-metadata 0.247.0", "wit-bindgen-core", - "wit-component", + "wit-component 0.247.0", ] [[package]] @@ -3979,6 +4698,25 @@ dependencies = [ "wit-bindgen-rust", ] +[[package]] +name = "wit-component" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a866b19dba2c94d706ec58c92a4c62ab63e482b4c935d2a085ac94caecb136" +dependencies = [ + "anyhow", + "bitflags 2.13.2", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder 0.239.0", + "wasm-metadata 0.239.0", + "wasmparser 0.239.0", + "wit-parser 0.239.0", +] + [[package]] name = "wit-component" version = "0.247.0" @@ -3992,10 +4730,46 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", + "wasm-encoder 0.247.0", + "wasm-metadata 0.247.0", + "wasmparser 0.247.0", + "wit-parser 0.247.0", +] + +[[package]] +name = "wit-parser" +version = "0.236.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16e4833a20cd6e85d6abfea0e63a399472d6f88c6262957c17f546879a80ba15" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser 0.236.1", +] + +[[package]] +name = "wit-parser" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55c92c939d667b7bf0c6bf2d1f67196529758f99a2a45a3355cc56964fd5315d" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser 0.239.0", ] [[package]] @@ -4014,7 +4788,7 @@ dependencies = [ "serde_derive", "serde_json", "unicode-xid", - "wasmparser", + "wasmparser 0.247.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index f55ce0c12..c2c15c1a8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server"] -members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-mods/Cargo.toml b/crates/horizon-mods/Cargo.toml new file mode 100644 index 000000000..93b46eb14 --- /dev/null +++ b/crates/horizon-mods/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "horizon-mods" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.86" +description = "Horizon's mod runtime: sandboxed WebAssembly components (docs/mods.md)" + +[dependencies] +serde = { version = "1", features = ["derive"] } +toml = "1.1.6" +zip = { version = "2", default-features = false, features = ["deflate"] } +log = "0.4" +# The 36 LTS line: security fixes until August 2027, and it builds on the client's Rust. +wasmtime = { version = "36.0.18", default-features = false, features = ["runtime", "cranelift", "component-model", "std"], optional = true } +# Turns a mod's core module into a component (cargo horizon-mod build, the tests). +wit-component = { version = "0.239", optional = true } + +[features] +default = ["runtime"] +# Loads and runs mods; without it only manifests and packaging (cargo horizon-mod). +runtime = ["dep:wasmtime"] +pack = ["dep:wit-component"] + +[dev-dependencies] +horizon-mods = { path = ".", features = ["pack"] } + +[lints] +workspace = true diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs new file mode 100644 index 000000000..f2bb3833c --- /dev/null +++ b/crates/horizon-mods/src/lib.rs @@ -0,0 +1,14 @@ +//! Horizon's mods (`docs/mods.md`): WebAssembly components written against +//! `crates/horizon-mod-sdk/wit/horizon.wit`, each in its own sandbox with +//! no file, network or clock access, a memory cap and a time budget per +//! call. A mod that traps or overruns is turned off; the game goes on. +//! +//! Nothing here runs unless a mod is installed and turned on: an empty +//! [`Mods`] makes no engine and every hook returns at once. +pub mod manifest; +#[cfg(feature = "runtime")] +mod runtime; + +pub use manifest::{Capability, Manifest, Package, Side}; +#[cfg(feature = "runtime")] +pub use runtime::*; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs new file mode 100644 index 000000000..4a0f5f31e --- /dev/null +++ b/crates/horizon-mods/src/manifest.rs @@ -0,0 +1,255 @@ +//! `horizon-mod.toml`, a mod's manifest, and the `.hmod` file around it. +use serde::Deserialize; +use std::{fmt, io::Read, path::Path}; + +/// The manifest's file name, beside `mod.wasm`. +pub const MANIFEST: &str = "horizon-mod.toml"; +/// The component's file name in a `.hmod` or a mod folder. +pub const WASM: &str = "mod.wasm"; +/// The API (WIT package `horizon:mods`) versions this build runs: a mod +/// built for any 0.1.x SDK. +pub const API: &str = "0.1"; +/// The biggest `mod.wasm` a mod may ship. +const MAX_WASM: u64 = 32 << 20; + +#[derive(Clone, Debug, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + /// `[a-z0-9_]`, 1 to 64 characters: the mod's folder, log and settings key. + pub id: String, + pub name: String, + pub version: String, + #[serde(default)] + pub description: String, + #[serde(default)] + pub authors: Vec, + /// The API version the mod was built for: `0.1`. + pub api: String, + #[serde(default)] + pub side: Side, + #[serde(default)] + pub capabilities: Vec, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum Side { + /// Runs in the player's game only (HUD, keys, chat commands). + #[default] + Client, + /// Runs where the world is simulated (rules, blocks); not run yet. + Server, + /// Both, and the server tells clients which version it expects. + Both, +} + +/// What a mod may do beyond writing its log. Each is a WIT interface the +/// component imports; the player sees them before turning the mod on. +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "kebab-case")] +pub enum Capability { + GameRead, + Chat, + Hud, +} +impl Capability { + pub const ALL: [Capability; 3] = [Capability::GameRead, Capability::Chat, Capability::Hud]; + /// The WIT interface it grants, in `horizon:mods`. + pub fn interface(self) -> &'static str { + match self { + Capability::GameRead => "game", + Capability::Chat => "chat", + Capability::Hud => "hud", + } + } + /// What the player reads before turning the mod on: "May ". + pub fn describe(self) -> &'static str { + match self { + Capability::GameRead => "see your position, health and the time", + Capability::Chat => "show you chat messages", + Capability::Hud => "draw text on your screen", + } + } + /// The capability a component import needs, `Ok(None)` for one every + /// mod has; `Err` for an import Horizon does not offer. + pub fn of_import(name: &str) -> Result, String> { + let unknown = || format!("imports {name}, which Horizon does not offer"); + let rest = name.strip_prefix("horizon:mods/").ok_or_else(unknown)?; + let (interface, version) = rest.split_once('@').ok_or_else(unknown)?; + if !version.starts_with("0.1.") { + return Err(format!("needs API {version}; this Horizon runs {API}")); + } + if interface == "log" { + return Ok(None); + } + Capability::ALL + .into_iter() + .find(|c| c.interface() == interface) + .map(Some) + .ok_or_else(unknown) + } +} +impl fmt::Display for Capability { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Capability::GameRead => "game-read", + Capability::Chat => "chat", + Capability::Hud => "hud", + }; + f.write_str(name) + } +} + +impl Manifest { + pub fn parse(text: &str) -> Result { + let m: Manifest = toml::from_str(text).map_err(|e| format!("{MANIFEST}: {e}"))?; + let id_ok = (1..=64).contains(&m.id.len()) + && m.id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'); + if !id_ok { + return Err(format!( + "{MANIFEST}: id {:?} is not [a-z0-9_]{{1,64}}", + m.id + )); + } + if m.api != API { + return Err(format!("built for API {}; this Horizon runs {API}", m.api)); + } + Ok(m) + } + /// Checks that the component's imports need only declared capabilities. + pub fn check_imports<'a>( + &self, + imports: impl IntoIterator, + ) -> Result<(), String> { + for name in imports { + if let Some(c) = Capability::of_import(name)? + && !self.capabilities.contains(&c) + { + return Err(format!("uses capability {c}, missing from {MANIFEST}")); + } + } + Ok(()) + } +} + +/// A mod as found on disk: its manifest and component bytes. +pub struct Package { + pub manifest: Manifest, + pub wasm: Vec, +} +impl Package { + /// A `.hmod` (a zip holding `horizon-mod.toml` and `mod.wasm`) or a + /// folder holding the same two files. + pub fn read(path: &Path) -> Result { + let (toml, wasm) = if path.is_dir() { + let toml = std::fs::read_to_string(path.join(MANIFEST)); + let wasm = std::fs::read(path.join(WASM)); + ( + toml.map_err(|e| format!("{MANIFEST}: {e}"))?, + wasm.map_err(|e| format!("{WASM}: {e}"))?, + ) + } else { + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + let mut entry = |name: &str| -> Result, String> { + let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?; + let mut out = Vec::new(); + f.take(MAX_WASM + 1) + .read_to_end(&mut out) + .map_err(|e| e.to_string())?; + Ok(out) + }; + let toml = String::from_utf8(entry(MANIFEST)?) + .map_err(|_| format!("{MANIFEST}: not UTF-8"))?; + (toml, entry(WASM)?) + }; + if wasm.len() as u64 > MAX_WASM { + return Err(format!("{WASM} is over {} MiB", MAX_WASM >> 20)); + } + Ok(Package { + manifest: Manifest::parse(&toml)?, + wasm, + }) + } + /// The `.hmod` bytes for `manifest_text` and a component. + pub fn write(manifest_text: &str, wasm: &[u8]) -> Result, String> { + use std::io::Write; + Manifest::parse(manifest_text)?; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default(); + let err = |e: zip::result::ZipError| e.to_string(); + zip.start_file(MANIFEST, options).map_err(err)?; + zip.write_all(manifest_text.as_bytes()) + .map_err(|e| e.to_string())?; + zip.start_file(WASM, options).map_err(err)?; + zip.write_all(wasm).map_err(|e| e.to_string())?; + Ok(zip.finish().map_err(err)?.into_inner()) + } +} + +/// Turns a `wasm32-unknown-unknown` cdylib built with the SDK into the +/// component the game loads. +#[cfg(feature = "pack")] +pub fn componentize(core: &[u8]) -> Result, String> { + wit_component::ComponentEncoder::default() + .module(core) + .and_then(|e| e.validate(true).encode()) + .map_err(|e| format!("{e:#}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = r#" +id = "coords_hud" +name = "Coordinates HUD" +version = "0.1.0" +api = "0.1" +capabilities = ["game-read", "hud"] +"#; + + #[test] + fn parses_and_checks_imports() { + let m = Manifest::parse(EXAMPLE).unwrap(); + assert_eq!(m.side, Side::Client); + assert_eq!(m.capabilities, [Capability::GameRead, Capability::Hud]); + let ok = [ + "horizon:mods/log@0.1.0", + "horizon:mods/game@0.1.0", + "horizon:mods/hud@0.1.2", + ]; + assert_eq!(m.check_imports(ok), Ok(())); + let chat = m.check_imports(["horizon:mods/chat@0.1.0"]); + assert_eq!( + chat, + Err("uses capability chat, missing from horizon-mod.toml".into()) + ); + assert!(m.check_imports(["wasi:filesystem/types@0.2.0"]).is_err()); + assert!(m.check_imports(["horizon:mods/game@0.2.0"]).is_err()); + } + + #[test] + fn refuses_bad_ids_and_apis() { + let bad_id = EXAMPLE.replace("coords_hud", "Coords HUD"); + assert!(Manifest::parse(&bad_id).unwrap_err().contains("is not")); + let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.2\""); + assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.2")); + let unknown = format!("{EXAMPLE}network = true\n"); + assert!(Manifest::parse(&unknown).is_err()); + } + + #[test] + fn hmod_round_trips() { + let dir = std::env::temp_dir().join(format!("horizon-mods-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("coords_hud.hmod"); + std::fs::write(&path, Package::write(EXAMPLE, b"\0asm").unwrap()).unwrap(); + let p = Package::read(&path).unwrap(); + assert_eq!(p.manifest.id, "coords_hud"); + assert_eq!(p.wasm, b"\0asm"); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs new file mode 100644 index 000000000..7e3741287 --- /dev/null +++ b/crates/horizon-mods/src/runtime.rs @@ -0,0 +1,498 @@ +//! Loading and calling mods with wasmtime's component model. +use crate::manifest::{Manifest, Package, Side}; +use std::{ + path::{Path, PathBuf}, + sync::Arc, + time::{Duration, Instant, SystemTime}, +}; +use wasmtime::{ + Config, Engine, Store, StoreLimits, StoreLimitsBuilder, Trap, + component::{Component, HasSelf, Linker}, +}; + +mod bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "horizon-mod", + }); +} +pub use bindings::horizon::mods::{ + game::{Clock, Player}, + hud::{Corner, Line}, +}; +use bindings::{ + HorizonMod, + exports::horizon::mods::events::Registration, + horizon::mods::{chat, game, hud, log as mod_log}, +}; + +/// A mod's linear memory cap. +const MEMORY: usize = 64 << 20; +/// Fuel (about one unit per WebAssembly instruction) per call: a bound on +/// runaway loops, far above the hooks' time budgets. +const FUEL_INIT: u64 = 2_000_000_000; +const FUEL_TICK: u64 = 50_000_000; +const FUEL_FRAME: u64 = 10_000_000; +const FUEL_EVENT: u64 = 100_000_000; +/// Chat lines a mod may show per call, HUD lines and their length. +const CHAT_PER_CALL: usize = 8; +const HUD_LINES: usize = 16; +const LINE_CHARS: usize = 256; + +/// What mods may read of the game, copied once per tick by the game. +#[derive(Clone, Debug, Default)] +pub struct Snapshot { + pub player: Option, + pub clock: Option, +} + +/// What mods asked the game to show since the last [`Mods::drain`]. +#[derive(Clone, Debug, PartialEq)] +pub enum Output { + /// `chat.show`: a line after the mod's name. + Chat { name: String, text: String }, + /// A mod command's feedback, red when `error`. + Feedback { text: String, error: bool }, + /// The mod was turned off: it trapped, overran or failed to start. + Stopped { name: String, reason: String }, +} + +/// A mod's text panel, drawn every frame until it changes. +#[derive(Clone, Debug)] +pub struct Panel { + pub corner: Corner, + pub lines: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Status { + /// Installed and turned off by the player. + Off, + Running, + /// Could not load or start, or stopped while running. + Failed(String), +} + +/// One installed mod, for the Mods page. +pub struct Entry { + pub path: PathBuf, + /// None when the manifest could not be read (`status` says why). + pub manifest: Option, + pub status: Status, + /// The mod's average time per call of its busiest hook. + pub cost: Duration, + run: Option, + modified: Option, +} + +struct Running { + store: Store, + exports: HorizonMod, + hooks: Registration, +} + +struct State { + name: String, + id: String, + snapshot: Arc, + out: Vec, + panel: Option, + limits: StoreLimits, +} + +/// The installed mods and the engine running them. `Mods::default()` is +/// the state with none: no engine, and every hook a no-op. +#[derive(Default)] +pub struct Mods { + engine: Option<(Engine, Linker)>, + entries: Vec, + snapshot: Arc, + out: Vec, +} + +/// The `.hmod` files and mod folders in `dir`, by name. +pub fn find(dir: &Path) -> Vec { + let Ok(read) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found: Vec = read + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.extension().is_some_and(|e| e == "hmod") + || p.join(crate::manifest::MANIFEST).is_file() + }) + .collect(); + found.sort(); + found +} + +impl Mods { + /// Reads every mod at `paths` and starts those `enabled` says are on. + /// A command that `reserved` (vanilla's commands) or an earlier mod + /// already uses is refused. + pub fn load( + paths: &[PathBuf], + enabled: impl Fn(&str) -> bool, + reserved: impl Fn(&str) -> bool, + ) -> Mods { + let mut mods = Mods::default(); + for path in paths { + let modified = modified(path); + let mut entry = Entry { + path: path.clone(), + manifest: None, + status: Status::Off, + cost: Duration::ZERO, + run: None, + modified, + }; + match Package::read(path) { + Err(e) => entry.status = Status::Failed(e), + Ok(package) => { + let on = enabled(&package.manifest.id); + entry.manifest = Some(package.manifest.clone()); + if on { + entry.status = match mods.start(&package, &reserved) { + Ok(run) => { + entry.run = Some(run); + Status::Running + } + Err(e) => Status::Failed(e), + }; + } + } + } + if let (Status::Failed(reason), Some(m)) = (&entry.status, &entry.manifest) { + log::warn!("Horizon: mod {} did not start: {reason}", m.id); + } + mods.entries.push(entry); + } + mods + } + + fn engine(&mut self) -> Result<&(Engine, Linker), String> { + if self.engine.is_none() { + let mut config = Config::new(); + config.wasm_component_model(true).consume_fuel(true); + let engine = Engine::new(&config).map_err(|e| e.to_string())?; + let mut linker = Linker::new(&engine); + HorizonMod::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; + self.engine = Some((engine, linker)); + } + Ok(self.engine.as_ref().expect("made above")) + } + + fn start( + &mut self, + package: &Package, + reserved: &dyn Fn(&str) -> bool, + ) -> Result { + let m = &package.manifest; + if m.side == Side::Server { + return Err("server mods do not run yet".into()); + } + let taken: Vec = self + .entries + .iter() + .filter_map(|e| e.run.as_ref()) + .flat_map(|r| r.hooks.commands.iter().cloned()) + .collect(); + let snapshot = self.snapshot.clone(); + let (engine, linker) = self.engine()?; + let component = + Component::new(engine, &package.wasm).map_err(|e| format!("not a component: {e}"))?; + let ty = component.component_type(); + let imports: Vec = ty + .imports(engine) + .map(|(name, _)| name.to_string()) + .collect(); + m.check_imports(imports.iter().map(String::as_str))?; + let state = State { + name: m.name.clone(), + id: m.id.clone(), + snapshot, + out: Vec::new(), + panel: None, + limits: StoreLimitsBuilder::new() + .memory_size(MEMORY) + .instances(16) + .build(), + }; + let mut store = Store::new(engine, state); + store.limiter(|s| &mut s.limits); + store.set_fuel(FUEL_INIT).map_err(|e| e.to_string())?; + let exports = + HorizonMod::instantiate(&mut store, &component, linker).map_err(|e| reason(&e))?; + let mut hooks = exports + .horizon_mods_events() + .call_init(&mut store) + .map_err(|e| reason(&e))??; + hooks.commands.retain(|c| { + let free = !reserved(c) && !taken.contains(c); + if !free { + log::warn!("Horizon: mod {} cannot take /{c}: already a command", m.id); + } + free + }); + self.out.append(&mut store.data_mut().out); + Ok(Running { + store, + exports, + hooks, + }) + } + + /// True when at least one mod runs: the game skips its mod work otherwise. + pub fn is_running(&self) -> bool { + self.entries.iter().any(|e| e.run.is_some()) + } + pub fn entries(&self) -> &[Entry] { + &self.entries + } + /// What mods read until the next snapshot. + pub fn set_snapshot(&mut self, snapshot: Snapshot) { + self.snapshot = Arc::new(snapshot); + } + + /// Calls `f` on every running mod whose hooks `wants`, with `fuel`. + fn each( + &mut self, + fuel: u64, + wants: impl Fn(&Registration) -> bool, + mut f: impl FnMut(&HorizonMod, &mut Store) -> wasmtime::Result<()>, + ) { + for i in 0..self.entries.len() { + if self.entries[i] + .run + .as_ref() + .is_some_and(|r| wants(&r.hooks)) + { + self.call(i, fuel, &mut f); + } + } + } + + /// One call into mod `i`; a trap or an overrun turns the mod off. + fn call( + &mut self, + i: usize, + fuel: u64, + f: impl FnOnce(&HorizonMod, &mut Store) -> wasmtime::Result, + ) -> Option { + let entry = &mut self.entries[i]; + let run = entry.run.as_mut()?; + run.store.data_mut().snapshot = self.snapshot.clone(); + let started = Instant::now(); + let result = run + .store + .set_fuel(fuel) + .and_then(|()| f(&run.exports, &mut run.store)); + // An average over about the last 64 calls. + entry.cost = (entry.cost * 63 + started.elapsed()) / 64; + self.out.append(&mut run.store.data_mut().out); + match result { + Ok(r) => Some(r), + Err(e) => { + let reason = reason(&e); + log::warn!("Horizon: mod {} stopped: {reason}", run.store.data().id); + let name = run.store.data().name.clone(); + self.out.push(Output::Stopped { + name, + reason: reason.clone(), + }); + entry.status = Status::Failed(reason); + entry.run = None; + None + } + } + } + + /// A game tick. + pub fn tick(&mut self, tick: u64) { + self.each( + FUEL_TICK, + |h| h.tick, + |m, s| m.horizon_mods_events().call_tick(s, tick), + ); + } + /// A rendered frame, `seconds` after the last. + pub fn frame(&mut self, seconds: f32) { + self.each( + FUEL_FRAME, + |h| h.frame, + |m, s| m.horizon_mods_events().call_frame(s, seconds), + ); + } + /// A chat line the player received, as plain text. + pub fn chat(&mut self, text: &str) { + self.each( + FUEL_EVENT, + |h| h.chat, + |m, s| m.horizon_mods_events().call_chat(s, text), + ); + } + /// Whether a running mod owns `/name`. + pub fn has_command(&self, name: &str) -> bool { + self.command_owner(name).is_some() + } + fn command_owner(&self, name: &str) -> Option { + self.entries.iter().position(|e| { + e.run + .as_ref() + .is_some_and(|r| r.hooks.commands.iter().any(|c| c == name)) + }) + } + /// Runs `line` (without its slash) if a mod owns its command; false + /// when none does. + pub fn command(&mut self, line: &str) -> bool { + let (name, args) = line.split_once(' ').unwrap_or((line, "")); + let Some(i) = self.command_owner(name) else { + return false; + }; + let result = self.call(i, FUEL_EVENT, |m, s| { + m.horizon_mods_events().call_command(s, name, args) + }); + match result { + Some(Ok(Some(text))) => self.out.push(Output::Feedback { text, error: false }), + Some(Err(text)) => self.out.push(Output::Feedback { text, error: true }), + Some(Ok(None)) | None => {} + } + true + } + /// The commands running mods own, for suggestions. + pub fn commands(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()) + .flat_map(|r| r.hooks.commands.iter().map(String::as_str)) + } + + /// The running mods' HUD panels. + pub fn panels(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref()) + } + /// What mods asked to show since the last call. + pub fn drain(&mut self) -> Vec { + std::mem::take(&mut self.out) + } + + /// Restarts the mods whose file changed since they loaded (mod + /// development: rebuild, and the game picks it up). True when any did. + pub fn reload_changed(&mut self, reserved: impl Fn(&str) -> bool) -> bool { + let mut any = false; + for i in 0..self.entries.len() { + let entry = &self.entries[i]; + let now = modified(&entry.path); + let was_on = entry.status != Status::Off; + if now == entry.modified || !was_on { + continue; + } + any = true; + self.entries[i].modified = now; + self.entries[i].run = None; + let started = Package::read(&self.entries[i].path).and_then(|p| { + self.entries[i].manifest = Some(p.manifest.clone()); + self.start(&p, &reserved) + }); + let entry = &mut self.entries[i]; + let id = entry.manifest.as_ref().map_or("?", |m| m.id.as_str()); + match started { + Ok(run) => { + log::info!("Horizon: mod {id} reloaded"); + entry.run = Some(run); + entry.status = Status::Running; + } + Err(e) => { + log::warn!("Horizon: mod {id} did not reload: {e}"); + entry.status = Status::Failed(e); + } + } + } + any + } +} + +fn modified(path: &Path) -> Option { + let meta = std::fs::metadata(path).ok()?; + if meta.is_dir() { + // A folder mod changes when its component does. + return std::fs::metadata(path.join(crate::manifest::WASM)) + .ok()? + .modified() + .ok(); + } + meta.modified().ok() +} + +/// A trap or error, as the player reads it. +fn reason(e: &wasmtime::Error) -> String { + match e.downcast_ref::() { + Some(Trap::OutOfFuel) => "it took too long (an endless loop?)".into(), + Some(Trap::UnreachableCodeReached) => "it crashed (a panic)".into(), + Some(trap) => format!("it crashed: {trap}"), + None => format!("{e:#}"), + } +} + +fn clip(text: String) -> String { + match text.char_indices().nth(LINE_CHARS) { + Some((at, _)) => text[..at].to_string(), + None => text, + } +} + +impl mod_log::Host for State { + fn write(&mut self, level: mod_log::Level, message: String) { + let level = match level { + mod_log::Level::Debug => log::Level::Debug, + mod_log::Level::Info => log::Level::Info, + mod_log::Level::Warn => log::Level::Warn, + mod_log::Level::Error => log::Level::Error, + }; + log::log!(level, "[mod {}] {}", self.id, clip(message)); + } +} +impl game::Host for State { + fn get_player(&mut self) -> Option { + self.snapshot.player.clone() + } + fn get_clock(&mut self) -> Option { + self.snapshot.clock + } +} +impl chat::Host for State { + fn show(&mut self, text: String) { + let shown = self + .out + .iter() + .filter(|o| matches!(o, Output::Chat { .. })) + .count(); + if shown < CHAT_PER_CALL { + let name = self.name.clone(); + self.out.push(Output::Chat { + name, + text: clip(text), + }); + } + } +} +impl hud::Host for State { + fn set_panel(&mut self, corner: Corner, lines: Vec) { + let lines = lines + .into_iter() + .take(HUD_LINES) + .map(|l| Line { + text: clip(l.text), + color: l.color & 0xFF_FFFF, + }) + .collect(); + self.panel = Some(Panel { corner, lines }); + } + fn clear(&mut self) { + self.panel = None; + } +} diff --git a/crates/horizon-mods/tests/guest/Cargo.toml b/crates/horizon-mods/tests/guest/Cargo.toml new file mode 100644 index 000000000..0e725324a --- /dev/null +++ b/crates/horizon-mods/tests/guest/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "horizon-mods-test-guest" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish = false +description = "A mod that misbehaves on command, for horizon-mods' sandbox tests" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/crates/horizon-mods/tests/guest/src/lib.rs b/crates/horizon-mods/tests/guest/src/lib.rs new file mode 100644 index 000000000..86caf17bf --- /dev/null +++ b/crates/horizon-mods/tests/guest/src/lib.rs @@ -0,0 +1,44 @@ +//! A mod for the runtime's tests: `/spin` loops forever, `/panic` panics, +//! `/grow` asks for a gigabyte, `/hello` chats; `tick` and `frame` do +//! nothing, to measure the cost of a call. +use horizon_mod_sdk::{Mod, Registration, chat}; + +struct Guest { + ticks: u64, +} + +impl Mod for Guest { + fn init() -> Result<(Self, Registration), String> { + let hooks = ["spin", "panic", "grow", "hello"] + .into_iter() + .fold(Registration::new(), Registration::command) + .on_tick() + .on_frame(); + Ok((Guest { ticks: 0 }, hooks)) + } + fn tick(&mut self, _tick: u64) { + self.ticks += 1; + } + fn command(&mut self, name: &str, args: &str) -> Result, String> { + match name { + "spin" => { + let mut n = 0u64; + while std::hint::black_box(n) != u64::MAX { + n = n.wrapping_add(2); + } + Ok(None) + } + "panic" => panic!("asked to"), + "grow" => { + let big = std::hint::black_box(vec![1u8; 1 << 30]); + Ok(Some(format!("{}", big.len()))) + } + _ => { + chat::show(&format!("hello {args} after {} ticks", self.ticks)); + Ok(None) + } + } + } +} + +horizon_mod_sdk::export_mod!(Guest); diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs new file mode 100644 index 000000000..6a0389d55 --- /dev/null +++ b/crates/horizon-mods/tests/sandbox.rs @@ -0,0 +1,243 @@ +//! Loads real mods built with the SDK: the coords-hud example and a guest +//! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`. +use horizon_mods::{ + Clock, Corner, Mods, Output, Package, Player, Snapshot, Status, manifest::componentize, +}; +use std::{ + path::{Path, PathBuf}, + process::Command, + sync::OnceLock, + time::Instant, +}; + +const GUEST_MANIFEST: &str = r#" +id = "test_guest" +name = "Test Guest" +version = "0.1.0" +api = "0.1" +capabilities = ["chat"] +"#; + +/// Builds both mods once and writes their `.hmod` files; returns the folder. +fn mods_dir() -> &'static Path { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let target = root.join("target/mods-test"); + let status = Command::new(env!("CARGO")) + .current_dir(&root) + .args(["build", "--release", "--target", "wasm32-unknown-unknown"]) + .args([ + "-p", + "coords-hud", + "-p", + "horizon-mods-test-guest", + "--target-dir", + ]) + .arg(&target) + .status() + .expect("cargo runs"); + assert!( + status.success(), + "building the test mods needs `rustup target add wasm32-unknown-unknown`" + ); + let built = target.join("wasm32-unknown-unknown/release"); + let dir = target.join("mods"); + std::fs::create_dir_all(&dir).unwrap(); + let example = root.join("crates/horizon-mod-sdk/examples/coords-hud/horizon-mod.toml"); + let mods = [ + ("coords_hud", std::fs::read_to_string(example).unwrap()), + ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), + ]; + for (name, manifest) in mods { + let core = std::fs::read(built.join(format!("{name}.wasm"))).unwrap(); + let hmod = Package::write(&manifest, &componentize(&core).unwrap()).unwrap(); + std::fs::write(dir.join(format!("{name}.hmod")), hmod).unwrap(); + } + dir + }) +} + +fn load(name: &str) -> Mods { + Mods::load(&[mods_dir().join(name)], |_| true, |c| c == "give") +} + +fn player() -> Snapshot { + Snapshot { + player: Some(Player { + x: 12.5, + y: 64.0, + z: -3.25, + yaw: 180.0, + pitch: 0.0, + health: 20.0, + food: 20, + dimension: "minecraft:overworld".into(), + }), + clock: Some(Clock { + game_time: 100, + day_time: 24000 + 6000, + }), + } +} + +#[test] +fn coords_hud_draws_and_answers() { + let mut mods = load("coords_hud.hmod"); + assert_eq!(mods.entries()[0].status, Status::Running); + assert_eq!(mods.commands().collect::>(), ["where", "coords"]); + mods.set_snapshot(player()); + mods.tick(1); + let panel = mods.panels().next().expect("a panel after a tick"); + assert_eq!(panel.corner, Corner::TopLeft); + let lines: Vec<&str> = panel.lines.iter().map(|l| l.text.as_str()).collect(); + assert_eq!( + lines, + [ + "XYZ 12.5 / 64.0 / -3.2", + "Facing North (-Z)", + "Day 2, 12:00" + ] + ); + + assert!(mods.command("where")); + let chat = Output::Chat { + name: "Coordinates HUD".into(), + text: "12, 64, -4 in minecraft:overworld".into(), + }; + assert_eq!(mods.drain(), [chat]); + assert!(mods.command("coords")); + mods.tick(2); + assert_eq!(mods.panels().count(), 0); + let hidden = Output::Feedback { + text: "Coordinates panel hidden".into(), + error: false, + }; + assert_eq!(mods.drain(), [hidden]); + assert!(!mods.command("gamemode creative")); +} + +#[test] +fn off_mods_cost_nothing() { + let mods = Mods::load(&[mods_dir().join("coords_hud.hmod")], |_| false, |_| false); + assert_eq!(mods.entries()[0].status, Status::Off); + assert!(!mods.is_running()); + assert_eq!(mods.commands().count(), 0); +} + +#[test] +fn undeclared_capabilities_are_refused() { + let dir = mods_dir().join("undeclared"); + std::fs::create_dir_all(&dir).unwrap(); + let wasm = Package::read(&mods_dir().join("horizon_mods_test_guest.hmod")) + .unwrap() + .wasm; + let manifest = GUEST_MANIFEST.replace("[\"chat\"]", "[]"); + std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); + std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); + let mods = Mods::load(&[dir], |_| true, |_| false); + let refused = Status::Failed("uses capability chat, missing from horizon-mod.toml".into()); + assert_eq!(mods.entries()[0].status, refused); +} + +#[test] +fn vanilla_commands_win() { + let mods = Mods::load( + &[mods_dir().join("coords_hud.hmod")], + |_| true, + |c| c == "where", + ); + assert_eq!(mods.commands().collect::>(), ["coords"]); +} + +#[test] +fn a_misbehaving_mod_is_stopped_alone() { + for (command, reason) in [ + ("spin", "it took too long (an endless loop?)"), + ("panic", "it crashed (a panic)"), + ("grow", "it crashed (a panic)"), + ] { + let paths = [ + mods_dir().join("coords_hud.hmod"), + mods_dir().join("horizon_mods_test_guest.hmod"), + ]; + let mut mods = Mods::load(&paths, |_| true, |_| false); + let started = Instant::now(); + assert!(mods.command(command)); + assert!(started.elapsed().as_secs() < 5, "/{command} was cut short"); + let stopped = Output::Stopped { + name: "Test Guest".into(), + reason: reason.into(), + }; + assert_eq!(mods.drain(), [stopped], "/{command}"); + assert_eq!(mods.entries()[1].status, Status::Failed(reason.into())); + // The other mod runs on, and the stopped one's command is gone. + assert!(mods.is_running()); + assert!(!mods.command("hello")); + mods.set_snapshot(player()); + mods.tick(1); + assert_eq!(mods.panels().count(), 1); + } +} + +#[test] +fn hot_reload_restarts_a_changed_mod() { + let dir = mods_dir().join("reload"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("guest.hmod"); + std::fs::copy(mods_dir().join("horizon_mods_test_guest.hmod"), &path).unwrap(); + let mut mods = Mods::load(std::slice::from_ref(&path), |_| true, |_| false); + mods.tick(1); + assert!(!mods.reload_changed(|_| false)); + // A rebuild: same bytes, newer file. + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(later) + .unwrap(); + assert!(mods.reload_changed(|_| false)); + assert!(mods.command("hello world")); + let chat = Output::Chat { + name: "Test Guest".into(), + text: "hello world after 0 ticks".into(), + }; + assert_eq!(mods.drain(), [chat]); +} + +/// `cargo test -p horizon-mods --release -- --ignored --nocapture`: the +/// cost of the per-tick and per-frame hooks (docs/mods.md, Performance). +#[test] +#[ignore] +fn hook_overhead() { + let time = |mods: &mut Mods, frame: bool| { + let n = 200_000; + for i in 0..1000 { + mods.tick(i); + } + let started = Instant::now(); + for i in 0..n { + if frame { + mods.frame(0.016); + } else { + mods.tick(i); + } + } + started.elapsed().as_nanos() as f64 / n as f64 + }; + let mut guest = load("horizon_mods_test_guest.hmod"); + let mut hud = load("coords_hud.hmod"); + hud.set_snapshot(player()); + let mut none = Mods::default(); + println!("no mods, tick: {:8.1} ns", time(&mut none, false)); + println!("empty tick hook: {:8.1} ns", time(&mut guest, false)); + println!("empty frame hook: {:8.1} ns", time(&mut guest, true)); + println!("coords-hud tick hook: {:8.1} ns", time(&mut hud, false)); + let started = Instant::now(); + let _ = load("coords_hud.hmod"); + println!( + "load coords-hud: {:8.1} ms", + started.elapsed().as_secs_f64() * 1000.0 + ); +}