jshift 0.7.0

Schema-guided typed JSON on raw bytes: path get/mutate, open views, project — without a Value tree.
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
//! Optional **axum** extractors (feature `axum`).
//!
//! Map request bodies to jshift types **without** building `serde_json::Value`:
//!
//! | Type | Request | Response |
//! | --- | --- | --- |
//! | [`JshiftJson<T>`] | body → `T: JsonView` **+ retained raw bytes** | **open** `write_into` on raw (unknowns kept); schema-only if built without a body |
//! | [`JshiftDoc`] | body → [`TypedDoc`] | raw buffer as `application/json` |
//!
//! Prefer these over `axum::Json<T>` when `T` is a jshift view (sparse decode,
//! open mutate). Prefer [`JshiftDoc`] when you only need path ops on the buffer
//! without a typed view.
//!
//! # Open vs closed response ([`JshiftJson`])
//!
//! Extraction keeps the **request body**. Returning that same extractor after
//! editing `value` re-emits via [`JsonView::write_into`] on a copy of the body —
//! unknown keys are preserved (open document).
//!
//! Building a response with [`JshiftJson::new`] / [`From`] (no raw body) uses
//! [`JsonView::to_schema_bytes`] (closed card). Use that when the handler
//! invents a response that was never the request body.
//!
//! # Example
//!
//! ```ignore
//! use axum::{routing::post, Router};
//! use jshift::{JshiftJson, JsonView};
//!
//! #[derive(JsonView)]
//! struct CreateUser {
//!     #[json(path = "email")]
//!     email: String,
//! }
//!
//! // Open round-trip: return the extractor (raw retained) so extras survive.
//! async fn create(mut req: JshiftJson<CreateUser>) -> JshiftJson<CreateUser> {
//!     req.value.email = req.value.email.to_lowercase();
//!     req
//! }
//!
//! // Closed card: no request body attached.
//! async fn minted() -> JshiftJson<CreateUser> {
//!     JshiftJson::new(CreateUser { email: "a@b.c".into() })
//! }
//!
//! let app = Router::new().route("/users", post(create));
//! ```
//!
//! # Content-Type
//!
//! Accepts `application/json` and any `*/*+json` subtype (RFC 6839), compared
//! **case-insensitively**, with optional parameters (`charset=utf-8`).
//!
//! # Rejection map
//!
//! | Failure | Status |
//! | --- | --- |
//! | Missing / wrong Content-Type | **415** Unsupported Media Type |
//! | Body read error | **400** Bad Request |
//! | [`JsonView`] decode error | **422** Unprocessable Entity |
//!
//! Body size limits remain the responsibility of axum’s `DefaultBodyLimit` (or
//! your reverse proxy) — same as `axum::Json`.

use std::fmt;
use std::ops::{Deref, DerefMut};

use crate::error::Error as JshiftError;
use crate::typed_doc::TypedDoc;
use crate::view::JsonView;
use axum::body::Bytes;
use axum::extract::{FromRequest, Request};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};

/// Axum extractor/response for `T: JsonView`.
///
/// # Request
///
/// Requires a JSON `Content-Type`, buffers the body, decodes with
/// [`JsonView::read_from`] (path-selective), and **retains the raw bytes** for
/// open response encoding.
///
/// # Response
///
/// | How built | Encode path |
/// | --- | --- |
/// | From extractor (has raw body) | [`JsonView::write_into`] on a clone of the body — **unknowns preserved** |
/// | [`JshiftJson::new`] / [`From`] / [`JshiftJson::closed`] | [`JsonView::to_schema_bytes`] — **schema-only card** |
///
/// # Ergonomics
///
/// * [`Deref`] / [`DerefMut`] to `T` (`req.email` works).
/// * Public field [`value`](Self::value) for explicit access.
/// * Prefer returning the **same** `JshiftJson` after edits for open round-trip.
#[derive(Debug, Clone)]
pub struct JshiftJson<T> {
    /// Typed view (schema fields).
    pub value: T,
    /// Original request body when extracted; `None` → closed schema response.
    raw: Option<Vec<u8>>,
}

impl<T> JshiftJson<T> {
    /// Wrap a value **without** a raw body (response will be schema-only).
    #[inline]
    pub const fn new(value: T) -> Self {
        Self { value, raw: None }
    }

    /// Alias of [`new`](Self::new): closed card, no open document.
    #[inline]
    pub const fn closed(value: T) -> Self {
        Self::new(value)
    }

    /// Build from a view plus optional raw body (open response if `raw` is `Some`).
    #[inline]
    pub fn from_parts(value: T, raw: Option<Vec<u8>>) -> Self {
        Self { value, raw }
    }

    /// Unwrap the typed view (drops retained body).
    #[inline]
    pub fn into_inner(self) -> T {
        self.value
    }

    /// Split into view + optional raw body.
    #[inline]
    pub fn into_parts(self) -> (T, Option<Vec<u8>>) {
        (self.value, self.raw)
    }

    /// Borrow the retained request body, if any.
    #[inline]
    pub fn raw(&self) -> Option<&[u8]> {
        self.raw.as_deref()
    }

    /// Whether a request body is retained for open response encoding.
    #[inline]
    pub fn has_raw(&self) -> bool {
        self.raw.is_some()
    }

    /// Drop the retained body so the next response uses schema-only emit.
    #[inline]
    pub fn into_closed(self) -> Self {
        Self {
            value: self.value,
            raw: None,
        }
    }

    /// Replace the typed value, keeping the same raw body (open path unchanged).
    #[inline]
    pub fn map_value<U>(self, f: impl FnOnce(T) -> U) -> JshiftJson<U> {
        JshiftJson {
            value: f(self.value),
            raw: self.raw,
        }
    }
}

impl<T: Default> Default for JshiftJson<T> {
    #[inline]
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T> From<T> for JshiftJson<T> {
    /// Closed wrapper (no raw body). Prefer returning an extracted `JshiftJson`
    /// when you need open unknown-field preservation on the way out.
    #[inline]
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

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

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for JshiftJson<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

/// Axum extractor/response for a raw [`TypedDoc`] (owned body bytes).
///
/// Use when the handler should **path-scan and/or mutate in place** and forward
/// the buffer (unknown fields preserved) without a typed view. Prefer
/// [`JshiftJson`] when you want both a typed projection **and** open round-trip.
#[derive(Debug, Clone)]
pub struct JshiftDoc(pub TypedDoc);

impl JshiftDoc {
    /// Wrap a document.
    #[inline]
    pub fn new(doc: TypedDoc) -> Self {
        Self(doc)
    }

    /// Unwrap into [`TypedDoc`].
    #[inline]
    pub fn into_inner(self) -> TypedDoc {
        self.0
    }
}

impl From<TypedDoc> for JshiftDoc {
    #[inline]
    fn from(doc: TypedDoc) -> Self {
        Self(doc)
    }
}

impl Deref for JshiftDoc {
    type Target = TypedDoc;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for JshiftDoc {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Rejection when jshift JSON extraction fails.
#[derive(Debug)]
pub enum JshiftRejection {
    /// Missing or non-JSON `Content-Type`.
    MissingJsonContentType,
    /// Failed to buffer the request body.
    Body(String),
    /// [`JsonView::read_from`] (or related) failed.
    Decode(JshiftError),
}

impl fmt::Display for JshiftRejection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JshiftRejection::MissingJsonContentType => {
                f.write_str("Expected request with `Content-Type: application/json`")
            }
            JshiftRejection::Body(e) => write!(f, "Failed to read request body: {e}"),
            JshiftRejection::Decode(e) => write!(f, "Failed to decode JSON body: {e}"),
        }
    }
}

impl std::error::Error for JshiftRejection {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            JshiftRejection::Decode(e) => Some(e),
            _ => None,
        }
    }
}

impl IntoResponse for JshiftRejection {
    fn into_response(self) -> Response {
        let status = match &self {
            JshiftRejection::MissingJsonContentType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            JshiftRejection::Body(_) => StatusCode::BAD_REQUEST,
            JshiftRejection::Decode(_) => StatusCode::UNPROCESSABLE_ENTITY,
        };
        let mut body = Vec::with_capacity(64 + self.to_string().len());
        body.extend_from_slice(br#"{"error":"#);
        crate::convert::write_json_string(&mut body, &self.to_string());
        body.push(b'}');
        let mut res = (status, body).into_response();
        res.headers_mut().insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );
        res
    }
}

/// `application/json` or `*+json`, case-insensitive, parameters ignored.
#[inline]
fn json_content_type(headers: &HeaderMap) -> bool {
    let Some(ct) = headers.get(header::CONTENT_TYPE) else {
        return false;
    };
    let Ok(s) = ct.to_str() else {
        return false;
    };
    let mime = s.split(';').next().unwrap_or("").trim();
    if mime.eq_ignore_ascii_case("application/json") {
        return true;
    }
    let b = mime.as_bytes();
    b.len() >= 5 && b[b.len() - 5..].eq_ignore_ascii_case(b"+json")
}

/// Prefer reclaiming a unique `Bytes` buffer as `Vec<u8>` (no second copy).
#[inline]
fn bytes_into_vec(bytes: Bytes) -> Vec<u8> {
    Vec::from(bytes)
}

fn json_response(bytes: Vec<u8>) -> Response {
    let mut res = bytes.into_response();
    res.headers_mut().insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static("application/json"),
    );
    res
}

fn encode_error_response(e: impl fmt::Display) -> Response {
    let mut body = Vec::new();
    body.extend_from_slice(br#"{"error":"#);
    crate::convert::write_json_string(&mut body, &format!("jshift response encode failed: {e}"));
    body.push(b'}');
    let mut res = (StatusCode::INTERNAL_SERVER_ERROR, body).into_response();
    res.headers_mut().insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static("application/json"),
    );
    res
}

impl<S, T> FromRequest<S> for JshiftJson<T>
where
    T: JsonView,
    S: Send + Sync,
{
    type Rejection = JshiftRejection;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        if !json_content_type(req.headers()) {
            return Err(JshiftRejection::MissingJsonContentType);
        }
        let bytes = Bytes::from_request(req, state)
            .await
            .map_err(|e| JshiftRejection::Body(e.to_string()))?;
        let raw = bytes_into_vec(bytes);
        let value = T::read_from(&raw).map_err(JshiftRejection::Decode)?;
        Ok(JshiftJson {
            value,
            raw: Some(raw),
        })
    }
}

impl<S> FromRequest<S> for JshiftDoc
where
    S: Send + Sync,
{
    type Rejection = JshiftRejection;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        if !json_content_type(req.headers()) {
            return Err(JshiftRejection::MissingJsonContentType);
        }
        let bytes = Bytes::from_request(req, state)
            .await
            .map_err(|e| JshiftRejection::Body(e.to_string()))?;
        Ok(JshiftDoc(TypedDoc::from_vec(bytes_into_vec(bytes))))
    }
}

impl<T: JsonView> IntoResponse for JshiftJson<T> {
    fn into_response(self) -> Response {
        match self.raw {
            // Open path: patch schema fields into the original body.
            Some(mut buf) => match self.value.write_into(&mut buf) {
                Ok(()) => json_response(buf),
                Err(e) => encode_error_response(e),
            },
            // Closed path: no request body attached.
            None => match self.value.to_schema_bytes() {
                Ok(bytes) => json_response(bytes),
                Err(e) => encode_error_response(e),
            },
        }
    }
}

impl IntoResponse for JshiftDoc {
    fn into_response(self) -> Response {
        json_response(self.0.into_bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{find_value, parse_path, FromJsonSlice, ProjectPlan, ToJsonBytes};
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    struct IdOnly {
        id: u64,
    }

    impl JsonView for IdOnly {
        fn read_from(json: &[u8]) -> Result<Self, crate::Error> {
            let slice = find_value(json, &parse_path("id"))?;
            Ok(Self {
                id: u64::from_json_slice(slice).ok_or(crate::Error::TypeMismatch {
                    expected: "u64",
                    found: "bad",
                })?,
            })
        }
        fn write_into(&self, json: &mut Vec<u8>) -> Result<(), crate::Error> {
            crate::upsert_at_path(json, &parse_path("id"), &self.id.to_json_bytes())
        }
        fn project_plan() -> ProjectPlan {
            ProjectPlan::from_paths(&["id"]).unwrap()
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn jshift_json_open_response_preserves_unknowns() {
        // Return the same extractor so raw body is kept → open write_into.
        async fn handler(mut req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
            req.value.id += 1;
            req
        }

        let app = axum::Router::new().route("/", axum::routing::post(handler));
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header(header::CONTENT_TYPE, "application/json; charset=utf-8")
                    .body(Body::from(r#"{"id":7,"noise":true}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        let s = std::str::from_utf8(&body).unwrap();
        assert!(s.contains("\"id\":8"), "{s}");
        assert!(s.contains("\"noise\""), "unknowns must survive open response: {s}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn jshift_json_closed_response_is_schema_only() {
        async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
            // Drop raw → schema-only emit
            JshiftJson::closed(IdOnly {
                id: req.value.id + 1,
            })
        }

        let app = axum::Router::new().route("/", axum::routing::post(handler));
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header(header::CONTENT_TYPE, "application/json")
                    .body(Body::from(r#"{"id":7,"noise":true}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = res.into_body().collect().await.unwrap().to_bytes();
        let s = std::str::from_utf8(&body).unwrap();
        assert!(s.contains("\"id\":8"));
        assert!(!s.contains("noise"), "closed must drop unknowns: {s}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn accepts_json_suffix_and_case() {
        async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
            req
        }
        let app = axum::Router::new().route("/", axum::routing::post(handler));
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header(header::CONTENT_TYPE, "Application/vnd.api+JSON")
                    .body(Body::from(r#"{"id":1}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn rejects_non_json_content_type() {
        async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
            req
        }
        let app = axum::Router::new().route("/", axum::routing::post(handler));
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header(header::CONTENT_TYPE, "text/plain")
                    .body(Body::from(r#"{"id":1}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert!(body.starts_with(b"{\"error\":"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn decode_error_is_422() {
        async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
            req
        }
        let app = axum::Router::new().route("/", axum::routing::post(handler));
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header(header::CONTENT_TYPE, "application/json")
                    .body(Body::from(r#"{"nope":true}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn jshift_doc_preserves_unknowns() {
        async fn handler(JshiftDoc(mut doc): JshiftDoc) -> JshiftDoc {
            let _ = doc.mutate().upsert("seen", &true);
            JshiftDoc(doc)
        }
        let app = axum::Router::new().route("/", axum::routing::post(handler));
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header(header::CONTENT_TYPE, "application/json")
                    .body(Body::from(r#"{"keep":1}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = res.into_body().collect().await.unwrap().to_bytes();
        let s = std::str::from_utf8(&body).unwrap();
        assert!(s.contains("\"keep\""));
        assert!(s.contains("\"seen\""));
    }

    #[test]
    fn content_type_helpers() {
        let mut h = HeaderMap::new();
        h.insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("APPLICATION/JSON"),
        );
        assert!(json_content_type(&h));
        h.insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/vnd.api+json"),
        );
        assert!(json_content_type(&h));
        h.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/json"));
        assert!(!json_content_type(&h));
    }
}