rusty-gasket 0.1.2

A plugin-based Rust framework for backend HTTP services
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
//! Novice-friendly request extractors for API handlers.
//!
//! These wrappers sit on top of axum's extractors and keep generated API code
//! readable. Handlers can ask for domain concepts such as [`JsonBody`],
//! [`QueryParams`], [`PathParams`], [`Pagination`], [`RequestContext`], and
//! [`Context`] instead of spelling lower-level axum plumbing in every route.

use std::ops::Deref;
use std::time::Duration;

use axum::Json;
use axum::extract::{FromRef, FromRequest, FromRequestParts, Path, Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::error::ErrorDetail;
use crate::observability::{RequestId, X_REQUEST_ID};

const DEFAULT_PAGE_SIZE: usize = 50;
const MAX_PAGE_SIZE: usize = 500;
const MAX_IDEMPOTENCY_KEY_LENGTH: usize = 255;

/// JSON request body extractor with Rusty Gasket's standard error shape.
///
/// Use this instead of `axum::Json<T>` in generated handlers when you want
/// invalid JSON and deserialization failures to return the framework's
/// consistent JSON error body with a correlation ID.
#[derive(Debug, Clone)]
pub struct JsonBody<T>(pub T);

impl<T> JsonBody<T> {
    /// Consume the extractor and return the parsed body.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for JsonBody<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<S, T> FromRequest<S> for JsonBody<T>
where
    S: Send + Sync,
    T: DeserializeOwned,
{
    type Rejection = Response;

    async fn from_request(
        request: axum::extract::Request,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        Json::<T>::from_request(request, state)
            .await
            .map(|Json(value)| Self(value))
            .map_err(|rejection| {
                standard_bad_request("INVALID_JSON", "Request body is not valid JSON.", rejection)
            })
    }
}

/// Query-string extractor with Rusty Gasket's standard error shape.
#[derive(Debug, Clone)]
pub struct QueryParams<T>(pub T);

impl<T> QueryParams<T> {
    /// Consume the extractor and return the parsed query parameters.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for QueryParams<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<S, T> FromRequestParts<S> for QueryParams<T>
where
    S: Send + Sync,
    T: DeserializeOwned,
{
    type Rejection = Response;

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        Query::<T>::from_request_parts(parts, state)
            .await
            .map(|Query(value)| Self(value))
            .map_err(|rejection| {
                standard_bad_request("INVALID_QUERY", "Query parameters are invalid.", rejection)
            })
    }
}

/// Path-parameter extractor with Rusty Gasket's standard error shape.
#[derive(Debug, Clone)]
pub struct PathParams<T>(pub T);

impl<T> PathParams<T> {
    /// Consume the extractor and return the parsed path parameters.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for PathParams<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<S, T> FromRequestParts<S> for PathParams<T>
where
    S: Send + Sync,
    T: DeserializeOwned + Send,
{
    type Rejection = Response;

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        Path::<T>::from_request_parts(parts, state)
            .await
            .map(|Path(value)| Self(value))
            .map_err(|rejection| {
                standard_bad_request("INVALID_PATH", "Path parameters are invalid.", rejection)
            })
    }
}

/// Idempotency key supplied by callers for retry-safe mutation endpoints.
///
/// This extractor standardizes the `Idempotency-Key` header validation and
/// error response. It does not store responses by itself; applications can use
/// the extracted key with their database, cache, or job table so replay behavior
/// is explicit and durable.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IdempotencyKey(String);

impl IdempotencyKey {
    /// Borrow the validated idempotency key.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the extractor and return the owned key.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

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

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        let key = parts
            .headers
            .get("idempotency-key")
            .ok_or_else(missing_idempotency_key_response)?
            .to_str()
            .map_err(|_| invalid_idempotency_key_response())?
            .trim();

        if key.is_empty()
            || key.len() > MAX_IDEMPOTENCY_KEY_LENGTH
            || !key.bytes().all(|byte| byte.is_ascii_graphic())
        {
            return Err(invalid_idempotency_key_response());
        }

        Ok(Self(key.to_owned()))
    }
}

/// Validation contract for request types.
///
/// Implement this on request DTOs and use [`Validated<T>`] in handlers to parse
/// and validate JSON in one readable step.
pub trait Validate {
    /// Validate the parsed request value.
    ///
    /// # Errors
    /// Returns validation errors that should be sent to the caller as a 400
    /// response.
    fn validate(&self) -> Result<(), ValidationErrors>;
}

/// A single validation error for generated API request types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// Field or logical constraint that failed.
    pub field: String,
    /// Human-readable validation message.
    pub message: String,
}

impl ValidationError {
    /// Create a validation error for a field.
    #[must_use]
    pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            message: message.into(),
        }
    }
}

/// Collection of validation errors.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ValidationErrors {
    errors: Vec<ValidationError>,
}

impl ValidationErrors {
    /// Create an empty validation error collection.
    #[must_use]
    pub fn new() -> Self {
        Self { errors: Vec::new() }
    }

    /// Create a collection with one validation error.
    #[must_use]
    pub fn one(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            errors: vec![ValidationError::new(field, message)],
        }
    }

    /// Add another validation error.
    pub fn push(&mut self, field: impl Into<String>, message: impl Into<String>) {
        self.errors.push(ValidationError::new(field, message));
    }

    /// Whether no validation errors are present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Borrow the collected validation errors.
    #[must_use]
    pub fn errors(&self) -> &[ValidationError] {
        &self.errors
    }

    fn into_error_details(self) -> Vec<ErrorDetail> {
        self.errors
            .into_iter()
            .map(|error| ErrorDetail::with_description(error.field, error.message))
            .collect()
    }
}

/// JSON body extractor that runs request validation before the handler starts.
#[derive(Debug, Clone)]
pub struct Validated<T>(pub T);

impl<T> Validated<T> {
    /// Consume the extractor and return the validated request value.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for Validated<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<S, T> FromRequest<S> for Validated<T>
where
    S: Send + Sync,
    T: DeserializeOwned + Validate,
{
    type Rejection = Response;

    async fn from_request(
        request: axum::extract::Request,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        let body = JsonBody::<T>::from_request(request, state).await?;
        body.validate().map_err(validation_error_response)?;
        Ok(Self(body.into_inner()))
    }
}

/// Standard pagination query parameters.
///
/// Accepts `?page=1&limit=50`. Missing values default to page 1 and a limit of
/// 50. Limits above 500 are capped to protect services from accidental large
/// responses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Pagination {
    page: usize,
    limit: usize,
}

impl Pagination {
    /// Current 1-based page number.
    #[must_use]
    pub const fn page(&self) -> usize {
        self.page
    }

    /// Maximum number of items requested.
    #[must_use]
    pub const fn limit(&self) -> usize {
        self.limit
    }

    /// Zero-based offset for SQL-style pagination.
    #[must_use]
    pub const fn offset(&self) -> usize {
        (self.page - 1) * self.limit
    }
}

#[derive(Debug, serde::Deserialize)]
struct RawPagination {
    page: Option<usize>,
    limit: Option<usize>,
}

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

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        let query = QueryParams::<RawPagination>::from_request_parts(parts, state).await?;
        let page = query.page.unwrap_or(1);
        if page == 0 {
            return Err(validation_error_response(ValidationErrors::one(
                "page",
                "page must be at least 1",
            )));
        }

        let limit = query.limit.unwrap_or(DEFAULT_PAGE_SIZE).min(MAX_PAGE_SIZE);
        if limit == 0 {
            return Err(validation_error_response(ValidationErrors::one(
                "limit",
                "limit must be at least 1",
            )));
        }

        Ok(Self { page, limit })
    }
}

/// Request metadata commonly needed by handlers and logs.
#[derive(Debug, Clone)]
pub struct RequestContext {
    method: http::Method,
    uri: http::Uri,
    request_id: Option<String>,
}

impl RequestContext {
    /// HTTP method for the current request.
    #[must_use]
    pub const fn method(&self) -> &http::Method {
        &self.method
    }

    /// Request URI.
    #[must_use]
    pub const fn uri(&self) -> &http::Uri {
        &self.uri
    }

    /// Correlation/request ID generated or propagated by the logging middleware.
    #[must_use]
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }
}

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

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        _state: &S,
    ) -> Result<Self, Self::Rejection> {
        let request_id = parts
            .extensions
            .get::<RequestId>()
            .map(|request_id| request_id.as_str().to_owned())
            .or_else(|| {
                parts
                    .headers
                    .get(X_REQUEST_ID)
                    .and_then(|value| value.to_str().ok())
                    .map(str::to_owned)
            });

        Ok(Self {
            method: parts.method.clone(),
            uri: parts.uri.clone(),
            request_id,
        })
    }
}

/// Friendly wrapper around axum state extraction.
///
/// Generated handlers can ask for `Context<AppServices>` instead of
/// `State<AppServices>`, making the function signature read like application
/// code while still using axum's proven state extraction underneath.
#[derive(Debug, Clone)]
pub struct Context<T>(pub T);

impl<T> Context<T> {
    /// Consume the extractor and return the inner application context.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for Context<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<S, T> FromRequestParts<S> for Context<T>
where
    S: Send + Sync,
    T: FromRef<S> + Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(
        parts: &mut http::request::Parts,
        state: &S,
    ) -> Result<Self, Self::Rejection> {
        State::<T>::from_request_parts(parts, state)
            .await
            .map(|State(value)| Self(value))
            .map_err(|_| {
                crate::error::quick_error_response(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "CONTEXT_NOT_AVAILABLE",
                    "Application context is not available for this route.",
                )
            })
    }
}

/// Duration helper for configuring middleware from seconds.
#[must_use]
pub const fn seconds(value: u64) -> Duration {
    Duration::from_secs(value)
}

fn standard_bad_request(code: &str, message: &str, _rejection: impl IntoResponse) -> Response {
    tracing::debug!(
        status = StatusCode::BAD_REQUEST.as_u16(),
        "Request extraction failed"
    );
    crate::error::quick_error_response(StatusCode::BAD_REQUEST, code, message)
}

fn validation_error_response(errors: ValidationErrors) -> Response {
    crate::error::quick_error_response_with_details(
        StatusCode::BAD_REQUEST,
        "VALIDATION_ERROR",
        "Request validation failed.",
        errors.into_error_details(),
    )
}

fn missing_idempotency_key_response() -> Response {
    crate::error::quick_error_response(
        StatusCode::BAD_REQUEST,
        "IDEMPOTENCY_KEY_REQUIRED",
        "Idempotency-Key header is required for this endpoint.",
    )
}

fn invalid_idempotency_key_response() -> Response {
    crate::error::quick_error_response(
        StatusCode::BAD_REQUEST,
        "INVALID_IDEMPOTENCY_KEY",
        "Idempotency-Key header must be visible ASCII text between 1 and 255 characters.",
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::Router;
    use axum::routing::{get, post};
    use http_body_util::BodyExt;
    use pretty_assertions::assert_eq;
    use serde::{Deserialize, Serialize};
    use tower::ServiceExt;

    #[derive(Debug, Deserialize, Serialize)]
    struct CreateThing {
        name: String,
    }

    impl Validate for CreateThing {
        fn validate(&self) -> Result<(), ValidationErrors> {
            if self.name.trim().is_empty() {
                return Err(ValidationErrors::one("name", "name is required"));
            }
            Ok(())
        }
    }

    async fn create_thing(Validated(body): Validated<CreateThing>) -> Json<CreateThing> {
        Json(body)
    }

    async fn read_pagination(pagination: Pagination) -> Json<Pagination> {
        Json(pagination)
    }

    async fn read_idempotency_key(idempotency_key: IdempotencyKey) -> String {
        idempotency_key.into_string()
    }

    async fn read_context(RequestContextPattern(context): RequestContextPattern) -> String {
        context.request_id().unwrap_or("missing").to_owned()
    }

    struct RequestContextPattern(RequestContext);

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

        async fn from_request_parts(
            parts: &mut http::request::Parts,
            state: &S,
        ) -> Result<Self, Self::Rejection> {
            RequestContext::from_request_parts(parts, state)
                .await
                .map(Self)
        }
    }

    async fn response_body(response: Response) -> serde_json::Value {
        let body = response
            .into_body()
            .collect()
            .await
            .expect("collect response body")
            .to_bytes();
        serde_json::from_slice(&body).expect("response body should be JSON")
    }

    #[tokio::test]
    async fn validated_json_rejects_blank_field() {
        let app = Router::new().route("/things", post(create_thing));
        let request = http::Request::builder()
            .method("POST")
            .uri("/things")
            .header("content-type", "application/json")
            .body(axum::body::Body::from(r#"{"name": ""}"#))
            .expect("build request");

        let response = app.oneshot(request).await.expect("route response");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = response_body(response).await;
        assert_eq!(body["error"], "VALIDATION_ERROR");
        assert_eq!(body["details"][0]["issue"], "name");
    }

    #[tokio::test]
    async fn pagination_defaults_and_caps_limit() {
        let app = Router::new().route("/things", get(read_pagination));
        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/things?page=2&limit=9999")
                    .body(axum::body::Body::empty())
                    .expect("build request"),
            )
            .await
            .expect("route response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = response_body(response).await;
        assert_eq!(body["page"], 2);
        assert_eq!(body["limit"], MAX_PAGE_SIZE);
    }

    #[tokio::test]
    async fn request_context_reads_request_id_header_without_logging_middleware() {
        let app = Router::new().route("/context", get(read_context));
        let response = app
            .oneshot(
                http::Request::builder()
                    .uri("/context")
                    .header(X_REQUEST_ID, "request-123")
                    .body(axum::body::Body::empty())
                    .expect("build request"),
            )
            .await
            .expect("route response");

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn idempotency_key_extractor_reads_standard_header() {
        let app = Router::new().route("/orders", post(read_idempotency_key));
        let response = app
            .oneshot(
                http::Request::builder()
                    .method("POST")
                    .uri("/orders")
                    .header("idempotency-key", "order-create-123")
                    .body(axum::body::Body::empty())
                    .expect("build request"),
            )
            .await
            .expect("route response");

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn idempotency_key_extractor_rejects_missing_header() {
        let app = Router::new().route("/orders", post(read_idempotency_key));
        let response = app
            .oneshot(
                http::Request::builder()
                    .method("POST")
                    .uri("/orders")
                    .body(axum::body::Body::empty())
                    .expect("build request"),
            )
            .await
            .expect("route response");

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = response_body(response).await;
        assert_eq!(body["error"], "IDEMPOTENCY_KEY_REQUIRED");
    }
}