use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use unitype_core::check::CheckedWorkspace;
use unitype_core::ir::Type;
use unitype_core::value::Value;
use wasmtime::{Engine, Instance, Module, Store};
use crate::environment::{Environment, Reach};
use crate::error::ExecError;
use crate::implementation::Implementation;
const MEMORY: &str = "memory";
const ALLOC: &str = "unitype_alloc";
const INVOKE: &str = "unitype_invoke";
pub const DEFAULT_FUEL: u64 = 1_000_000_000;
pub struct WasmHost {
engine: Engine,
compiled: Mutex<HashMap<PathBuf, Module>>,
}
impl Default for WasmHost {
fn default() -> Self {
Self::new()
}
}
impl WasmHost {
pub fn new() -> Self {
let mut config = wasmtime::Config::new();
config.consume_fuel(true);
Self {
engine: Engine::new(&config).expect("a default engine configuration is valid"),
compiled: Mutex::new(HashMap::new()),
}
}
pub async fn invoke(
&self,
ws: &CheckedWorkspace,
environment: &Environment,
implementation: &Implementation,
args: Vec<Value>,
params: &[Type],
expected: &Type,
) -> Result<Value, ExecError> {
let Reach::Wasm { module, fuel } = &environment.reach else {
return Err(ExecError::Unreachable {
environment: environment.id.to_string(),
detail: "this is not a WebAssembly environment".into(),
});
};
let compiled = self.module(module, &environment.id)?;
let body = crate::subprocess::request_line(ws, implementation, &args, params)?;
let budget = fuel.unwrap_or(DEFAULT_FUEL);
let answer = self.exchange(&compiled, &body, budget, implementation)?;
crate::subprocess::read_answer(ws, implementation, &answer, expected)
}
fn module(&self, path: &Path, environment: &unitype_core::Ident) -> Result<Module, ExecError> {
let mut compiled = self
.compiled
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(found) = compiled.get(path) {
return Ok(found.clone());
}
let module =
Module::from_file(&self.engine, path).map_err(|source| ExecError::Unreachable {
environment: environment.to_string(),
detail: format!("could not load {}: {source}", path.display()),
})?;
compiled.insert(path.to_path_buf(), module.clone());
Ok(module)
}
fn exchange(
&self,
module: &Module,
body: &[u8],
fuel: u64,
implementation: &Implementation,
) -> Result<String, ExecError> {
let id = || implementation.id.to_string();
let protocol = |detail: String| ExecError::Protocol { id: id(), detail };
let mut store = Store::new(&self.engine, ());
store
.set_fuel(fuel)
.map_err(|e| protocol(format!("could not meter the guest: {e}")))?;
let instance = Instance::new(&mut store, module, &[])
.map_err(|e| protocol(format!("the module would not start: {e}")))?;
let memory = instance
.get_memory(&mut store, MEMORY)
.ok_or_else(|| protocol(format!("it exports no `{MEMORY}`")))?;
let alloc = instance
.get_typed_func::<i32, i32>(&mut store, ALLOC)
.map_err(|_| protocol(format!("it exports no `{ALLOC}(i32) -> i32`")))?;
let invoke = instance
.get_typed_func::<(i32, i32), i64>(&mut store, INVOKE)
.map_err(|_| protocol(format!("it exports no `{INVOKE}(i32, i32) -> i64`")))?;
let len = i32::try_from(body.len())
.map_err(|_| protocol("the request is larger than a guest can address".into()))?;
let at = alloc
.call(&mut store, len)
.map_err(|e| self.trapped(e, &store, implementation, fuel, "asking for room"))?;
memory
.write(&mut store, at as usize, body)
.map_err(|e| protocol(format!("the room it gave back is not usable: {e}")))?;
let packed = invoke
.call(&mut store, (at, len))
.map_err(|e| self.trapped(e, &store, implementation, fuel, "running"))?;
let out_at = ((packed >> 32) & 0xFFFF_FFFF) as usize;
let out_len = (packed & 0xFFFF_FFFF) as usize;
let data = memory.data(&store);
let end = out_at
.checked_add(out_len)
.filter(|end| *end <= data.len())
.ok_or_else(|| {
protocol(format!(
"it pointed its answer at {out_at}..{}, which is outside its own memory",
out_at.saturating_add(out_len)
))
})?;
String::from_utf8(data[out_at..end].to_vec())
.map_err(|e| protocol(format!("its answer is not text: {e}")))
}
fn trapped(
&self,
error: wasmtime::Error,
store: &Store<()>,
implementation: &Implementation,
budget: u64,
doing: &str,
) -> ExecError {
if store.get_fuel().is_ok_and(|left| left == 0) {
return ExecError::Exhausted {
id: implementation.id.to_string(),
budget,
};
}
ExecError::Failed {
id: implementation.id.to_string(),
message: format!("it stopped while {doing}: {error}"),
}
}
}