use super::Failure;
use crate::i18n::Messages;
use serde::Serialize;
use std::borrow::Cow;
#[derive(Debug, Serialize)]
pub struct FailureEnvelope<'a> {
error: FailureBody<'a>,
}
#[derive(Debug, Serialize)]
struct FailureBody<'a> {
category: &'static str,
code: &'static str,
message: Cow<'a, str>,
#[serde(skip_serializing_if = "Option::is_none")]
hint: Option<Cow<'a, str>>,
retryable: bool,
exit: u8,
#[serde(skip_serializing_if = "<[String]>::is_empty")]
causes: &'a [String],
#[serde(skip_serializing_if = "<[String]>::is_empty")]
conditions: &'a [String],
}
impl<'a> FailureEnvelope<'a> {
#[must_use]
pub fn new(failure: &'a Failure) -> Self {
Self::localised(failure, None)
}
#[must_use]
pub fn localised(failure: &'a Failure, messages: Option<&Messages>) -> Self {
let details = failure.details();
let message = messages
.and_then(|carried| carried.failure_message(failure.code(), details))
.map_or(Cow::Borrowed(failure.message()), Cow::Owned);
let hint = failure.hint().map(|hint| {
messages
.and_then(|carried| carried.failure_hint(failure.code(), details))
.map_or(Cow::Borrowed(hint), Cow::Owned)
});
Self {
error: FailureBody {
category: failure.category().as_str(),
code: failure.code(),
message,
hint,
retryable: failure.is_retryable(),
exit: failure.exit_number().code(),
causes: failure.causes(),
conditions: failure.extra_conditions(),
},
}
}
}
pub fn write_failure<W: std::io::Write>(writer: &mut W, failure: &Failure) -> std::io::Result<()> {
let messages = crate::i18n::active();
write_failure_localised(writer, failure, Some(messages.as_ref()))
}
pub fn write_failure_localised<W: std::io::Write>(
writer: &mut W,
failure: &Failure,
messages: Option<&Messages>,
) -> std::io::Result<()> {
let envelope = FailureEnvelope::localised(failure, messages);
match serde_json::to_string(&envelope) {
Ok(line) => writeln!(writer, "{line}"),
Err(_) => writeln!(writer, r#"{{"error":{{"code":"{}"}}}}"#, failure.code()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Category;
#[test]
fn absent_fields_are_omitted_rather_than_emitted_empty() {
let failure = Failure::usage("usage.unknown_value", "value out of domain");
let line = serde_json::to_string(&FailureEnvelope::new(&failure)).expect("serialises");
assert!(
!line.contains("hint"),
"absent hint must not appear: {line}"
);
assert!(!line.contains("causes"), "empty causes must not appear");
assert!(
!line.contains("conditions"),
"empty conditions must not appear"
);
}
#[test]
fn every_failure_carries_the_mandatory_fields() {
let failure = Failure::new(Category::Conflict, "conflict.deadlock", "deadlock found")
.with_hint("repeat the transaction");
let line = serde_json::to_string(&FailureEnvelope::new(&failure)).expect("serialises");
for field in ["category", "code", "message", "retryable", "exit", "hint"] {
assert!(line.contains(field), "missing {field} in {line}");
}
assert!(line.contains(r#""retryable":true"#));
assert!(line.contains(r#""exit":9"#));
}
#[test]
fn the_written_line_is_valid_and_newline_terminated() {
let failure = Failure::absence("absence.table", "table not found");
let mut buffer = Vec::new();
write_failure(&mut buffer, &failure).expect("writes");
let text = String::from_utf8(buffer).expect("utf8");
assert!(text.ends_with('\n'));
let parsed: serde_json::Value = serde_json::from_str(text.trim_end()).expect("valid json");
assert_eq!(parsed["error"]["category"], "absence");
assert_eq!(parsed["error"]["exit"], 8);
}
fn written(failure: &Failure, tag: &str) -> serde_json::Value {
let language = crate::i18n::negotiate::parse(tag).expect("a language");
let messages = crate::i18n::Messages::load(language).expect("carried by this build");
let mut buffer = Vec::new();
write_failure_localised(&mut buffer, failure, Some(&messages)).expect("writes");
let text = String::from_utf8(buffer).expect("utf8");
serde_json::from_str(text.trim_end()).expect("valid json")
}
#[test]
fn the_language_changes_the_prose_and_never_the_identifiers() {
let failure = Failure::validation(
"sql.multiple_statements",
"the text carries more than one statement",
)
.with_hint("send one statement per call");
let english = written(&failure, "en");
let portuguese = written(&failure, "pt-BR");
assert_ne!(english["error"]["message"], portuguese["error"]["message"]);
assert_ne!(english["error"]["hint"], portuguese["error"]["hint"]);
for field in ["code", "category", "exit", "retryable"] {
assert_eq!(
english["error"][field], portuguese["error"][field],
"`{field}` must not change with the language"
);
}
}
#[test]
fn an_untranslated_code_never_costs_the_reader_a_diagnosis() {
let failure = Failure::server("server.condition", "column `b` has no default");
let portuguese = written(&failure, "pt-BR");
assert_eq!(portuguese["error"]["message"], "column `b` has no default");
assert_eq!(portuguese["error"]["code"], "server.condition");
}
}