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).
63pub trait RecordFramer: Send {
64    /// Feed the next run of decoded bytes.
65    fn push(&mut self, bytes: &[u8]) -> io::Result<()>;
66
67    /// End of the stream/object: complete an unterminated final record if the
68    /// format allows one, and validate any end-of-stream structure.
69    fn finish(&mut self) -> io::Result<()>;
70
71    /// Pop the next completed record, in stream order.
72    fn pop(&mut self) -> Option<Vec<u8>>;
73
74    /// Total decoded bytes fed so far (for metrics).
75    fn decoded_bytes(&self) -> u64;
76}
77
78/// A [`Write`] adapter over a [`RecordFramer`], so a source whose decompressor
79/// (or any other `Write`-sink codec) emits decoded bytes through `Write` can
80/// feed a framer without the framer implementing `Write` itself. Every
81/// `write` forwards the buffer to [`RecordFramer::push`].
82pub struct FramerWriter {
83    framer: Box<dyn RecordFramer>,
84}
85
86impl FramerWriter {
87    /// Wrap `framer` as a `Write` target.
88    #[must_use]
89    pub fn new(framer: Box<dyn RecordFramer>) -> FramerWriter {
90        FramerWriter { framer }
91    }
92
93    /// The wrapped framer (shared), for reading `decoded_bytes`.
94    #[must_use]
95    pub fn framer(&self) -> &dyn RecordFramer {
96        &*self.framer
97    }
98
99    /// The wrapped framer, for popping records, reading `decoded_bytes`, and
100    /// `finish`.
101    pub fn framer_mut(&mut self) -> &mut dyn RecordFramer {
102        &mut *self.framer
103    }
104
105    /// Reclaim the wrapped framer (e.g. after a decompressor's end-of-stream
106    /// validation hands the writer back).
107    #[must_use]
108    pub fn into_inner(self) -> Box<dyn RecordFramer> {
109        self.framer
110    }
111}
112
113impl std::fmt::Debug for FramerWriter {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.debug_struct("FramerWriter").finish_non_exhaustive()
116    }
117}
118
119impl Write for FramerWriter {
120    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
121        self.framer.push(buf)?;
122        Ok(buf.len())
123    }
124
125    fn flush(&mut self) -> io::Result<()> {
126        Ok(())
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use std::collections::VecDeque;
134
135    /// A minimal in-crate [`RecordFramer`] for exercising the seam without a
136    /// concrete framer; those live in the format crates. It concatenates
137    /// everything pushed and emits it as one record at `finish`.
138    #[derive(Default)]
139    struct WholeFramer {
140        buf: Vec<u8>,
141        ready: VecDeque<Vec<u8>>,
142        decoded: u64,
143    }
144
145    impl RecordFramer for WholeFramer {
146        fn push(&mut self, bytes: &[u8]) -> io::Result<()> {
147            self.decoded += bytes.len() as u64;
148            self.buf.extend_from_slice(bytes);
149            Ok(())
150        }
151
152        fn finish(&mut self) -> io::Result<()> {
153            if !self.buf.is_empty() {
154                self.ready.push_back(std::mem::take(&mut self.buf));
155            }
156            Ok(())
157        }
158
159        fn pop(&mut self) -> Option<Vec<u8>> {
160            self.ready.pop_front()
161        }
162
163        fn decoded_bytes(&self) -> u64 {
164            self.decoded
165        }
166    }
167
168    #[test]
169    fn record_framer_is_object_safe() {
170        // Compiles only if the trait is dyn-compatible (the seam's contract).
171        let mut framer: Box<dyn RecordFramer> = Box::new(WholeFramer::default());
172        framer.push(b"x").unwrap();
173        framer.finish().unwrap();
174        assert_eq!(framer.pop(), Some(b"x".to_vec()));
175    }
176
177    #[test]
178    fn framer_writer_forwards_writes_to_push_and_counts_bytes() {
179        let mut w = FramerWriter::new(Box::new(WholeFramer::default()));
180        w.write_all(b"a\nb\n").unwrap();
181        assert_eq!(
182            w.framer().decoded_bytes(),
183            4,
184            "every written byte reaches push"
185        );
186        w.framer_mut().finish().unwrap();
187        let mut out = Vec::new();
188        while let Some(r) = w.framer_mut().pop() {
189            out.push(r);
190        }
191        assert_eq!(out, vec![b"a\nb\n".to_vec()]);
192    }
193
194    #[test]
195    fn framer_writer_into_inner_reclaims_the_framer() {
196        let w = FramerWriter::new(Box::new(WholeFramer::default()));
197        let framer = w.into_inner();
198        assert_eq!(framer.decoded_bytes(), 0);
199    }
200}