1
//! Runtime error types and the classification of wasmtime errors into them.
2

            
3
use thiserror::Error;
4

            
5
use super::{EvalValue, HostCondition, ScriptRaise};
6

            
7
#[derive(Debug, Error, PartialEq)]
8
pub 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.
57
const 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)`.
63
146513
pub fn classify_runtime_error(err: &wasmtime::Error) -> EngineError {
64
146513
    if let Some(trap) = err.downcast_ref::<wasmtime::Trap>() {
65
13114
        match *trap {
66
6273
            wasmtime::Trap::OutOfFuel => return EngineError::OutOfFuel,
67
3041
            wasmtime::Trap::Interrupt => return EngineError::EpochInterrupt,
68
3800
            _ => {}
69
        }
70
133399
    }
71
137199
    if let Some(condition) = err
72
137199
        .chain()
73
273248
        .find_map(|cause| cause.downcast_ref::<HostCondition>())
74
    {
75
765
        return EngineError::ScriptRaised {
76
765
            code: condition.code.to_uppercase(),
77
765
            message: condition.message.clone(),
78
765
            detail: condition.detail.clone(),
79
765
        };
80
136434
    }
81
136434
    if let Some(raise) = err
82
136434
        .chain()
83
271911
        .find_map(|cause| cause.downcast_ref::<ScriptRaise>())
84
    {
85
118948
        return EngineError::ScriptRaised {
86
118948
            code: raise.code.clone(),
87
118948
            message: raise.message.clone(),
88
118948
            detail: raise.detail.clone(),
89
118948
        };
90
17486
    }
91
17486
    if err
92
17486
        .chain()
93
34208
        .any(|cause| cause.to_string() == FIBER_LIMIT_MESSAGE)
94
    {
95
12542
        return EngineError::FiberLimit;
96
4944
    }
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
4944
    let mut combined = err.to_string();
101
4944
    for cause in err.chain().skip(1) {
102
4371
        combined.push_str(": ");
103
4371
        combined.push_str(&cause.to_string());
104
    }
105
4944
    EngineError::Trap(combined)
106
146513
}
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]
121
53776
pub fn err_code_and_message(err: &EngineError) -> (String, String) {
122
53776
    match err {
123
53203
        EngineError::ScriptRaised { code, message, .. } => (code.clone(), message.clone()),
124
        EngineError::HostCondition { code, message, .. } => (code.clone(), message.clone()),
125
1
        EngineError::Trap(msg) => ("runtime".to_string(), msg.clone()),
126
380
        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
1
        EngineError::OutOfFuel => ("runtime".to_string(), "fuel exhausted".to_string()),
136
190
        EngineError::EpochInterrupt => ("runtime".to_string(), "epoch deadline".to_string()),
137
1
        EngineError::FiberLimit => ("runtime".to_string(), "fiber limit reached".to_string()),
138
    }
139
53776
}