Skip to main content

scripting/runtime/
error.rs

1//! Runtime error types and the classification of wasmtime errors into them.
2
3use thiserror::Error;
4
5use super::{EvalValue, HostCondition, ScriptRaise};
6
7#[derive(Debug, Error, PartialEq)]
8pub enum EngineError {
9    #[error("engine config rejected: {0}")]
10    Config(String),
11    #[error("module cache lock poisoned")]
12    CachePoisoned,
13    #[error("module compilation failed: {0}")]
14    Compile(String),
15    #[error("module instantiation failed: {0}")]
16    Instantiate(String),
17    #[error("fuel configuration failed: {0}")]
18    Fuel(String),
19    #[error("missing export `{0}`")]
20    MissingExport(String),
21    #[error("fuel exhausted before completion")]
22    OutOfFuel,
23    #[error("epoch deadline reached before completion")]
24    EpochInterrupt,
25    #[error("store limit of fibers has been reached")]
26    FiberLimit,
27    /// A structured error raised in-guest, surfaced via the `__nomi_raise`
28    /// host fn (a [`ScriptRaise`] error). Two
29    /// sources converge here (ADR-0026): a script `(error 'code "msg")`, and
30    /// an engine error like a commodity mismatch — both `throw $nomi_error`
31    /// in-guest, and the boundary wrapper around each host-invoked body
32    /// catches an uncaught throw and bridges it to `__nomi_raise`. The
33    /// classifier lifts the [`ScriptRaise`] and surfaces the code symbol
34    /// (`COMMODITY-MISMATCH`, a script's own symbol, …) onto the wire
35    /// envelope's `:code` slot. Codes are reader-folded (upper-cased)
36    /// symbols, not free-form strings. `detail` is the detail value.
37    #[error("script raised {code}: {message}")]
38    ScriptRaised {
39        code: String,
40        message: String,
41        detail: Option<EvalValue>,
42    },
43    /// A thrown [`HostCondition`] restored at the rpc boundary; `code` is the
44    /// lowercase wire symbol, not reader-folded.
45    #[error("{message}")]
46    HostCondition {
47        code: String,
48        message: String,
49        detail: Option<EvalValue>,
50    },
51    #[error("execution trapped: {0}")]
52    Trap(String),
53}
54
55/// wasmtime's untyped error for a store past its fiber cap (64 live fibers),
56/// which nested async host calls such as `catch-each` reach.
57const FIBER_LIMIT_MESSAGE: &str = "store limit of fibers has been reached";
58
59/// Classifies a [`wasmtime::Error`] thrown during execution into a typed
60/// [`EngineError`]. Order: [`wasmtime::Trap`] (fuel/epoch), a
61/// [`HostCondition`] or [`ScriptRaise`] in the chain, then the fiber cap; the rest falls
62/// through as `Trap(message)`.
63pub fn classify_runtime_error(err: &wasmtime::Error) -> EngineError {
64    if let Some(trap) = err.downcast_ref::<wasmtime::Trap>() {
65        match *trap {
66            wasmtime::Trap::OutOfFuel => return EngineError::OutOfFuel,
67            wasmtime::Trap::Interrupt => return EngineError::EpochInterrupt,
68            _ => {}
69        }
70    }
71    if let Some(condition) = err
72        .chain()
73        .find_map(|cause| cause.downcast_ref::<HostCondition>())
74    {
75        return EngineError::ScriptRaised {
76            code: condition.code.to_uppercase(),
77            message: condition.message.clone(),
78            detail: condition.detail.clone(),
79        };
80    }
81    if let Some(raise) = err
82        .chain()
83        .find_map(|cause| cause.downcast_ref::<ScriptRaise>())
84    {
85        return EngineError::ScriptRaised {
86            code: raise.code.clone(),
87            message: raise.message.clone(),
88            detail: raise.detail.clone(),
89        };
90    }
91    if err
92        .chain()
93        .any(|cause| cause.to_string() == FIBER_LIMIT_MESSAGE)
94    {
95        return EngineError::FiberLimit;
96    }
97    // Walk the error chain so host-fn `wasmtime::Error::msg("...")` causes
98    // (e.g. "get-commodity: invalid uuid '...'") surface alongside the
99    // wasmtime wrapper's "error while executing at wasm backtrace" header.
100    let mut combined = err.to_string();
101    for cause in err.chain().skip(1) {
102        combined.push_str(": ");
103        combined.push_str(&cause.to_string());
104    }
105    EngineError::Trap(combined)
106}
107
108/// Maps an `EngineError` to the `(code, message)` pair scripts and
109/// batch consumers see when a script fails — code is a kebab-case
110/// symbol (matching the wire envelope's `:code` slot for catch-each
111/// cells and `server::script` per-tx reports), message is the
112/// engine's own diagnostic string.
113///
114/// Engine-bound deadlines (`OutOfFuel`, `EpochInterrupt`) also have a
115/// mapping here so callers that *do* want to surface them to scripts
116/// (batch runners that don't care about catch-each's "engine deadlines
117/// aren't catchable" rule) can. catch-each filters the deadlines out
118/// before reaching this mapper. A `HostCondition` or `ScriptRaised` maps to
119/// `(code, message)`; its detail is dropped, so catch-each cells carry no detail.
120#[must_use]
121pub fn err_code_and_message(err: &EngineError) -> (String, String) {
122    match err {
123        EngineError::ScriptRaised { code, message, .. } => (code.clone(), message.clone()),
124        EngineError::HostCondition { code, message, .. } => (code.clone(), message.clone()),
125        EngineError::Trap(msg) => ("runtime".to_string(), msg.clone()),
126        EngineError::Compile(msg) => ("compile".to_string(), msg.clone()),
127        EngineError::Instantiate(msg) => ("runtime".to_string(), msg.clone()),
128        EngineError::Fuel(msg) => ("runtime".to_string(), msg.clone()),
129        EngineError::MissingExport(msg) => ("runtime".to_string(), msg.clone()),
130        EngineError::Config(msg) => ("runtime".to_string(), msg.clone()),
131        EngineError::CachePoisoned => (
132            "runtime".to_string(),
133            "module cache lock poisoned".to_string(),
134        ),
135        EngineError::OutOfFuel => ("runtime".to_string(), "fuel exhausted".to_string()),
136        EngineError::EpochInterrupt => ("runtime".to_string(), "epoch deadline".to_string()),
137        EngineError::FiberLimit => ("runtime".to_string(), "fiber limit reached".to_string()),
138    }
139}