ruso_runtime/runtime/error.rs
1//! The error type every fallible runtime operation returns.
2
3use thiserror::Error;
4
5use crate::contract::QualifiedMatch;
6use crate::runtime::binary::BytecodeError;
7
8/// An error that aborts execution. Most variants carry a message; the
9/// `#[from]` variants wrap lower-level errors (bytecode decode, HTTP, I/O,
10/// regex). A failed `match` does not produce one of these — only `assert`,
11/// `fail`, and genuine transport/decoding failures do.
12#[derive(Debug, Error)]
13pub enum RuntimeError {
14 /// The `.rbc` input could not be decoded or failed validation.
15 #[error("bytecode: {0}")]
16 Bytecode(#[from] BytecodeError),
17
18 /// An instruction referenced a probe name the program does not define.
19 #[error("unknown request or probe: {0}")]
20 UnknownTarget(String),
21
22 /// An HTTP-only operation (`extract`, a header matcher) was aimed at a
23 /// DNS, TCP, or UDP probe.
24 #[error("request {name} is not HTTP (dns/tcp probe)")]
25 WrongProbeKind {
26 /// Name of the probe that is not HTTP.
27 name: String,
28 },
29
30 /// A `match` could not be evaluated at all — not the same as a matcher
31 /// that evaluated to false, which simply clears `matched`.
32 #[error("match failed: {0}")]
33 MatchFailed(String),
34
35 /// An `assert` evaluated to false and aborted the script.
36 #[error("assertion failed: {0}")]
37 AssertFailed(String),
38
39 /// An `extract` found nothing to bind: the regex did not match, or the
40 /// named header was absent.
41 #[error("extract failed for variable {name}: {reason}")]
42 ExtractFailed {
43 /// The variable that was to be bound.
44 name: String,
45 /// Why nothing could be extracted.
46 reason: String,
47 },
48
49 /// Internal control-flow signal (`break`, `continue`, `stop`, `exit`)
50 /// travelling as an error. The executor consumes these; they never reach
51 /// a caller.
52 #[error("flow control: {0}")]
53 Flow(String),
54
55 /// A duration literal (`500ms`, `2s`) could not be parsed.
56 #[error("invalid duration: {0}")]
57 InvalidDuration(String),
58
59 /// The HTTP client failed: DNS, connect, TLS, timeout, or body decode.
60 /// Call [`RuntimeError::full_message`] for the underlying cause.
61 #[error("http error: {0}")]
62 Http(#[from] reqwest::Error),
63
64 /// A socket operation failed (TCP/UDP connect, read, or write).
65 #[error("io error: {0}")]
66 Io(#[from] std::io::Error),
67
68 /// A regex in a matcher, `extract`, or `evidence` rule failed to compile.
69 #[error("regex error: {0}")]
70 Regex(#[from] regex::Error),
71
72 /// Anything that does not fit the variants above; carries its own message.
73 #[error("{0}")]
74 Other(String),
75}
76
77impl RuntimeError {
78 /// Build a [`RuntimeError::MatchFailed`] that names the matcher that could
79 /// not be evaluated alongside `detail`.
80 pub fn match_failed(matcher: &QualifiedMatch, detail: impl Into<String>) -> Self {
81 Self::MatchFailed(format!("{matcher:?}: {}", detail.into()))
82 }
83
84 /// Build a [`RuntimeError::AssertFailed`] that names the assertion that
85 /// did not hold alongside `detail`.
86 pub fn assert_failed(matcher: &QualifiedMatch, detail: impl Into<String>) -> Self {
87 Self::AssertFailed(format!("{matcher:?}: {}", detail.into()))
88 }
89
90 /// The complete error message, including every underlying cause.
91 ///
92 /// `thiserror`'s `Display` renders only this error's own message. For the
93 /// wrapped HTTP and I/O variants the real reason — a rejected TLS
94 /// certificate, a connection reset, a response body that failed to decode —
95 /// lives in the [`source`](std::error::Error::source) chain and would
96 /// otherwise be dropped, leaving an opaque `"http error: …"`. This walks
97 /// that chain and joins it into one line so logs and scan reports carry the
98 /// actual cause.
99 pub fn full_message(&self) -> String {
100 join_source_chain(self)
101 }
102}
103
104/// Render an error and its [`source`](std::error::Error::source) chain as a
105/// single `"top: cause: root-cause"` line.
106///
107/// Only causes that add new text are appended: some errors (notably `reqwest`)
108/// repeat their own `Display` as their first source, which would otherwise
109/// duplicate a segment.
110fn join_source_chain(error: &dyn std::error::Error) -> String {
111 let mut message = error.to_string();
112 let mut next = error.source();
113 while let Some(cause) = next {
114 let cause_text = cause.to_string();
115 if !message.contains(&cause_text) {
116 message.push_str(": ");
117 message.push_str(&cause_text);
118 }
119 next = cause.source();
120 }
121 message
122}
123
124#[cfg(test)]
125mod tests {
126 use super::join_source_chain;
127 use std::error::Error;
128 use std::fmt;
129
130 /// A minimal error whose source chain we control, for exercising
131 /// [`join_source_chain`] without depending on reqwest/io internals.
132 #[derive(Debug)]
133 struct Layer {
134 message: &'static str,
135 source: Option<Box<Layer>>,
136 }
137
138 impl Layer {
139 fn leaf(message: &'static str) -> Box<Self> {
140 Box::new(Self {
141 message,
142 source: None,
143 })
144 }
145 fn wrap(message: &'static str, source: Box<Layer>) -> Self {
146 Self {
147 message,
148 source: Some(source),
149 }
150 }
151 }
152
153 impl fmt::Display for Layer {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 f.write_str(self.message)
156 }
157 }
158
159 impl Error for Layer {
160 fn source(&self) -> Option<&(dyn Error + 'static)> {
161 self.source.as_deref().map(|s| s as &(dyn Error + 'static))
162 }
163 }
164
165 #[test]
166 fn single_error_has_no_suffix() {
167 let err = Layer {
168 message: "io error",
169 source: None,
170 };
171 assert_eq!(join_source_chain(&err), "io error");
172 }
173
174 #[test]
175 fn joins_each_distinct_cause() {
176 let err = Layer::wrap(
177 "error sending request",
178 Box::new(Layer::wrap(
179 "client error (Connect)",
180 Layer::leaf("invalid peer certificate"),
181 )),
182 );
183 assert_eq!(
184 join_source_chain(&err),
185 "error sending request: client error (Connect): invalid peer certificate"
186 );
187 }
188
189 #[test]
190 fn skips_a_cause_already_present() {
191 // reqwest repeats its top-level Display as its own first source.
192 let err = Layer::wrap(
193 "error sending request",
194 Box::new(Layer::wrap(
195 "error sending request",
196 Layer::leaf("UnknownIssuer"),
197 )),
198 );
199 assert_eq!(
200 join_source_chain(&err),
201 "error sending request: UnknownIssuer"
202 );
203 }
204}