docspec-http 1.0.1

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

// Reason: docspec-http is an HTTP server unconditionally requiring std;
// alloc is not in the extern prelude for std crates without `extern crate alloc`.
#![allow(clippy::std_instead_of_alloc)]

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,
}

impl ProblemJson {
    /// 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.
    ///
    /// # Panics
    ///
    /// Does not panic for any well-formed `ProblemJson` instance. The
    /// internal `.expect()` calls would only trigger on a bug in
    /// `docspec-json` (the key/value sequence is statically valid JSON and
    /// the `Vec<u8>` writer is infallible).
    #[inline]
    #[must_use]
    pub fn to_json_bytes(&self) -> Vec<u8> {
        // Reason: emission of a fixed 4-field object into Vec<u8> cannot fail
        // in practice — Vec writes are infallible and the key/value sequence
        // is statically valid JSON. Any error here would indicate a bug in
        // docspec-json itself, not runtime input.
        #[allow(clippy::expect_used)]
        {
            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(())
                })
                .expect("ProblemJson object emission is infallible");
            emitter.finish().expect("ProblemJson finish is infallible")
        }
    }
}

/// 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)]
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.
    ///
    /// → HTTP 500 Internal Server Error.
    Internal,
    /// 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 `text/markdown`.
    ///
    /// → HTTP 415 Unsupported Media Type.
    UnsupportedMediaType {
        /// The content-type that was received, if any.
        received: Option<String>,
    },
}

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 {
        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/*, or */*",
                ),
                None,
            ),
            Self::UnsupportedMediaType { received: None } => (
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                "Unsupported Media Type",
                Cow::Borrowed("Content-Type must be text/markdown"),
                None,
            ),
            Self::UnsupportedMediaType {
                received: Some(content_type),
            } => (
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                "Unsupported Media Type",
                Cow::Owned(format!(
                    "Content-Type must be text/markdown, 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,
            ),
        };

        if status == StatusCode::INTERNAL_SERVER_ERROR || status == StatusCode::UNPROCESSABLE_ENTITY
        {
            sentry::capture_message(detail.as_ref(), sentry::Level::Error);
        }

        let body = ProblemJson {
            detail,
            status: status.as_u16(),
            title,
            type_uri: "about:blank",
        }
        .to_json_bytes();

        let mut response = (status, body).into_response();
        response.headers_mut().insert(
            CONTENT_TYPE,
            HeaderValue::from_static("application/problem+json; charset=utf-8"),
        );
        if let Some(allowed) = allow {
            response
                .headers_mut()
                .insert(ALLOW, HeaderValue::from_static(allowed));
        }
        response
    }
}

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,
        }
    }
}

#[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()
    }

    #[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.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.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.into_response();
        assert!(response.headers().get(ALLOW).is_none());
    }

    #[test]
    fn internal_error_is_captured_by_sentry() {
        let events = sentry::test::with_captured_events(|| {
            let _response = HttpError::Internal.into_response();
        });
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].level, sentry::Level::Error);
        assert_eq!(
            events[0].message.as_deref(),
            Some("An unexpected error occurred during conversion")
        );
    }

    #[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"));
    }

    #[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).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).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, 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.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.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"
        );
    }
}