Lines
83.33 %
Functions
100 %
Branches
//! Runtime error types and the classification of wasmtime errors into them.
use thiserror::Error;
use super::{EvalValue, HostCondition, ScriptRaise};
#[derive(Debug, Error, PartialEq)]
pub enum EngineError {
#[error("engine config rejected: {0}")]
Config(String),
#[error("module cache lock poisoned")]
CachePoisoned,
#[error("module compilation failed: {0}")]
Compile(String),
#[error("module instantiation failed: {0}")]
Instantiate(String),
#[error("fuel configuration failed: {0}")]
Fuel(String),
#[error("missing export `{0}`")]
MissingExport(String),
#[error("fuel exhausted before completion")]
OutOfFuel,
#[error("epoch deadline reached before completion")]
EpochInterrupt,
#[error("store limit of fibers has been reached")]
FiberLimit,
/// A structured error raised in-guest, surfaced via the `__nomi_raise`
/// host fn (a [`ScriptRaise`] error). Two
/// sources converge here (ADR-0026): a script `(error 'code "msg")`, and
/// an engine error like a commodity mismatch — both `throw $nomi_error`
/// in-guest, and the boundary wrapper around each host-invoked body
/// catches an uncaught throw and bridges it to `__nomi_raise`. The
/// classifier lifts the [`ScriptRaise`] and surfaces the code symbol
/// (`COMMODITY-MISMATCH`, a script's own symbol, …) onto the wire
/// envelope's `:code` slot. Codes are reader-folded (upper-cased)
/// symbols, not free-form strings. `detail` is the detail value.
#[error("script raised {code}: {message}")]
ScriptRaised {
code: String,
message: String,
detail: Option<EvalValue>,
},
/// A thrown [`HostCondition`] restored at the rpc boundary; `code` is the
/// lowercase wire symbol, not reader-folded.
#[error("{message}")]
HostCondition {
#[error("execution trapped: {0}")]
Trap(String),
}
/// wasmtime's untyped error for a store past its fiber cap (64 live fibers),
/// which nested async host calls such as `catch-each` reach.
const FIBER_LIMIT_MESSAGE: &str = "store limit of fibers has been reached";
/// Classifies a [`wasmtime::Error`] thrown during execution into a typed
/// [`EngineError`]. Order: [`wasmtime::Trap`] (fuel/epoch), a
/// [`HostCondition`] or [`ScriptRaise`] in the chain, then the fiber cap; the rest falls
/// through as `Trap(message)`.
pub fn classify_runtime_error(err: &wasmtime::Error) -> EngineError {
if let Some(trap) = err.downcast_ref::<wasmtime::Trap>() {
match *trap {
wasmtime::Trap::OutOfFuel => return EngineError::OutOfFuel,
wasmtime::Trap::Interrupt => return EngineError::EpochInterrupt,
_ => {}
if let Some(condition) = err
.chain()
.find_map(|cause| cause.downcast_ref::<HostCondition>())
{
return EngineError::ScriptRaised {
code: condition.code.to_uppercase(),
message: condition.message.clone(),
detail: condition.detail.clone(),
};
if let Some(raise) = err
.find_map(|cause| cause.downcast_ref::<ScriptRaise>())
code: raise.code.clone(),
message: raise.message.clone(),
detail: raise.detail.clone(),
if err
.any(|cause| cause.to_string() == FIBER_LIMIT_MESSAGE)
return EngineError::FiberLimit;
// Walk the error chain so host-fn `wasmtime::Error::msg("...")` causes
// (e.g. "get-commodity: invalid uuid '...'") surface alongside the
// wasmtime wrapper's "error while executing at wasm backtrace" header.
let mut combined = err.to_string();
for cause in err.chain().skip(1) {
combined.push_str(": ");
combined.push_str(&cause.to_string());
EngineError::Trap(combined)
/// Maps an `EngineError` to the `(code, message)` pair scripts and
/// batch consumers see when a script fails — code is a kebab-case
/// symbol (matching the wire envelope's `:code` slot for catch-each
/// cells and `server::script` per-tx reports), message is the
/// engine's own diagnostic string.
///
/// Engine-bound deadlines (`OutOfFuel`, `EpochInterrupt`) also have a
/// mapping here so callers that *do* want to surface them to scripts
/// (batch runners that don't care about catch-each's "engine deadlines
/// aren't catchable" rule) can. catch-each filters the deadlines out
/// before reaching this mapper. A `HostCondition` or `ScriptRaised` maps to
/// `(code, message)`; its detail is dropped, so catch-each cells carry no detail.
#[must_use]
pub fn err_code_and_message(err: &EngineError) -> (String, String) {
match err {
EngineError::ScriptRaised { code, message, .. } => (code.clone(), message.clone()),
EngineError::HostCondition { code, message, .. } => (code.clone(), message.clone()),
EngineError::Trap(msg) => ("runtime".to_string(), msg.clone()),
EngineError::Compile(msg) => ("compile".to_string(), msg.clone()),
EngineError::Instantiate(msg) => ("runtime".to_string(), msg.clone()),
EngineError::Fuel(msg) => ("runtime".to_string(), msg.clone()),
EngineError::MissingExport(msg) => ("runtime".to_string(), msg.clone()),
EngineError::Config(msg) => ("runtime".to_string(), msg.clone()),
EngineError::CachePoisoned => (
"runtime".to_string(),
"module cache lock poisoned".to_string(),
),
EngineError::OutOfFuel => ("runtime".to_string(), "fuel exhausted".to_string()),
EngineError::EpochInterrupt => ("runtime".to_string(), "epoch deadline".to_string()),
EngineError::FiberLimit => ("runtime".to_string(), "fiber limit reached".to_string()),