fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Error codes, the [`ApiError`] handlers return, and the JSON:API error documents every error
//! response becomes.

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;

/// The media type of Fusion Stack error documents.
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,
}

/// The shared error table, `spec/error-codes.json`, which every Fusion Stack server package sends.
static TABLE: LazyLock<Table> = LazyLock::new(|| {
    serde_json::from_str(include_str!("../resources/error-codes.json"))
        .expect("resources/error-codes.json is valid")
});

/// A machine-readable error code with the HTTP status it is sent with and a short title. An
/// application implements it for its own codes, such as `invoice_not_finalised`.
pub trait ErrorCode: fmt::Debug + Send + Sync {
    /// The code, such as `invalid_api_version`.
    fn code(&self) -> &str;
    /// The HTTP status the code is sent with.
    fn status(&self) -> u16;
    /// A short, human-readable summary that does not change between occurrences.
    fn title(&self) -> &str;
    /// What the code means, for the OpenAPI document. Empty leaves it at the title.
    fn description(&self) -> &str {
        ""
    }
}

macro_rules! codes {
    ($($variant:ident => $code:literal,)*) => {
        /// The error codes Fusion Stack itself sends. Their statuses and titles come from the
        /// shared error table, so both server packages send the same ones.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        pub enum ApiErrorCode {
            $(#[doc = concat!("`", $code, "`")] $variant,)*
        }

        impl ApiErrorCode {
            /// Every code, in the order of the shared error table.
            pub const ALL: &[Self] = &[$(Self::$variant,)*];

            /// The code as it is sent, such as `invalid_api_version`.
            #[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")
    }

    /// The code for an HTTP error status that has no more specific code.
    #[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())
    }
}

/// An error with a Fusion Stack error code, rendered as one JSON:API error object. Return it from
/// a handler or middleware with `?` or `Err(..)?`; it converts into `laravel::Error`.
///
/// ```
/// use fusion_stack::errors::{ApiError, ApiErrorCode};
///
/// let error = ApiError::new(ApiErrorCode::InvalidFilter, "Unknown filter [colour].")
///     .parameter("filter[colour]");
/// ```
#[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 {
    /// An error with the code's status and title.
    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(),
        }
    }

    /// A `not_found` error for a record that does not exist, worded without naming the model.
    #[must_use]
    pub fn not_found() -> Self {
        Self::new(
            ApiErrorCode::NotFound,
            "The requested resource could not be found.",
        )
    }

    /// Points at the request document member at fault, as a JSON pointer such as `/data/attributes/email`.
    #[must_use]
    pub fn pointer(mut self, pointer: impl Into<String>) -> Self {
        self.source
            .insert("pointer".into(), Value::String(pointer.into()));
        self
    }

    /// Names the query parameter at fault, such as `include`.
    #[must_use]
    pub fn parameter(mut self, parameter: impl Into<String>) -> Self {
        self.source
            .insert("parameter".into(), Value::String(parameter.into()));
        self
    }

    /// Names the request header at fault, such as `Api-Version`.
    #[must_use]
    pub fn header_source(mut self, header: impl Into<String>) -> Self {
        self.source
            .insert("header".into(), Value::String(header.into()));
        self
    }

    /// Adds a link, such as `about` to an upgrade guide.
    #[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
    }

    /// Adds a `meta` member, such as `latest_version`.
    #[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
    }

    /// Adds a response header, such as `Retry-After`.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// The error's code, such as `invalid_api_version`.
    #[must_use]
    pub fn code(&self) -> &str {
        &self.code
    }

    /// The HTTP status the error is sent with.
    #[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 {
    /// The error as a `laravel::Error` with its status and headers, for `Err(error.into_error())`.
    /// Laravel for Rust converts any error with `?`, but that conversion gives it a 500 status,
    /// which the error handler then logs as a failure.
    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
    }
}

/// The hidden context value that carries a 405's methods from [`AllowHeader`] to the renderer.
const ALLOWED: &str = "fusion_stack.allowed_methods";

/// Writes `Allow` as Symfony, and so the PHP package, does (`GET, HEAD` rather than Laravel for
/// Rust's `GET,HEAD`), and keeps its methods for the 405 error's detail. Global middleware, because
/// the framework renders an unmatched method's error before it copies the `Allow` header over.
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))
    }
}

/// One error object, with empty members left out, in the order the PHP package writes them.
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")
}

/// The title of a code sent with a status: `http_error` takes the status's reason phrase.
fn title(code: ApiErrorCode, status: u16) -> String {
    if code == ApiErrorCode::HttpError {
        reason(status).to_owned()
    } else {
        code.title().to_owned()
    }
}

/// Whether the request's path matches one of the patterns, where `*` matches anything.
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))
}

/// Replaces an error response with a JSON:API error document. Registered with
/// `errors.respond`, so it runs for every error the application renders.
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();
    // An ApiError converted with `?` instead of into_error() arrives as a 500: send its own status.
    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
}

/// Replaces the field's name in a validation message with "this field", so "The email field is
/// required." becomes "This field is required.". The pointer says which field; the message must not
/// name it, because the name differs between API versions.
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: &regex::Captures<'_>| {
                    if captures[1].starts_with('T') {
                        "This field"
                    } else {
                        "this field"
                    }
                })
                .into_owned();
        }
    }
    message.to_owned()
}

/// The query parameter or request document member a validated field came from. In a JSON:API
/// document a bare field name refers to an attribute.
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() {
        // Expected values from ApiErrorCode::forStatus() in 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."
        );
        // "email" elsewhere in the message is not the field's name.
        assert_eq!(
            without_field_name("Enter a valid email address.", "email"),
            "Enter a valid email address."
        );
    }
}