Horizon mods runtime: load sandboxed WebAssembly components with wasmtime

Manifest and .hmod reading, capability checks against the component's imports,
fuel and memory limits per call, a trapping mod stopped alone, hot reload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 14:01:57 +02:00
parent 670e055f4a
commit b3906d803d
10 changed files with 1890 additions and 17 deletions
+1 -1
View File
@@ -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:
Generated
+789 -15
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -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]
+29
View File
@@ -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
+14
View File
@@ -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::*;
+255
View File
@@ -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<String>,
/// The API version the mod was built for: `0.1`.
pub api: String,
#[serde(default)]
pub side: Side,
#[serde(default)]
pub capabilities: Vec<Capability>,
}
#[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 <this>".
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<Option<Capability>, 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<Self, String> {
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<Item = &'a str>,
) -> 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<u8>,
}
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<Self, String> {
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<Vec<u8>, 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<Vec<u8>, 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<Vec<u8>, 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();
}
}
+498
View File
@@ -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<Player>,
pub clock: Option<Clock>,
}
/// 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<Line>,
}
#[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<Manifest>,
pub status: Status,
/// The mod's average time per call of its busiest hook.
pub cost: Duration,
run: Option<Running>,
modified: Option<SystemTime>,
}
struct Running {
store: Store<State>,
exports: HorizonMod,
hooks: Registration,
}
struct State {
name: String,
id: String,
snapshot: Arc<Snapshot>,
out: Vec<Output>,
panel: Option<Panel>,
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<State>)>,
entries: Vec<Entry>,
snapshot: Arc<Snapshot>,
out: Vec<Output>,
}
/// The `.hmod` files and mod folders in `dir`, by name.
pub fn find(dir: &Path) -> Vec<PathBuf> {
let Ok(read) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut found: Vec<PathBuf> = 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<State>), 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::<State, HasSelf<State>>(&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<Running, String> {
let m = &package.manifest;
if m.side == Side::Server {
return Err("server mods do not run yet".into());
}
let taken: Vec<String> = 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<String> = 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<State>) -> 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<R>(
&mut self,
i: usize,
fuel: u64,
f: impl FnOnce(&HorizonMod, &mut Store<State>) -> wasmtime::Result<R>,
) -> Option<R> {
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<usize> {
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<Item = &str> {
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<Item = &Panel> {
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<Output> {
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<SystemTime> {
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::<Trap>() {
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<Player> {
self.snapshot.player.clone()
}
fn get_clock(&mut self) -> Option<Clock> {
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<Line>) {
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;
}
}
@@ -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
@@ -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<Option<String>, 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);
+243
View File
@@ -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<PathBuf> = 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::<Vec<_>>(), ["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::<Vec<_>>(), ["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
);
}