axum-api-kit 2.0.0

Shared response types for Axum JSON APIs: ApiError, ListResponse, and HealthResponse
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
//! RFC 9457 `application/problem+json` error responses.
//!
//! [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) (Problem Details for HTTP
//! APIs) defines a standard JSON error shape - `type`, `title`, `status`,
//! `detail`, `instance`, plus arbitrary extension members - served with the
//! `application/problem+json` media type. [`Problem`] implements that shape as
//! a chainable builder that converts into an Axum response.
//!
//! # `Problem` vs [`ApiError`](crate::ApiError)
//!
//! [`ApiError`](crate::ApiError)'s flat `{ code, message, details }` body is
//! the kit's default and remains the right choice for services that own both
//! ends of the wire. Reach for `Problem` when the error format needs to
//! interoperate: API gateways that understand problem+json, OpenAPI tooling
//! that expects the RFC 9457 members, or polyglot clients standardizing on the
//! RFC across services.
//!
//! A separate type exists because `ApiError`'s serialization and factory
//! tuples are frozen under the 1.x stability promise, and `axum::Json` can
//! only emit `Content-Type: application/json`; `Problem` builds its own
//! response so it can send `application/problem+json`. The `From` impls in
//! this module bridge an existing `ApiError` (or a factory tuple) into a
//! `Problem` losslessly.
//!
//! # Content negotiation (opt-in)
//!
//! [`Problem`]'s plain [`IntoResponse`] impl always emits
//! `Content-Type: application/problem+json`; that behavior is frozen and does
//! not change for existing users. Handlers can opt into Accept-header
//! negotiation, serving the same body bytes as plain `application/json` when
//! the client strictly prefers it: extract [`ProblemFormat`] and finish with
//! [`Problem::into_response_with`], or call [`Problem::into_response_for`]
//! with the request's [`HeaderMap`]. The exact (deliberately minimal) rules
//! live on [`ProblemFormat::negotiate`]; every ambiguous case, including no
//! `Accept` header and `*/*`, stays `application/problem+json`.
//!
//! # problem+json extractor rejections (opt-in)
//!
//! The [`ProblemJson`](crate::ProblemJson) (features `problem` + `extract`)
//! and [`ProblemValidatedJson`](crate::ProblemValidatedJson) (features
//! `problem` + `validator`) extractors are the problem-flavored siblings of
//! [`ApiJson`](crate::ApiJson) and [`ValidatedJson`](crate::ValidatedJson):
//! same deserialization, validation, and status codes, but failures reject
//! with an RFC 9457 body (`Content-Type` negotiated via [`ProblemFormat`]).
//! The existing extractors' rejection bodies are frozen and never change; the
//! format is chosen by naming the extractor in the handler signature.
//!
//! # Out of scope
//!
//! - HTTP-date `Retry-After` values (only delay-seconds are emitted).
//!
//! A candidate for a future minor release.

use std::convert::Infallible;

use axum::{
    extract::FromRequestParts,
    http::{header, request::Parts, HeaderMap, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use serde::Serialize;

use crate::ApiError;

/// The `application/problem+json` media type from RFC 9457.
///
/// # Example
///
/// ```rust
/// use axum_api_kit::APPLICATION_PROBLEM_JSON;
///
/// assert_eq!(APPLICATION_PROBLEM_JSON, "application/problem+json");
/// ```
pub const APPLICATION_PROBLEM_JSON: &str = "application/problem+json";

/// An RFC 9457 problem details response body.
///
/// Serializes as:
/// ```json
/// { "title": "Not Found", "status": 404 }
/// { "type": "https://example.com/probs/out-of-credit", "title": "Insufficient credit",
///   "status": 403, "detail": "Balance is 30, item costs 50",
///   "instance": "/account/12345/msgs/abc", "balance": 30 }
/// ```
///
/// Implements [`IntoResponse`] with `Content-Type: application/problem+json`
/// and an optional delay-seconds `Retry-After` header.
///
/// # Example
///
/// ```rust
/// use axum::{http::StatusCode, response::IntoResponse};
/// use axum_api_kit::Problem;
///
/// async fn handler() -> impl IntoResponse {
///     Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
///         .with_type("https://example.com/probs/out-of-credit")
///         .with_detail("Balance is 30, item costs 50")
///         .with_instance("/account/12345/msgs/abc")
///         .with_extension("balance", 30)
/// }
/// ```
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Problem {
    /// A URI reference identifying the problem type. Absent means "about:blank" per RFC 9457.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub type_uri: Option<String>,
    /// A short, human-readable summary of the problem type. Stable per problem type.
    pub title: String,
    /// The HTTP status code, duplicated in the body per RFC 9457.
    pub status: u16,
    /// A human-readable explanation specific to this occurrence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    /// A URI reference identifying this specific occurrence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance: Option<String>,
    /// RFC 9457 extension members, flattened to top-level JSON keys.
    #[serde(flatten)]
    #[cfg_attr(feature = "openapi", schema(value_type = Object))]
    pub extensions: serde_json::Map<String, serde_json::Value>,
    /// Optional Retry-After header delay. Header-only; never serialized in the body.
    #[serde(skip)]
    #[cfg_attr(feature = "openapi", schema(ignore))]
    pub retry_after: Option<std::time::Duration>,
}

impl Problem {
    /// Builds a minimal `Problem` with the given status and title.
    ///
    /// `type`, `detail`, and `instance` start absent, extensions start empty,
    /// and no `Retry-After` header is emitted.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found");
    /// assert_eq!(
    ///     serde_json::to_value(&problem).unwrap(),
    ///     serde_json::json!({ "title": "Not Found", "status": 404 })
    /// );
    /// ```
    pub fn new(status: StatusCode, title: impl Into<String>) -> Self {
        Self {
            type_uri: None,
            title: title.into(),
            status: status.as_u16(),
            detail: None,
            instance: None,
            extensions: serde_json::Map::new(),
            retry_after: None,
        }
    }

    /// Sets the `type` member: a URI reference identifying the problem type.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_type("https://example.com/probs/out-of-credit");
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["type"], "https://example.com/probs/out-of-credit");
    /// ```
    pub fn with_type(mut self, type_uri: impl Into<String>) -> Self {
        self.type_uri = Some(type_uri.into());
        self
    }

    /// Sets the `detail` member: a human-readable explanation specific to this
    /// occurrence.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_detail("Balance is 30, item costs 50");
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["detail"], "Balance is 30, item costs 50");
    /// ```
    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// Sets the `instance` member: a URI reference identifying this specific
    /// occurrence.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_instance("/account/12345/msgs/abc");
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["instance"], "/account/12345/msgs/abc");
    /// ```
    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
        self.instance = Some(instance.into());
        self
    }

    /// Adds an RFC 9457 extension member, serialized as a top-level JSON key.
    ///
    /// If `key` is one of the reserved members (`"type"`, `"title"`,
    /// `"status"`, `"detail"`, `"instance"`), the call is a silent no-op so
    /// the flattened extensions can never emit duplicate JSON keys. This
    /// mirrors the [`ApiError::with_source`] silent-no-op precedent.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
    ///     .with_extension("balance", 30)
    ///     .with_extension("status", 999); // reserved key: ignored
    /// let v = serde_json::to_value(&problem).unwrap();
    /// assert_eq!(v["balance"], 30);
    /// assert_eq!(v["status"], 403);
    /// ```
    pub fn with_extension(
        mut self,
        key: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> Self {
        let key = key.into();
        if matches!(
            key.as_str(),
            "type" | "title" | "status" | "detail" | "instance"
        ) {
            return self;
        }
        self.extensions.insert(key, value.into());
        self
    }

    /// Emits a delay-seconds `Retry-After` header on the response, rounded up
    /// to whole seconds (1500ms becomes `"2"`).
    ///
    /// The delay never appears in the JSON body; add it via
    /// [`with_extension`](Self::with_extension) if body presence is wanted.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::{http::StatusCode, response::IntoResponse};
    /// use axum_api_kit::Problem;
    /// use std::time::Duration;
    ///
    /// let res = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
    ///     .with_retry_after(Duration::from_secs(30))
    ///     .into_response();
    /// assert_eq!(res.headers().get("retry-after").unwrap(), "30");
    /// ```
    pub fn with_retry_after(mut self, delay: std::time::Duration) -> Self {
        self.retry_after = Some(delay);
        self
    }

    /// Returns the `status` field as a [`StatusCode`], falling back to
    /// `500 Internal Server Error` when it is not a valid status.
    ///
    /// `StatusCode::from_u16` accepts `100..=999`, so the fallback only
    /// triggers for a hand-set `pub status` outside that range.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_api_kit::Problem;
    ///
    /// let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found");
    /// assert_eq!(problem.status_code(), StatusCode::NOT_FOUND);
    /// ```
    pub fn status_code(&self) -> StatusCode {
        StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
    }

    /// Converts into a response, choosing the `Content-Type` by negotiating
    /// against the request's `Accept` headers.
    ///
    /// Shorthand for `self.into_response_with(ProblemFormat::negotiate(headers))`;
    /// see [`ProblemFormat::negotiate`] for the exact rules. Plain
    /// `application/json` is served only when the client strictly prefers it;
    /// every ambiguous case (no `Accept` header, `*/*`, ties, unparseable
    /// values) serves `application/problem+json`. The body bytes and any
    /// `Retry-After` header are identical either way, and the plain
    /// [`IntoResponse`] behavior is untouched.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
    /// use axum_api_kit::Problem;
    ///
    /// let mut headers = HeaderMap::new();
    /// headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
    ///
    /// let res = Problem::new(StatusCode::NOT_FOUND, "Not Found").into_response_for(&headers);
    /// assert_eq!(res.headers().get(header::CONTENT_TYPE).unwrap(), "application/json");
    ///
    /// let res = Problem::new(StatusCode::NOT_FOUND, "Not Found").into_response_for(&HeaderMap::new());
    /// assert_eq!(
    ///     res.headers().get(header::CONTENT_TYPE).unwrap(),
    ///     "application/problem+json"
    /// );
    /// ```
    pub fn into_response_for(self, headers: &HeaderMap) -> Response {
        self.into_response_with(ProblemFormat::negotiate(headers))
    }

    /// Converts into a response served as the given [`ProblemFormat`].
    ///
    /// Pairs with the [`ProblemFormat`] extractor, which negotiates the format
    /// from the request's `Accept` headers before the handler runs. The JSON
    /// body bytes and any `Retry-After` header are identical for both formats;
    /// only the `Content-Type` header differs.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::{header, StatusCode};
    /// use axum_api_kit::{Problem, ProblemFormat};
    ///
    /// let res = Problem::new(StatusCode::NOT_FOUND, "Not Found")
    ///     .into_response_with(ProblemFormat::Json);
    /// assert_eq!(res.headers().get(header::CONTENT_TYPE).unwrap(), "application/json");
    /// ```
    pub fn into_response_with(self, format: ProblemFormat) -> Response {
        // axum::Json hardcodes Content-Type: application/json, so the response
        // is built via the (StatusCode, [(HeaderName, HeaderValue); 1], Vec<u8>)
        // tuple instead; the header part's insert overrides the
        // application/octet-stream default that Vec<u8> alone would set. The
        // same tuple pattern is used by Created::with_location in success.rs.
        // On the practically unreachable serialization failure, both the status
        // line and the body say 500 so they stay consistent.
        let retry = self.retry_after;
        let (status, body) = match serde_json::to_vec(&self) {
            Ok(bytes) => (self.status_code(), bytes),
            Err(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                br#"{"title":"Internal Server Error","status":500}"#.to_vec(),
            ),
        };
        let mut res = (
            status,
            [(
                header::CONTENT_TYPE,
                HeaderValue::from_static(format.content_type()),
            )],
            body,
        )
            .into_response();
        if let Some(d) = retry {
            res.headers_mut().insert(
                header::RETRY_AFTER,
                HeaderValue::from(crate::error::ceil_secs(d)),
            );
        }
        res
    }
}

impl IntoResponse for Problem {
    fn into_response(self) -> Response {
        // The frozen 1.x default: always application/problem+json. Content
        // negotiation is opt-in via into_response_for / into_response_with.
        self.into_response_with(ProblemFormat::ProblemJson)
    }
}

/// The media type a [`Problem`] response is served as: the RFC 9457 default
/// `application/problem+json`, or plain `application/json` for clients that
/// explicitly prefer it.
///
/// This is the opt-in content negotiation half of the `problem` feature.
/// [`Problem`]'s plain [`IntoResponse`] impl always emits
/// `application/problem+json`; nothing changes for existing users. To
/// negotiate, either extract `ProblemFormat` in a handler (it implements
/// [`FromRequestParts`] infallibly, reading the `Accept` headers) and finish
/// with [`Problem::into_response_with`], or call
/// [`Problem::into_response_for`] with the request's [`HeaderMap`] directly.
///
/// Both formats serve byte-identical JSON bodies; only the `Content-Type`
/// header differs. [`Default`] is [`ProblemFormat::ProblemJson`].
///
/// # Example
///
/// ```rust,no_run
/// use axum::{http::StatusCode, response::Response, routing::get, Router};
/// use axum_api_kit::{Problem, ProblemFormat};
///
/// // Accept: application/json          -> Content-Type: application/json
/// // Accept: */* (or no Accept header) -> Content-Type: application/problem+json
/// async fn not_found(format: ProblemFormat) -> Response {
///     Problem::new(StatusCode::NOT_FOUND, "Not Found").into_response_with(format)
/// }
///
/// let app: Router = Router::new().route("/missing", get(not_found));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProblemFormat {
    /// Serve `Content-Type: application/problem+json` (the RFC 9457 media
    /// type, and the default in every ambiguous case).
    #[default]
    ProblemJson,
    /// Serve `Content-Type: application/json`, for clients whose `Accept`
    /// header strictly prefers plain JSON.
    Json,
}

impl ProblemFormat {
    /// Chooses the response format from a request's `Accept` headers.
    ///
    /// This is a minimal, hand-rolled matcher, deliberately not a full
    /// RFC 9110 implementation. The rules:
    ///
    /// 1. Recognized media ranges are `application/problem+json`,
    ///    `application/json`, `application/*`, and `*/*` (ASCII
    ///    case-insensitive, across all `Accept` headers). Every other range,
    ///    including other `+json` suffix types, is ignored.
    /// 2. A range's weight is its `q` parameter (default `1`). Parameters
    ///    other than the first `q` are ignored. A range whose `q` value does
    ///    not parse per the RFC 9110 `qvalue` grammar (`0` to `1` with at
    ///    most three decimals) is ignored entirely.
    /// 3. Each of the two servable types takes its weight from the most
    ///    specific matching range (an exact match beats `application/*`,
    ///    which beats `*/*`); among equally specific matches the highest `q`
    ///    wins.
    /// 4. [`ProblemFormat::Json`] is returned only when plain
    ///    `application/json` ends up with a strictly higher weight than
    ///    `application/problem+json`. Everything else (no `Accept` header,
    ///    `*/*`, `application/*`, equal weights, `q=0` on both, unparseable
    ///    headers) returns [`ProblemFormat::ProblemJson`].
    ///
    /// | `Accept` | result |
    /// |---|---|
    /// | (absent) | problem+json |
    /// | `*/*` | problem+json |
    /// | `application/*` | problem+json |
    /// | `application/json` | plain JSON |
    /// | `application/problem+json` | problem+json |
    /// | `application/json, */*` | problem+json (tie at `q=1`) |
    /// | `application/json;q=0.9, application/problem+json;q=0.5` | plain JSON |
    /// | `application/problem+json, application/json` | problem+json (tie) |
    /// | `text/html` | problem+json (neither matched) |
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::{header, HeaderMap, HeaderValue};
    /// use axum_api_kit::ProblemFormat;
    ///
    /// let mut headers = HeaderMap::new();
    /// headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
    /// assert_eq!(ProblemFormat::negotiate(&headers), ProblemFormat::Json);
    ///
    /// assert_eq!(
    ///     ProblemFormat::negotiate(&HeaderMap::new()),
    ///     ProblemFormat::ProblemJson
    /// );
    /// ```
    pub fn negotiate(headers: &HeaderMap) -> Self {
        // Weight of the best matching range seen so far for each servable
        // type: (specificity, q in thousandths). Specificity: 3 exact match,
        // 2 application/*, 1 */*, 0 nothing matched yet.
        let mut problem = (0u8, 0u16);
        let mut json = (0u8, 0u16);

        for value in headers.get_all(header::ACCEPT) {
            let Ok(value) = value.to_str() else {
                // Non-UTF8 header values cannot express a preference we
                // recognize; skip them (the default then wins).
                continue;
            };
            for range in value.split(',') {
                let mut parts = range.split(';');
                // split always yields at least one segment.
                let media = parts.next().unwrap_or("").trim().to_ascii_lowercase();

                let mut q = 1000u16; // qvalue defaults to 1 per RFC 9110
                let mut malformed = false;
                for param in parts {
                    let (key, val) = match param.split_once('=') {
                        Some((key, val)) => (key.trim(), Some(val.trim())),
                        None => (param.trim(), None),
                    };
                    if key.eq_ignore_ascii_case("q") {
                        match val.and_then(parse_qvalue) {
                            Some(thousandths) => q = thousandths,
                            None => malformed = true,
                        }
                        break; // the first q parameter decides
                    }
                }
                if malformed {
                    continue;
                }

                let (specificity, to_problem, to_json) = match media.as_str() {
                    "application/problem+json" => (3u8, true, false),
                    "application/json" => (3, false, true),
                    "application/*" => (2, true, true),
                    "*/*" => (1, true, true),
                    _ => continue,
                };
                let update = |slot: &mut (u8, u16)| {
                    if specificity > slot.0 {
                        *slot = (specificity, q);
                    } else if specificity == slot.0 && q > slot.1 {
                        slot.1 = q;
                    }
                };
                if to_problem {
                    update(&mut problem);
                }
                if to_json {
                    update(&mut json);
                }
            }
        }

        if json.1 > problem.1 {
            Self::Json
        } else {
            Self::ProblemJson
        }
    }

    /// The `Content-Type` value this format serves.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum_api_kit::{ProblemFormat, APPLICATION_PROBLEM_JSON};
    ///
    /// assert_eq!(ProblemFormat::ProblemJson.content_type(), APPLICATION_PROBLEM_JSON);
    /// assert_eq!(ProblemFormat::Json.content_type(), "application/json");
    /// ```
    pub fn content_type(self) -> &'static str {
        match self {
            Self::ProblemJson => APPLICATION_PROBLEM_JSON,
            Self::Json => "application/json",
        }
    }
}

impl<S> FromRequestParts<S> for ProblemFormat
where
    S: Send + Sync,
{
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        Ok(Self::negotiate(&parts.headers))
    }
}

/// Parses an RFC 9110 `qvalue` into thousandths (`0..=1000`).
///
/// Grammar: `( "0" [ "." *3DIGIT ] ) / ( "1" [ "." *3("0") ] )`. Anything
/// else (empty, `.5`, `1.5`, more than three decimals, stray characters)
/// returns `None`, and [`ProblemFormat::negotiate`] ignores the whole media
/// range that carried it.
fn parse_qvalue(s: &str) -> Option<u16> {
    let (int, frac) = match s.split_once('.') {
        Some((int, frac)) => (int, frac),
        None => (s, ""),
    };
    if frac.len() > 3 || !frac.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    match int {
        "0" => {
            let mut thousandths = 0u16;
            for digit in frac.bytes() {
                thousandths = thousandths * 10 + u16::from(digit - b'0');
            }
            for _ in frac.len()..3 {
                thousandths *= 10;
            }
            Some(thousandths)
        }
        "1" => frac.bytes().all(|digit| digit == b'0').then_some(1000),
        _ => None,
    }
}

/// Convert a `(StatusCode, ApiError)` pair into a [`Problem`], losslessly.
///
/// | source | `Problem` member |
/// |---|---|
/// | status | `status` |
/// | status canonical reason | `title` (falls back to `code` for nonstandard statuses; cosmetic) |
/// | `message` | `detail` |
/// | `code` | `"code"` extension member |
/// | `details` (when present) | `"details"` extension member, verbatim |
///
/// `details` is kept under the single `"details"` key, never flattened, so
/// validation field maps cannot collide with reserved members. `type` and
/// `instance` are left absent, and no `Retry-After` header is set.
impl From<(StatusCode, ApiError)> for Problem {
    fn from((status, err): (StatusCode, ApiError)) -> Self {
        let title = status
            .canonical_reason()
            .map(str::to_owned)
            .unwrap_or_else(|| err.code.clone());
        let mut extensions = serde_json::Map::new();
        extensions.insert("code".to_owned(), serde_json::Value::String(err.code));
        if let Some(details) = err.details {
            extensions.insert("details".to_owned(), details);
        }
        Self {
            type_uri: None,
            title,
            status: status.as_u16(),
            detail: Some(err.message),
            instance: None,
            extensions,
            retry_after: None,
        }
    }
}

/// Convert a `(StatusCode, Json<ApiError>)` factory tuple into a [`Problem`].
///
/// Unwraps the [`Json`] and delegates to [`From<(StatusCode, ApiError)>`], so
/// existing factory results convert directly:
/// `Problem::from(ApiError::not_found("nope"))`.
impl From<(StatusCode, Json<ApiError>)> for Problem {
    fn from((status, Json(err)): (StatusCode, Json<ApiError>)) -> Self {
        Problem::from((status, err))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::time::Duration;

    #[test]
    fn minimal_serialization_omits_optional_members() {
        let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found");
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v, json!({ "title": "Not Found", "status": 404 }));
        assert!(v.get("type").is_none());
        assert!(v.get("detail").is_none());
        assert!(v.get("instance").is_none());
    }

    #[test]
    fn full_shape_serializes_all_rfc_members() {
        let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
            .with_type("https://example.com/probs/out-of-credit")
            .with_detail("Balance is 30, item costs 50")
            .with_instance("/account/12345/msgs/abc");
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v["type"], "https://example.com/probs/out-of-credit");
        assert_eq!(v["title"], "Insufficient credit");
        assert_eq!(v["status"], 403);
        assert_eq!(v["detail"], "Balance is 30, item costs 50");
        assert_eq!(v["instance"], "/account/12345/msgs/abc");
        assert!(v.get("type_uri").is_none());
    }

    #[test]
    fn extensions_flatten_to_top_level() {
        let problem = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
            .with_extension("balance", 30);
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v["balance"], 30);
        assert!(v.get("extensions").is_none());
    }

    #[test]
    fn with_extension_ignores_reserved_keys() {
        let problem = Problem::new(StatusCode::NOT_FOUND, "Not Found")
            .with_extension("status", 999)
            .with_extension("type", "https://example.com/overridden")
            .with_extension("title", "Overridden")
            .with_extension("detail", "overridden")
            .with_extension("instance", "/overridden");
        let v = serde_json::to_value(&problem).unwrap();
        assert_eq!(v, json!({ "title": "Not Found", "status": 404 }));
    }

    #[test]
    fn retry_after_never_serialized() {
        let problem = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
            .with_retry_after(Duration::from_secs(30));
        let v = serde_json::to_value(&problem).unwrap();
        assert!(v.get("retry_after").is_none());
    }

    #[tokio::test]
    async fn into_response_status_content_type_body() {
        let res = Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
            .with_type("https://example.com/probs/out-of-credit")
            .with_detail("Balance is 30, item costs 50")
            .with_instance("/account/12345/msgs/abc")
            .with_extension("balance", 30)
            .into_response();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
        assert_eq!(
            res.headers().get(header::CONTENT_TYPE).unwrap(),
            APPLICATION_PROBLEM_JSON
        );
        let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            body,
            json!({
                "type": "https://example.com/probs/out-of-credit",
                "title": "Insufficient credit",
                "status": 403,
                "detail": "Balance is 30, item costs 50",
                "instance": "/account/12345/msgs/abc",
                "balance": 30
            })
        );
    }

    #[tokio::test]
    async fn retry_after_header_seconds() {
        let res = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
            .with_retry_after(Duration::from_secs(30))
            .into_response();
        assert_eq!(res.headers().get(header::RETRY_AFTER).unwrap(), "30");

        let res = Problem::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests")
            .with_retry_after(Duration::from_millis(1500))
            .into_response();
        assert_eq!(res.headers().get(header::RETRY_AFTER).unwrap(), "2");
    }

    #[test]
    fn from_status_apierror_maps_fields() {
        let err =
            ApiError::new("NOT_FOUND", "item 42 does not exist").with_details(json!({ "id": 42 }));
        let problem = Problem::from((StatusCode::NOT_FOUND, err));
        assert_eq!(problem.title, "Not Found");
        assert_eq!(problem.status, 404);
        assert_eq!(problem.detail.as_deref(), Some("item 42 does not exist"));
        assert_eq!(problem.extensions["code"], "NOT_FOUND");
        assert_eq!(problem.extensions["details"], json!({ "id": 42 }));

        let no_details = Problem::from((StatusCode::NOT_FOUND, ApiError::new("NOT_FOUND", "nope")));
        assert!(!no_details.extensions.contains_key("details"));
    }

    #[test]
    fn from_status_json_apierror_unwraps() {
        let via_factory = Problem::from(ApiError::not_found("nope"));
        let direct = Problem::from((StatusCode::NOT_FOUND, ApiError::new("NOT_FOUND", "nope")));
        assert_eq!(
            serde_json::to_value(&via_factory).unwrap(),
            serde_json::to_value(&direct).unwrap()
        );
    }

    #[test]
    fn status_code_falls_back_to_500() {
        // StatusCode::from_u16 accepts 100..=999, so use a value below 100.
        let problem = Problem {
            type_uri: None,
            title: "weird".to_owned(),
            status: 42,
            detail: None,
            instance: None,
            extensions: serde_json::Map::new(),
            retry_after: None,
        };
        assert_eq!(problem.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    fn accept(value: &'static str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(header::ACCEPT, HeaderValue::from_static(value));
        headers
    }

    #[test]
    fn qvalue_grammar() {
        assert_eq!(parse_qvalue("1"), Some(1000));
        assert_eq!(parse_qvalue("1."), Some(1000));
        assert_eq!(parse_qvalue("1.0"), Some(1000));
        assert_eq!(parse_qvalue("1.000"), Some(1000));
        assert_eq!(parse_qvalue("0"), Some(0));
        assert_eq!(parse_qvalue("0."), Some(0));
        assert_eq!(parse_qvalue("0.5"), Some(500));
        assert_eq!(parse_qvalue("0.85"), Some(850));
        assert_eq!(parse_qvalue("0.855"), Some(855));

        assert_eq!(parse_qvalue("1.001"), None);
        assert_eq!(parse_qvalue("1.5"), None);
        assert_eq!(parse_qvalue("0.8555"), None); // more than three decimals
        assert_eq!(parse_qvalue(".5"), None);
        assert_eq!(parse_qvalue(""), None);
        assert_eq!(parse_qvalue("abc"), None);
        assert_eq!(parse_qvalue("01"), None);
        assert_eq!(parse_qvalue("-1"), None);
        assert_eq!(parse_qvalue("0.5x"), None);
    }

    #[test]
    fn negotiate_defaults_to_problem_json_in_every_ambiguous_case() {
        // No Accept header at all.
        assert_eq!(
            ProblemFormat::negotiate(&HeaderMap::new()),
            ProblemFormat::ProblemJson
        );
        for value in [
            "*/*",
            "application/*",
            "application/problem+json",
            "application/json, */*",                      // tie at q=1
            "application/problem+json, application/json", // tie at q=1
            "application/json;q=0.5, application/problem+json;q=0.5", // explicit tie
            "text/html",                                  // neither matched
            "application/json;q=0",                       // refused, nothing else
            "application/json;q=abc",                     // malformed q: range ignored
            "application/json;q",                         // bare q with no value: range ignored
            "application/json;q=1.5", // q outside the RFC grammar: range ignored
            "application/vnd.api+json", // +json suffix types are not matched
            ";;;,,,",                 // unparseable garbage
        ] {
            assert_eq!(
                ProblemFormat::negotiate(&accept(value)),
                ProblemFormat::ProblemJson,
                "Accept: {value}"
            );
        }
    }

    #[test]
    fn negotiate_serves_plain_json_on_strict_preference() {
        for value in [
            "application/json",
            "Application/JSON", // ASCII case-insensitive
            " application/json ; q=1 ",
            "application/json;q=0.9, application/problem+json;q=0.5",
            "application/json, application/problem+json;q=0.8",
            "text/html;q=1, application/json;q=0.9", // unrelated types are ignored
            "*/*;q=0.1, application/json;q=0.2",
            // Specificity: the exact problem+json match (q=0.5) beats the
            // wildcard (q=1) for problem+json, so plain JSON wins at 1 > 0.5.
            "application/*;q=1, application/problem+json;q=0.5",
        ] {
            assert_eq!(
                ProblemFormat::negotiate(&accept(value)),
                ProblemFormat::Json,
                "Accept: {value}"
            );
        }
    }

    #[test]
    fn negotiate_keeps_problem_json_on_strict_preference_for_it() {
        for value in [
            "application/problem+json;q=0.9, application/json;q=0.5",
            "application/json;q=0.1, application/problem+json",
            "application/*;q=1, application/json;q=0.5", // specificity, mirrored
        ] {
            assert_eq!(
                ProblemFormat::negotiate(&accept(value)),
                ProblemFormat::ProblemJson,
                "Accept: {value}"
            );
        }
    }

    #[test]
    fn negotiate_scans_all_accept_headers() {
        let mut headers = HeaderMap::new();
        headers.append(header::ACCEPT, HeaderValue::from_static("text/html"));
        headers.append(header::ACCEPT, HeaderValue::from_static("application/json"));
        assert_eq!(ProblemFormat::negotiate(&headers), ProblemFormat::Json);
    }

    #[test]
    fn negotiate_skips_non_utf8_accept_values() {
        let mut headers = HeaderMap::new();
        headers.insert(header::ACCEPT, HeaderValue::from_bytes(&[0xFF]).unwrap());
        assert_eq!(
            ProblemFormat::negotiate(&headers),
            ProblemFormat::ProblemJson
        );
    }

    #[test]
    fn problem_format_default_and_content_types() {
        assert_eq!(ProblemFormat::default(), ProblemFormat::ProblemJson);
        assert_eq!(
            ProblemFormat::ProblemJson.content_type(),
            APPLICATION_PROBLEM_JSON
        );
        assert_eq!(ProblemFormat::Json.content_type(), "application/json");
    }

    #[tokio::test]
    async fn into_response_with_json_changes_only_content_type() {
        let problem = || {
            Problem::new(StatusCode::FORBIDDEN, "Insufficient credit")
                .with_detail("Balance is 30, item costs 50")
                .with_extension("balance", 30)
                .with_retry_after(Duration::from_secs(30))
        };
        let default = problem().into_response();
        let negotiated = problem().into_response_with(ProblemFormat::Json);

        assert_eq!(negotiated.status(), default.status());
        assert_eq!(
            negotiated.headers().get(header::CONTENT_TYPE).unwrap(),
            "application/json"
        );
        assert_eq!(negotiated.headers().get(header::RETRY_AFTER).unwrap(), "30");

        let default_body = axum::body::to_bytes(default.into_body(), usize::MAX)
            .await
            .unwrap();
        let negotiated_body = axum::body::to_bytes(negotiated.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(
            default_body, negotiated_body,
            "bodies must be byte-identical across formats"
        );
    }

    #[tokio::test]
    async fn into_response_for_negotiates_from_headers() {
        let res = Problem::new(StatusCode::NOT_FOUND, "Not Found")
            .into_response_for(&accept("application/json"));
        assert_eq!(
            res.headers().get(header::CONTENT_TYPE).unwrap(),
            "application/json"
        );

        let res =
            Problem::new(StatusCode::NOT_FOUND, "Not Found").into_response_for(&HeaderMap::new());
        assert_eq!(
            res.headers().get(header::CONTENT_TYPE).unwrap(),
            APPLICATION_PROBLEM_JSON
        );
    }

    #[tokio::test]
    async fn plain_into_response_is_unchanged_by_negotiation_support() {
        // Locks the frozen 1.x behavior byte-for-byte: exactly the status,
        // header set, and body bytes Problem::into_response emitted in 1.3.0,
        // regardless of the negotiation machinery added alongside it.
        let res = Problem::new(StatusCode::NOT_FOUND, "Not Found")
            .with_retry_after(Duration::from_secs(30))
            .into_response();
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
        assert_eq!(res.headers().len(), 2);
        assert_eq!(
            res.headers().get(header::CONTENT_TYPE).unwrap(),
            APPLICATION_PROBLEM_JSON
        );
        assert_eq!(res.headers().get(header::RETRY_AFTER).unwrap(), "30");
        let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&bytes[..], br#"{"title":"Not Found","status":404}"#);

        // And the minimal case without Retry-After.
        let res = Problem::new(StatusCode::NOT_FOUND, "Not Found").into_response();
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
        assert_eq!(res.headers().len(), 1);
        assert_eq!(
            res.headers().get(header::CONTENT_TYPE).unwrap(),
            APPLICATION_PROBLEM_JSON
        );
        let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(&bytes[..], br#"{"title":"Not Found","status":404}"#);
    }
}