nitr_core/error/info.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Structured diagnostics: classification of raw Lua and Rust errors into
7//! [`ErrorInfo`], parsed from what mlua already captured at raise time.
8
9use super::{Error, is_memory_error};
10/// How many Lua traceback frames survive into diagnostics. Beyond this the
11/// stack is elided: deep stacks repeat the same application frames, and an
12/// error firing in a loop must not turn each failure into a page of output.
13pub(super) const MAX_TRACEBACK_LINES: usize = 12;
14
15/// How many wrapped causes of an error chain survive into diagnostics.
16const MAX_CAUSE_DEPTH: usize = 5;
17
18/// The message the execution-budget instruction hook raises with. Shared
19/// with classification: the hook's failure surfaces as an ordinary Lua
20/// error (it fires inside the VM), and this is what identifies it as a
21/// timeout rather than a script bug.
22pub(crate) const EXEC_BUDGET_MSG: &str = "handler execution exceeded its time budget";
23
24/// What Lua raises when an asynchronous builtin is called somewhere it
25/// cannot suspend.
26///
27/// Every builtin that awaits — `nitr.fetch`, the `nitr.db` methods,
28/// `nitr.crypto.password_hash` and its two siblings, `req:multipart`,
29/// `req:text` — is a Lua function that yields, and a yield needs a
30/// coroutine the async executor is driving. Two places do not have one: the
31/// **top level** of a handler or config script (evaluated once at startup,
32/// outside the executor) and a bare `coroutine.resume`/`wrap` the
33/// application drives itself.
34///
35/// The VM's own words for that are `attempt to yield from outside a
36/// coroutine`, which names neither the builtin nor the fix. Classification
37/// replaces it — see [`ASYNC_OUTSIDE_HINT`].
38pub(super) const LUA_YIELD_OUTSIDE: &str = "attempt to yield from outside a coroutine";
39
40/// The explanation that replaces [`LUA_YIELD_OUTSIDE`].
41///
42/// Prefixed with the builtin's name when the traceback names it, or with a
43/// generic phrase when it does not.
44const ASYNC_OUTSIDE_HINT: &str = "is asynchronous and cannot be called here. A script's top \
45 level runs once at startup, outside the async executor, and a \
46 coroutine your own code resumes is not driven by it either — neither \
47 has anything to suspend into. Call it from inside a handler or a \
48 middleware instead. A value the script needs at load time has to be \
49 computed without an async builtin: `nitr hash-password` mints a \
50 password hash to paste into a table, for instance";
51
52/// A classified view of an [`Error`]: what broke, where, and why, as
53/// separate fields instead of one interpolated string.
54///
55/// Built on the error path only — the happy path never constructs one — by
56/// parsing what mlua already captured at raise time (position-prefixed
57/// messages and tracebacks), so classification adds no capture cost of its
58/// own. Production diagnostics use the concise fields (`kind`, `source`,
59/// `line`, `module`, `message`); the bounded `traceback` and `cause` chain
60/// exist for development mode and for error handlers that ask for them.
61#[derive(Debug, Clone)]
62pub struct ErrorInfo {
63 /// The classified failure: `"lua"` (a script error), `"nitr"` (a
64 /// `nitr.*` builtin or Nitr's own boundary), `"module"` (a registered
65 /// extension module), `"timeout"`, `"memory"`, or `"panic"`. The set is
66 /// closed, so branching on it is stable in a way matching on message
67 /// text never is — but it is *classification*, not provenance: `"nitr"`
68 /// and `"timeout"` are recognized by message shape, so a script that
69 /// raises `"nitr.db: ..."` or the budget message verbatim lands in
70 /// those kinds too. It is fit for logging and error pages; no
71 /// security decision may rest on it.
72 pub kind: &'static str,
73 /// The message with any position prefix and traceback stripped.
74 pub message: String,
75 /// The chunk that raised the error (the script path when the chunk was
76 /// loaded from a file), when the message carried a position.
77 pub source: Option<String>,
78 /// The line within [`source`](Self::source).
79 pub line: Option<u32>,
80 /// The failing module (`"nitr.db"`, or an extension's mount name),
81 /// when the error crossed the Rust/Lua boundary with attribution.
82 pub module: Option<String>,
83 /// The Lua call stack at the raise site, innermost first, bounded to
84 /// [`MAX_TRACEBACK_LINES`] frames.
85 pub traceback: Option<String>,
86 /// The underlying Rust error chain, outermost first, bounded to
87 /// [`MAX_CAUSE_DEPTH`] entries.
88 pub cause: Vec<String>,
89}
90
91impl ErrorInfo {
92 /// Classifies an error into its structured form.
93 pub fn from_error(err: &Error) -> Self {
94 match err {
95 Error::Timeout => Self::plain("timeout", err.to_string()),
96 Error::PoolBusy => Self::plain("nitr", err.to_string()),
97 Error::Panic(msg) => Self::plain("panic", msg.clone()),
98 Error::Lua(lua_err) => Self::from_lua(lua_err),
99 other => Self::plain("nitr", other.to_string()),
100 }
101 }
102
103 fn plain(kind: &'static str, message: String) -> Self {
104 Self {
105 kind,
106 message,
107 source: None,
108 line: None,
109 module: None,
110 traceback: None,
111 cause: Vec::new(),
112 }
113 }
114
115 fn from_lua(err: &mlua::Error) -> Self {
116 if is_memory_error(err) {
117 return Self::plain("memory", "Lua memory limit exceeded".into());
118 }
119
120 // Walk the chain once, collecting what each layer knows: the
121 // traceback mlua captured at the raise site, `WithContext` module
122 // tags, and the wrapped causes.
123 let mut kind: &'static str = "lua";
124 let mut module = None;
125 let mut traceback = None;
126 let mut cause = Vec::new();
127 let mut current = err;
128 loop {
129 match current {
130 mlua::Error::CallbackError {
131 traceback: tb,
132 cause: inner,
133 } => {
134 // An error raised on the Rust side of the boundary; the
135 // innermost Lua traceback is the raise site.
136 kind = "nitr";
137 traceback = Some(tb.as_str());
138 current = inner;
139 }
140 mlua::Error::WithContext {
141 context,
142 cause: inner,
143 } => {
144 if let Some(name) = context.strip_prefix("module ") {
145 kind = "module";
146 module = Some(name.to_string());
147 } else if let Some((name, _)) = context.split_once(':')
148 && name.starts_with("nitr.")
149 {
150 module = Some(name.to_string());
151 } else if cause.len() < MAX_CAUSE_DEPTH {
152 cause.push(context.clone());
153 }
154 current = inner;
155 }
156 // A misused builtin (wrong argument count or type) is a
157 // boundary failure too, with the real cause wrapped inside.
158 mlua::Error::BadArgument { cause: inner, .. } => {
159 kind = "nitr";
160 current = inner;
161 }
162 mlua::Error::ExternalError(inner) => {
163 // A foreign Rust error: keep its own source chain.
164 let mut src: Option<&dyn std::error::Error> = inner.source();
165 while let Some(err) = src {
166 if cause.len() >= MAX_CAUSE_DEPTH {
167 break;
168 }
169 cause.push(err.to_string());
170 src = err.source();
171 }
172 break;
173 }
174 _ => break,
175 }
176 }
177
178 // The innermost message may still carry the `source:line:` prefix
179 // and an embedded traceback (plain Lua runtime errors do). Take the
180 // raw message where the variant exposes one: `Display` prepends
181 // "runtime error: ", which would corrupt the position parse.
182 let text = match current {
183 mlua::Error::RuntimeError(msg) | mlua::Error::MemoryError(msg) => msg.clone(),
184 mlua::Error::SyntaxError { message, .. } => message.clone(),
185 other => other.to_string(),
186 };
187 Self::from_text(kind, module, traceback, cause, &text)
188 }
189
190 /// The builtin a `yield outside a coroutine` traceback was raised from.
191 ///
192 /// mlua's async trampoline reports itself as an anonymous `[string "?"]`
193 /// chunk, and that frame — the first one below `coroutine.yield` —
194 /// carries the name the script called the builtin by:
195 ///
196 /// ```text
197 /// [C]: in function 'coroutine.yield'
198 /// [string "?"]:28: in field 'password_hash' <- this one
199 /// app.lua:5: in main chunk
200 /// ```
201 ///
202 /// Only that frame is consulted. Every deeper frame is a *caller* of
203 /// the builtin, and naming one would blame the script's own function
204 /// for being asynchronous. An aliased call (`local h =
205 /// nitr.crypto.password_hash`) is named by its alias — `in local 'h'` —
206 /// which is the name the script knows the builtin by.
207 ///
208 /// Returns the bare name (`password_hash`), never a guessed path: the
209 /// traceback carries the reference the call resolved through and not
210 /// the table it hung off, so prefixing `nitr.` would print
211 /// `nitr.password_hash` for what the script wrote as
212 /// `nitr.crypto.password_hash`. `None` when the traceback has been
213 /// truncated past that frame or its shape changes — the caller falls
214 /// back to a generic phrase rather than inventing one.
215 fn async_callee(traceback: &str) -> Option<String> {
216 // Past `coroutine.yield` and any other `[C]` frames, the next frame
217 // is the trampoline's own; requiring its anonymous-chunk source
218 // makes a reshaped traceback yield nothing instead of a caller.
219 let frame = traceback
220 .lines()
221 .map(str::trim_start)
222 .skip_while(|frame| !frame.contains("coroutine.yield"))
223 .find(|frame| !frame.starts_with("[C]"))
224 .filter(|frame| frame.starts_with("[string"))?;
225 // Every way Lua names a call site: a table field or method, a plain
226 // function, or the local/upvalue/global an alias was bound to.
227 let rest = [
228 "in field '",
229 "in method '",
230 "in function '",
231 "in local '",
232 "in upvalue '",
233 "in global '",
234 ]
235 .into_iter()
236 .find_map(|pattern| frame.split_once(pattern))?
237 .1;
238 let name = rest.split_once('\'')?.0;
239 // A dotted name is a VM-qualified frame, not what the script wrote.
240 (!name.is_empty() && !name.contains('.')).then(|| name.to_string())
241 }
242
243 /// Classifies an error that arrives as bare text: what a Lua `pcall`
244 /// catches from an `error()` or a runtime failure (`app.lua:21:
245 /// attempt to call a nil value ...`, possibly with an appended
246 /// traceback). Rust-side errors keep their full chain and should go
247 /// through [`from_error`](Self::from_error) instead.
248 pub fn from_message(text: &str) -> Self {
249 Self::from_text("lua", None, None, Vec::new(), text)
250 }
251
252 /// The shared tail of classification: position, traceback split,
253 /// module attribution by message prefix, and kind refinements.
254 fn from_text(
255 mut kind: &'static str,
256 module: Option<String>,
257 traceback: Option<&str>,
258 cause: Vec<String>,
259 text: &str,
260 ) -> Self {
261 let (headline, embedded_tb) = split_traceback(text);
262 let (source, line, message) = parse_position(headline);
263
264 // A message the application prefixed with its origin (`nitr.db:
265 // database is locked`) attributes the module even without wrapping.
266 let module = module.or_else(|| {
267 message
268 .split_once(':')
269 .map(|(name, _)| name)
270 .filter(|name| {
271 name.strip_prefix("nitr.").is_some_and(|rest| {
272 !rest.is_empty() && rest.chars().all(char::is_alphanumeric)
273 })
274 })
275 .map(str::to_string)
276 });
277 if module.as_deref().is_some_and(|m| m.starts_with("nitr.")) && kind == "lua" {
278 kind = "nitr";
279 }
280 // The execution-budget hook fires inside the VM, so its failure
281 // arrives as an ordinary Lua error; reclassify by its message.
282 if message == EXEC_BUDGET_MSG {
283 kind = "timeout";
284 }
285
286 let traceback = traceback.or(embedded_tb).map(bound_traceback);
287 // A Rust-side error carries no position prefix, but its traceback's
288 // first *file* frame is the call site that invoked the builtin.
289 // `[C]` frames and anonymous `[string "..."]` chunks (mlua's async
290 // trampoline reports itself as `[string "?"]`) are not places a
291 // user can look, so they never supply a position.
292 let mut source = source.map(str::to_string);
293 let mut line = line;
294 if source.is_none()
295 && let Some(tb) = &traceback
296 {
297 for frame in tb.lines() {
298 let frame = frame.trim_start();
299 if frame.starts_with('[') {
300 continue;
301 }
302 if let (Some(frame_src), Some(frame_line), _) = parse_position(frame) {
303 source = Some(frame_src.to_string());
304 line = Some(frame_line);
305 break;
306 }
307 }
308 }
309
310 // An async builtin called where it cannot suspend. Translated last
311 // because naming the builtin needs the resolved traceback, and the
312 // VM's own wording ("attempt to yield from outside a coroutine")
313 // names neither what was called nor what to do instead. A script
314 // that *raises* the same words through `error()` keeps them: its
315 // traceback shows the `error` call where the genuine failure's
316 // shows the yield. Without a traceback the two cannot be told
317 // apart, and the genuine failure is the one that occurs.
318 let mut message = message.to_string();
319 if message == LUA_YIELD_OUTSIDE
320 && traceback
321 .as_deref()
322 .is_none_or(|tb| tb.contains("coroutine.yield"))
323 {
324 let what = traceback
325 .as_deref()
326 .and_then(Self::async_callee)
327 .map_or_else(|| "this builtin".to_string(), |name| format!("`{name}`"));
328 message = format!("{what} {ASYNC_OUTSIDE_HINT}");
329 kind = "nitr";
330 }
331
332 Self {
333 kind,
334 message,
335 source,
336 line,
337 module,
338 traceback,
339 cause,
340 }
341 }
342
343 /// The concise single-line form used by production diagnostics:
344 /// `kind: message (source:line)`.
345 pub fn concise(&self) -> String {
346 let mut out = format!("{}: {}", self.kind, self.message);
347 if let (Some(source), Some(line)) = (&self.source, self.line) {
348 out.push_str(&format!(" ({source}:{line})"));
349 }
350 out
351 }
352
353 /// [`concise`](Self::concise) with ANSI color: the kind bold red, the
354 /// message bold, the location cyan. Callers gate on the destination
355 /// being a terminal — this string must never reach an HTTP body or a
356 /// log file.
357 pub fn concise_colored(&self) -> String {
358 const RESET: &str = "\x1b[0m";
359 const BOLD: &str = "\x1b[1m";
360 const RED: &str = "\x1b[31m";
361 const CYAN: &str = "\x1b[36m";
362 let mut out = format!(
363 "{BOLD}{RED}{}:{RESET}{BOLD} {}{RESET}",
364 self.kind, self.message
365 );
366 if let (Some(source), Some(line)) = (&self.source, self.line) {
367 out.push_str(&format!(" {CYAN}({source}:{line}){RESET}"));
368 }
369 out
370 }
371}
372
373/// Splits an error message from the traceback Lua appended to it, if any.
374fn split_traceback(text: &str) -> (&str, Option<&str>) {
375 match text.split_once("\nstack traceback:") {
376 Some((head, tail)) => (head.trim_end(), Some(tail)),
377 None => (text.trim_end(), None),
378 }
379}
380
381/// Parses Lua's `source:line: message` position prefix. The source may
382/// itself contain colons (Windows drive letters), so the scan looks for the
383/// first `:<digits>: ` group rather than splitting on the first colon.
384pub(super) fn parse_position(text: &str) -> (Option<&str>, Option<u32>, &str) {
385 let bytes = text.as_bytes();
386 let mut i = 0;
387 while let Some(offset) = text[i..].find(':') {
388 let colon = i + offset;
389 let digits_start = colon + 1;
390 let mut end = digits_start;
391 while end < bytes.len() && bytes[end].is_ascii_digit() {
392 end += 1;
393 }
394 if end > digits_start && bytes.get(end) == Some(&b':') {
395 let source = &text[..colon];
396 let line = text[digits_start..end].parse().ok();
397 let message = text[end + 1..].trim_start();
398 if !source.is_empty() && line.is_some() {
399 return (Some(source), line, message);
400 }
401 }
402 i = colon + 1;
403 }
404 (None, None, text)
405}
406
407/// Bounds a traceback to [`MAX_TRACEBACK_LINES`] frames, eliding the rest:
408/// deep stacks repeat application frames, and diagnostics must stay
409/// readable when an error fires in a loop.
410pub(super) fn bound_traceback(tb: &str) -> String {
411 // `CallbackError` tracebacks embed their own label; the stored form is
412 // frames only, and renderers add the label exactly once.
413 let tb = tb
414 .trim_start_matches('\n')
415 .trim_start_matches("stack traceback:")
416 .trim_matches('\n');
417 let mut lines = tb.lines();
418 let kept: Vec<&str> = lines.by_ref().take(MAX_TRACEBACK_LINES).collect();
419 let elided = lines.count();
420 if elided == 0 {
421 kept.join("\n")
422 } else {
423 format!("{}\n\t(... {elided} more)", kept.join("\n"))
424 }
425}