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. A
4//! committed block that is not well-formed, cut by its ETB or holding any
5//! other error, is damaged: nothing in it is delivered, and by default the
6//! reader delivers the records before it and then fails with
7//! [`Error::DamagedBlock`] naming the offset to resume at; a reader made
8//! with [`StreamReader::continuing`] reads on past the block. The tail
9//! after the last commit is torn unless it holds only layout, notes or EOT.
10//! A SYN inside the stream tears the uncommitted bytes before it: they are
11//! no block and deliver nothing ([`StreamReader::torn_regions`]); the new
12//! document's blocks are read as usual.
13//!
14//! ```no_run
15//! let mut log = c0::open_log("events.c0")?;        // repairs a torn tail first
16//! log.start(&[("shape", "stream")])?;
17//! log.record(&["create", "a1b2", "1718208000"])?;
18//! let bytes = c0::read_log("events.c0")?;
19//! let r = c0::StreamReader::new(&bytes);
20//! assert!(!r.torn());
21//! # Ok::<(), std::io::Error>(())
22//! ```
23
24use crate::*;
25use std::borrow::Cow;
26use std::collections::HashMap;
27use std::fs::{self, File, OpenOptions};
28use std::io::{self, Write};
29use std::path::Path;
30
31/// Scans a buffer for commits and exposes the committed region, block by
32/// block, and its records. Zero-copy: accessors return slices into the
33/// original buffer.
34pub struct StreamReader<'a> {
35    buf: &'a [u8],
36    committed_end: usize,
37    blocks: Vec<(usize, usize)>,
38    damaged: Vec<usize>,
39    // Uncommitted bytes torn by a mid-stream SYN, [start, end): skipped
40    // like damaged blocks. Layout alone before a SYN is not a tear.
41    torn_regions: Vec<(usize, usize)>,
42    torn: bool,
43    continue_past_damage: bool,
44    // The committed region parsed with damaged blocks skipped; an error
45    // only when one lies outside every block.
46    container: Result<Container<'a>>,
47}
48
49impl<'a> StreamReader<'a> {
50    /// A reader that stops at the first damaged block.
51    pub fn new(buf: &'a [u8]) -> Self {
52        Self::with_options(buf, false)
53    }
54
55    /// A reader that skips damaged blocks and reads on.
56    pub fn continuing(buf: &'a [u8]) -> Self {
57        Self::with_options(buf, true)
58    }
59
60    fn with_options(buf: &'a [u8], continue_past_damage: bool) -> Self {
61        let mut r = StreamReader {
62            buf,
63            committed_end: 0,
64            blocks: Vec::new(),
65            damaged: Vec::new(),
66            torn_regions: Vec::new(),
67            torn: false,
68            continue_past_damage,
69            container: Err(Error::other("unparsed")),
70        };
71        r.scan();
72        r.container = r.parse_committed();
73        r
74    }
75
76    pub fn buf(&self) -> &'a [u8] {
77        self.buf
78    }
79
80    /// Offset just past the last ETB and its payload.
81    pub fn committed_end(&self) -> usize {
82        self.committed_end
83    }
84
85    /// The committed region of the buffer.
86    pub fn committed(&self) -> &'a [u8] {
87        &self.buf[..self.committed_end]
88    }
89
90    /// Everything after the last commit.
91    pub fn tail(&self) -> &'a [u8] {
92        &self.buf[self.committed_end..]
93    }
94
95    /// Whether data trails the last commit (layout, notes and EOT alone do
96    /// not count).
97    pub fn torn(&self) -> bool {
98        self.torn
99    }
100
101    /// `[start, end)` of every region torn by a SYN inside the stream: the
102    /// uncommitted bytes between a commit (or the start) and the SYN that
103    /// began the next document. They belong to no block and deliver
104    /// nothing. Layout alone before a SYN is not a tear. The torn tail
105    /// after the last commit is [`StreamReader::torn`], not listed here.
106    pub fn torn_regions(&self) -> &[(usize, usize)] {
107        &self.torn_regions
108    }
109
110    /// Whether the reader goes on past a damaged block.
111    pub fn continue_past_damage(&self) -> bool {
112        self.continue_past_damage
113    }
114
115    pub fn block_count(&self) -> usize {
116        self.blocks.len()
117    }
118
119    /// Committed block `i`: the bytes from the previous commit to this
120    /// block's ETB (marker and payload excluded).
121    pub fn block(&self, i: usize) -> &'a [u8] {
122        let (s, e) = self.blocks[i];
123        &self.buf[s..e]
124    }
125
126    /// `[start, end)` of every committed block.
127    pub fn block_ranges(&self) -> &[(usize, usize)] {
128        &self.blocks
129    }
130
131    pub fn blocks(&self) -> impl Iterator<Item = &'a [u8]> + '_ {
132        (0..self.blocks.len()).map(move |i| self.block(i))
133    }
134
135    /// Offset after a block's ETB and payload: the start of the next block.
136    pub fn block_end(&self, i: usize) -> usize {
137        self.blocks
138            .get(i + 1)
139            .map_or(self.committed_end, |&(s, _)| s)
140    }
141
142    /// Indexes of committed blocks that are not well-formed.
143    pub fn damaged(&self) -> &[usize] {
144        &self.damaged
145    }
146
147    pub fn is_damaged(&self, i: usize) -> bool {
148        self.damaged.contains(&i)
149    }
150
151    /// The committed region with damaged blocks removed: borrowed when no
152    /// block is damaged, otherwise the sound blocks concatenated.
153    pub fn undamaged(&self) -> Cow<'a, [u8]> {
154        if self.damaged.is_empty() {
155            return Cow::Borrowed(self.committed());
156        }
157        let mut out = Vec::new();
158        for (i, &(s, e)) in self.blocks.iter().enumerate() {
159            if !self.damaged.contains(&i) {
160                out.extend_from_slice(&self.buf[s..e]);
161            }
162        }
163        Cow::Owned(out)
164    }
165
166    /// The committed region as documents, damaged blocks left out. Fails
167    /// with [`Error::DamagedBlock`] when a block is damaged, unless the
168    /// reader continues past damage.
169    pub fn container(&self) -> Result<&Container<'a>> {
170        self.check_damage()?;
171        self.container.as_ref().map_err(Clone::clone)
172    }
173
174    /// The first document of the committed region.
175    pub fn document(&self) -> Result<&Document<'a>> {
176        self.container()?
177            .first()
178            .ok_or_else(|| Error::other("the committed region holds no document"))
179    }
180
181    /// Every committed record in order, up to the first damaged block; then
182    /// [`Error::DamagedBlock`], unless continuing, in which case every
183    /// record of every sound block.
184    pub fn each_record<F: FnMut(&Record<'a>)>(&self, mut f: F) -> Result<()> {
185        let c = self.container.as_ref().map_err(Clone::clone)?;
186        let limit = if self.continue_past_damage {
187            usize::MAX
188        } else {
189            self.damaged
190                .first()
191                .map_or(usize::MAX, |&d| self.blocks[d].0)
192        };
193        for doc in c.documents() {
194            for g in doc.body().groups() {
195                for r in g.records() {
196                    if r.offset() >= limit {
197                        self.check_damage()?;
198                    }
199                    f(r);
200                }
201            }
202        }
203        self.check_damage()
204    }
205
206    /// Logical values of every committed record (headings and header rows
207    /// excluded); see [`StreamReader::each_record`].
208    pub fn records(&self) -> Result<Vec<Vec<Vec<u8>>>> {
209        let mut out = Vec::new();
210        let mut err = None;
211        self.each_record(|r| match r.values() {
212            Ok(vs) => out.push(vs.into_iter().map(|v| v.into_owned()).collect()),
213            Err(e) => err = Some(e),
214        })?;
215        match err {
216            Some(e) => Err(e),
217            None => Ok(out),
218        }
219    }
220
221    fn check_damage(&self) -> Result<()> {
222        if self.continue_past_damage {
223            return Ok(());
224        }
225        match self.damaged.first() {
226            Some(&d) => Err(Error::DamagedBlock {
227                index: d,
228                resume_offset: self.block_end(d),
229            }),
230            None => Ok(()),
231        }
232    }
233
234    // Parse the committed region, torn regions skipped. Any error inside a
235    // committed block marks that block damaged; the region is then parsed
236    // again with the block skipped, so what follows is read in the context
237    // before it.
238    fn parse_committed(&mut self) -> Result<Container<'a>> {
239        let mut skip: HashMap<usize, usize> = self.torn_regions.iter().copied().collect();
240        let container = loop {
241            let mut parser = Parser::with_skip(self.buf, skip.clone());
242            match Container::parse(self.buf, self.committed_end, &mut parser) {
243                Ok(c) => break c,
244                Err(e) => {
245                    let Some(pos) = e.position() else {
246                        return Err(e);
247                    };
248                    let Some(i) = self.block_at(pos) else {
249                        return Err(e);
250                    };
251                    if skip.contains_key(&self.blocks[i].0) {
252                        return Err(e);
253                    }
254                    self.damaged.push(i);
255                    skip.insert(self.blocks[i].0, self.block_end(i));
256                }
257            }
258        };
259        self.damaged.sort_unstable();
260        Ok(container)
261    }
262
263    // The block holding byte `pos` of the committed region.
264    fn block_at(&self, pos: usize) -> Option<usize> {
265        self.blocks.iter().rposition(|&(s, _)| s <= pos)
266    }
267
268    fn scan(&mut self) {
269        let buf = self.buf;
270        let len = buf.len();
271        let mut pos = 0;
272        let mut block_start = 0;
273        let mut in_text = false;
274        while pos < len {
275            let b = buf[pos];
276            if in_text {
277                if b == DLE {
278                    pos += 2;
279                    continue;
280                } else if b == ETX {
281                    in_text = false;
282                } else if b == ETB {
283                    self.blocks.push((block_start, pos));
284                    pos = self.payload_end(pos + 1);
285                    block_start = pos;
286                    in_text = false;
287                    continue;
288                } else if b == SYN || b == EOT || b == EM {
289                    // framing cuts the text
290                    in_text = false;
291                    if b == SYN {
292                        self.tear(block_start, pos);
293                        block_start = pos;
294                    }
295                }
296                pos += 1;
297            } else {
298                if b == STX {
299                    in_text = true;
300                } else if b == ETB {
301                    self.blocks.push((block_start, pos));
302                    pos = self.payload_end(pos + 1);
303                    block_start = pos;
304                    continue;
305                } else if b == SYN && pos > 0 {
306                    // tears the uncommitted bytes before it; a new document begins
307                    self.tear(block_start, pos);
308                    block_start = pos;
309                }
310                pos += 1;
311            }
312        }
313        self.torn = self.torn_tail();
314    }
315
316    // A SYN at `end` tears the uncommitted bytes from `start`: a torn
317    // region unless it holds layout alone.
318    fn tear(&mut self, start: usize, end: usize) {
319        if scan::layout(self.buf, start, end) < end {
320            self.torn_regions.push((start, end));
321        }
322    }
323
324    // After an ETB: skip its payload and return committed_end (which
325    // excludes layout after the payload).
326    fn payload_end(&mut self, pos: usize) -> usize {
327        let buf = self.buf;
328        let len = buf.len();
329        let mut p = scan::layout(buf, pos, len);
330        if p < len && buf[p] >= 0x20 {
331            p = scan::plain(buf, p, len);
332            // trailing spaces of the payload are layout
333            while p > pos && buf[p - 1] == SP {
334                p -= 1;
335            }
336        } else {
337            p = pos; // no payload: layout after ETB belongs to the next block
338        }
339        self.committed_end = p;
340        p
341    }
342
343    // Is the tail more than layout, notes and EOT?
344    fn torn_tail(&self) -> bool {
345        let buf = self.buf;
346        let len = buf.len();
347        let mut pos = self.committed_end;
348        loop {
349            pos = scan::layout(buf, pos, len);
350            if pos >= len {
351                return false;
352            }
353            let b = buf[pos];
354            if b == EOT {
355                pos += 1;
356            } else if b == EM {
357                return false; // the raw region is not data of the log
358            } else if b == BEL {
359                let p2 = scan::layout(buf, pos + 1, len);
360                if p2 < len && buf[p2] < 0x20 && buf[p2] != STX {
361                    return true; // a dead element is data
362                }
363                match scan::comment(buf, pos, len) {
364                    Ok(p) => pos = p,
365                    Err(_) => return true,
366                }
367            } else {
368                return true;
369            }
370        }
371    }
372}
373
374/// Position just past the last commit, found by scanning backward
375/// (treating an ETB behind an odd run of DLEs as escaped). A shortcut for
376/// well-formed input; the forward scan of [`StreamReader`] is authoritative.
377pub fn last_commit_end(buf: &[u8]) -> usize {
378    let mut i = buf.len();
379    while i > 0 {
380        i -= 1;
381        if buf[i] != ETB {
382            continue;
383        }
384        let dles = buf[..i].iter().rev().take_while(|&&b| b == DLE).count();
385        if dles % 2 == 0 {
386            return scan::plain(buf, i + 1, buf.len());
387        }
388    }
389    0
390}
391
392// Build one block's bytes plus its trailing ETB.
393fn commit_bytes<F: FnOnce(&mut Builder)>(f: F) -> Vec<u8> {
394    let mut b = Builder::new();
395    f(&mut b);
396    b.etb();
397    b.into_bytes()
398}
399
400/// Appends committed blocks to any [`Write`] sink. Each `record`, `map`,
401/// `header`, `group` or `batch` is one block, written with its ETB in a
402/// single append and flushed. For files prefer [`open_log`], which repairs
403/// a torn tail first and can fsync each commit.
404pub struct StreamWriter<W: Write> {
405    sink: W,
406}
407
408impl<W: Write> StreamWriter<W> {
409    pub fn new(sink: W) -> Self {
410        StreamWriter { sink }
411    }
412
413    /// A new log: SYN and its heading, committed.
414    pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
415        self.batch(|b| {
416            b.syn();
417            for (k, v) in heading {
418                b.heading(k, v);
419            }
420        })
421    }
422
423    /// Append one positional record as a committed block.
424    pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
425        self.batch(|b| {
426            b.record(fields);
427        })
428    }
429
430    /// Append one keyed record as a committed block.
431    pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
432        self.batch(|b| {
433            b.map(pairs);
434        })
435    }
436
437    /// Append a header row as a committed block.
438    pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
439        self.batch(|b| {
440            b.header(names);
441        })
442    }
443
444    /// Append a group line (and header row) as a committed block.
445    pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
446        self.batch(|b| {
447            b.group(name, headers);
448        })
449    }
450
451    /// Several writes under one ETB: atomic as a batch.
452    pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
453        self.sink.write_all(&commit_bytes(f))?;
454        self.sink.flush()
455    }
456
457    pub fn get_ref(&self) -> &W {
458        &self.sink
459    }
460
461    pub fn get_mut(&mut self) -> &mut W {
462        &mut self.sink
463    }
464
465    /// Recover the underlying sink.
466    pub fn into_inner(self) -> W {
467        self.sink
468    }
469}
470
471/// An append-only log file with ETB commits. Each commit is flushed and,
472/// when `sync` is set, fsync'd. Dropping the value closes the file.
473pub struct FileLog {
474    w: StreamWriter<File>,
475    sync: bool,
476}
477
478impl FileLog {
479    /// A new log: SYN and its heading, committed.
480    pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
481        self.w.start(heading)?;
482        self.sync()
483    }
484
485    pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
486        self.w.record(fields)?;
487        self.sync()
488    }
489
490    pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
491        self.w.map(pairs)?;
492        self.sync()
493    }
494
495    pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
496        self.w.header(names)?;
497        self.sync()
498    }
499
500    pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
501        self.w.group(name, headers)?;
502        self.sync()
503    }
504
505    /// Several writes under one ETB: atomic as a batch.
506    pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
507        self.w.batch(f)?;
508        self.sync()
509    }
510
511    fn sync(&mut self) -> io::Result<()> {
512        if self.sync {
513            self.w.get_mut().sync_all()?;
514        }
515        Ok(())
516    }
517}
518
519/// Open an append-only log file, repairing any torn tail first. Each
520/// commit is fsync'd.
521pub fn open_log(path: impl AsRef<Path>) -> io::Result<FileLog> {
522    open_log_with(path, true)
523}
524
525/// Like [`open_log`], with explicit control over per-commit fsync.
526pub fn open_log_with(path: impl AsRef<Path>, sync: bool) -> io::Result<FileLog> {
527    let path = path.as_ref();
528    if path.exists() {
529        repair_log(path)?;
530    }
531    let file = OpenOptions::new().create(true).append(true).open(path)?;
532    Ok(FileLog {
533        w: StreamWriter::new(file),
534        sync,
535    })
536}
537
538/// Truncate an uncommitted tail so the file ends at a commit.
539pub fn repair_log(path: impl AsRef<Path>) -> io::Result<()> {
540    let path = path.as_ref();
541    let bytes = fs::read(path)?;
542    let r = StreamReader::new(&bytes);
543    if r.torn() {
544        let f = OpenOptions::new().write(true).open(path)?;
545        f.set_len(r.committed_end() as u64)?;
546    }
547    Ok(())
548}
549
550/// Read a log file into a byte buffer; wrap it with [`StreamReader::new`].
551pub fn read_log(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
552    fs::read(path)
553}