footing 0.1.18

Feature-gated foundations for Rust backend services
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
use std::fmt;

use axum::{
    Json,
    http::{HeaderValue, StatusCode, header::CONTENT_TYPE},
    response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::result::{ClassifyError, ErrorDescriptor, ErrorKind};

use super::{ProblemCode, ProblemType};
use crate::http::request_context::{RequestContext, RequestId};

/// Media type used for RFC 9457 problem responses.
pub const PROBLEM_JSON_MEDIA_TYPE: &str = "application/problem+json";

#[derive(Clone, Serialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[non_exhaustive]
/// Client-safe RFC 9457 problem payload with correlation and validation details.
pub struct ProblemDetails {
    #[serde(rename = "type")]
    /// URI identifying the problem type.
    #[cfg_attr(feature = "openapi", schema(inline))]
    type_uri: ProblemType,
    /// Short, human-readable problem title.
    title: String,
    /// HTTP status code associated with the problem.
    #[cfg_attr(feature = "openapi", schema(minimum = 400, maximum = 599))]
    status: u16,
    /// Stable machine-readable error code.
    #[cfg_attr(feature = "openapi", schema(inline))]
    code: ProblemCode,
    /// Human-readable explanation specific to this occurrence.
    detail: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// URI identifying this specific problem occurrence.
    #[cfg_attr(feature = "openapi", schema(nullable = false))]
    instance: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Request identifier used for log correlation.
    #[cfg_attr(feature = "openapi", schema(inline, nullable = false))]
    request_id: Option<RequestId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Distributed trace identifier, when tracing is active.
    #[cfg_attr(feature = "openapi", schema(nullable = false))]
    trace_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Structured, client-safe problem-specific details.
    details: Option<Value>,
}

impl ProblemDetails {
    #[must_use]
    /// Returns the problem type URI.
    pub fn type_uri(&self) -> &str {
        self.type_uri.as_str()
    }

    #[must_use]
    /// Returns the human-readable title.
    pub fn title(&self) -> &str {
        &self.title
    }

    #[must_use]
    /// Returns the HTTP status code.
    pub const fn status(&self) -> u16 {
        self.status
    }

    #[must_use]
    /// Returns the stable machine-readable code.
    pub fn code(&self) -> &str {
        self.code.as_str()
    }

    #[must_use]
    /// Returns the client-safe detail.
    pub fn detail(&self) -> &str {
        &self.detail
    }

    #[must_use]
    /// Returns the problem instance URI, when present.
    pub fn instance(&self) -> Option<&str> {
        self.instance.as_deref()
    }

    #[must_use]
    /// Returns the request identifier, when present.
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_ref().map(RequestId::as_str)
    }

    #[must_use]
    /// Returns the trace identifier, when present.
    pub fn trace_id(&self) -> Option<&str> {
        self.trace_id.as_deref()
    }

    #[must_use]
    /// Returns structured client-safe details, when present.
    pub const fn details(&self) -> Option<&Value> {
        self.details.as_ref()
    }
}

impl<'de> Deserialize<'de> for ProblemDetails {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct ProblemDetailsWire {
            #[serde(rename = "type")]
            type_uri: ProblemType,
            title: String,
            status: u16,
            code: ProblemCode,
            detail: String,
            instance: Option<String>,
            request_id: Option<RequestId>,
            trace_id: Option<String>,
            details: Option<Value>,
        }

        let wire = ProblemDetailsWire::deserialize(deserializer)?;
        let status = StatusCode::from_u16(wire.status).map_err(serde::de::Error::custom)?;
        if !is_problem_status(status) {
            return Err(serde::de::Error::custom(
                "problem status must be a 4xx or 5xx status code",
            ));
        }
        Ok(Self {
            type_uri: wire.type_uri,
            title: wire.title,
            status: wire.status,
            code: wire.code,
            detail: wire.detail,
            instance: wire.instance,
            request_id: wire.request_id,
            trace_id: wire.trace_id,
            details: wire.details,
        })
    }
}

impl fmt::Debug for ProblemDetails {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProblemDetails")
            .field("status", &self.status)
            .field("code", &self.code)
            .field("request_id", &self.request_id)
            .field("trace_id", &self.trace_id)
            .field("type_uri", &"[REDACTED]")
            .field("title", &"[REDACTED]")
            .field("detail", &"[REDACTED]")
            .field("instance", &self.instance.as_ref().map(|_| "[REDACTED]"))
            .field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

#[derive(Clone)]
/// Represents API problem.
pub struct ApiProblem {
    status: StatusCode,
    body: Box<ProblemDetails>,
}

impl fmt::Debug for ApiProblem {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ApiProblem")
            .field("status", &self.status)
            .field("body", &self.body)
            .finish()
    }
}

/// Converts an error into a safe RFC 9457 API response.
pub trait IntoApiProblem {
    /// Consumes this value and returns API problem.
    fn into_api_problem(self) -> ApiProblem;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Enumerates the supported error category values.
pub enum ErrorCategory {
    /// Indicates validation.
    Validation,
    /// Indicates authentication.
    Authentication,
    /// Indicates authorization.
    Authorization,
    /// Indicates not found.
    NotFound,
    /// Indicates conflict.
    Conflict,
    /// Indicates rate limit.
    RateLimit,
    /// Indicates dependency.
    Dependency,
    /// Indicates internal.
    Internal,
}

impl ErrorCategory {
    #[must_use]
    /// Returns the status.
    pub const fn status(self) -> StatusCode {
        match self {
            Self::Validation => StatusCode::BAD_REQUEST,
            Self::Authentication => StatusCode::UNAUTHORIZED,
            Self::Authorization => StatusCode::FORBIDDEN,
            Self::NotFound => StatusCode::NOT_FOUND,
            Self::Conflict => StatusCode::CONFLICT,
            Self::RateLimit => StatusCode::TOO_MANY_REQUESTS,
            Self::Dependency => StatusCode::SERVICE_UNAVAILABLE,
            Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl From<ErrorKind> for ErrorCategory {
    fn from(kind: ErrorKind) -> Self {
        match kind {
            ErrorKind::Validation => Self::Validation,
            ErrorKind::Authentication => Self::Authentication,
            ErrorKind::Authorization => Self::Authorization,
            ErrorKind::NotFound => Self::NotFound,
            ErrorKind::Conflict => Self::Conflict,
            ErrorKind::RateLimit => Self::RateLimit,
            ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => Self::Dependency,
            ErrorKind::Internal => Self::Internal,
        }
    }
}

#[derive(Clone)]
/// Errors that can occur while handling public.
pub struct PublicError {
    category: ErrorCategory,
    code: ProblemCode,
    detail: String,
    details: Option<Value>,
}

impl fmt::Debug for PublicError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PublicError")
            .field("category", &self.category)
            .field("code", &self.code)
            .field("detail", &"[REDACTED]")
            .field("details", &self.details.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

impl PublicError {
    #[must_use]
    /// Creates a new instance.
    pub fn new(category: ErrorCategory, code: ProblemCode, detail: impl Into<String>) -> Self {
        Self {
            category,
            code,
            detail: detail.into(),
            details: None,
        }
    }

    #[must_use]
    /// Creates validation.
    pub fn validation(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::new(ErrorCategory::Validation, code, detail)
    }

    #[must_use]
    /// Creates dependency.
    pub fn dependency(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::new(ErrorCategory::Dependency, code, detail)
    }

    #[must_use]
    /// Creates internal.
    pub fn internal(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::new(ErrorCategory::Internal, code, detail)
    }

    #[must_use]
    /// Creates a value from descriptor.
    pub fn from_descriptor(descriptor: ErrorDescriptor) -> Self {
        Self::new(
            ErrorCategory::from(descriptor.kind()),
            ProblemCode::from_error_code(descriptor.code().clone()),
            descriptor.public_message(),
        )
    }

    #[must_use]
    /// Configures details and returns the updated value.
    pub fn with_details(mut self, details: Value) -> Self {
        self.details = Some(details);
        self
    }

    #[must_use]
    /// Returns the category.
    pub const fn category(&self) -> ErrorCategory {
        self.category
    }

    #[must_use]
    /// Returns the code.
    pub fn code(&self) -> &ProblemCode {
        &self.code
    }

    #[must_use]
    /// Returns the detail.
    pub fn detail(&self) -> &str {
        &self.detail
    }
}

impl IntoApiProblem for PublicError {
    fn into_api_problem(self) -> ApiProblem {
        let mut problem =
            ApiProblem::from_valid_status(self.category.status(), self.code, self.detail);
        if let Some(details) = self.details {
            problem = problem.with_details(details);
        }
        problem
    }
}

impl From<PublicError> for ApiProblem {
    fn from(error: PublicError) -> Self {
        error.into_api_problem()
    }
}

impl ApiProblem {
    /// Attempts to create an API problem with an error status.
    pub fn try_new(
        status: StatusCode,
        code: ProblemCode,
        detail: impl Into<String>,
    ) -> Result<Self, ApiProblemStatusError> {
        if !is_problem_status(status) {
            return Err(ApiProblemStatusError::InvalidStatus {
                status: status.as_u16(),
            });
        }

        Ok(Self::from_valid_status(status, code, detail))
    }

    fn from_valid_status(status: StatusCode, code: ProblemCode, detail: impl Into<String>) -> Self {
        Self {
            status,
            body: Box::new(ProblemDetails {
                type_uri: ProblemType::about_blank(),
                title: status.canonical_reason().unwrap_or("HTTP error").to_owned(),
                detail: detail.into(),
                status: status.as_u16(),
                code,
                instance: None,
                request_id: None,
                trace_id: None,
                details: None,
            }),
        }
    }

    #[must_use]
    /// Creates bad request.
    pub fn bad_request(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::BAD_REQUEST, code, detail)
    }

    #[must_use]
    /// Creates unauthorized.
    pub fn unauthorized(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::UNAUTHORIZED, code, detail)
    }

    #[must_use]
    /// Creates forbidden.
    pub fn forbidden(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::FORBIDDEN, code, detail)
    }

    #[must_use]
    /// Creates not found.
    pub fn not_found(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::NOT_FOUND, code, detail)
    }

    #[must_use]
    /// Creates service unavailable.
    pub fn service_unavailable(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::SERVICE_UNAVAILABLE, code, detail)
    }

    #[must_use]
    /// Creates conflict.
    pub fn conflict(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::CONFLICT, code, detail)
    }

    #[must_use]
    /// Creates unprocessable entity.
    pub fn unprocessable_entity(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::UNPROCESSABLE_ENTITY, code, detail)
    }

    #[must_use]
    /// Creates payload too large.
    pub fn payload_too_large(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::PAYLOAD_TOO_LARGE, code, detail)
    }

    #[must_use]
    /// Creates too many requests.
    pub fn too_many_requests(code: ProblemCode, detail: impl Into<String>) -> Self {
        Self::from_valid_status(StatusCode::TOO_MANY_REQUESTS, code, detail)
    }

    #[must_use]
    /// Creates internal error.
    pub fn internal_error() -> Self {
        Self::from_valid_status(
            StatusCode::INTERNAL_SERVER_ERROR,
            ProblemCode::INTERNAL_ERROR,
            "internal server error",
        )
    }

    #[must_use]
    /// Configures request identifier and returns the updated value.
    pub fn with_request_id(mut self, request_id: &RequestId) -> Self {
        self.body.request_id = Some(request_id.clone());
        self
    }

    #[must_use]
    /// Configures trace identifier and returns the updated value.
    pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
        let trace_id = trace_id.into();
        if !trace_id.trim().is_empty() {
            self.body.trace_id = Some(trace_id);
        }
        self
    }

    #[must_use]
    /// Adds request and trace identifiers safe for client correlation.
    pub fn with_request_context(mut self, context: &RequestContext) -> Self {
        self.body.request_id = Some(context.request_id().clone());
        if let Some(trace_id) = context.trace_id() {
            self.body.trace_id = Some(trace_id.to_owned());
        }
        self
    }

    #[must_use]
    /// Returns the maybe request identifier.
    pub fn maybe_request_id(self, request_id: Option<&RequestId>) -> Self {
        if let Some(request_id) = request_id {
            self.with_request_id(request_id)
        } else {
            self
        }
    }

    #[must_use]
    /// Configures type and returns the updated value.
    pub fn with_type(mut self, type_uri: ProblemType) -> Self {
        self.body.type_uri = type_uri;
        self
    }

    #[must_use]
    /// Configures title and returns the updated value.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.body.title = title.into();
        self
    }

    #[must_use]
    /// Configures instance and returns the updated value.
    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
        self.body.instance = Some(instance.into());
        self
    }

    #[must_use]
    /// Adds structured details explicitly intended for the client.
    ///
    /// Secrets and internal diagnostic data must not be included.
    pub fn with_details(mut self, details: Value) -> Self {
        self.body.details = Some(details);
        self
    }

    #[must_use]
    /// Returns the status.
    pub const fn status(&self) -> StatusCode {
        self.status
    }

    #[must_use]
    /// Returns the body.
    pub fn body(&self) -> &ProblemDetails {
        &self.body
    }

    #[must_use]
    /// Consumes this value and returns body.
    pub fn into_body(self) -> ProblemDetails {
        *self.body
    }
}

impl IntoApiProblem for ApiProblem {
    fn into_api_problem(self) -> ApiProblem {
        self
    }
}

impl IntoResponse for ApiProblem {
    fn into_response(self) -> Response {
        let mut response = (self.status, Json(self.body)).into_response();
        response.headers_mut().insert(
            CONTENT_TYPE,
            HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
        );
        response
    }
}

impl std::fmt::Display for ApiProblem {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "HTTP problem {} ({})",
            self.body.code,
            self.status.as_u16()
        )
    }
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling API problem status.
pub enum ApiProblemStatusError {
    #[error("problem status must be a 4xx or 5xx status code, got {status}")]
    /// The status is invalid.
    InvalidStatus {
        #[doc = "The HTTP status code."]
        status: u16,
    },
}

impl ClassifyError for ApiProblemStatusError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal("api_problem_invalid_status")
    }
}

fn is_problem_status(status: StatusCode) -> bool {
    status.is_client_error() || status.is_server_error()
}