docspec-http 1.21.9

HTTP API server for DocSpec document conversion
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
//! Error types for the HTTP server.

use std::borrow::Cow;

use axum::{
    http::{
        header::{ALLOW, CONTENT_TYPE},
        HeaderValue, StatusCode,
    },
    response::{IntoResponse, Response},
};
use docspec_json::{JsonEmitter, StrusonBackend};

/// RFC 7807 Problem Details for HTTP APIs.
///
/// Contains exactly four fields per [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807):
/// `type`, `title`, `status`, and `detail`. Serialized without `serde`
/// via [`ProblemJson::to_json_bytes`].
#[derive(Debug)]
pub struct ProblemJson {
    /// Human-readable explanation specific to this occurrence.
    ///
    /// May contain user-supplied data such as path names or MIME type strings.
    /// Dynamic values are stored as [`Cow::Owned`]; static strings as [`Cow::Borrowed`].
    pub detail: Cow<'static, str>,
    /// HTTP status code generated by this occurrence.
    pub status: u16,
    /// Short, human-readable summary of the problem type.
    ///
    /// Matches the standard HTTP reason phrase for the status code.
    pub title: &'static str,
    /// URI reference identifying the problem type.
    ///
    /// This server always uses `"about:blank"`.
    pub type_uri: &'static str,
}

/// Pre-encoded RFC 7807 body used when serializing a `ProblemJson` fails.
///
/// Written out verbatim so the fallback never re-enters the JSON emitter that
/// just failed.
const SERIALIZATION_FALLBACK_JSON: &[u8] = br#"{"type":"about:blank","title":"Internal Server Error","status":500,"detail":"Error response serialization failed"}"#;

impl ProblemJson {
    fn try_to_json_bytes(&self) -> docspec_core::Result<Vec<u8>> {
        let mut emitter = JsonEmitter::new(StrusonBackend::new(Vec::new()));
        emitter.object(|builder| {
            builder.key("type").value(self.type_uri)?;
            builder.key("title").value(self.title)?;
            builder.key("status").value(u32::from(self.status))?;
            builder.key("detail").value(self.detail.as_ref())?;
            Ok(())
        })?;
        emitter.finish()
    }

    /// Serialize this problem detail as a JSON-encoded byte vector.
    ///
    /// Emits exactly four fields in document order:
    /// `"type"`, `"title"`, `"status"`, `"detail"`. String fields are
    /// JSON-escaped (RFC 8259 §7) by the underlying writer; the status is
    /// an unquoted integer.
    ///
    /// Uses [`JsonEmitter`] backed by `struson` for serialization. If
    /// serialization fails, returns a static RFC 7807 `500` body rather than
    /// panicking, so constructing an error response can never itself abort the
    /// request.
    #[inline]
    #[must_use]
    pub fn to_json_bytes(&self) -> Vec<u8> {
        Self::bytes_or_fallback(self.try_to_json_bytes())
    }

    /// Unwraps a serialization result, degrading to the static fallback body.
    fn bytes_or_fallback(serialized: docspec_core::Result<Vec<u8>>) -> Vec<u8> {
        serialized.unwrap_or_else(|_| SERIALIZATION_FALLBACK_JSON.to_vec())
    }
}

/// Builds the RFC 7807 response, degrading to a static body if serialization fails.
fn problem_response(
    problem: &ProblemJson,
    status: StatusCode,
    allow: Option<&'static str>,
) -> Response {
    problem_response_from(problem.try_to_json_bytes(), status, allow)
}

/// Builds the RFC 7807 response from an already-attempted serialization.
///
/// Split from [`problem_response`] so the degraded path can be exercised
/// directly: with a `Vec<u8>` sink the emitter never fails in practice, so the
/// `Err` arm is otherwise unreachable from a test.
fn problem_response_from(
    serialized: docspec_core::Result<Vec<u8>>,
    status: StatusCode,
    allow: Option<&'static str>,
) -> Response {
    let mut response = match serialized {
        Ok(body) => {
            let mut ok_response = (status, body).into_response();
            if let Some(allowed) = allow {
                ok_response
                    .headers_mut()
                    .insert(ALLOW, HeaderValue::from_static(allowed));
            }
            ok_response
        }
        Err(error) => {
            tracing::error!(%error, "problem JSON serialization failed; sending static fallback");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                SERIALIZATION_FALLBACK_JSON,
            )
                .into_response()
        }
    };
    response.headers_mut().insert(
        CONTENT_TYPE,
        HeaderValue::from_static("application/problem+json; charset=utf-8"),
    );
    response
}

/// HTTP-layer errors returned by the conversion API.
///
/// Each variant maps to a specific HTTP status code and is serialized as
/// an RFC 7807 Problem JSON body via [`IntoResponse`].
#[derive(Debug)]
#[non_exhaustive]
pub enum HttpError {
    /// The request body bytes are not valid UTF-8.
    ///
    /// → HTTP 400 Bad Request.
    BodyNotUtf8,
    /// The request body was empty (`Content-Length: 0` or no body).
    ///
    /// → HTTP 400 Bad Request.
    EmptyBody,
    /// An unexpected internal error occurred during conversion.
    ///
    /// The `source` error is captured for observability (sent to Sentry via
    /// [`sentry::capture_error`], logged at `warn!` in stderr) and drives the
    /// error chain visible to operators. It is **never** exposed to the HTTP
    /// client — the RFC 7807 response detail is always the generic
    /// "An unexpected error occurred during conversion" string.
    ///
    /// → HTTP 500 Internal Server Error.
    Internal {
        /// The underlying error that caused this internal failure.
        source: Box<dyn core::error::Error + Send + Sync + 'static>,
    },
    /// The HTTP method is not supported on this endpoint.
    ///
    /// → HTTP 405 Method Not Allowed (response includes an `Allow` header).
    MethodNotAllowed {
        /// Comma-separated list of allowed methods for this endpoint.
        allowed: &'static str,
    },
    /// The `Accept` header excludes all formats this server produces.
    ///
    /// → HTTP 406 Not Acceptable.
    NotAcceptable,
    /// No route matches the requested method + path.
    ///
    /// → HTTP 404 Not Found.
    NotFound {
        /// The HTTP method of the unmatched request (e.g. `"GET"`).
        method: String,
        /// The path of the unmatched request (e.g. `"/unknown"`).
        path: String,
    },
    /// Document conversion failed due to invalid or malformed input.
    ///
    /// → HTTP 422 Unprocessable Entity.
    Unprocessable {
        /// Explanation of what made the input invalid.
        detail: String,
    },
    /// The `Content-Type` header is not one of the supported types: `text/markdown`, `text/html`, or `application/vnd.openxmlformats-officedocument.wordprocessingml.document`.
    ///
    /// → HTTP 415 Unsupported Media Type.
    UnsupportedMediaType {
        /// The content-type that was received, if any.
        received: Option<String>,
    },
}

/// Constructs a `PostHog` `$exception` event for an HTTP error.
///
/// The `sentry_event_id` property correlates this event with the corresponding
/// Sentry event when both backends are active. Each call uses a fresh `distinct_id`
/// (per-event UUID with `$is_anonymous = true`) because the sync `IntoResponse`
/// context does not have access to the request ID.
#[cfg(feature = "posthog")]
fn build_posthog_error_event(detail: &str, sentry_event_id: Option<String>) -> posthog_rs::Event {
    let distinct_id = uuid::Uuid::new_v4().to_string();
    let mut event = posthog_rs::Event::new("$exception", &distinct_id);
    drop(event.insert_prop("$exception_message", detail));
    drop(event.insert_prop("$is_anonymous", true));
    if let Some(sentry_id) = sentry_event_id {
        drop(event.insert_prop("sentry_event_id", sentry_id));
    }
    event
}

#[cfg(feature = "sentry")]
#[inline]
fn capture_sentry(
    detail: &str,
    source: Option<&(dyn core::error::Error + Send + Sync + 'static)>,
) -> sentry::types::Uuid {
    source.map_or_else(
        || sentry::capture_message(detail, sentry::Level::Error),
        sentry::capture_error,
    )
}

#[cfg(any(feature = "sentry", feature = "posthog"))]
fn capture_error_telemetry(
    status: StatusCode,
    detail: &str,
    source: Option<&(dyn core::error::Error + Send + Sync + 'static)>,
) {
    if status != StatusCode::INTERNAL_SERVER_ERROR && status != StatusCode::UNPROCESSABLE_ENTITY {
        return;
    }

    #[cfg(not(feature = "sentry"))]
    let _ = source;

    #[cfg(all(feature = "sentry", not(feature = "posthog")))]
    {
        let _ = capture_sentry(detail, source);
    }
    #[cfg(all(feature = "sentry", feature = "posthog"))]
    let sentry_id_string: Option<String> = Some(capture_sentry(detail, source).to_string());
    #[cfg(all(not(feature = "sentry"), feature = "posthog"))]
    let sentry_id_string: Option<String> = None;
    #[cfg(feature = "posthog")]
    {
        let client_arc: Option<std::sync::Arc<posthog_rs::Client>> =
            match crate::telemetry::posthog_client_slot().read() {
                Ok(guard) => guard.as_ref().map(std::sync::Arc::clone),
                Err(_poisoned) => {
                    tracing::warn!("posthog slot poisoned; skipping error capture");
                    None
                }
            };
        if let Some(client) = client_arc {
            let event = build_posthog_error_event(detail, sentry_id_string);
            client.capture(event);
        }
    }
}

impl IntoResponse for HttpError {
    /// Convert this error into an HTTP response with an RFC 7807 Problem JSON body.
    ///
    /// Sets `Content-Type: application/problem+json; charset=utf-8` and a JSON body
    /// with exactly four fields: `type`, `title`, `status`, `detail`.
    /// [`HttpError::MethodNotAllowed`] additionally sets the `Allow` response header.
    #[inline]
    fn into_response(self) -> Response {
        #[cfg(any(feature = "sentry", feature = "posthog"))]
        self.capture_to_telemetry();

        let (status, title, detail, allow): (
            StatusCode,
            &'static str,
            Cow<'static, str>,
            Option<&'static str>,
        ) = match self {
            Self::EmptyBody => (
                StatusCode::BAD_REQUEST,
                "Bad Request",
                Cow::Borrowed("Request body is empty"),
                None,
            ),
            Self::BodyNotUtf8 => (
                StatusCode::BAD_REQUEST,
                "Bad Request",
                Cow::Borrowed("Request body is not valid UTF-8"),
                None,
            ),
            Self::NotFound { method, path } => (
                StatusCode::NOT_FOUND,
                "Not Found",
                Cow::Owned(format!("No route matches {method} {path}")),
                None,
            ),
            Self::MethodNotAllowed { allowed } => (
                StatusCode::METHOD_NOT_ALLOWED,
                "Method Not Allowed",
                Cow::Owned(format!("Method not allowed. Allowed methods: {allowed}.")),
                Some(allowed),
            ),
            Self::NotAcceptable => (
                StatusCode::NOT_ACCEPTABLE,
                "Not Acceptable",
                Cow::Borrowed(
                    "Accept header must include application/vnd.docspec.blocknote+json, \
                     application/vnd.blocknote+json, application/vnd.oxa+json, \
                     application/vnd.pandoc.native, text/html, application/*, or */*",
                ),
                None,
            ),
            Self::UnsupportedMediaType { received: None } => (
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                "Unsupported Media Type",
                Cow::Borrowed("Content-Type must be text/markdown, text/html, or application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
                None,
            ),
            Self::UnsupportedMediaType {
                received: Some(content_type),
            } => (
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                "Unsupported Media Type",
                Cow::Owned(format!(
                    "Content-Type must be text/markdown, text/html, or application/vnd.openxmlformats-officedocument.wordprocessingml.document, got {content_type}"
                )),
                None,
            ),
            Self::Unprocessable { detail } => (
                StatusCode::UNPROCESSABLE_ENTITY,
                "Unprocessable Entity",
                Cow::Owned(detail),
                None,
            ),
            Self::Internal { .. } => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Internal Server Error",
                Cow::Borrowed("An unexpected error occurred during conversion"),
                None,
            ),
        };

        let problem = ProblemJson {
            detail,
            status: status.as_u16(),
            title,
            type_uri: "about:blank",
        };
        problem_response(&problem, status, allow)
    }
}

impl HttpError {
    /// Returns a stable, low-cardinality string identifying the error class.
    /// Safe to use as a Prometheus label value — never contains per-request data.
    #[inline]
    #[must_use]
    pub fn error_class(&self) -> &'static str {
        match self {
            Self::BodyNotUtf8 => "body_not_utf8",
            Self::EmptyBody => "empty_body",
            Self::Internal { .. } => "internal",
            Self::MethodNotAllowed { .. } => "method_not_allowed",
            Self::NotAcceptable => "not_acceptable",
            Self::NotFound { .. } => "not_found",
            Self::Unprocessable { .. } => "unprocessable",
            Self::UnsupportedMediaType { .. } => "unsupported_media_type",
        }
    }

    /// Returns the result class for Prometheus labels: `"client_error"` for 4xx, `"server_error"` for 5xx.
    #[inline]
    #[must_use]
    pub fn result_class(&self) -> &'static str {
        use crate::metrics::{RESULT_CLIENT_ERROR, RESULT_SERVER_ERROR};
        match self {
            Self::BodyNotUtf8
            | Self::EmptyBody
            | Self::MethodNotAllowed { .. }
            | Self::NotAcceptable
            | Self::NotFound { .. }
            | Self::Unprocessable { .. }
            | Self::UnsupportedMediaType { .. } => RESULT_CLIENT_ERROR,
            Self::Internal { .. } => RESULT_SERVER_ERROR,
        }
    }

    /// Wrap an unexpected internal error as [`HttpError::Internal`].
    ///
    /// The source is preserved end-to-end for observability — it flows to
    /// Sentry via [`sentry::capture_error`] (walking the [`core::error::Error::source`]
    /// chain) and is logged at `warn!` level via [`core::fmt::Debug`] formatting.
    #[inline]
    #[must_use]
    pub fn internal<E>(source: E) -> Self
    where
        E: core::error::Error + Send + Sync + 'static,
    {
        Self::Internal {
            source: Box::new(source),
        }
    }

    /// Capture this error to configured telemetry backends (Sentry, `PostHog`)
    /// when the variant is a 500 or 422.
    #[cfg(any(feature = "sentry", feature = "posthog"))]
    pub(crate) fn capture_to_telemetry(&self) {
        match self {
            Self::Internal { source } => {
                capture_error_telemetry(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "An unexpected error occurred during conversion",
                    Some(source.as_ref()),
                );
            }
            Self::Unprocessable { detail } => {
                capture_error_telemetry(StatusCode::UNPROCESSABLE_ENTITY, detail.as_str(), None);
            }
            Self::BodyNotUtf8
            | Self::EmptyBody
            | Self::MethodNotAllowed { .. }
            | Self::NotAcceptable
            | Self::NotFound { .. }
            | Self::UnsupportedMediaType { .. } => {}
        }
    }
}

#[cfg(test)]
mod tests {
    // Reason: test code legitimately panics on assertion failures; unwrap, expect,
    // and slice indexing are standard testing patterns that express expected outcomes.
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use axum::{
        http::{
            header::{ALLOW, CONTENT_TYPE},
            StatusCode,
        },
        response::IntoResponse as _,
    };

    use super::*;

    async fn body_bytes(error: HttpError) -> Vec<u8> {
        axum::body::to_bytes(error.into_response().into_body(), usize::MAX)
            .await
            .unwrap()
            .to_vec()
    }

    fn dummy_error() -> std::io::Error {
        std::io::Error::other("dummy internal error")
    }

    fn serialization_error() -> docspec_core::Error {
        docspec_core::Error::Other {
            message: "forced serialization failure".to_string(),
        }
    }

    #[test]
    fn bytes_or_fallback_returns_static_body_when_serialization_fails() {
        assert_eq!(
            ProblemJson::bytes_or_fallback(Err(serialization_error())),
            br#"{"type":"about:blank","title":"Internal Server Error","status":500,"detail":"Error response serialization failed"}"#
                .to_vec()
        );
    }

    #[test]
    fn bytes_or_fallback_passes_through_successful_serialization() {
        assert_eq!(
            ProblemJson::bytes_or_fallback(Ok(b"{\"ok\":true}".to_vec())),
            b"{\"ok\":true}".to_vec()
        );
    }

    #[tokio::test]
    async fn problem_response_degrades_to_500_fallback_when_serialization_fails() {
        let response =
            problem_response_from(Err(serialization_error()), StatusCode::BAD_REQUEST, None);

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(
            response.headers().get(CONTENT_TYPE).unwrap(),
            "application/problem+json; charset=utf-8"
        );
        assert_eq!(
            axum::body::to_bytes(response.into_body(), usize::MAX)
                .await
                .unwrap()
                .to_vec(),
            br#"{"type":"about:blank","title":"Internal Server Error","status":500,"detail":"Error response serialization failed"}"#
                .to_vec()
        );
    }

    #[tokio::test]
    async fn problem_response_drops_allow_header_on_serialization_failure() {
        let response = problem_response_from(
            Err(serialization_error()),
            StatusCode::METHOD_NOT_ALLOWED,
            Some("POST, OPTIONS"),
        );

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(response.headers().get(ALLOW), None);
    }

    #[test]
    fn all_variants_have_correct_status_codes() {
        assert_eq!(
            HttpError::EmptyBody.into_response().status(),
            StatusCode::BAD_REQUEST
        );
        assert_eq!(
            HttpError::BodyNotUtf8.into_response().status(),
            StatusCode::BAD_REQUEST
        );
        assert_eq!(
            HttpError::NotFound {
                method: "GET".to_owned(),
                path: "/foo".to_owned()
            }
            .into_response()
            .status(),
            StatusCode::NOT_FOUND
        );
        assert_eq!(
            HttpError::MethodNotAllowed { allowed: "GET" }
                .into_response()
                .status(),
            StatusCode::METHOD_NOT_ALLOWED
        );
        assert_eq!(
            HttpError::NotAcceptable.into_response().status(),
            StatusCode::NOT_ACCEPTABLE
        );
        assert_eq!(
            HttpError::UnsupportedMediaType { received: None }
                .into_response()
                .status(),
            StatusCode::UNSUPPORTED_MEDIA_TYPE
        );
        assert_eq!(
            HttpError::Unprocessable {
                detail: "bad".to_owned()
            }
            .into_response()
            .status(),
            StatusCode::UNPROCESSABLE_ENTITY
        );
        assert_eq!(
            HttpError::internal(dummy_error()).into_response().status(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[test]
    fn method_not_allowed_has_allow_header() {
        let response = HttpError::MethodNotAllowed { allowed: "GET" }.into_response();
        let allow_val = response.headers().get(ALLOW).unwrap();
        assert_eq!(allow_val, "GET");
    }

    #[test]
    fn content_type_is_problem_json() {
        let response = HttpError::internal(dummy_error()).into_response();
        let content_type = response.headers().get(CONTENT_TYPE).unwrap();
        assert_eq!(content_type, "application/problem+json; charset=utf-8");
    }

    #[test]
    fn no_allow_header_on_non_405_variants() {
        let response = HttpError::internal(dummy_error()).into_response();
        assert!(response.headers().get(ALLOW).is_none());
    }

    #[cfg(feature = "sentry")]
    #[test]
    fn internal_error_is_captured_by_sentry_with_source_chain() {
        let events = sentry::test::with_captured_events(|| {
            let _response = HttpError::internal(dummy_error()).into_response();
        });
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].level, sentry::Level::Error);
        assert!(
            events[0].message.is_none(),
            "capture_error must not populate top-level message"
        );
        let first_exception = events[0]
            .exception
            .values
            .first()
            .expect("exception chain must be populated by capture_error");
        assert_eq!(
            first_exception.value.as_deref(),
            Some("dummy internal error"),
            "exception value must equal the Display of the source error"
        );
    }

    #[cfg(feature = "sentry")]
    #[test]
    fn unprocessable_error_is_captured_by_sentry() {
        let events = sentry::test::with_captured_events(|| {
            let _response = HttpError::Unprocessable {
                detail: "bad input".to_owned(),
            }
            .into_response();
        });
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].level, sentry::Level::Error);
        assert_eq!(events[0].message.as_deref(), Some("bad input"));
    }

    #[cfg(feature = "sentry")]
    #[test]
    fn client_errors_are_not_captured_by_sentry() {
        let events = sentry::test::with_captured_events(|| {
            drop(HttpError::EmptyBody.into_response());
            drop(HttpError::BodyNotUtf8.into_response());
            drop(
                HttpError::NotFound {
                    method: "GET".to_owned(),
                    path: "/x".to_owned(),
                }
                .into_response(),
            );
            drop(HttpError::MethodNotAllowed { allowed: "GET" }.into_response());
            drop(HttpError::NotAcceptable.into_response());
            drop(HttpError::UnsupportedMediaType { received: None }.into_response());
        });
        assert_eq!(events.len(), 0, "4xx errors must not be captured");
    }

    #[tokio::test]
    async fn serializes_with_four_fields() {
        let bytes = body_bytes(HttpError::internal(dummy_error())).await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "type": "about:blank",
                "title": "Internal Server Error",
                "status": 500,
                "detail": "An unexpected error occurred during conversion",
            })
        );
    }

    #[tokio::test]
    async fn no_instance_key_in_output() {
        let bytes = body_bytes(HttpError::EmptyBody).await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(
            json.get("instance").is_none(),
            "unexpected 'instance' key in output"
        );
    }

    #[tokio::test]
    async fn not_found_problem_body_is_exact() {
        let bytes = body_bytes(HttpError::NotFound {
            method: "GET".to_owned(),
            path: "/api/v99".to_owned(),
        })
        .await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "type": "about:blank",
                "title": "Not Found",
                "status": 404,
                "detail": "No route matches GET /api/v99",
            })
        );
    }

    #[tokio::test]
    async fn internal_detail_is_fixed() {
        let bytes = body_bytes(HttpError::internal(dummy_error())).await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            json["detail"].as_str().unwrap(),
            "An unexpected error occurred during conversion"
        );
    }

    #[tokio::test]
    async fn unsupported_media_type_with_received_problem_body_is_exact() {
        let bytes = body_bytes(HttpError::UnsupportedMediaType {
            received: Some("application/json".to_owned()),
        })
        .await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "type": "about:blank",
                "title": "Unsupported Media Type",
                "status": 415,
                "detail": "Content-Type must be text/markdown, text/html, or application/vnd.openxmlformats-officedocument.wordprocessingml.document, got application/json",
            })
        );
    }

    #[tokio::test]
    async fn unprocessable_problem_body_is_exact() {
        let message = "heading level jumped from 1 to 3".to_owned();
        let bytes = body_bytes(HttpError::Unprocessable {
            detail: message.clone(),
        })
        .await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "type": "about:blank",
                "title": "Unprocessable Entity",
                "status": 422,
                "detail": message,
            })
        );
    }

    #[tokio::test]
    async fn control_char_in_detail_is_escaped() {
        let bytes = body_bytes(HttpError::Unprocessable {
            detail: "bad\x01input".to_owned(),
        })
        .await;
        assert_eq!(
            bytes.as_slice(),
            br#"{"type":"about:blank","title":"Unprocessable Entity","status":422,"detail":"bad\u0001input"}"#
        );
    }

    #[test]
    fn body_not_utf8_error_class_returns_body_not_utf8() {
        assert_eq!(HttpError::BodyNotUtf8.error_class(), "body_not_utf8");
    }

    #[test]
    fn empty_body_error_class_returns_empty_body() {
        assert_eq!(HttpError::EmptyBody.error_class(), "empty_body");
    }

    #[test]
    fn internal_error_class_returns_internal() {
        assert_eq!(HttpError::internal(dummy_error()).error_class(), "internal");
    }

    #[test]
    fn method_not_allowed_error_class_returns_method_not_allowed() {
        assert_eq!(
            HttpError::MethodNotAllowed { allowed: "GET" }.error_class(),
            "method_not_allowed"
        );
    }

    #[test]
    fn not_acceptable_error_class_returns_not_acceptable() {
        assert_eq!(HttpError::NotAcceptable.error_class(), "not_acceptable");
    }

    #[test]
    fn not_found_error_class_returns_not_found() {
        assert_eq!(
            HttpError::NotFound {
                method: "GET".to_owned(),
                path: "/foo".to_owned()
            }
            .error_class(),
            "not_found"
        );
    }

    #[test]
    fn unprocessable_error_class_returns_unprocessable() {
        assert_eq!(
            HttpError::Unprocessable {
                detail: "bad".to_owned()
            }
            .error_class(),
            "unprocessable"
        );
    }

    #[test]
    fn unsupported_media_type_error_class_returns_unsupported_media_type() {
        assert_eq!(
            HttpError::UnsupportedMediaType { received: None }.error_class(),
            "unsupported_media_type"
        );
    }

    #[test]
    fn body_not_utf8_result_class_returns_client_error() {
        assert_eq!(HttpError::BodyNotUtf8.result_class(), "client_error");
    }

    #[test]
    fn empty_body_result_class_returns_client_error() {
        assert_eq!(HttpError::EmptyBody.result_class(), "client_error");
    }

    #[test]
    fn internal_result_class_returns_server_error() {
        assert_eq!(
            HttpError::internal(dummy_error()).result_class(),
            "server_error"
        );
    }

    #[test]
    fn method_not_allowed_result_class_returns_client_error() {
        assert_eq!(
            HttpError::MethodNotAllowed { allowed: "GET" }.result_class(),
            "client_error"
        );
    }

    #[test]
    fn not_acceptable_result_class_returns_client_error() {
        assert_eq!(HttpError::NotAcceptable.result_class(), "client_error");
    }

    #[test]
    fn not_found_result_class_returns_client_error() {
        assert_eq!(
            HttpError::NotFound {
                method: "GET".to_owned(),
                path: "/foo".to_owned()
            }
            .result_class(),
            "client_error"
        );
    }

    #[test]
    fn unprocessable_result_class_returns_client_error() {
        assert_eq!(
            HttpError::Unprocessable {
                detail: "bad".to_owned()
            }
            .result_class(),
            "client_error"
        );
    }

    #[test]
    fn unsupported_media_type_result_class_returns_client_error() {
        assert_eq!(
            HttpError::UnsupportedMediaType { received: None }.result_class(),
            "client_error"
        );
    }

    #[cfg(feature = "posthog")]
    mod posthog_tests {
        #![allow(clippy::expect_used, clippy::unwrap_used)]
        use super::super::HttpError;
        use super::dummy_error;
        use axum::response::IntoResponse as _;

        #[cfg(all(feature = "sentry", feature = "posthog"))]
        #[test]
        fn internal_error_into_response_does_not_panic_with_both_features() {
            let response = HttpError::internal(dummy_error()).into_response();
            assert_eq!(
                response.status(),
                axum::http::StatusCode::INTERNAL_SERVER_ERROR
            );
        }

        #[cfg(all(feature = "posthog", not(feature = "sentry")))]
        #[test]
        fn internal_error_into_response_does_not_panic_with_posthog_only() {
            let response = HttpError::internal(dummy_error()).into_response();
            assert_eq!(
                response.status(),
                axum::http::StatusCode::INTERNAL_SERVER_ERROR
            );
        }

        #[test]
        fn client_error_returns_correct_status_and_posthog_block_is_bypassed() {
            let response = HttpError::NotFound {
                method: "GET".to_owned(),
                path: "/foo".to_owned(),
            }
            .into_response();
            assert_eq!(response.status(), axum::http::StatusCode::NOT_FOUND);
        }

        #[test]
        fn into_response_outside_tokio_runtime_does_not_panic() {
            let response = HttpError::internal(dummy_error()).into_response();
            assert_eq!(
                response.status(),
                axum::http::StatusCode::INTERNAL_SERVER_ERROR
            );
        }
    }
}