Skip to main content

c0/
stream.rs

1//! Stream mode: ETB-committed append logs (DESIGN.md "Stream Mode").
2//!
3//! An unescaped ETB is always a commit, inside open text or a level too:
4//! such a block is damaged and yields nothing. The tail after the last
5//! commit is torn unless it holds only layout, notes or EOT.
6//!
7//! ```no_run
8//! let mut log = c0::open_log("events.c0")?;        // repairs a torn tail first
9//! log.start(&[("shape", "stream")])?;
10//! log.record(&["create", "a1b2", "1718208000"])?;
11//! let bytes = c0::read_log("events.c0")?;
12//! let r = c0::StreamReader::new(&bytes);
13//! assert!(!r.torn());
14//! # Ok::<(), std::io::Error>(())
15//! ```
16
17use crate::*;
18use std::borrow::Cow;
19use std::fs::{self, File, OpenOptions};
20use std::io::{self, Write};
21use std::path::Path;
22
23/// Scans a buffer for commits and exposes the committed region, block by
24/// block. Zero-copy: accessors return slices into the original buffer.
25pub struct StreamReader<'a> {
26    buf: &'a [u8],
27    committed_end: usize,
28    blocks: Vec<(usize, usize)>,
29    damaged: Vec<usize>,
30    torn: bool,
31}
32
33impl<'a> StreamReader<'a> {
34    pub fn new(buf: &'a [u8]) -> Self {
35        let mut r = StreamReader {
36            buf,
37            committed_end: 0,
38            blocks: Vec::new(),
39            damaged: Vec::new(),
40            torn: false,
41        };
42        r.scan();
43        r
44    }
45
46    pub fn buf(&self) -> &'a [u8] {
47        self.buf
48    }
49
50    /// Offset just past the last ETB and its payload.
51    pub fn committed_end(&self) -> usize {
52        self.committed_end
53    }
54
55    /// The committed region of the buffer.
56    pub fn committed(&self) -> &'a [u8] {
57        &self.buf[..self.committed_end]
58    }
59
60    /// Everything after the last commit.
61    pub fn tail(&self) -> &'a [u8] {
62        &self.buf[self.committed_end..]
63    }
64
65    /// Whether data trails the last commit (layout, notes and EOT alone do
66    /// not count).
67    pub fn torn(&self) -> bool {
68        self.torn
69    }
70
71    pub fn block_count(&self) -> usize {
72        self.blocks.len()
73    }
74
75    /// Committed block `i`: the bytes from the previous commit to this
76    /// block's ETB (marker and payload excluded).
77    pub fn block(&self, i: usize) -> &'a [u8] {
78        let (s, e) = self.blocks[i];
79        &self.buf[s..e]
80    }
81
82    /// `[start, end)` of every committed block.
83    pub fn block_ranges(&self) -> &[(usize, usize)] {
84        &self.blocks
85    }
86
87    pub fn blocks(&self) -> impl Iterator<Item = &'a [u8]> + '_ {
88        (0..self.blocks.len()).map(move |i| self.block(i))
89    }
90
91    /// Indexes of blocks cut by an ETB inside open text or a level.
92    pub fn damaged(&self) -> &[usize] {
93        &self.damaged
94    }
95
96    pub fn is_damaged(&self, i: usize) -> bool {
97        self.damaged.contains(&i)
98    }
99
100    /// The committed region with damaged blocks removed: borrowed when no
101    /// block is damaged, otherwise the undamaged blocks concatenated.
102    /// Read it with [`Document::new`] or [`Body::new`].
103    pub fn undamaged(&self) -> Cow<'a, [u8]> {
104        if self.damaged.is_empty() {
105            return Cow::Borrowed(self.committed());
106        }
107        let mut out = Vec::new();
108        for (i, &(s, e)) in self.blocks.iter().enumerate() {
109            if !self.damaged.contains(&i) {
110                out.extend_from_slice(&self.buf[s..e]);
111            }
112        }
113        Cow::Owned(out)
114    }
115
116    /// Logical values of every committed record (headings and header rows
117    /// excluded), undamaged blocks only.
118    pub fn records(&self) -> Result<Vec<Vec<Vec<u8>>>> {
119        let bytes = self.undamaged();
120        let doc = Document::new(&bytes)?;
121        let mut out = Vec::new();
122        for g in doc.groups() {
123            for r in g.records() {
124                out.push(r.values()?.into_iter().map(|v| v.into_owned()).collect());
125            }
126        }
127        Ok(out)
128    }
129
130    fn scan(&mut self) {
131        let buf = self.buf;
132        let len = buf.len();
133        let mut pos = 0;
134        let mut block_start = 0;
135        let mut in_text = false;
136        let mut depth = 0usize;
137        while pos < len {
138            let b = buf[pos];
139            if in_text {
140                if b == DLE {
141                    pos += 2;
142                    continue;
143                } else if b == ETX {
144                    in_text = false;
145                } else if b == ETB {
146                    self.commit(block_start, pos, true);
147                    pos = self.payload_end(pos + 1);
148                    block_start = pos;
149                    in_text = false;
150                    depth = 0;
151                    continue;
152                } else if b == SYN || b == EOT || b == EM {
153                    // framing cuts the text; the block is torn or damaged
154                    in_text = false;
155                    depth = 0;
156                    if b == SYN {
157                        block_start = pos;
158                    }
159                }
160                pos += 1;
161            } else {
162                if b == STX {
163                    in_text = true;
164                } else if b == DLE {
165                    depth += 1;
166                } else if b == CAN {
167                    depth = depth.saturating_sub(1);
168                } else if b == ETB {
169                    self.commit(block_start, pos, depth > 0);
170                    pos = self.payload_end(pos + 1);
171                    block_start = pos;
172                    depth = 0;
173                    continue;
174                } else if b == SYN && pos > 0 {
175                    // tears the uncommitted bytes before it; a new document begins
176                    block_start = pos;
177                    depth = 0;
178                }
179                pos += 1;
180            }
181        }
182        self.torn = self.torn_tail();
183    }
184
185    fn commit(&mut self, start: usize, stop: usize, damaged: bool) {
186        self.blocks.push((start, stop));
187        if damaged {
188            self.damaged.push(self.blocks.len() - 1);
189        }
190    }
191
192    // After an ETB: skip its payload and return committed_end (which
193    // excludes layout after the payload).
194    fn payload_end(&mut self, pos: usize) -> usize {
195        let buf = self.buf;
196        let len = buf.len();
197        let mut p = scan::layout(buf, pos, len);
198        if p < len && buf[p] >= 0x20 {
199            p = scan::plain(buf, p, len);
200            // trailing spaces of the payload are layout
201            while p > pos && buf[p - 1] == SP {
202                p -= 1;
203            }
204        } else {
205            p = pos; // no payload: layout after ETB belongs to the next block
206        }
207        self.committed_end = p;
208        p
209    }
210
211    // Is the tail more than layout, notes and EOT?
212    fn torn_tail(&self) -> bool {
213        let buf = self.buf;
214        let len = buf.len();
215        let mut pos = self.committed_end;
216        loop {
217            pos = scan::layout(buf, pos, len);
218            if pos >= len {
219                return false;
220            }
221            let b = buf[pos];
222            if b == EOT {
223                pos += 1;
224            } else if b == EM {
225                return false; // the raw region is not data of the log
226            } else if b == BEL {
227                let p2 = scan::layout(buf, pos + 1, len);
228                if p2 < len && buf[p2] < 0x20 && buf[p2] != STX {
229                    return true; // a dead element is data
230                }
231                match scan::comment(buf, pos, len) {
232                    Ok(p) => pos = p,
233                    Err(_) => return true,
234                }
235            } else {
236                return true;
237            }
238        }
239    }
240}
241
242/// Position just past the last commit, found by scanning backward
243/// (treating an ETB behind an odd run of DLEs as escaped). A shortcut for
244/// well-formed input; the forward scan of [`StreamReader`] is authoritative.
245pub fn last_commit_end(buf: &[u8]) -> usize {
246    let mut i = buf.len();
247    while i > 0 {
248        i -= 1;
249        if buf[i] != ETB {
250            continue;
251        }
252        let dles = buf[..i].iter().rev().take_while(|&&b| b == DLE).count();
253        if dles % 2 == 0 {
254            return scan::plain(buf, i + 1, buf.len());
255        }
256    }
257    0
258}
259
260// Build one block's bytes plus its trailing ETB.
261fn commit_bytes<F: FnOnce(&mut Builder)>(f: F) -> Vec<u8> {
262    let mut b = Builder::new();
263    f(&mut b);
264    b.etb();
265    b.into_bytes()
266}
267
268/// Appends committed blocks to any [`Write`] sink. Each `record`, `map`,
269/// `header`, `group` or `batch` is one block, written with its ETB in a
270/// single append and flushed. For files prefer [`open_log`], which repairs
271/// a torn tail first and can fsync each commit.
272pub struct StreamWriter<W: Write> {
273    sink: W,
274}
275
276impl<W: Write> StreamWriter<W> {
277    pub fn new(sink: W) -> Self {
278        StreamWriter { sink }
279    }
280
281    /// A new log: SYN and its heading, committed.
282    pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
283        self.batch(|b| {
284            b.syn();
285            for (k, v) in heading {
286                b.heading(k, v);
287            }
288        })
289    }
290
291    /// Append one positional record as a committed block.
292    pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
293        self.batch(|b| {
294            b.record(fields);
295        })
296    }
297
298    /// Append one keyed record as a committed block.
299    pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
300        self.batch(|b| {
301            b.map(pairs);
302        })
303    }
304
305    /// Append a header row as a committed block.
306    pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
307        self.batch(|b| {
308            b.header(names);
309        })
310    }
311
312    /// Append a group line (and header row) as a committed block.
313    pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
314        self.batch(|b| {
315            b.group(name, headers);
316        })
317    }
318
319    /// Several writes under one ETB: atomic as a batch.
320    pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
321        self.sink.write_all(&commit_bytes(f))?;
322        self.sink.flush()
323    }
324
325    pub fn get_ref(&self) -> &W {
326        &self.sink
327    }
328
329    pub fn get_mut(&mut self) -> &mut W {
330        &mut self.sink
331    }
332
333    /// Recover the underlying sink.
334    pub fn into_inner(self) -> W {
335        self.sink
336    }
337}
338
339/// An append-only log file with ETB commits. Each commit is flushed and,
340/// when `sync` is set, fsync'd. Dropping the value closes the file.
341pub struct FileLog {
342    w: StreamWriter<File>,
343    sync: bool,
344}
345
346impl FileLog {
347    /// A new log: SYN and its heading, committed.
348    pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
349        self.w.start(heading)?;
350        self.sync()
351    }
352
353    pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
354        self.w.record(fields)?;
355        self.sync()
356    }
357
358    pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
359        self.w.map(pairs)?;
360        self.sync()
361    }
362
363    pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
364        self.w.header(names)?;
365        self.sync()
366    }
367
368    pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
369        self.w.group(name, headers)?;
370        self.sync()
371    }
372
373    /// Several writes under one ETB: atomic as a batch.
374    pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
375        self.w.batch(f)?;
376        self.sync()
377    }
378
379    fn sync(&mut self) -> io::Result<()> {
380        if self.sync {
381            self.w.get_mut().sync_all()?;
382        }
383        Ok(())
384    }
385}
386
387/// Open an append-only log file, repairing any torn tail first. Each
388/// commit is fsync'd.
389pub fn open_log(path: impl AsRef<Path>) -> io::Result<FileLog> {
390    open_log_with(path, true)
391}
392
393/// Like [`open_log`], with explicit control over per-commit fsync.
394pub fn open_log_with(path: impl AsRef<Path>, sync: bool) -> io::Result<FileLog> {
395    let path = path.as_ref();
396    if path.exists() {
397        repair_log(path)?;
398    }
399    let file = OpenOptions::new().create(true).append(true).open(path)?;
400    Ok(FileLog {
401        w: StreamWriter::new(file),
402        sync,
403    })
404}
405
406/// Truncate an uncommitted tail so the file ends at a commit.
407pub fn repair_log(path: impl AsRef<Path>) -> io::Result<()> {
408    let path = path.as_ref();
409    let bytes = fs::read(path)?;
410    let r = StreamReader::new(&bytes);
411    if r.torn() {
412        let f = OpenOptions::new().write(true).open(path)?;
413        f.set_len(r.committed_end() as u64)?;
414    }
415    Ok(())
416}
417
418/// Read a log file into a byte buffer; wrap it with [`StreamReader::new`].
419pub fn read_log(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
420    fs::read(path)
421}