autumn-web 0.4.0

An opinionated, convention-over-configuration web framework for Rust
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
//! Framework error type and result alias.
//!
//! [`AutumnError`] wraps any `Error + Send + Sync` with an HTTP status code.
//! The blanket [`From`] impl maps all errors to `500 Internal Server Error`,
//! so the `?` operator works in handlers with zero ceremony.
//!
//! For non-500 cases, use the status refinement constructors:
//!
//! - [`AutumnError::not_found`] -- 404
//! - [`AutumnError::bad_request`] -- 400
//! - [`AutumnError::unprocessable`] -- 422
//! - [`AutumnError::service_unavailable`] -- 503
//! - [`AutumnError::with_status`] -- arbitrary status code
//!
//! For simple string messages without wrapping an error type:
//!
//! - [`AutumnError::not_found_msg`] -- 404 with a message
//! - [`AutumnError::bad_request_msg`] -- 400 with a message
//! - [`AutumnError::unprocessable_msg`] -- 422 with a message
//! - [`AutumnError::service_unavailable_msg`] -- 503 with a message
//!
//! # Response format
//!
//! When an `AutumnError` is returned from a handler, it renders as JSON:
//!
//! ```json
//! { "error": { "status": 404, "message": "user not found" } }
//! ```
//!
//! # Examples
//!
//! ```rust
//! use autumn_web::error::AutumnError;
//! use http::StatusCode;
//!
//! // Blanket From impl: any Error becomes 500
//! let err: AutumnError = std::io::Error::other("disk full").into();
//! assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
//!
//! // Explicit status constructors
//! let err = AutumnError::not_found(std::io::Error::other("no such user"));
//! assert_eq!(err.status(), StatusCode::NOT_FOUND);
//! ```

use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde::Serialize;

/// Simple error type wrapping a string message.
///
/// Used by the `_msg` convenience constructors on [`AutumnError`] so callers
/// don't need to wrap strings in `std::io::Error`.
#[derive(Debug)]
struct StringError(String);

impl std::fmt::Display for StringError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for StringError {}

/// JSON body for RFC 7807 Problem Details responses.
#[derive(Clone, Debug, Serialize)]
pub struct ProblemDetails {
    /// Problem type URI. Autumn uses stable `https://autumn.dev/problems/...`
    /// URIs for framework-generated errors.
    #[serde(rename = "type")]
    pub type_uri: String,
    /// Short human-readable title for the status/problem class.
    pub title: String,
    /// HTTP status code.
    pub status: u16,
    /// Client-safe human-readable explanation.
    pub detail: String,
    /// Request path or URI reference for the specific occurrence.
    pub instance: Option<String>,
    /// Stable machine-readable Autumn error code.
    pub code: String,
    /// Request ID for log correlation, when the request pipeline assigned one.
    pub request_id: Option<String>,
    /// Field-level validation failures. Empty for non-validation errors.
    pub errors: Vec<ProblemFieldError>,
}

/// Field-level validation detail in the Problem Details `errors` extension.
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub struct ProblemFieldError {
    /// Field name as seen by the request payload or form.
    pub field: String,
    /// Stable list of validation messages for this field.
    pub messages: Vec<String>,
}

/// Framework error type wrapping any error with an HTTP status code.
///
/// # Usage
///
/// The `?` operator converts any `std::error::Error` into an `AutumnError`
/// with status `500 Internal Server Error`:
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn handler() -> AutumnResult<&'static str> {
///     autumn_web::reexports::tokio::fs::read_to_string("missing.txt").await?; // becomes 500 on error
///     Ok("ok")
/// }
/// ```
///
/// For expected errors, use a status refinement constructor:
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/users/{id}")]
/// async fn get_user(axum::extract::Path(id): axum::extract::Path<i32>) -> AutumnResult<String> {
///     if id < 0 {
///         return Err(AutumnError::bad_request(
///             std::io::Error::other("id must be positive"),
///         ));
///     }
///     Ok(format!("user {id}"))
/// }
/// ```
///
/// # Why no `Error` impl
///
/// `AutumnError` intentionally does **not** implement [`std::error::Error`].
/// Doing so would conflict with the blanket `From<E: Error>` impl (the
/// reflexive `From<T> for T` would overlap). This type is a *response*
/// wrapper, not a propagatable error.
pub struct AutumnError {
    inner: Box<dyn std::error::Error + Send + Sync>,
    status: StatusCode,
    details: Option<std::collections::HashMap<String, Vec<String>>>,
    problem_type: Option<&'static str>,
}

/// Convenience alias -- the standard return type for Autumn handlers.
///
/// Equivalent to `Result<T, AutumnError>`. Use this as the return type
/// for any handler that might fail.
///
/// # Examples
///
/// ```rust,no_run
/// use autumn_web::prelude::*;
///
/// #[get("/")]
/// async fn index() -> AutumnResult<&'static str> {
///     Ok("hello")
/// }
/// ```
pub type AutumnResult<T> = Result<T, AutumnError>;

impl<E> From<E> for AutumnError
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn from(err: E) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::INTERNAL_SERVER_ERROR,
            details: None,
            problem_type: None,
        }
    }
}

impl AutumnError {
    /// Override the HTTP status code.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err: AutumnError = std::io::Error::other("forbidden").into();
    /// let err = err.with_status(StatusCode::FORBIDDEN);
    /// assert_eq!(err.status(), StatusCode::FORBIDDEN);
    /// ```
    #[must_use]
    pub const fn with_status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    /// Create a `500 Internal Server Error`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::internal_server_error(std::io::Error::other("boom"));
    /// assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    pub fn internal_server_error(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::INTERNAL_SERVER_ERROR,
            details: None,
            problem_type: None,
        }
    }

    /// Create a `404 Not Found` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::not_found(std::io::Error::other("no such user"));
    /// assert_eq!(err.status(), StatusCode::NOT_FOUND);
    /// ```
    pub fn not_found(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::NOT_FOUND,
            details: None,
            problem_type: None,
        }
    }

    /// Create a `400 Bad Request` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::bad_request(std::io::Error::other("invalid input"));
    /// assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    /// ```
    pub fn bad_request(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::BAD_REQUEST,
            details: None,
            problem_type: None,
        }
    }

    /// Create a `422 Unprocessable Entity` error.
    ///
    /// Use this for validation failures where the request is syntactically
    /// valid but semantically incorrect.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unprocessable(std::io::Error::other("age must be positive"));
    /// assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    /// ```
    pub fn unprocessable(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::UNPROCESSABLE_ENTITY,
            details: None,
            problem_type: None,
        }
    }

    /// Create a `503 Service Unavailable` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::service_unavailable(std::io::Error::other("pool exhausted"));
    /// assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
    /// ```
    pub fn service_unavailable(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::SERVICE_UNAVAILABLE,
            details: None,
            problem_type: None,
        }
    }

    /// Create a `401 Unauthorized` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unauthorized(std::io::Error::other("not logged in"));
    /// assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    /// ```
    pub fn unauthorized(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::UNAUTHORIZED,
            details: None,
            problem_type: None,
        }
    }

    /// Create a `403 Forbidden` error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::forbidden(std::io::Error::other("not allowed"));
    /// assert_eq!(err.status(), StatusCode::FORBIDDEN);
    /// ```
    pub fn forbidden(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::FORBIDDEN,
            details: None,
            problem_type: None,
        }
    }

    /// Create a `422 Unprocessable Entity` error with field-level
    /// validation details.
    ///
    /// Use this when a request fails multiple field-specific validation rules
    /// (e.g., in a form submission). It attaches the `details` parameter, a mapping
    /// of field names to their respective error messages, so the client can display
    /// errors next to the relevant inputs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    /// use std::collections::HashMap;
    ///
    /// let mut errors = HashMap::new();
    /// errors.insert("username".to_string(), vec!["Username is taken".to_string()]);
    ///
    /// let err = AutumnError::validation(errors);
    /// assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    /// ```
    #[must_use]
    pub fn validation(details: std::collections::HashMap<String, Vec<String>>) -> Self {
        Self {
            inner: Box::new(StringError("Validation failed".into())),
            status: StatusCode::UNPROCESSABLE_ENTITY,
            details: Some(details),
            problem_type: None,
        }
    }

    // ── String-message convenience constructors ────────────────

    /// Create a `500 Internal Server Error` from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::internal_server_error_msg("Database explosion");
    /// assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    pub fn internal_server_error_msg(msg: impl Into<String>) -> Self {
        Self::internal_server_error(StringError(msg.into()))
    }

    /// Create a `404 Not Found` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::not_found_msg("No such user");
    /// assert_eq!(err.status(), StatusCode::NOT_FOUND);
    /// assert_eq!(err.to_string(), "No such user");
    /// ```
    pub fn not_found_msg(msg: impl Into<String>) -> Self {
        Self::not_found(StringError(msg.into()))
    }

    /// Create a `400 Bad Request` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::bad_request_msg("Invalid input parameter");
    /// assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    /// ```
    pub fn bad_request_msg(msg: impl Into<String>) -> Self {
        Self::bad_request(StringError(msg.into()))
    }

    /// Create a `422 Unprocessable Entity` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unprocessable_msg("Title is required");
    /// assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    /// ```
    pub fn unprocessable_msg(msg: impl Into<String>) -> Self {
        Self::unprocessable(StringError(msg.into()))
    }

    /// Create a `401 Unauthorized` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::unauthorized_msg("Please log in to continue");
    /// assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    /// ```
    pub fn unauthorized_msg(msg: impl Into<String>) -> Self {
        Self::unauthorized(StringError(msg.into()))
    }

    /// Create a `403 Forbidden` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::forbidden_msg("You lack admin privileges");
    /// assert_eq!(err.status(), StatusCode::FORBIDDEN);
    /// ```
    pub fn forbidden_msg(msg: impl Into<String>) -> Self {
        Self::forbidden(StringError(msg.into()))
    }

    /// Create a `503 Service Unavailable` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::service_unavailable_msg("Database connection pool exhausted");
    /// assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
    /// ```
    pub fn service_unavailable_msg(msg: impl Into<String>) -> Self {
        Self::service_unavailable(StringError(msg.into()))
    }

    /// Create a `409 Conflict` error.
    ///
    /// Use this for optimistic-lock conflicts surfaced by repository `update`
    /// calls when the client's expected version is stale.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::conflict(std::io::Error::other("stale version"));
    /// assert_eq!(err.status(), StatusCode::CONFLICT);
    /// ```
    pub fn conflict(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            inner: Box::new(err),
            status: StatusCode::CONFLICT,
            details: None,
            problem_type: Some("https://autumn.dev/problems/conflict"),
        }
    }

    /// Create a `409 Conflict` error from a plain string message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err = AutumnError::conflict_msg("Concurrent edit: please reload and retry");
    /// assert_eq!(err.status(), StatusCode::CONFLICT);
    /// ```
    pub fn conflict_msg(msg: impl Into<String>) -> Self {
        Self::conflict(StringError(msg.into()))
    }

    /// Returns the HTTP status code associated with this error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use autumn_web::error::AutumnError;
    /// use http::StatusCode;
    ///
    /// let err: AutumnError = std::io::Error::other("boom").into();
    /// assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    #[must_use]
    pub const fn status(&self) -> StatusCode {
        self.status
    }

    /// Return the wrapped error's source chain as displayable messages.
    ///
    /// The top-level [`AutumnError`] display already prints the wrapped error
    /// message, so this list starts at that wrapped error's first source.
    #[must_use]
    pub fn source_chain(&self) -> Vec<String> {
        let mut chain = Vec::new();
        let mut source = self.inner.source();
        while let Some(error) = source {
            chain.push(error.to_string());
            source = error.source();
        }
        chain
    }
}

impl std::fmt::Display for AutumnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl std::fmt::Debug for AutumnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AutumnError")
            .field("status", &self.status)
            .field("inner", &self.inner)
            .field("details", &self.details)
            .field("problem_type", &self.problem_type)
            .finish()
    }
}

impl ProblemDetails {
    /// Build a Problem Details payload from framework error metadata.
    #[must_use]
    pub fn new(
        status: StatusCode,
        detail: impl Into<String>,
        details: Option<&std::collections::HashMap<String, Vec<String>>>,
    ) -> Self {
        problem_details(status, detail.into(), details, None, None, None, true)
    }
}

/// Build the canonical Problem Details payload.
#[must_use]
pub(crate) fn problem_details(
    status: StatusCode,
    detail: String,
    details: Option<&std::collections::HashMap<String, Vec<String>>>,
    explicit_type: Option<&'static str>,
    request_id: Option<String>,
    instance: Option<String>,
    expose_internal_detail: bool,
) -> ProblemDetails {
    let has_validation_errors = details.is_some_and(|map| !map.is_empty());
    let safe_detail = if status.is_server_error() && !expose_internal_detail {
        server_error_detail(status)
    } else {
        detail
    };

    ProblemDetails {
        type_uri: explicit_type
            .unwrap_or_else(|| problem_type_for(status, has_validation_errors))
            .to_owned(),
        title: problem_title_for(status, has_validation_errors).to_owned(),
        status: status.as_u16(),
        detail: safe_detail,
        instance,
        code: problem_code_for(status, has_validation_errors).to_owned(),
        request_id,
        errors: validation_errors(details),
    }
}

/// Serialize a Problem Details payload for middleware that cannot return
/// `axum::Json` directly because its response body type is generic.
#[must_use]
pub(crate) fn problem_details_json_string(
    status: StatusCode,
    detail: impl Into<String>,
    details: Option<&std::collections::HashMap<String, Vec<String>>>,
    explicit_type: Option<&'static str>,
    request_id: Option<String>,
    instance: Option<String>,
    expose_internal_detail: bool,
) -> String {
    let problem = problem_details(
        status,
        detail.into(),
        details,
        explicit_type,
        request_id,
        instance,
        expose_internal_detail,
    );
    problem_details_to_json_string(&problem)
}

/// Serialize an already-built Problem Details payload.
#[must_use]
pub(crate) fn problem_details_to_json_string(problem: &ProblemDetails) -> String {
    serde_json::to_string(&problem).unwrap_or_else(|_| {
        r#"{"type":"https://autumn.dev/problems/internal-server-error","title":"Internal Server Error","status":500,"detail":"Internal server error","instance":null,"code":"autumn.internal_server_error","request_id":null,"errors":[]}"#.to_owned()
    })
}

fn validation_errors(
    details: Option<&std::collections::HashMap<String, Vec<String>>>,
) -> Vec<ProblemFieldError> {
    let mut errors: Vec<_> = details
        .into_iter()
        .flat_map(std::collections::HashMap::iter)
        .map(|(field, messages)| ProblemFieldError {
            field: field.clone(),
            messages: messages.clone(),
        })
        .collect();
    errors.sort_by(|left, right| left.field.cmp(&right.field));
    errors
}

const fn problem_type_for(status: StatusCode, has_validation_errors: bool) -> &'static str {
    if has_validation_errors {
        return "https://autumn.dev/problems/validation-failed";
    }

    match status {
        StatusCode::BAD_REQUEST => "https://autumn.dev/problems/bad-request",
        StatusCode::UNAUTHORIZED => "https://autumn.dev/problems/unauthorized",
        StatusCode::FORBIDDEN => "https://autumn.dev/problems/forbidden",
        StatusCode::NOT_FOUND => "https://autumn.dev/problems/not-found",
        StatusCode::CONFLICT => "https://autumn.dev/problems/conflict",
        StatusCode::PAYLOAD_TOO_LARGE => "https://autumn.dev/problems/payload-too-large",
        StatusCode::UNPROCESSABLE_ENTITY => "https://autumn.dev/problems/unprocessable-entity",
        StatusCode::INTERNAL_SERVER_ERROR => "https://autumn.dev/problems/internal-server-error",
        StatusCode::NOT_IMPLEMENTED => "https://autumn.dev/problems/not-implemented",
        StatusCode::SERVICE_UNAVAILABLE => "https://autumn.dev/problems/service-unavailable",
        _ => "about:blank",
    }
}

fn problem_title_for(status: StatusCode, has_validation_errors: bool) -> &'static str {
    if has_validation_errors {
        return "Validation Failed";
    }

    match status {
        StatusCode::BAD_REQUEST => "Bad Request",
        StatusCode::UNAUTHORIZED => "Unauthorized",
        StatusCode::FORBIDDEN => "Forbidden",
        StatusCode::NOT_FOUND => "Not Found",
        StatusCode::CONFLICT => "Conflict",
        StatusCode::PAYLOAD_TOO_LARGE => "Payload Too Large",
        StatusCode::UNPROCESSABLE_ENTITY => "Unprocessable Entity",
        StatusCode::INTERNAL_SERVER_ERROR => "Internal Server Error",
        StatusCode::NOT_IMPLEMENTED => "Not Implemented",
        StatusCode::SERVICE_UNAVAILABLE => "Service Unavailable",
        _ => status.canonical_reason().unwrap_or("Error"),
    }
}

fn problem_code_for(status: StatusCode, has_validation_errors: bool) -> &'static str {
    if has_validation_errors {
        return "autumn.validation_failed";
    }

    match status {
        StatusCode::BAD_REQUEST => "autumn.bad_request",
        StatusCode::UNAUTHORIZED => "autumn.unauthorized",
        StatusCode::FORBIDDEN => "autumn.forbidden",
        StatusCode::NOT_FOUND => "autumn.not_found",
        StatusCode::CONFLICT => "autumn.conflict",
        StatusCode::PAYLOAD_TOO_LARGE => "autumn.payload_too_large",
        StatusCode::UNPROCESSABLE_ENTITY => "autumn.unprocessable_entity",
        StatusCode::INTERNAL_SERVER_ERROR => "autumn.internal_server_error",
        StatusCode::NOT_IMPLEMENTED => "autumn.not_implemented",
        StatusCode::SERVICE_UNAVAILABLE => "autumn.service_unavailable",
        _ if status.is_client_error() => "autumn.client_error",
        _ if status.is_server_error() => "autumn.server_error",
        _ => "autumn.error",
    }
}

fn server_error_detail(status: StatusCode) -> String {
    match status {
        StatusCode::SERVICE_UNAVAILABLE => "Service unavailable".to_owned(),
        StatusCode::NOT_IMPLEMENTED => "Not implemented".to_owned(),
        _ => "Internal server error".to_owned(),
    }
}

impl IntoResponse for AutumnError {
    fn into_response(self) -> Response {
        let status = self.status;
        let message = self.inner.to_string();
        let details = self.details.clone();
        let problem_type = self.problem_type;

        // Stash error metadata for exception filters to inspect without
        // parsing the response body.
        let error_info = crate::middleware::AutumnErrorInfo {
            status,
            message: message.clone(),
            details: details.clone(),
            problem_type,
        };

        let body = problem_details(
            status,
            message,
            details.as_ref(),
            problem_type,
            None,
            None,
            true,
        );
        let mut response = (status, axum::Json(body)).into_response();
        response.headers_mut().insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/problem+json"),
        );
        if status == StatusCode::CONFLICT {
            response.headers_mut().insert(
                "HX-Trigger",
                HeaderValue::from_static(r#"{"autumn:conflict":true}"#),
            );
        }
        response.extensions_mut().insert(error_info);
        response
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::StatusCode;

    #[derive(Debug)]
    struct TestError(String);

    impl std::fmt::Display for TestError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl std::error::Error for TestError {}

    #[derive(Debug)]
    struct WrappedError {
        message: String,
        source: TestError,
    }

    impl std::fmt::Display for WrappedError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.message)
        }
    }

    impl std::error::Error for WrappedError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&self.source)
        }
    }

    #[test]
    fn blanket_from_defaults_to_500() {
        let err: AutumnError = TestError("boom".into()).into();
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn internal_server_error_is_500() {
        let err = AutumnError::internal_server_error(TestError("boom".into()));
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_not_found_error() {
        let err = AutumnError::not_found(std::io::Error::other("no such user"));
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn not_found_is_404() {
        let err = AutumnError::not_found(TestError("missing".into()));
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn bad_request_is_400() {
        let err = AutumnError::bad_request(TestError("invalid input".into()));
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn unprocessable_is_422() {
        let err = AutumnError::unprocessable(TestError("bad entity".into()));
        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[test]
    fn unauthorized_is_401() {
        let err = AutumnError::unauthorized(TestError("unauthorized".into()));
        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn forbidden_is_403() {
        let err = AutumnError::forbidden(TestError("forbidden".into()));
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn validation_is_422() {
        let mut details = std::collections::HashMap::new();
        details.insert("field".to_string(), vec!["error".to_string()]);
        let err = AutumnError::validation(details);
        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[test]
    fn service_unavailable_is_503() {
        let err = AutumnError::service_unavailable(TestError("pool exhausted".into()));
        assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[test]
    fn internal_server_error_msg_is_500() {
        let err = AutumnError::internal_server_error_msg("db failure");
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.to_string(), "db failure");
    }

    #[test]
    fn not_found_msg_is_404() {
        let err = AutumnError::not_found_msg("no such user");
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.to_string(), "no such user");
    }

    #[test]
    fn bad_request_msg_is_400() {
        let err = AutumnError::bad_request_msg("invalid input");
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn unprocessable_msg_is_422() {
        let err = AutumnError::unprocessable_msg("title required");
        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[test]
    fn unauthorized_msg_is_401() {
        let err = AutumnError::unauthorized_msg("login required");
        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn forbidden_msg_is_403() {
        let err = AutumnError::forbidden_msg("no access");
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn service_unavailable_msg_is_503() {
        let err = AutumnError::service_unavailable_msg("db down");
        assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(err.to_string(), "db down");
    }

    #[test]
    fn with_status_overrides() {
        let err: AutumnError = TestError("forbidden".into()).into();
        let err = err.with_status(StatusCode::FORBIDDEN);
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
    }

    #[test]
    fn display_uses_inner_message() {
        let err: AutumnError = TestError("something broke".into()).into();
        assert_eq!(err.to_string(), "something broke");
    }

    #[test]
    fn source_chain_lists_inner_sources() {
        let err = AutumnError::internal_server_error(WrappedError {
            message: "failed to backfill".to_string(),
            source: TestError("database connection dropped".to_string()),
        });

        assert_eq!(
            err.source_chain(),
            vec!["database connection dropped".to_string()]
        );
    }

    #[test]
    fn into_response_has_correct_status() {
        let err = AutumnError::not_found(TestError("not found".into()));
        let response = err.into_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn into_response_has_json_body() -> Result<(), axum::Error> {
        let err = AutumnError::not_found(TestError("not found".into()));
        let response = err.into_response();

        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid json");

        assert_eq!(json["status"], 404);
        assert_eq!(json["detail"], "not found");
        assert_eq!(json["code"], "autumn.not_found");
        Ok(())
    }

    #[test]
    fn debug_shows_status_and_inner() {
        let err = AutumnError::bad_request(TestError("oops".into()));
        let debug = format!("{err:?}");
        assert!(debug.contains("AutumnError"));
        assert!(debug.contains("400"));
    }

    #[tokio::test]
    async fn msg_constructor_produces_valid_json_response() -> Result<(), axum::Error> {
        let err = AutumnError::unprocessable_msg("title required");
        let response = err.into_response();

        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid json");
        assert_eq!(json["status"], 422);
        assert_eq!(json["detail"], "title required");
        assert_eq!(json["code"], "autumn.unprocessable_entity");
        Ok(())
    }

    #[tokio::test]
    async fn service_unavailable_response_is_503() -> Result<(), axum::Error> {
        let err = AutumnError::service_unavailable_msg("db down");
        let response = err.into_response();

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid json");
        assert_eq!(json["status"], 503);
        assert_eq!(json["detail"], "db down");
        assert_eq!(json["code"], "autumn.service_unavailable");
        Ok(())
    }

    #[test]
    fn conflict_is_409() {
        let err = AutumnError::conflict(TestError("stale version".into()));
        assert_eq!(err.status(), StatusCode::CONFLICT);
    }

    #[test]
    fn conflict_msg_is_409() {
        let err = AutumnError::conflict_msg("please reload and retry");
        assert_eq!(err.status(), StatusCode::CONFLICT);
        assert_eq!(err.to_string(), "please reload and retry");
    }

    #[tokio::test]
    async fn conflict_response_is_409_json() -> Result<(), axum::Error> {
        let err = AutumnError::conflict_msg("version mismatch");
        let response = err.into_response();

        assert_eq!(response.status(), StatusCode::CONFLICT);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
        let json: serde_json::Value = serde_json::from_slice(&body).expect("valid json");
        assert_eq!(json["status"], 409);
        assert_eq!(json["detail"], "version mismatch");
        assert_eq!(json["type"], "https://autumn.dev/problems/conflict");
        assert_eq!(json["title"], "Conflict");
        Ok(())
    }

    #[tokio::test]
    async fn conflict_response_has_hx_trigger_header() -> Result<(), axum::Error> {
        let err = AutumnError::conflict_msg("version mismatch");
        let response = err.into_response();

        assert_eq!(response.status(), StatusCode::CONFLICT);
        let hx_trigger = response
            .headers()
            .get("HX-Trigger")
            .expect("HX-Trigger header present");
        assert_eq!(hx_trigger, r#"{"autumn:conflict":true}"#);
        Ok(())
    }
}