use std::collections::HashMap;
use std::fmt;
use std::sync::LazyLock;
use laravel::http::{Request, Response, StatusCode};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use crate::State;
use crate::request_id;
pub const CONTENT_TYPE: &str = "application/vnd.api+json";
#[derive(Deserialize)]
struct Table {
codes: Vec<Entry>,
fallbacks: HashMap<String, String>,
}
#[derive(Deserialize)]
struct Entry {
code: String,
status: u16,
title: String,
#[serde(default)]
description: String,
}
static TABLE: LazyLock<Table> = LazyLock::new(|| {
serde_json::from_str(include_str!("../resources/error-codes.json"))
.expect("resources/error-codes.json is valid")
});
pub trait ErrorCode: fmt::Debug + Send + Sync {
fn code(&self) -> &str;
fn status(&self) -> u16;
fn title(&self) -> &str;
fn description(&self) -> &str {
""
}
}
macro_rules! codes {
($($variant:ident => $code:literal,)*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ApiErrorCode {
$(#[doc = concat!("`", $code, "`")] $variant,)*
}
impl ApiErrorCode {
pub const ALL: &[Self] = &[$(Self::$variant,)*];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
$(Self::$variant => $code,)*
}
}
fn from_code(code: &str) -> Option<Self> {
match code {
$($code => Some(Self::$variant),)*
_ => None,
}
}
}
};
}
codes! {
BadRequest => "bad_request",
Unauthenticated => "unauthenticated",
Forbidden => "forbidden",
InsufficientScope => "insufficient_scope",
NotFound => "not_found",
MethodNotAllowed => "method_not_allowed",
Conflict => "conflict",
ValidationFailed => "validation_failed",
RateLimited => "rate_limited",
InvalidApiVersion => "invalid_api_version",
ApiVersionRetired => "api_version_retired",
ApiVersionBrownout => "api_version_brownout",
EndpointUnavailableForVersion => "endpoint_unavailable_for_version",
InvalidInclude => "invalid_include",
InvalidFieldset => "invalid_fieldset",
InvalidFilter => "invalid_filter",
InvalidSort => "invalid_sort",
InvalidPage => "invalid_page",
InvalidIdempotencyKey => "invalid_idempotency_key",
IdempotencyKeyMismatch => "idempotency_key_mismatch",
IdempotencyInProgress => "idempotency_in_progress",
HttpError => "http_error",
ServerError => "server_error",
ServiceUnavailable => "service_unavailable",
}
impl ApiErrorCode {
fn entry(self) -> &'static Entry {
TABLE
.codes
.iter()
.find(|entry| entry.code == self.as_str())
.expect("every ApiErrorCode is in the shared error table")
}
#[must_use]
pub fn for_status(status: u16) -> Self {
let fallbacks = &TABLE.fallbacks;
let code = fallbacks
.get(&status.to_string())
.or_else(|| (status >= 500).then(|| &fallbacks["server"]))
.unwrap_or(&fallbacks["default"]);
Self::from_code(code).expect("the shared error table's fallbacks are known codes")
}
}
impl ErrorCode for ApiErrorCode {
fn code(&self) -> &str {
self.as_str()
}
fn status(&self) -> u16 {
self.entry().status
}
fn title(&self) -> &str {
&self.entry().title
}
fn description(&self) -> &str {
&self.entry().description
}
}
impl fmt::Display for ApiErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone)]
pub struct ApiError {
code: String,
status: u16,
title: String,
detail: String,
source: Map<String, Value>,
links: Map<String, Value>,
meta: Map<String, Value>,
pub(crate) headers: Vec<(String, String)>,
}
impl ApiError {
pub fn new(code: impl ErrorCode, detail: impl Into<String>) -> Self {
Self {
code: code.code().to_owned(),
status: code.status(),
title: code.title().to_owned(),
detail: detail.into(),
source: Map::new(),
links: Map::new(),
meta: Map::new(),
headers: Vec::new(),
}
}
#[must_use]
pub fn not_found() -> Self {
Self::new(
ApiErrorCode::NotFound,
"The requested resource could not be found.",
)
}
#[must_use]
pub fn pointer(mut self, pointer: impl Into<String>) -> Self {
self.source
.insert("pointer".into(), Value::String(pointer.into()));
self
}
#[must_use]
pub fn parameter(mut self, parameter: impl Into<String>) -> Self {
self.source
.insert("parameter".into(), Value::String(parameter.into()));
self
}
#[must_use]
pub fn header_source(mut self, header: impl Into<String>) -> Self {
self.source
.insert("header".into(), Value::String(header.into()));
self
}
#[must_use]
pub fn link(mut self, name: impl Into<String>, url: impl Into<String>) -> Self {
self.links.insert(name.into(), Value::String(url.into()));
self
}
#[must_use]
pub fn meta(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
self.meta.insert(
key.into(),
serde_json::to_value(value).unwrap_or(Value::Null),
);
self
}
#[must_use]
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
#[must_use]
pub fn code(&self) -> &str {
&self.code
}
#[must_use]
pub const fn status(&self) -> u16 {
self.status
}
fn object(&self) -> Value {
error_object(
self.status,
&self.code,
&self.title,
&self.detail,
&self.source,
&self.links,
&self.meta,
)
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl std::error::Error for ApiError {}
impl ApiError {
pub fn into_error(self) -> laravel::Error {
let headers = self.headers.clone();
let mut converted = laravel::Error::new(self.status, self);
for (name, value) in headers {
converted = converted.with_header(name, value);
}
converted
}
}
const ALLOWED: &str = "fusion_stack.allowed_methods";
pub(crate) struct AllowHeader;
impl laravel::http::Middleware for AllowHeader {
async fn handle(
&self,
request: Request,
next: laravel::http::Next,
) -> laravel::Result<Response> {
let mut response = next.run(request).await.into_http();
let allow = response
.headers()
.get(laravel::http::header::ALLOW)
.and_then(|value| value.to_str().ok())
.map(|allow| {
allow
.split(',')
.map(str::trim)
.collect::<Vec<_>>()
.join(", ")
});
if let Some(allow) = allow {
if let Ok(value) = allow.parse() {
response
.headers_mut()
.insert(laravel::http::header::ALLOW, value);
}
laravel::context::add_hidden(ALLOWED, allow);
}
Ok(Response::from_http(response))
}
}
fn error_object(
status: u16,
code: &str,
title: &str,
detail: &str,
source: &Map<String, Value>,
links: &Map<String, Value>,
meta: &Map<String, Value>,
) -> Value {
let mut object = Map::new();
object.insert("status".into(), json!(status.to_string()));
object.insert("code".into(), json!(code));
object.insert("title".into(), json!(title));
object.insert("detail".into(), json!(detail));
for (key, member) in [("source", source), ("links", links), ("meta", meta)] {
if !member.is_empty() {
object.insert(key.into(), Value::Object(member.clone()));
}
}
Value::Object(object)
}
fn reason(status: u16) -> &'static str {
StatusCode::from_u16(status)
.ok()
.and_then(|status| status.canonical_reason())
.unwrap_or("Error")
}
fn title(code: ApiErrorCode, status: u16) -> String {
if code == ApiErrorCode::HttpError {
reason(status).to_owned()
} else {
code.title().to_owned()
}
}
pub(crate) fn path_matches(patterns: &[String], path: &str) -> bool {
let path = path.trim_start_matches('/');
patterns
.iter()
.any(|pattern| crate::glob(pattern.trim_start_matches('/'), path))
}
pub(crate) fn render(
state: &State,
response: Response,
error: &laravel::Error,
request: &Request,
) -> Response {
if !path_matches(&state.config.error_paths, request.path()) {
return response;
}
let http = response.into_http();
let (mut parts, _) = http.into_parts();
if let Some(error) = error.downcast_ref::<ApiError>()
&& let Ok(status) = StatusCode::from_u16(error.status)
{
parts.status = status;
}
let status = parts.status.as_u16();
let mut errors = objects(error, request, status);
let id = request_id::of(request);
if state.config.request_ids {
for object in &mut errors {
if let Some(object) = object.as_object_mut() {
let meta = object.entry("meta").or_insert_with(|| json!({}));
if let Some(meta) = meta.as_object_mut() {
meta.insert("request_id".into(), json!(id));
}
}
}
}
let headers = &mut parts.headers;
headers.remove(laravel::http::header::CONTENT_LENGTH);
headers.insert(
laravel::http::header::CONTENT_TYPE,
CONTENT_TYPE.parse().expect("a valid header value"),
);
if state.config.request_ids
&& let Ok(value) = id.parse()
{
headers.insert(request_id::HEADER, value);
}
let body = serde_json::to_vec(&json!({ "errors": errors })).expect("error documents serialize");
Response::from_http(laravel::axum::http::Response::from_parts(
parts,
body.into(),
))
}
fn objects(error: &laravel::Error, request: &Request, status: u16) -> Vec<Value> {
if let Some(error) = error.downcast_ref::<ApiError>() {
return vec![error.object()];
}
if let Some(invalid) = error.downcast_ref::<laravel::validation::InvalidInput>() {
return validation_errors(invalid, request, status);
}
#[cfg(feature = "database")]
if error.is::<laravel::model::ModelNotFound>() {
return vec![ApiError::not_found().object()];
}
let code = ApiErrorCode::for_status(status);
let path = request.path().trim_start_matches('/');
let detail = if status >= 500 {
"An unexpected error occurred.".to_owned()
} else if request.current_route().is_none() && status == 404 {
format!("The route {path} could not be found.")
} else if request.current_route().is_none() && status == 405 {
format!(
"The {} method is not supported for route {path}. Supported methods: {}.",
request.method(),
laravel::context::get_hidden::<String>(ALLOWED).unwrap_or_default()
)
} else {
let message = error.to_string();
if message.is_empty() || message == reason(status) {
title(code, status)
} else {
message
}
};
vec![error_object(
status,
code.as_str(),
&title(code, status),
&detail,
&Map::new(),
&Map::new(),
&Map::new(),
)]
}
fn validation_errors(
invalid: &laravel::validation::InvalidInput,
request: &Request,
status: u16,
) -> Vec<Value> {
let code = ApiErrorCode::ValidationFailed;
let mut errors = Vec::new();
for (field, messages) in invalid.errors() {
let source = source(field, request);
for message in messages {
let detail = without_field_name(message, field);
errors.push(error_object(
status,
code.as_str(),
&title(code, status),
&detail,
&source,
&Map::new(),
&Map::new(),
));
}
}
errors
}
fn without_field_name(message: &str, field: &str) -> String {
let last = field.rsplit('.').next().unwrap_or(field);
let mut names = vec![
field.to_owned(),
field.replace('_', " "),
last.to_owned(),
last.replace('_', " "),
];
names.dedup();
for name in names {
let pattern = format!(
r"(?i)\b(the)(?: selected)? {}(?: field)?\b",
regex::escape(&name)
);
let Ok(regex) = Regex::new(&pattern) else {
continue;
};
if regex.is_match(message) {
return regex
.replace_all(message, |captures: ®ex::Captures<'_>| {
if captures[1].starts_with('T') {
"This field"
} else {
"this field"
}
})
.into_owned();
}
}
message.to_owned()
}
fn source(field: &str, request: &Request) -> Map<String, Value> {
let mut segments: Vec<&str> = field.split('.').collect();
let mut source = Map::new();
let in_query = request.uri().query().is_some_and(|query| {
query.split('&').any(|pair| {
let key = pair.split('=').next().unwrap_or_default();
key == segments[0]
|| key.starts_with(&format!("{}[", segments[0]))
|| key.starts_with(&format!("{}%5B", segments[0]))
})
});
if in_query {
let first = segments.remove(0);
let rest: String = segments
.iter()
.map(|segment| format!("[{segment}]"))
.collect();
source.insert("parameter".into(), json!(format!("{first}{rest}")));
return source;
}
let json_api = request
.header(laravel::http::header::CONTENT_TYPE)
.is_some_and(|value| value.contains(CONTENT_TYPE));
if segments[0] != "data" && json_api {
segments.splice(0..0, ["data", "attributes"]);
}
let pointer: String = segments
.iter()
.map(|segment| format!("/{}", segment.replace('~', "~0").replace('/', "~1")))
.collect();
source.insert("pointer".into(), json!(pointer));
source
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_code_in_the_shared_table_is_an_api_error_code() {
let codes: Vec<&str> = TABLE
.codes
.iter()
.map(|entry| entry.code.as_str())
.collect();
let variants: Vec<&str> = ApiErrorCode::ALL.iter().map(|code| code.as_str()).collect();
assert_eq!(codes, variants);
}
#[test]
fn statuses_without_their_own_code_fall_back_like_the_php_package() {
let cases = [
(400, "bad_request"),
(401, "unauthenticated"),
(403, "forbidden"),
(404, "not_found"),
(405, "method_not_allowed"),
(409, "conflict"),
(410, "http_error"),
(418, "http_error"),
(422, "validation_failed"),
(429, "rate_limited"),
(500, "server_error"),
(502, "server_error"),
(503, "service_unavailable"),
];
for (status, code) in cases {
assert_eq!(
ApiErrorCode::for_status(status).as_str(),
code,
"status {status}"
);
}
}
#[test]
fn statuses_and_titles_come_from_the_table() {
assert_eq!(ApiErrorCode::IdempotencyKeyMismatch.status(), 422);
assert_eq!(
ApiErrorCode::IdempotencyKeyMismatch.title(),
"Idempotency key reused"
);
assert_eq!(title(ApiErrorCode::HttpError, 418), "I'm a teapot");
}
#[test]
fn validation_messages_stop_naming_the_field() {
assert_eq!(
without_field_name("The email field must be a valid email address.", "email"),
"This field must be a valid email address."
);
assert_eq!(
without_field_name("The selected status is invalid.", "data.attributes.status"),
"This field is invalid."
);
assert_eq!(
without_field_name("The full name field is required.", "full_name"),
"This field is required."
);
assert_eq!(
without_field_name("Enter a valid email address.", "email"),
"Enter a valid email address."
);
}
}