use std::collections::HashMap;
use std::sync::Mutex;
use wasmtime::{
Config, Engine, Instance, Linker, Module, Store, StoreLimits, StoreLimitsBuilder, TypedFunc,
};
use crate::corroborate::FunctionRun;
use crate::error::{QueryError, QueryResult};
use crate::functions::CtxHostState;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RunLimits {
pub max_fuel: u64,
pub max_mem_mb: u32,
}
impl Default for RunLimits {
fn default() -> Self {
Self {
max_fuel: 100_000_000,
max_mem_mb: 64,
}
}
}
#[derive(Clone, Debug)]
pub struct Execution {
pub output: Vec<u8>,
pub run: FunctionRun,
}
struct HostState {
limits: StoreLimits,
}
const MODULE_CACHE_CAP: usize = 64;
pub struct FunctionRuntime {
engine: Engine,
modules: Mutex<HashMap<[u8; 32], Module>>,
ctx_linker: Linker<CtxHostState>,
}
impl FunctionRuntime {
pub(crate) fn engine(&self) -> &Engine {
&self.engine
}
pub fn new() -> QueryResult<Self> {
let mut config = Config::new();
config.consume_fuel(true);
config.wasm_backtrace(false);
let engine = Engine::new(&config).map_err(|e| QueryError::Engine(e.to_string()))?;
let ctx_linker = crate::functions::ctx_linker(&engine)?;
Ok(Self {
engine,
modules: Mutex::new(HashMap::new()),
ctx_linker,
})
}
pub(crate) fn ctx_linker(&self) -> &Linker<CtxHostState> {
&self.ctx_linker
}
pub(crate) fn module(
&self,
workload_hash: &[u8; 32],
module_wasm: &[u8],
) -> QueryResult<Module> {
let mut modules = self.modules.lock().unwrap_or_else(|p| p.into_inner());
if let Some(module) = modules.get(workload_hash) {
return Ok(module.clone());
}
let module = Module::new(&self.engine, module_wasm)
.map_err(|e| QueryError::Compile(e.to_string()))?;
if modules.len() >= MODULE_CACHE_CAP {
modules.clear();
}
modules.insert(*workload_hash, module.clone());
Ok(module)
}
pub fn run(
&self,
module_wasm: &[u8],
input: &[u8],
limits: &RunLimits,
) -> QueryResult<Execution> {
self.run_prehashed(&hash(module_wasm), module_wasm, input, None, limits)
}
pub fn run_prehashed(
&self,
workload_hash: &[u8; 32],
module_wasm: &[u8],
input: &[u8],
input_digest: Option<[u8; 32]>,
limits: &RunLimits,
) -> QueryResult<Execution> {
let workload_hash = *workload_hash;
let input_digest = input_digest.unwrap_or_else(|| hash(input));
let module = self.module(&workload_hash, module_wasm)?;
let max_bytes = limits.max_mem_mb as usize * 1024 * 1024;
let mut store = Store::new(
&self.engine,
HostState {
limits: StoreLimitsBuilder::new().memory_size(max_bytes).build(),
},
);
store.limiter(|h| &mut h.limits);
store
.set_fuel(limits.max_fuel)
.map_err(|e| QueryError::Fuel(e.to_string()))?;
let instance = Instance::new(&mut store, &module, &[])
.map_err(|e| QueryError::Instantiate(e.to_string()))?;
let memory = instance
.get_memory(&mut store, "memory")
.ok_or(QueryError::MissingExport("memory"))?;
let alloc: TypedFunc<i32, i32> = instance
.get_typed_func(&mut store, "alloc")
.map_err(|_| QueryError::MissingExport("alloc"))?;
let run: TypedFunc<(i32, i32), i64> = instance
.get_typed_func(&mut store, "run")
.map_err(|_| QueryError::MissingExport("run"))?;
let in_len =
i32::try_from(input.len()).map_err(|_| QueryError::Abi("input too large".into()))?;
let in_ptr = alloc
.call(&mut store, in_len)
.map_err(|e| QueryError::Trap(e.to_string()))?;
memory
.write(&mut store, in_ptr as usize, input)
.map_err(|e| QueryError::Abi(format!("input write: {e}")))?;
let packed = run
.call(&mut store, (in_ptr, in_len))
.map_err(|e| QueryError::Trap(e.to_string()))?;
let packed = packed as u64;
let out_ptr = (packed >> 32) as usize;
let out_len = (packed & 0xFFFF_FFFF) as usize;
let output = crate::functions::read_output(memory.data(&store), out_ptr, out_len)?;
let output_digest = hash(&output);
let remaining = store.get_fuel().map_err(|e| QueryError::Fuel(e.to_string()))?;
let fuel_used = limits.max_fuel.saturating_sub(remaining);
let mem_peak_mb = (memory.data_size(&store) / (1024 * 1024)) as u32;
Ok(Execution {
output,
run: FunctionRun {
workload_hash,
input_digest,
output_digest,
fuel_used,
mem_peak_mb,
},
})
}
}
fn hash(bytes: &[u8]) -> [u8; 32] {
*blake3::hash(bytes).as_bytes()
}