use std::fmt;
use std::time::Duration;
use serde_json::Value;
use crate::vm::{CommandResult, Vm};
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Api(#[from] ApiError),
#[error("network error during {operation}{}; whether it took effect is unknown", code_suffix(.source))]
Network {
operation: String,
#[source]
source: reqwest::Error,
},
#[error("invalid {operation} response{}", detail.as_ref().map(|d| format!(": {d}")).unwrap_or_default())]
Protocol {
operation: String,
detail: Option<String>,
},
#[error(transparent)]
Command(Box<CommandError>),
#[error(transparent)]
Interrupted(Box<Interrupted>),
#[error(transparent)]
VmNotReady(Box<VmNotReady>),
#[error("process {process} on VM {vm} ended without an exit status")]
ProcessLost {
process: String,
vm: String,
},
#[error("no such file or directory on VM {vm}: {path}")]
FileNotFound {
vm: String,
path: String,
},
#[error("is a directory on VM {vm}: {path}")]
IsADirectory {
vm: String,
path: String,
},
#[error("no process {process} on VM {vm}")]
NoSuchProcess {
process: String,
vm: String,
},
#[error("process {process} on VM {vm} is still running")]
ProcessTimeout {
process: String,
vm: String,
},
#[error("{0}")]
InvalidArgument(String),
#[error("{0}")]
Config(String),
#[error("{context}: {source}")]
Io {
context: String,
#[source]
source: std::io::Error,
},
}
impl Error {
pub fn status(&self) -> Option<u16> {
match self {
Error::Api(e) => Some(e.status),
_ => None,
}
}
pub fn api(&self) -> Option<&ApiError> {
match self {
Error::Api(e) => Some(e),
_ => None,
}
}
pub fn is_not_found(&self) -> bool {
matches!(self, Error::FileNotFound { .. } | Error::NoSuchProcess { .. })
|| self.api().is_some_and(|e| e.kind() == ApiErrorKind::NotFound)
}
pub fn is_permission_denied(&self) -> bool {
self.api().is_some_and(|e| e.kind() == ApiErrorKind::PermissionDenied)
}
pub fn is_timeout(&self) -> bool {
match self {
Error::Interrupted(e) => e.kind == InterruptKind::Timeout,
Error::ProcessTimeout { .. } => true,
Error::Network { source, .. } => source.is_timeout(),
_ => false,
}
}
pub(crate) fn protocol(operation: &str) -> Error {
Error::Protocol {
operation: operation.to_string(),
detail: None,
}
}
pub(crate) fn undecodable(operation: &str, err: &serde_json::Error) -> Error {
let msg = err.to_string();
let msg = msg.split(" at line ").next().unwrap_or_default();
let detail = if let Some(rest) = msg.strip_prefix("invalid type: ") {
let kind = rest.split([' ', ',']).next().unwrap_or_default();
let expected = rest
.rsplit_once(", expected ")
.map(|(_, e)| e)
.unwrap_or("something else");
format!("invalid type: {kind}, expected {expected}")
} else if msg.starts_with("missing field ") {
msg.to_string()
} else {
"unexpected shape".to_string()
};
Error::Protocol {
operation: operation.to_string(),
detail: Some(detail),
}
}
pub(crate) fn invalid(message: impl Into<String>) -> Error {
Error::InvalidArgument(message.into())
}
pub(crate) fn io(context: impl Into<String>, source: std::io::Error) -> Error {
Error::Io {
context: context.into(),
source,
}
}
}
fn code_suffix(err: &reqwest::Error) -> String {
if err.is_timeout() {
" (timeout)".to_string()
} else if err.is_connect() {
" (connect)".to_string()
} else {
String::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApiErrorKind {
Authentication,
PermissionDenied,
NotFound,
RateLimited,
VmNotRunning,
Other,
}
#[derive(Debug, Clone)]
pub struct ApiError {
pub operation: String,
pub status: u16,
pub body: String,
kind: ApiErrorKind,
vm: Option<String>,
}
impl ApiError {
pub(crate) fn new(operation: &str, status: u16, body: String) -> ApiError {
let kind = match status {
401 => ApiErrorKind::Authentication,
403 => ApiErrorKind::PermissionDenied,
404 => ApiErrorKind::NotFound,
429 => ApiErrorKind::RateLimited,
_ => ApiErrorKind::Other,
};
ApiError {
operation: operation.to_string(),
status,
body,
kind,
vm: None,
}
}
pub(crate) fn ssh(vm: &str, status: u16, body: String) -> ApiError {
if status == 422 {
match error_code(&body).as_deref() {
Some("vm_not_found") => return ApiError::new("ssh", 404, body),
Some("vm_not_running") => {
let mut e = ApiError::new("ssh", 422, body);
e.kind = ApiErrorKind::VmNotRunning;
e.vm = Some(vm.to_string());
return e;
}
_ => {}
}
}
ApiError::new("ssh", status, body)
}
pub fn kind(&self) -> ApiErrorKind {
self.kind
}
pub fn code(&self) -> Option<String> {
error_code(&self.body)
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "exe.dev API error ({}) during {}", self.status, self.operation)?;
if let Some(vm) = &self.vm {
return write!(f, ": VM {vm} is not running");
}
if let Some(reason) = error_text(&self.body) {
write!(f, ": {reason}")?;
}
Ok(())
}
}
impl std::error::Error for ApiError {}
#[derive(Debug, Clone)]
pub struct CommandError {
pub result: CommandResult,
}
impl fmt::Display for CommandError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "command exited with status {}", self.result.exit_code)?;
let stderr = self.result.stderr_lossy();
if let Some(last) = stderr.lines().rev().find(|l| !l.trim().is_empty()).and_then(one_line) {
write!(f, ": {last}")?;
}
Ok(())
}
}
impl std::error::Error for CommandError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InterruptKind {
Disconnected,
OutputLimit,
Timeout,
}
#[derive(Debug, Clone)]
pub struct Interrupted {
pub kind: InterruptKind,
pub captured: bool,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub reason: Option<String>,
pub timeout: Option<Duration>,
}
impl Interrupted {
pub fn stdout_lossy(&self) -> String {
String::from_utf8_lossy(&self.stdout).into_owned()
}
pub fn stderr_lossy(&self) -> String {
String::from_utf8_lossy(&self.stderr).into_owned()
}
}
impl fmt::Display for Interrupted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self.kind {
InterruptKind::Disconnected => "the connection ended before the command's exit status arrived",
InterruptKind::OutputLimit => "the command's output exceeded max_output",
InterruptKind::Timeout => "the command did not finish within its timeout",
})
}
}
impl std::error::Error for Interrupted {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetupFailure {
pub result: String,
pub exit_code: Option<i32>,
pub signal: Option<i32>,
pub output: String,
}
#[derive(Debug)]
pub struct VmNotReady {
pub name: String,
pub vm: Option<Vm>,
pub failure: String,
pub setup: Option<SetupFailure>,
pub source: Option<Error>,
}
impl fmt::Display for VmNotReady {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VM {} {}", self.name, self.failure)
}
}
impl std::error::Error for VmNotReady {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|e| e as &(dyn std::error::Error + 'static))
}
}
impl VmNotReady {
pub(crate) fn setup_failed(name: &str, setup: SetupFailure) -> VmNotReady {
let failure = if setup.result == "unsupported" {
"setup script did not run: this VM's image does not run setup scripts".to_string()
} else if setup.result == "not-run" {
"setup script did not run".to_string()
} else if let Some(code) = setup.exit_code {
format!("setup script failed (exit code {code})")
} else if let Some(sig) = setup.signal {
format!("setup script failed (signal {sig})")
} else {
format!("setup script failed ({})", setup.result)
};
VmNotReady {
name: name.to_string(),
vm: None,
failure,
setup: Some(setup),
source: None,
}
}
}
pub(crate) fn parse_documents(body: &str) -> Option<Vec<Value>> {
let text = body.trim();
if text.is_empty() {
return None;
}
if let Ok(v) = serde_json::from_str::<Value>(text) {
return Some(vec![v]);
}
text.lines()
.filter(|l| !l.trim().is_empty())
.map(serde_json::from_str::<Value>)
.collect::<std::result::Result<Vec<_>, _>>()
.ok()
}
pub(crate) fn is_error_document(doc: &Value) -> bool {
doc.as_object().is_some_and(|o| o.len() == 1 && o.contains_key("error"))
}
fn error_string(doc: &Value) -> Option<&str> {
doc.get("error").and_then(Value::as_str)
}
pub(crate) fn error_text(body: &str) -> Option<String> {
let docs = parse_documents(body)?;
let doc = docs
.iter()
.find(|d| is_error_document(d))
.or_else(|| docs.iter().find(|d| error_string(d).is_some()))?;
one_line(error_string(doc)?)
}
pub(crate) fn error_code(body: &str) -> Option<String> {
let docs = parse_documents(body)?;
let doc = docs.iter().find(|d| error_string(d).is_some())?;
doc.get("code").and_then(Value::as_str).map(str::to_string)
}
pub(crate) fn one_line(text: &str) -> Option<String> {
let text = strip_escapes(text);
let mut out = String::new();
let mut space = false;
for c in text.chars() {
if c.is_whitespace() {
space = true;
continue;
}
if is_control(c) {
continue;
}
if space && !out.is_empty() {
out.push(' ');
}
space = false;
out.push(c);
}
if out.chars().count() > 200 {
let mut short: String = out.chars().take(199).collect();
short.push('…');
return Some(short);
}
(!out.is_empty()).then_some(out)
}
fn is_control(c: char) -> bool {
c.is_control() || matches!(c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
}
fn strip_escapes(text: &str) -> String {
let chars: Vec<char> = text.chars().collect();
let mut out = String::with_capacity(text.len());
let mut i = 0;
while i < chars.len() {
if chars[i] != '\x1b' || i + 1 >= chars.len() {
out.push(chars[i]);
i += 1;
continue;
}
match chars[i + 1] {
'[' => {
let mut j = i + 2;
while j < chars.len() && ('0'..='?').contains(&chars[j]) {
j += 1;
}
while j < chars.len() && (' '..='/').contains(&chars[j]) {
j += 1;
}
if j < chars.len() && ('@'..='~').contains(&chars[j]) {
i = j + 1;
} else {
out.push(chars[i]);
i += 1;
}
}
']' => {
let mut j = i + 2;
while j < chars.len() && chars[j] != '\x07' && chars[j] != '\x1b' {
j += 1;
}
if j < chars.len() && chars[j] == '\x07' {
j += 1;
} else if j + 1 < chars.len() && chars[j] == '\x1b' && chars[j + 1] == '\\' {
j += 2;
}
i = j;
}
'@'..='Z' | '\\'..='_' => i += 2,
_ => {
out.push(chars[i]);
i += 1;
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn undecodable_results_name_the_problem_not_the_value() {
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Key {
token: u32,
label: String,
}
let err = serde_json::from_value::<Key>(serde_json::json!({"token": "exe0.secret", "label": "x"})).unwrap_err();
let msg = Error::undecodable("ssh-key generate-api-key", &err).to_string();
assert_eq!(
msg,
"invalid ssh-key generate-api-key response: invalid type: string, expected u32"
);
let err = serde_json::from_value::<Key>(serde_json::json!({"token": 1})).unwrap_err();
let msg = Error::undecodable("whoami", &err).to_string();
assert_eq!(msg, "invalid whoami response: missing field `label`");
}
#[test]
fn error_text_is_one_safe_line() {
let body = r#"{"error": "bad\n\u001b[31mthing\u001b[0m \u202e here"}"#;
assert_eq!(error_text(body).as_deref(), Some("bad thing here"));
let long = format!(r#"{{"error": "{}"}}"#, "x".repeat(300));
assert_eq!(error_text(&long).unwrap().chars().count(), 200);
assert_eq!(error_text("not json"), None);
assert_eq!(
error_text("{\"ok\": 1}\n{\"error\": \"second\"}").as_deref(),
Some("second")
);
}
#[test]
fn api_error_kinds() {
assert_eq!(
ApiError::new("ls", 403, String::new()).kind(),
ApiErrorKind::PermissionDenied
);
let e = ApiError::ssh(
"box",
422,
r#"{"error": "VM \"box\" not found", "code": "vm_not_found"}"#.into(),
);
assert_eq!((e.kind(), e.status), (ApiErrorKind::NotFound, 404));
let e = ApiError::ssh("box", 422, r#"{"error": "x", "code": "vm_not_running"}"#.into());
assert_eq!(e.kind(), ApiErrorKind::VmNotRunning);
assert_eq!(
e.to_string(),
"exe.dev API error (422) during ssh: VM box is not running"
);
let e = ApiError::new("new", 400, r#"{"error": "no such image"}"#.into());
assert_eq!(e.to_string(), "exe.dev API error (400) during new: no such image");
}
}