tickertape 1.0.0

A local, append-only event journal on memory-mapped segment files, with live cross-process readers and replay
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
//! Directory-level helpers shared by the writer, the readers and inspection: naming, listing, opening and
//! validating segment files, and file identity.

use std::fs::{self, File};
use std::io;
use std::os::unix::fs::{FileExt, MetadataExt};
use std::path::{Path, PathBuf};

use crate::error::{CorruptReason, Error, Result};
use crate::format::{self, SegmentHeader};

/// Name of the lock file.
pub(crate) const LOCK_FILE: &str = "writer.lock";
/// Name of the checkpoint marker file.
pub(crate) const CHECKPOINT_FILE: &str = "checkpoint";
/// Name of the notify record (ADRs 0017 and 0021).
pub(crate) const NOTIFY_FILE: &str = "notify";
/// Name of the prepared, not yet published next segment (ADR 0022).
pub(crate) const SPARE_FILE: &str = "next-segment.tmp";
/// Name of the quarantine directory.
pub(crate) const QUARANTINE_DIR: &str = "quarantine";
/// Suffix of temporary segment files.
pub(crate) const TMP_SUFFIX: &str = ".tmp";

/// Path of the segment starting at `base_seq`.
pub(crate) fn segment_path(dir: &Path, base_seq: u64) -> PathBuf {
    dir.join(format::segment_file_name(base_seq))
}

/// Path of the temporary file for the segment starting at `base_seq`.
pub(crate) fn tmp_path(dir: &Path, base_seq: u64) -> PathBuf {
    dir.join(format!(
        "{}{TMP_SUFFIX}",
        format::segment_file_name(base_seq)
    ))
}

/// Lists the segments in `dir` as `(base_seq, path)`, sorted by `base_seq`.
pub(crate) fn list_segments(dir: &Path) -> Result<Vec<(u64, PathBuf)>> {
    let entries = fs::read_dir(dir).map_err(|e| Error::io("list journal directory", dir, e))?;
    let mut out = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|e| Error::io("list journal directory", dir, e))?;
        if let Some(name) = entry.file_name().to_str() {
            if let Some(base) = format::parse_segment_file_name(name) {
                out.push((base, entry.path()));
            }
        }
    }
    out.sort_unstable_by_key(|(base, _)| *base);
    Ok(out)
}

/// The base sequence numbers [`find_bases`] picks out of a listing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Bases {
    /// The oldest segment's base (`None` if the listing has no segments).
    pub(crate) oldest: Option<u64>,
    /// The newest segment's base that is `<= seq` (`None` if there is none).
    pub(crate) floor: Option<u64>,
}

/// Picks the oldest base and the newest base `<= seq` out of one listing of `dir`, as [`list_segments`] would list
/// it, without collecting or sorting the names: time proportional to the directory's entries, memory constant.
pub(crate) fn find_bases(dir: &Path, seq: u64) -> Result<Bases> {
    let entries = fs::read_dir(dir).map_err(|e| Error::io("list journal directory", dir, e))?;
    let mut out = Bases::default();
    for entry in entries {
        let entry = entry.map_err(|e| Error::io("list journal directory", dir, e))?;
        if let Some(base) = entry
            .file_name()
            .to_str()
            .and_then(format::parse_segment_file_name)
        {
            out.oldest = Some(out.oldest.map_or(base, |o| o.min(base)));
            if base <= seq {
                out.floor = Some(out.floor.map_or(base, |f| f.max(base)));
            }
        }
    }
    Ok(out)
}

/// Lists stale temporary segment files (`*.tape.tmp`) in `dir`.
pub(crate) fn list_tmp_files(dir: &Path) -> Result<Vec<PathBuf>> {
    let entries = fs::read_dir(dir).map_err(|e| Error::io("list journal directory", dir, e))?;
    let mut out = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|e| Error::io("list journal directory", dir, e))?;
        if let Some(name) = entry.file_name().to_str() {
            if let Some(stem) = name.strip_suffix(TMP_SUFFIX) {
                if format::parse_segment_file_name(stem).is_some() {
                    out.push(entry.path());
                }
            }
        }
    }
    Ok(out)
}

/// Reads and validates a segment's header from an open file: header rules, actual file size, and file name.
pub(crate) fn read_header(file: &File, path: &Path, base_from_name: u64) -> Result<SegmentHeader> {
    let actual = file
        .metadata()
        .map_err(|e| Error::io("stat segment", path, e))?
        .len();
    let mut buf = [0u8; format::SEGMENT_HEADER_LEN];
    if actual < buf.len() as u64 {
        return Err(Error::corrupt(
            path,
            0,
            CorruptReason::SizeMismatch {
                expected: format::SEGMENT_HEADER_LEN as u64,
                actual,
            },
        ));
    }
    file.read_exact_at(&mut buf, 0)
        .map_err(|e| Error::io("read segment header", path, e))?;
    if buf[..8] == format::MAGIC {
        let version = u16::from_le_bytes([buf[8], buf[9]]);
        if version != format::FORMAT_VERSION {
            return Err(Error::UnsupportedVersion {
                path: path.to_path_buf(),
                found: version,
                supported: format::FORMAT_VERSION,
            });
        }
    }
    let header = format::decode_segment_header(&buf).map_err(|r| Error::corrupt(path, 0, r))?;
    if header.segment_size != actual {
        return Err(Error::corrupt(
            path,
            0,
            CorruptReason::SizeMismatch {
                expected: header.segment_size,
                actual,
            },
        ));
    }
    if header.base_seq != base_from_name {
        return Err(Error::corrupt(
            path,
            0,
            CorruptReason::BaseSeqMismatch {
                from_name: base_from_name,
                from_header: header.base_seq,
            },
        ));
    }
    Ok(header)
}

/// A file's identity: (device, inode).
pub(crate) type Identity = (u64, u64);

/// The identity of an open file.
pub(crate) fn file_identity(file: &File, path: &Path) -> Result<Identity> {
    let meta = file
        .metadata()
        .map_err(|e| Error::io("stat segment", path, e))?;
    Ok((meta.dev(), meta.ino()))
}

/// The identity of whatever `path` names now, or `None` if nothing does ("not found").
///
/// Any other failure (`EACCES`, `EIO`, `ENOMEM`, ...) says nothing about whether the file is still in place, so it
/// is returned as an error rather than taken for a removal.
pub(crate) fn path_identity(path: &Path) -> Result<Option<Identity>> {
    match fs::metadata(path) {
        Ok(m) => Ok(Some((m.dev(), m.ino()))),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(Error::io("stat segment", path, e)),
    }
}

/// Opens a directory so that it can be synced.
pub(crate) fn open_dir(dir: &Path) -> Result<File> {
    File::open(dir).map_err(|e| Error::io("open directory", dir, e))
}

/// Syncs a directory's entries.
pub(crate) fn sync_dir(dir: &Path) -> Result<()> {
    let f = open_dir(dir)?;
    crate::mmap::sync_all(&f).map_err(|e| Error::io("sync directory", dir, e))
}

/// Window size for [`scan_open`].
pub(crate) const SCAN_WINDOW: usize = 1 << 20;

/// A [`format::SegmentView`] over a segment file read with `pread` in windows, so that scanning a segment needs memory
/// for one window of at most [`SCAN_WINDOW`] bytes, never the whole file: callers read a larger record in pieces of
/// at most that size ([`format::SegmentView::max_piece`]). An I/O error makes the view return `None`; the
/// error is kept and reported by [`scan_open`].
pub(crate) struct PreadView<'f> {
    file: &'f File,
    len: u64,
    /// Bytes to fetch per `pread` (more if one request is larger).
    window_len: u64,
    /// The bytes at `[window.0, window.0 + window.1.len())`.
    window: std::cell::RefCell<(u64, Vec<u8>)>,
    error: std::cell::RefCell<Option<std::io::Error>>,
}

impl<'f> PreadView<'f> {
    /// A view of `file`, whose length is `len`, fetching `window_len` bytes per `pread`.
    pub(crate) fn new(file: &'f File, len: u64, window_len: usize) -> PreadView<'f> {
        PreadView {
            file,
            len,
            window_len: window_len as u64,
            window: std::cell::RefCell::new((0, Vec::new())),
            error: std::cell::RefCell::new(None),
        }
    }

    /// Forgets the cached window, so that the next access reads the file again.
    pub(crate) fn invalidate(&self) {
        self.window.borrow_mut().1.clear();
    }

    /// The first I/O error a read hit, if any (the view returned `None` for it).
    pub(crate) fn take_error(&self) -> Option<std::io::Error> {
        self.error.borrow_mut().take()
    }

    /// Makes `[offset, offset + len)` (already checked against the file length) available in the window.
    fn fill(&self, offset: u64, len: u64) -> bool {
        let mut window = self.window.borrow_mut();
        let (start, buf) = &mut *window;
        if offset >= *start && offset + len <= *start + buf.len() as u64 {
            return true;
        }
        // Every caller reads in pieces of at most `max_piece`: the window never grows past it, whatever length a
        // damaged slot claims (validation streams longer bodies, `format::read_slot`).
        debug_assert!(len <= SCAN_WINDOW as u64, "pread window of {len} bytes");
        let want = len.max(self.window_len).min(self.len - offset);
        buf.resize(want as usize, 0);
        match self.file.read_exact_at(buf, offset) {
            Ok(()) => {
                *start = offset;
                true
            }
            Err(e) => {
                buf.clear();
                self.error.borrow_mut().get_or_insert(e);
                false
            }
        }
    }
}

impl format::SegmentView for PreadView<'_> {
    fn len(&self) -> u64 {
        self.len
    }

    fn commit_word(&self, offset: u64) -> Option<u32> {
        if offset % format::RECORD_ALIGN as u64 != 0 {
            return None;
        }
        self.with_bytes(offset, format::COMMIT_WORD_LEN as u64, |b| {
            u32::from_le_bytes([b[0], b[1], b[2], b[3]])
        })
    }

    fn with_bytes<R>(&self, offset: u64, len: u64, f: impl FnOnce(&[u8]) -> R) -> Option<R> {
        if offset.checked_add(len)? > self.len || !self.fill(offset, len) {
            return None;
        }
        let window = self.window.borrow();
        let at = (offset - window.0) as usize;
        Some(f(&window.1[at..at + len as usize]))
    }

    fn max_piece(&self) -> u64 {
        SCAN_WINDOW as u64
    }
}

/// [`scan_open`] of the segment file at `path` (used by this module's tests).
#[cfg(test)]
pub(crate) fn scan_file(path: &Path, base: u64) -> Result<format::ScanResult> {
    let file = File::open(path).map_err(|e| Error::io("open segment", path, e))?;
    scan_open(&file, path, base)
}

/// Scans an open segment file from its first record slot, expecting `base` there, reading it with `pread` in bounded
/// windows (the file is never mapped, so other processes can't affect memory safety); `path` names it in errors.
pub(crate) fn scan_open(file: &File, path: &Path, base: u64) -> Result<format::ScanResult> {
    scan_open_from(file, path, format::SEGMENT_HEADER_LEN as u64, base)
}

/// [`scan_open`] from `offset`, expecting `seq` there.
pub(crate) fn scan_open_from(
    file: &File,
    path: &Path,
    offset: u64,
    seq: u64,
) -> Result<format::ScanResult> {
    with_pread_view(file, path, |view| format::scan_segment(view, offset, seq))
}

/// The commit word at `offset` of an open segment file, read with a fresh 4-byte `pread` (0 if it lies outside the
/// file or is misaligned).
pub(crate) fn commit_word_open(file: &File, path: &Path, offset: u64) -> Result<u32> {
    let len = file
        .metadata()
        .map_err(|e| Error::io("stat segment", path, e))?
        .len();
    let word_len = format::COMMIT_WORD_LEN as u64;
    if offset % format::RECORD_ALIGN as u64 != 0
        || offset.checked_add(word_len).is_none_or(|end| end > len)
    {
        return Ok(0);
    }
    let mut word = [0; format::COMMIT_WORD_LEN];
    file.read_exact_at(&mut word, offset)
        .map_err(|e| Error::io("read segment", path, e))?;
    Ok(u32::from_le_bytes(word))
}

/// [`format::find_history_after_empty`] on an open segment file, read with `pread` in bounded windows.
pub(crate) fn history_after_empty_open(
    file: &File,
    path: &Path,
    offset: u64,
    expected_seq: u64,
) -> Result<Option<format::LaterHistory>> {
    with_pread_view(file, path, |view| {
        format::find_history_after_empty(view, offset, expected_seq)
    })
}

fn with_pread_view<R>(file: &File, path: &Path, f: impl FnOnce(&PreadView<'_>) -> R) -> Result<R> {
    let len = file
        .metadata()
        .map_err(|e| Error::io("stat segment", path, e))?
        .len();
    let view = PreadView::new(file, len, SCAN_WINDOW);
    let result = f(&view);
    if let Some(e) = view.take_error() {
        return Err(Error::io("read segment", path, e));
    }
    Ok(result)
}

#[cfg(test)]
mod scan_tests {
    use super::*;
    use crate::{NewRecord, Writer, WriterConfig};

    #[test]
    fn find_bases_agrees_with_the_sorted_listing() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(find_bases(dir.path(), 5).unwrap(), Bases::default());
        // Names in no particular order, and files that are not segments: a temporary segment, the marker, the
        // prepared next segment, a name that only looks like one.
        let bases = [40u64, 7, 1000, 0, 123_456_789, 41];
        for base in bases {
            fs::write(segment_path(dir.path(), base), b"").unwrap();
        }
        for other in [
            tmp_path(dir.path(), 3),
            dir.path().join(CHECKPOINT_FILE),
            dir.path().join(SPARE_FILE),
            dir.path().join("00000000000000000002.tape.bak"),
        ] {
            fs::write(other, b"").unwrap();
        }
        let listed: Vec<u64> = list_segments(dir.path())
            .unwrap()
            .into_iter()
            .map(|(b, _)| b)
            .collect();
        assert_eq!(listed, [0, 7, 40, 41, 1000, 123_456_789]);
        for seq in [
            0,
            1,
            6,
            7,
            8,
            40,
            41,
            999,
            1000,
            1001,
            123_456_789,
            u64::MAX,
        ] {
            let expected = Bases {
                oldest: listed.first().copied(),
                floor: listed.iter().rev().find(|b| **b <= seq).copied(),
            };
            assert_eq!(find_bases(dir.path(), seq).unwrap(), expected, "seq {seq}");
        }
        fs::remove_file(segment_path(dir.path(), 0)).unwrap();
        assert_eq!(
            find_bases(dir.path(), 3).unwrap(),
            Bases {
                oldest: Some(7),
                floor: None
            }
        );
    }

    #[test]
    fn windowed_scan_matches_an_in_memory_scan() {
        let dir = tempfile::tempdir().unwrap();
        let mut w =
            Writer::open(dir.path(), WriterConfig::default().segment_size(4 << 20)).unwrap();
        // 1,000-byte payloads straddle the 1 MiB window boundaries; enough records to seal the first segment.
        let payload = vec![7u8; 1000];
        for _ in 0..5000 {
            w.append(&NewRecord {
                schema_id: 1,
                venue_ts_ns: 0,
                local_ts_ns: 0,
                payload: &payload,
            })
            .unwrap();
        }
        drop(w);
        for (base, path) in list_segments(dir.path()).unwrap() {
            let image = fs::read(&path).unwrap();
            let expected =
                format::scan_segment(&image[..], format::SEGMENT_HEADER_LEN as u64, base);
            assert_eq!(scan_file(&path, base).unwrap(), expected, "segment {base}");
        }
    }

    #[test]
    #[cfg_attr(miri, ignore = "writes megabytes")]
    fn records_longer_than_the_window_are_read_in_pieces() {
        // Review round 2, item 2: the window never grows past `SCAN_WINDOW` (asserted in `PreadView::fill`), for a
        // valid record of 3 MiB, the same record with a bad checksum, and the search after an empty commit word.
        let dir = tempfile::tempdir().unwrap();
        let mut w =
            Writer::open(dir.path(), WriterConfig::default().segment_size(4 << 20)).unwrap();
        for payload in [vec![1u8; 100], vec![7u8; 3 << 20], vec![2u8; 100]] {
            w.append(&NewRecord {
                schema_id: 1,
                venue_ts_ns: 0,
                local_ts_ns: 0,
                payload: &payload,
            })
            .unwrap();
        }
        drop(w);
        let (base, path) = list_segments(dir.path()).unwrap().pop().unwrap();
        let first = format::SEGMENT_HEADER_LEN as u64;
        let image = fs::read(&path).unwrap();
        let expected = format::scan_segment(&image[..], first, base);
        assert_eq!(expected.records, 3);
        assert_eq!(scan_file(&path, base).unwrap(), expected);
        let file = fs::OpenOptions::new().write(true).open(&path).unwrap();
        file.write_all_at(&[0; 4], first).unwrap();
        let open = File::open(&path).unwrap();
        assert!(matches!(
            history_after_empty_open(&open, &path, first, base).unwrap(),
            Some(format::LaterHistory::Record { seq: 1, .. })
        ));
        file.write_all_at(&[0xee], first + 200 + (1 << 20)).unwrap();
        file.write_all_at(&image[first as usize..first as usize + 4], first)
            .unwrap();
        let scan = scan_file(&path, base).unwrap();
        assert_eq!(scan.records, 1);
        assert_eq!(
            scan.end,
            format::ScanEnd::Invalid(CorruptReason::BadChecksum)
        );
        assert_eq!(commit_word_open(&open, &path, first).unwrap(), 100 + 40);
        assert_eq!(commit_word_open(&open, &path, first + 4).unwrap(), 0);
        assert_eq!(commit_word_open(&open, &path, 4 << 20).unwrap(), 0);
    }
}