Skip to main content

spate_core/framing/
mod.rs

1//! Streaming record framing: the seam that cuts a decoded byte stream into
2//! records.
3//!
4//! Framing is a **transport- and format-agnostic seam**. Any streaming or pull
5//! source (object-storage backfills in `spate-s3`, HTTP chunked bodies,
6//! WebSocket message streams, file tails) must turn a byte stream into records
7//! before a [`Deserializer`](crate::deser::Deserializer) decodes each one.
8//! That "one payload → one record" split lets a single decoder serve every
9//! source; the framer decides what one payload *is*.
10//!
11//! `spate-core` owns the seam here (the [`RecordFramer`] trait, the
12//! [`FramerWriter`] decompressor shim, and the [`FramingContract`] handshake).
13//! The concrete framers are owned by the **format** crates, because how a byte
14//! stream splits into records is a property of the format rather than the
15//! transport. `spate-json` provides newline-delimited framing for NDJSON, a
16//! future `spate-avro` an object-container block framer, and so on. A source
17//! stays format-agnostic and receives its framer at pipeline-assembly time
18//! (e.g. `S3Source::with_framer`), so the same framer serves every streaming
19//! source and no source hard-codes a format.
20//!
21//! A [`RecordFramer`] is fed decoded bytes in arbitrary chunks and yields
22//! completed record byte-slices. It **must be a pure function of the byte
23//! stream**, independent of how the bytes are chunked, so a source that
24//! resumes by record index replays deterministically; at-least-once resume
25//! depends on it (see the `spate-s3` offset model). Compression is *not* part
26//! of framing. A source that decompresses wraps its decompressor around a
27//! [`FramerWriter`], so the framer only ever sees already-decoded bytes.
28//!
29//! Dispatch through `Box<dyn RecordFramer>` happens once per fed chunk, never
30//! per record, so each impl's per-record scan stays monomorphized.
31
32use std::io::{self, Write};
33
34/// What one payload emitted by a source represents, so the framework can pair
35/// a source with a deserializer without the two being coordinated by hand.
36///
37/// - [`PerRecord`](FramingContract::PerRecord): the source already framed one
38///   record per payload, having run a [`RecordFramer`] over its byte stream
39///   (e.g. an `spate-s3` backfill framing each object with the format's
40///   framer). The deserializer must decode a *single* unit; a deserializer
41///   configured to *also* frame the payload is a double-framing error.
42/// - [`WholePayload`](FramingContract::WholePayload): the source emits whole
43///   payloads and the deserializer owns framing (e.g. a Kafka message, which
44///   may carry one record or many). This is the default for sources that do
45///   not frame.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum FramingContract {
49    /// One record per payload; the deserializer decodes a single unit.
50    PerRecord,
51    /// Whole payloads; the deserializer frames them.
52    WholePayload,
53}
54
55/// A streaming record framer: fed decoded bytes, yields record byte-payloads.
56///
57/// Concrete implementations live in the format crates (`spate-json`'s NDJSON
58/// framer, a future `spate-avro` container framer, ...). Implementations
59/// **must be a pure function of the byte stream**. The record sequence must
60/// not depend on how bytes are split across [`push`](Self::push) calls, so
61/// resume-by-record-index stays deterministic. Enforce any record-size bound
62/// inside `push` (return an error rather than buffer unboundedly), and check
63/// it against the record accumulated so far rather than against the bytes of
64/// the current `push`, so the framer fails at the same position in the stream
65/// however the bytes were split. A record completed before that position is
66/// queued for [`pop`](Self::pop) before the error returns, so a caller that
67/// drains after a failed [`push`](Self::push) or [`finish`](Self::finish)
68/// sees the same records as one that fed the stream whole.
69pub trait RecordFramer: Send {
70    /// Feed the next run of decoded bytes.
71    fn push(&mut self, bytes: &[u8]) -> io::Result<()>;
72
73    /// End of the stream/object: complete an unterminated final record if the
74    /// format allows one, and validate any end-of-stream structure.
75    fn finish(&mut self) -> io::Result<()>;
76
77    /// Pop the next completed record, in stream order.
78    fn pop(&mut self) -> Option<Vec<u8>>;
79
80    /// Total decoded bytes fed so far (for metrics).
81    fn decoded_bytes(&self) -> u64;
82
83    /// The byte after which a reader can start framing mid-stream, or `None`
84    /// when the format has no such byte.
85    ///
86    /// Returning `Some(delim)` promises that for any stream `S` and any index
87    /// `d` with `S[d] == delim`, framing `S` yields the records of `S[..=d]`
88    /// followed by the records of `S[d + 1..]`, each framed by a fresh framer
89    /// through [`finish`](Self::finish). A source may then split one stream
90    /// into byte ranges and frame each on its own. A format with a header, a
91    /// BOM, magic bytes, or a delimiter that can appear quoted inside a record
92    /// (CSV) returns `None`.
93    fn resync_delimiter(&self) -> Option<u8> {
94        None
95    }
96}
97
98/// A [`Write`] adapter over a [`RecordFramer`], so a source whose decompressor
99/// (or any other `Write`-sink codec) emits decoded bytes through `Write` can
100/// feed a framer without the framer implementing `Write` itself. Every
101/// `write` forwards the buffer to [`RecordFramer::push`].
102pub struct FramerWriter {
103    framer: Box<dyn RecordFramer>,
104}
105
106impl FramerWriter {
107    /// Wrap `framer` as a `Write` target.
108    #[must_use]
109    pub fn new(framer: Box<dyn RecordFramer>) -> FramerWriter {
110        FramerWriter { framer }
111    }
112
113    /// The wrapped framer (shared), for reading `decoded_bytes`.
114    #[must_use]
115    pub fn framer(&self) -> &dyn RecordFramer {
116        &*self.framer
117    }
118
119    /// The wrapped framer, for popping records, reading `decoded_bytes`, and
120    /// `finish`.
121    pub fn framer_mut(&mut self) -> &mut dyn RecordFramer {
122        &mut *self.framer
123    }
124
125    /// Reclaim the wrapped framer (e.g. after a decompressor's end-of-stream
126    /// validation hands the writer back).
127    #[must_use]
128    pub fn into_inner(self) -> Box<dyn RecordFramer> {
129        self.framer
130    }
131}
132
133impl std::fmt::Debug for FramerWriter {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        f.debug_struct("FramerWriter").finish_non_exhaustive()
136    }
137}
138
139impl Write for FramerWriter {
140    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
141        self.framer.push(buf)?;
142        Ok(buf.len())
143    }
144
145    fn flush(&mut self) -> io::Result<()> {
146        Ok(())
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use std::collections::VecDeque;
154
155    /// A minimal in-crate [`RecordFramer`] for exercising the seam without a
156    /// concrete framer; those live in the format crates. It concatenates
157    /// everything pushed and emits it as one record at `finish`.
158    #[derive(Default)]
159    struct WholeFramer {
160        buf: Vec<u8>,
161        ready: VecDeque<Vec<u8>>,
162        decoded: u64,
163    }
164
165    impl RecordFramer for WholeFramer {
166        fn push(&mut self, bytes: &[u8]) -> io::Result<()> {
167            self.decoded += bytes.len() as u64;
168            self.buf.extend_from_slice(bytes);
169            Ok(())
170        }
171
172        fn finish(&mut self) -> io::Result<()> {
173            if !self.buf.is_empty() {
174                self.ready.push_back(std::mem::take(&mut self.buf));
175            }
176            Ok(())
177        }
178
179        fn pop(&mut self) -> Option<Vec<u8>> {
180            self.ready.pop_front()
181        }
182
183        fn decoded_bytes(&self) -> u64 {
184            self.decoded
185        }
186    }
187
188    #[test]
189    fn record_framer_is_object_safe() {
190        // Compiles only if the trait is dyn-compatible (the seam's contract).
191        let mut framer: Box<dyn RecordFramer> = Box::new(WholeFramer::default());
192        framer.push(b"x").unwrap();
193        framer.finish().unwrap();
194        assert_eq!(framer.pop(), Some(b"x".to_vec()));
195    }
196
197    /// A framer that does not override `resync_delimiter` declares no resync
198    /// point.
199    #[test]
200    fn a_framer_declares_no_resync_delimiter_by_default() {
201        assert_eq!(WholeFramer::default().resync_delimiter(), None);
202    }
203
204    #[test]
205    fn framer_writer_forwards_writes_to_push_and_counts_bytes() {
206        let mut w = FramerWriter::new(Box::new(WholeFramer::default()));
207        w.write_all(b"a\nb\n").unwrap();
208        assert_eq!(
209            w.framer().decoded_bytes(),
210            4,
211            "every written byte reaches push"
212        );
213        w.framer_mut().finish().unwrap();
214        let mut out = Vec::new();
215        while let Some(r) = w.framer_mut().pop() {
216            out.push(r);
217        }
218        assert_eq!(out, vec![b"a\nb\n".to_vec()]);
219    }
220
221    #[test]
222    fn framer_writer_into_inner_reclaims_the_framer() {
223        let w = FramerWriter::new(Box::new(WholeFramer::default()));
224        let framer = w.into_inner();
225        assert_eq!(framer.decoded_bytes(), 0);
226    }
227}