use super::{Error, is_memory_error};
pub(super) const MAX_TRACEBACK_LINES: usize = 12;
const MAX_CAUSE_DEPTH: usize = 5;
pub(crate) const EXEC_BUDGET_MSG: &str = "handler execution exceeded its time budget";
pub(super) const LUA_YIELD_OUTSIDE: &str = "attempt to yield from outside a coroutine";
const ASYNC_OUTSIDE_HINT: &str = "is asynchronous and cannot be called here. A script's top \
level runs once at startup, outside the async executor, and a \
coroutine your own code resumes is not driven by it either — neither \
has anything to suspend into. Call it from inside a handler or a \
middleware instead. A value the script needs at load time has to be \
computed without an async builtin: `nitr hash-password` mints a \
password hash to paste into a table, for instance";
#[derive(Debug, Clone)]
pub struct ErrorInfo {
pub kind: &'static str,
pub message: String,
pub source: Option<String>,
pub line: Option<u32>,
pub module: Option<String>,
pub traceback: Option<String>,
pub cause: Vec<String>,
}
impl ErrorInfo {
pub fn from_error(err: &Error) -> Self {
match err {
Error::Timeout => Self::plain("timeout", err.to_string()),
Error::PoolBusy => Self::plain("nitr", err.to_string()),
Error::Panic(msg) => Self::plain("panic", msg.clone()),
Error::Lua(lua_err) => Self::from_lua(lua_err),
other => Self::plain("nitr", other.to_string()),
}
}
fn plain(kind: &'static str, message: String) -> Self {
Self {
kind,
message,
source: None,
line: None,
module: None,
traceback: None,
cause: Vec::new(),
}
}
fn from_lua(err: &mlua::Error) -> Self {
if is_memory_error(err) {
return Self::plain("memory", "Lua memory limit exceeded".into());
}
let mut kind: &'static str = "lua";
let mut module = None;
let mut traceback = None;
let mut cause = Vec::new();
let mut current = err;
loop {
match current {
mlua::Error::CallbackError {
traceback: tb,
cause: inner,
} => {
kind = "nitr";
traceback = Some(tb.as_str());
current = inner;
}
mlua::Error::WithContext {
context,
cause: inner,
} => {
if let Some(name) = context.strip_prefix("module ") {
kind = "module";
module = Some(name.to_string());
} else if let Some((name, _)) = context.split_once(':')
&& name.starts_with("nitr.")
{
module = Some(name.to_string());
} else if cause.len() < MAX_CAUSE_DEPTH {
cause.push(context.clone());
}
current = inner;
}
mlua::Error::BadArgument { cause: inner, .. } => {
kind = "nitr";
current = inner;
}
mlua::Error::ExternalError(inner) => {
let mut src: Option<&dyn std::error::Error> = inner.source();
while let Some(err) = src {
if cause.len() >= MAX_CAUSE_DEPTH {
break;
}
cause.push(err.to_string());
src = err.source();
}
break;
}
_ => break,
}
}
let text = match current {
mlua::Error::RuntimeError(msg) | mlua::Error::MemoryError(msg) => msg.clone(),
mlua::Error::SyntaxError { message, .. } => message.clone(),
other => other.to_string(),
};
Self::from_text(kind, module, traceback, cause, &text)
}
fn async_callee(traceback: &str) -> Option<String> {
let frame = traceback
.lines()
.map(str::trim_start)
.skip_while(|frame| !frame.contains("coroutine.yield"))
.find(|frame| !frame.starts_with("[C]"))
.filter(|frame| frame.starts_with("[string"))?;
let rest = [
"in field '",
"in method '",
"in function '",
"in local '",
"in upvalue '",
"in global '",
]
.into_iter()
.find_map(|pattern| frame.split_once(pattern))?
.1;
let name = rest.split_once('\'')?.0;
(!name.is_empty() && !name.contains('.')).then(|| name.to_string())
}
pub fn from_message(text: &str) -> Self {
Self::from_text("lua", None, None, Vec::new(), text)
}
fn from_text(
mut kind: &'static str,
module: Option<String>,
traceback: Option<&str>,
cause: Vec<String>,
text: &str,
) -> Self {
let (headline, embedded_tb) = split_traceback(text);
let (source, line, message) = parse_position(headline);
let module = module.or_else(|| {
message
.split_once(':')
.map(|(name, _)| name)
.filter(|name| {
name.strip_prefix("nitr.").is_some_and(|rest| {
!rest.is_empty() && rest.chars().all(char::is_alphanumeric)
})
})
.map(str::to_string)
});
if module.as_deref().is_some_and(|m| m.starts_with("nitr.")) && kind == "lua" {
kind = "nitr";
}
if message == EXEC_BUDGET_MSG {
kind = "timeout";
}
let traceback = traceback.or(embedded_tb).map(bound_traceback);
let mut source = source.map(str::to_string);
let mut line = line;
if source.is_none()
&& let Some(tb) = &traceback
{
for frame in tb.lines() {
let frame = frame.trim_start();
if frame.starts_with('[') {
continue;
}
if let (Some(frame_src), Some(frame_line), _) = parse_position(frame) {
source = Some(frame_src.to_string());
line = Some(frame_line);
break;
}
}
}
let mut message = message.to_string();
if message == LUA_YIELD_OUTSIDE
&& traceback
.as_deref()
.is_none_or(|tb| tb.contains("coroutine.yield"))
{
let what = traceback
.as_deref()
.and_then(Self::async_callee)
.map_or_else(|| "this builtin".to_string(), |name| format!("`{name}`"));
message = format!("{what} {ASYNC_OUTSIDE_HINT}");
kind = "nitr";
}
Self {
kind,
message,
source,
line,
module,
traceback,
cause,
}
}
pub fn concise(&self) -> String {
let mut out = format!("{}: {}", self.kind, self.message);
if let (Some(source), Some(line)) = (&self.source, self.line) {
out.push_str(&format!(" ({source}:{line})"));
}
out
}
pub fn concise_colored(&self) -> String {
const RESET: &str = "\x1b[0m";
const BOLD: &str = "\x1b[1m";
const RED: &str = "\x1b[31m";
const CYAN: &str = "\x1b[36m";
let mut out = format!(
"{BOLD}{RED}{}:{RESET}{BOLD} {}{RESET}",
self.kind, self.message
);
if let (Some(source), Some(line)) = (&self.source, self.line) {
out.push_str(&format!(" {CYAN}({source}:{line}){RESET}"));
}
out
}
}
fn split_traceback(text: &str) -> (&str, Option<&str>) {
match text.split_once("\nstack traceback:") {
Some((head, tail)) => (head.trim_end(), Some(tail)),
None => (text.trim_end(), None),
}
}
pub(super) fn parse_position(text: &str) -> (Option<&str>, Option<u32>, &str) {
let bytes = text.as_bytes();
let mut i = 0;
while let Some(offset) = text[i..].find(':') {
let colon = i + offset;
let digits_start = colon + 1;
let mut end = digits_start;
while end < bytes.len() && bytes[end].is_ascii_digit() {
end += 1;
}
if end > digits_start && bytes.get(end) == Some(&b':') {
let source = &text[..colon];
let line = text[digits_start..end].parse().ok();
let message = text[end + 1..].trim_start();
if !source.is_empty() && line.is_some() {
return (Some(source), line, message);
}
}
i = colon + 1;
}
(None, None, text)
}
pub(super) fn bound_traceback(tb: &str) -> String {
let tb = tb
.trim_start_matches('\n')
.trim_start_matches("stack traceback:")
.trim_matches('\n');
let mut lines = tb.lines();
let kept: Vec<&str> = lines.by_ref().take(MAX_TRACEBACK_LINES).collect();
let elided = lines.count();
if elided == 0 {
kept.join("\n")
} else {
format!("{}\n\t(... {elided} more)", kept.join("\n"))
}
}