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
//! Multi-file / multi-page JSON and incremental JSONL.
//!
//! Real pipelines rarely hold one giant buffer:
//!
//! * **Paginated APIs** — `page1.json`, `page2.json`, each
//!   `{"items":[…], "next":…}` (Shopify: `{"products":[…]}`)
//! * **Sharded dumps** — `part-000.jsonl`, `part-001.jsonl`
//! * **Incremental download** — TCP/HTTP chunks that split mid-line
//!
//! jshift keeps the **byte-level** model: stream **records** (lines or array
//! elements) across sources without merging pages into one `Value` or one
//! mega-buffer.
//!
//! # Quick map
//!
//! | Workload | API |
//! | --- | --- |
//! | Many JSONL files/buffers in order | [`for_each_jsonl_multi`], [`read_jsonl_multi`] |
//! | Chunked JSONL (incomplete lines) | [`JsonlDecoder`] |
//! | Paginated `{"items":[…]}` pages | [`for_each_page_items`] |
//! | Each page is a root `[…]` array | [`for_each_page_array`] |
//! | Each page is one JSON object | [`for_each_page_doc`] |
//!
//! Single-buffer JSONL remains in [`crate::jsonl`].
//!
//! # Catalog ingest (TeeFury / Shopify)
//!
//! A typical multi-page ingest does **not** need every variant/image blob —
//! only a listing card. Stream pages with [`for_each_page_items`] + a thin
//! [`JsonView`], or emit cards with [`crate::project_jmespath`] /
//! [`crate::ProjectPlan`]:
//!
//! ```ignore
//! // Live GET https://teefury.com/products.json?page=1..=10 (cached under benches/data/)
//! // cargo run --release --example teefury_ingest_bench --features derive
//! use jshift::{for_each_page_items, JsonView};
//!
//! #[derive(JsonView)]
//! struct ProductCard {
//!     #[json(path = "id")]
//!     id: u64,
//!     #[json(path = "title")]
//!     title: String,
//!     #[json(path = "handle")]
//!     handle: String,
//!     // body_html / variants / images never named → unread
//! }
//!
//! for_each_page_items::<ProductCard, _, _, _>(pages, "products", |_pos, card| {
//!     // write card to index / NDJSON / DB
//!     let _ = card;
//!     Ok(())
//! })?;
//! ```
//!
//! On real TeeFury pages (~3.6 MiB / 300 products across 10 pages), projecting
//! listing cards shrinks to **~1.2%** of input. vs deserializing the **full**
//! Shopify product (variants/images as `Value`), sparse jshift cards are about
//! **3–6×** faster depending on path (`JsonView` vs `ProjectPlan` emit). serde’s
//! sparse typed `Deserialize` can still win pure card decode on this shape —
//! see the README TeeFury table and `examples/teefury_ingest_bench.rs`.
//!
//! ```
//! use jshift::{for_each_page_item_raw, StreamPos};
//!
//! let p1 = br#"{"items":[{"id":1},{"id":2}],"next":2}"#;
//! let p2 = br#"{"items":[{"id":3}],"next":null}"#;
//! let mut n = 0usize;
//! for_each_page_item_raw([p1.as_slice(), p2.as_slice()], "items", |pos, _raw| {
//!     assert!(pos.source_index < 2);
//!     n += 1;
//!     Ok(())
//! })
//! .unwrap();
//! assert_eq!(n, 3);
//! ```

use crate::error::Error;
use crate::jsonl::json_lines;
use crate::typed_doc::{JsonDoc, TypedDocRef};
use crate::view::JsonView;
use crate::view_list::ViewList;

// ─── Stream position ─────────────────────────────────────────────────────────

/// Where a record came from in a multi-source stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct StreamPos {
    /// Index of the page / file / buffer (0-based).
    pub source_index: usize,
    /// Index of the record within that source (line or array element, 0-based).
    pub record_index: usize,
}

// ─── Incremental JSONL (chunked input) ───────────────────────────────────────

/// Incremental JSONL decoder for **chunked** input (HTTP body, growing file, pipe).
///
/// Feed arbitrary byte chunks with [`push`](Self::push); complete lines are
/// delivered without requiring a line to arrive in one `read`. A trailing
/// partial line stays in an internal carry buffer until more data or
/// [`finish`](Self::finish).
///
/// ```
/// use jshift::JsonlDecoder;
///
/// let mut d = JsonlDecoder::new();
/// d.push(br#"{"id":1}"#);
/// d.push(b"\n{\"id\":");
/// d.push(br#"2}"#);
/// d.push(b"\n");
/// let mut ids = Vec::new();
/// d.for_each_ready(|line| {
///     // line is a complete JSONL record (no trailing newline)
///     ids.push(line.to_vec());
///     Ok(())
/// })
/// .unwrap();
/// assert_eq!(ids.len(), 2);
/// assert!(d.pending().is_empty());
/// ```
#[derive(Debug, Clone, Default)]
pub struct JsonlDecoder {
    carry: Vec<u8>,
}

impl JsonlDecoder {
    /// Empty decoder.
    #[inline]
    pub fn new() -> Self {
        Self { carry: Vec::new() }
    }

    /// Pre-size the carry buffer (hint for large lines).
    #[inline]
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            carry: Vec::with_capacity(cap),
        }
    }

    /// Bytes held that are not yet a complete line.
    #[inline]
    pub fn pending(&self) -> &[u8] {
        &self.carry
    }

    /// Clear carry (e.g. after handling an error).
    #[inline]
    pub fn clear(&mut self) {
        self.carry.clear();
    }

    /// Append a chunk. Does not invoke callbacks; call [`for_each_ready`](Self::for_each_ready).
    #[inline]
    pub fn push(&mut self, chunk: &[u8]) {
        if chunk.is_empty() {
            return;
        }
        self.carry.extend_from_slice(chunk);
    }

    /// Invoke `f` for each **complete** line currently in the carry buffer.
    ///
    /// Processed bytes (including their `\n`) are drained from the carry.
    /// Incomplete trailing data remains in [`pending`](Self::pending).
    pub fn for_each_ready<F>(&mut self, mut f: F) -> Result<(), Error>
    where
        F: FnMut(&[u8]) -> Result<(), Error>,
    {
        let mut consumed = 0usize;
        let mut start = 0usize;
        let buf = self.carry.as_slice();
        while start < buf.len() {
            let rel = match buf[start..].iter().position(|&b| b == b'\n') {
                Some(i) => i,
                None => break,
            };
            let end = start + rel;
            let mut line = &buf[start..end];
            if line.last() == Some(&b'\r') {
                line = &line[..line.len() - 1];
            }
            if !line.is_empty() {
                f(line)?;
            }
            start = end + 1;
            consumed = start;
        }
        if consumed > 0 {
            self.carry.drain(..consumed);
        }
        Ok(())
    }

    /// Push `chunk` then immediately run [`for_each_ready`](Self::for_each_ready).
    #[inline]
    pub fn push_and_for_each<F>(&mut self, chunk: &[u8], f: F) -> Result<(), Error>
    where
        F: FnMut(&[u8]) -> Result<(), Error>,
    {
        self.push(chunk);
        self.for_each_ready(f)
    }

    /// After EOF: deliver a final non-empty pending line (no trailing `\n`), then clear.
    ///
    /// Returns `Ok(true)` if a final line was emitted.
    pub fn finish<F>(&mut self, mut f: F) -> Result<bool, Error>
    where
        F: FnMut(&[u8]) -> Result<(), Error>,
    {
        self.for_each_ready(&mut f)?;
        if self.carry.is_empty() {
            return Ok(false);
        }
        let mut line = self.carry.as_slice();
        if line.last() == Some(&b'\r') {
            line = &line[..line.len() - 1];
        }
        if line.is_empty() {
            self.carry.clear();
            return Ok(false);
        }
        // Copy out because f might not allow re-borrow after clear — use split.
        let owned = line.to_vec();
        self.carry.clear();
        f(&owned)?;
        Ok(true)
    }

    /// Typed helper: decode each ready line as `T: JsonView`.
    pub fn for_each_view_ready<T, F>(&mut self, mut f: F) -> Result<(), Error>
    where
        T: JsonView,
        F: FnMut(T) -> Result<(), Error>,
    {
        self.for_each_ready(|line| f(T::read_from(line)?))
    }
}

// ─── Multi JSONL sources ─────────────────────────────────────────────────────

/// Stream every non-empty JSONL line across many buffers (files/shards) in order.
///
/// Does **not** concatenate into one allocation: each source is scanned, then
/// dropped before the next (caller still owns the slices).
///
/// `f(pos, line_bytes)` — `line_bytes` is a subslice of the current source.
pub fn for_each_jsonl_multi<I, B, F>(sources: I, mut f: F) -> Result<(), Error>
where
    I: IntoIterator<Item = B>,
    B: AsRef<[u8]>,
    F: FnMut(StreamPos, &[u8]) -> Result<(), Error>,
{
    for (source_index, src) in sources.into_iter().enumerate() {
        let buf = src.as_ref();
        let mut record_index = 0usize;
        for line in json_lines(buf) {
            f(
                StreamPos {
                    source_index,
                    record_index,
                },
                line,
            )?;
            record_index += 1;
        }
    }
    Ok(())
}

/// Like [`for_each_jsonl_multi`], decoding each line as `T: JsonView`.
pub fn for_each_jsonl_view_multi<T, I, B, F>(sources: I, mut f: F) -> Result<(), Error>
where
    T: JsonView,
    I: IntoIterator<Item = B>,
    B: AsRef<[u8]>,
    F: FnMut(StreamPos, T) -> Result<(), Error>,
{
    for_each_jsonl_multi(sources, |pos, line| f(pos, T::read_from(line)?))
}

/// Iterator over `(StreamPos, line)` across multiple JSONL buffers.
///
/// Collects source refs so the iterator can be long-lived. Prefer
/// [`for_each_jsonl_multi`] when you only need a single pass without storing
/// source pointers.
pub fn read_jsonl_multi<'a, T: JsonView + 'a>(
    sources: impl IntoIterator<Item = &'a [u8]>,
) -> impl Iterator<Item = Result<(StreamPos, T), Error>> + 'a {
    let sources: Vec<&'a [u8]> = sources.into_iter().collect();
    sources
        .into_iter()
        .enumerate()
        .flat_map(|(source_index, buf)| {
            json_lines(buf)
                .enumerate()
                .map(move |(record_index, line)| {
                    let pos = StreamPos {
                        source_index,
                        record_index,
                    };
                    T::read_from(line).map(|t| (pos, t))
                })
        })
}

// ─── Paginated / multi-file JSON pages ───────────────────────────────────────

/// Each page is a JSON **object**; stream `T` from the array at `items_path`.
///
/// Typical paginated API:
///
/// ```json
/// {"items":[{"id":1},{"id":2}],"next":"…"}
/// ```
///
/// Shopify-style catalogs use `"products"` (see crate-level TeeFury note and
/// `examples/teefury_ingest_bench.rs` for a live multi-page card ingest vs serde).
///
/// Path is a jshift path string (`"items"`, `"products"`, `"data.results"`, …).
pub fn for_each_page_items<T, I, B, F>(
    pages: I,
    items_path: &str,
    mut f: F,
) -> Result<(), Error>
where
    T: JsonView,
    I: IntoIterator<Item = B>,
    B: AsRef<[u8]>,
    F: FnMut(StreamPos, T) -> Result<(), Error>,
{
    for (source_index, page) in pages.into_iter().enumerate() {
        let bytes = page.as_ref();
        let doc = TypedDocRef::from_slice(bytes);
        let list = ViewList::<T>::from_doc(&doc, items_path)?;
        let mut record_index = 0usize;
        list.each(|row| {
            let pos = StreamPos {
                source_index,
                record_index,
            };
            record_index += 1;
            f(pos, row)
        })?;
    }
    Ok(())
}

/// Each page is a root JSON **array**; stream each element as `T: JsonView`.
pub fn for_each_page_array<T, I, B, F>(pages: I, mut f: F) -> Result<(), Error>
where
    T: JsonView,
    I: IntoIterator<Item = B>,
    B: AsRef<[u8]>,
    F: FnMut(StreamPos, T) -> Result<(), Error>,
{
    for (source_index, page) in pages.into_iter().enumerate() {
        let bytes = page.as_ref();
        let list = ViewList::<T>::from_array_bytes(bytes)?;
        let mut record_index = 0usize;
        list.each(|row| {
            let pos = StreamPos {
                source_index,
                record_index,
            };
            record_index += 1;
            f(pos, row)
        })?;
    }
    Ok(())
}

/// Each page/file is one JSON document (object or array root).
///
/// Callback receives a zero-copy [`TypedDocRef`] over that page’s bytes.
pub fn for_each_page_doc<I, B, F>(pages: I, mut f: F) -> Result<(), Error>
where
    I: IntoIterator<Item = B>,
    B: AsRef<[u8]>,
    F: FnMut(StreamPos, TypedDocRef<'_>) -> Result<(), Error>,
{
    for (source_index, page) in pages.into_iter().enumerate() {
        let bytes = page.as_ref();
        let doc = TypedDocRef::from_slice(bytes);
        f(
            StreamPos {
                source_index,
                record_index: 0,
            },
            doc,
        )?;
    }
    Ok(())
}

/// Stream raw array element spans from the array at `items_path` across pages.
///
/// Lower-level than [`for_each_page_items`]: no `JsonView` decode.
pub fn for_each_page_item_raw<I, B, F>(
    pages: I,
    items_path: &str,
    mut f: F,
) -> Result<(), Error>
where
    I: IntoIterator<Item = B>,
    B: AsRef<[u8]>,
    F: FnMut(StreamPos, &[u8]) -> Result<(), Error>,
{
    for (source_index, page) in pages.into_iter().enumerate() {
        let bytes = page.as_ref();
        let doc = TypedDocRef::from_slice(bytes);
        let mut record_index = 0usize;
        for item in doc.elems(items_path)? {
            let span = item?;
            f(
                StreamPos {
                    source_index,
                    record_index,
                },
                span,
            )?;
            record_index += 1;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::build::ObjectBuilder;
    use crate::convert::{FromJsonSlice, ToJsonBytes};
    use crate::path::parse_path;
    use crate::scan::find_value;
    use crate::upsert_at_path;

    struct IdOnly {
        id: u64,
    }

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

    #[test]
    fn multi_jsonl_shards() {
        let a = br#"{"id":1}
{"id":2}
"#;
        let b = br#"{"id":3}
"#;
        let mut ids = Vec::new();
        for_each_jsonl_view_multi::<IdOnly, _, _, _>([a.as_slice(), b.as_slice()], |pos, row| {
            ids.push((pos.source_index, pos.record_index, row.id));
            Ok(())
        })
        .unwrap();
        assert_eq!(ids, vec![(0, 0, 1), (0, 1, 2), (1, 0, 3)]);
    }

    #[test]
    fn jsonl_decoder_chunked() {
        let mut d = JsonlDecoder::new();
        let mut ids = Vec::new();
        d.push(br#"{"id":1}"#);
        d.push(b"\n{\"i");
        d.for_each_ready(|line| {
            ids.push(IdOnly::read_from(line).unwrap().id);
            Ok(())
        })
        .unwrap();
        assert_eq!(ids, vec![1]);
        assert!(!d.pending().is_empty());
        d.push(br#"d":2}"#);
        d.push(b"\n");
        d.for_each_ready(|line| {
            ids.push(IdOnly::read_from(line).unwrap().id);
            Ok(())
        })
        .unwrap();
        assert_eq!(ids, vec![1, 2]);
        assert!(d.pending().is_empty());
    }

    #[test]
    fn page_items_paginated_api() {
        let p1 = ObjectBuilder::new()
            .raw_field(
                "items",
                br#"[{"id":1},{"id":2}]"#,
            )
            .field("next", &2u64)
            .finish();
        let p2 = ObjectBuilder::new()
            .raw_field("items", br#"[{"id":3}]"#)
            .null_field("next")
            .finish();
        let mut sum = 0u64;
        let mut n = 0usize;
        for_each_page_items::<IdOnly, _, _, _>([p1.as_slice(), p2.as_slice()], "items", |pos, row| {
            sum += row.id;
            n += 1;
            assert!(pos.source_index < 2);
            Ok(())
        })
        .unwrap();
        assert_eq!(sum, 6);
        assert_eq!(n, 3);
    }

    #[test]
    fn page_root_array() {
        let pages = [br#"[{"id":10},{"id":11}]"#.as_slice(), br#"[{"id":12}]"#.as_slice()];
        let mut ids = Vec::new();
        for_each_page_array::<IdOnly, _, _, _>(pages, |_pos, row| {
            ids.push(row.id);
            Ok(())
        })
        .unwrap();
        assert_eq!(ids, vec![10, 11, 12]);
    }

    #[test]
    fn page_doc_single_objects() {
        let pages = [br#"{"id":1,"page":0}"#.as_slice(), br#"{"id":2,"page":1}"#.as_slice()];
        let mut ids = Vec::new();
        for_each_page_doc(pages, |_pos, doc| {
            ids.push(doc.get::<u64>("id").unwrap());
            Ok(())
        })
        .unwrap();
        assert_eq!(ids, vec![1, 2]);
    }

    #[test]
    fn decoder_finish_without_newline() {
        let mut d = JsonlDecoder::new();
        d.push(br#"{"id":9}"#);
        let mut got = 0u64;
        assert!(d
            .finish(|line| {
                got = IdOnly::read_from(line).unwrap().id;
                Ok(())
            })
            .unwrap());
        assert_eq!(got, 9);
    }
}