Skip to main content

warpline_core/
error.rs

1//! The crate's error types.
2
3use crate::Usage;
4
5/// General error for [`Runtime`](crate::Runtime) construction, GC and module
6/// loading. Non-exhaustive.
7#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum Error {
10    #[error("io error: {0}")]
11    Io(#[from] std::io::Error),
12    #[error("wasmtime error: {0}")]
13    Wasmtime(#[from] wasmtime::Error),
14    /// On-disk module state is missing or malformed (bad pointer file, no
15    /// `.cwasm` and no source `.wasm` for a digest, ...).
16    #[error("corrupt or missing module state: {0}")]
17    Corrupt(String),
18    /// A module the caller named (by digest) is not in the registry.
19    #[error("not found: {0}")]
20    NotFound(String),
21    /// A [`RuntimeConfig`](crate::RuntimeConfig) value is out of range.
22    #[error("invalid configuration: {0}")]
23    Config(&'static str),
24    /// A background task panicked or a client could not be built.
25    #[error("internal error: {0}")]
26    Internal(String),
27}
28
29/// Why [`Runtime::stage`](crate::Runtime::stage) or
30/// [`Runtime::activate`](crate::Runtime::activate) failed. Non-exhaustive.
31#[derive(Debug, thiserror::Error)]
32#[non_exhaustive]
33pub enum PublishError {
34    /// Tenant or function name fails [`valid_name`](crate::valid_name).
35    #[error("invalid tenant or function name")]
36    InvalidName,
37    /// The bytes are not a valid WebAssembly component.
38    #[error("not a valid wasm component")]
39    Compile(#[source] wasmtime::Error),
40    /// The component compiles but does not fit the warpline handler world:
41    /// a missing `handle` export or an import the host does not provide.
42    #[error("component does not match the warpline handler world")]
43    ImportMismatch(#[source] wasmtime::Error),
44    #[error("io error: {0}")]
45    Io(#[from] std::io::Error),
46    /// The registry state was inconsistent or a background task failed; the
47    /// underlying [`Error`] says which.
48    #[error("registry error")]
49    Registry(#[source] Error),
50}
51
52/// Why [`Runtime::invoke`](crate::Runtime::invoke) failed. Non-exhaustive.
53///
54/// Variants that carry a [`Usage`] failed after the guest started running;
55/// those invocations were reported to the configured
56/// [`MeterSink`](crate::MeterSink). The others were rejected before the
57/// guest ran and were not metered.
58#[derive(Debug, thiserror::Error)]
59#[non_exhaustive]
60pub enum InvokeError {
61    #[error("invalid tenant or function name")]
62    InvalidName,
63    #[error("no module published for this function")]
64    NotFound,
65    /// `limits.cpu_budget_ms` or `limits.mem_cap_bytes` is outside the valid
66    /// range (possible only if the fields were mutated after `Limits::new`).
67    #[error("invalid limits: {0}")]
68    InvalidLimits(#[from] crate::ConfigError),
69    /// The host's memory budget cannot admit this invocation right now (or
70    /// the tenant's memory cap alone exceeds the whole budget).
71    #[error("host is at capacity")]
72    Overloaded,
73    /// The tenant already has `max_in_flight_per_tenant` invocations running.
74    #[error("tenant has too many invocations in flight")]
75    TenantBusy,
76    #[error("cpu budget exceeded ({budget_ms} ms)")]
77    CpuBudgetExceeded { usage: Usage, budget_ms: u64 },
78    #[error("memory cap exceeded (peak {} bytes, cap {cap_bytes} bytes)", usage.mem_peak_bytes)]
79    MemoryCapExceeded { usage: Usage, cap_bytes: usize },
80    #[error("wall-clock timeout")]
81    WallClockTimeout { usage: Usage },
82    #[error("output exceeds the {limit} byte limit")]
83    OutputTooLarge { usage: Usage, limit: usize },
84    #[error("guest trapped: {source}")]
85    GuestTrap {
86        usage: Usage,
87        #[source]
88        source: wasmtime::Error,
89    },
90    /// The module could not be loaded (corrupt registry state, compile
91    /// failure of the stored source, ...).
92    #[error("failed to load module: {0}")]
93    Load(#[source] Error),
94}
95
96impl InvokeError {
97    /// What the guest used before failing; `None` when it never ran.
98    pub fn usage(&self) -> Option<Usage> {
99        match self {
100            Self::CpuBudgetExceeded { usage, .. }
101            | Self::MemoryCapExceeded { usage, .. }
102            | Self::WallClockTimeout { usage }
103            | Self::OutputTooLarge { usage, .. }
104            | Self::GuestTrap { usage, .. } => Some(*usage),
105            _ => None,
106        }
107    }
108
109    /// A suitable HTTP status code: 400 invalid name / invalid limits, 404 not found, 503
110    /// overloaded, 429 tenant busy, 408 cpu budget / wall clock, 507 memory
111    /// cap, 502 output too large, 500 guest trap / load failure.
112    pub fn http_status(&self) -> u16 {
113        match self {
114            Self::InvalidName | Self::InvalidLimits(_) => 400,
115            Self::NotFound => 404,
116            Self::Overloaded => 503,
117            Self::TenantBusy => 429,
118            Self::CpuBudgetExceeded { .. } | Self::WallClockTimeout { .. } => 408,
119            Self::MemoryCapExceeded { .. } => 507,
120            Self::OutputTooLarge { .. } => 502,
121            Self::GuestTrap { .. } | Self::Load(_) => 500,
122        }
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn http_status_table() {
132        let u = Usage::new(0, 0, 0);
133        let trap = || wasmtime::Error::msg("trap");
134        let cases: Vec<(InvokeError, u16)> = vec![
135            (InvokeError::InvalidName, 400),
136            (InvokeError::NotFound, 404),
137            (
138                InvokeError::InvalidLimits(crate::ConfigError::CpuBudgetRange),
139                400,
140            ),
141            (InvokeError::Overloaded, 503),
142            (InvokeError::TenantBusy, 429),
143            (
144                InvokeError::CpuBudgetExceeded {
145                    usage: u,
146                    budget_ms: 1,
147                },
148                408,
149            ),
150            (InvokeError::WallClockTimeout { usage: u }, 408),
151            (
152                InvokeError::MemoryCapExceeded {
153                    usage: u,
154                    cap_bytes: 1,
155                },
156                507,
157            ),
158            (InvokeError::OutputTooLarge { usage: u, limit: 1 }, 502),
159            (
160                InvokeError::GuestTrap {
161                    usage: u,
162                    source: trap(),
163                },
164                500,
165            ),
166            (InvokeError::Load(Error::Corrupt("x".into())), 500),
167        ];
168        for (err, status) in cases {
169            assert_eq!(err.http_status(), status, "{err}");
170        }
171    }
172}