interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / src / board / journal.rs

2244 lines · 91852 bytes Raw Blame History
1//! The journal: writer lock, `BOARD_ID`, append with fsync before ACK, the torn-tail rule,
2//! bounded storage, explicit compaction and the read-only consistency check.
3//!
4//! **Commit order of one post (group commit).** The `fcntl` writer lock on `<root>/.lock`
5//! is held only for short in-memory and page-cache steps, never across an fsync, so
6//! concurrent writers share their disk flushes:
7//!
8//! 1. *lock*: reconcile, append the frame to `journal.log` at the next id, *unlock*;
9//! 2. `fdatasync(journal.log)`. This covers the writer's frame and every frame appended
10//! before it;
11//! 3. *lock*: commit every pending frame up to its own id, in id order: append the id to
12//! `topics/<topic>.idx` and to `inbox/<tag>.idx` of every addressee, then write the
13//! 64-byte entry at `(id - base) * 64` of `journal.idx`. That entry is the commit point:
14//! readers only see ids up to the last valid entry. A frame is committed only after it
15//! is durable, so `journal.idx` never names a frame a power loss could take. *unlock*;
16//! 4. `fdatasync` `journal.idx` and the touched index files together (one parallel group),
17//! return the receipt (the ACK), then send best-effort wake datagrams.
18//!
19//! The ACK therefore follows two fsync rounds, and a frame another writer committed for this
20//! one is synced again by this one before its ACK.
21//!
22//! **Pending frames and the torn-tail rule.** Bytes in `journal.log` after the last frame
23//! named by `journal.idx` belong to posts that were not acknowledged: in flight between steps
24//! 1 and 3, or from a writer that died there. A complete frame that verifies (length,
25//! CRC-32C, JSON body, next id, this mission) is pending: the next commit adopts it with its
26//! id (so a retry with the same idempotency key finds it). Anything else is the torn tail of
27//! a writer that died inside step 1 and is truncated, reported as
28//! [`Recovery::torn_tail_at`]. More than one frame's worth of unverifiable bytes is not a
29//! torn tail: it is refused as [`BoardError::Corrupt`], never guessed past. Neither is an
30//! unverifiable frame that `journal.idx` names as committed (directly, through a partly
31//! written or undecodable final entry, or because the table is being rebuilt), nor a
32//! journal that ends on a frame boundary before such a frame: that is damage to an
33//! acknowledged event, refused however short it is. A table this journal cannot place
34//! (another generation) still proves its last committed id, which every generation a
35//! compaction can leave holds: its last decodable entry's id plus one per partly written or
36//! undecodable slot after it. An empty or missing journal, or one whose frames end short
37//! of that id, is refused too, never rebuilt into an empty table that would reuse the ids.
38//! A reboot rebuild carries the same evidence (a partly written final entry counts) into
39//! its scan from offset 0. Recovery changes `journal.idx` only after the tail scan
40//! succeeded, so a refused recovery leaves both files byte for byte as they were and every
41//! retry refuses the same way. Readers never truncate; they stop at the commit point.
42//!
43//! **Directory syncs.** A new or renamed root entry (the journal, `journal.idx`, a
44//! subdirectory, `BOARD_ID`, the compacted generation) is durable only once the root
45//! directory is synced; every such sync that fails fails the operation (no receipt, no
46//! ACK), and `dirsync.pending` (`DIRSYNC_PENDING`) makes the next writer sync the root
47//! again before it acknowledges anything. The marker's lifecycle (mark, change, sync,
48//! clear) runs under the root-marker lock `<root>/dirsync.lock` ([`RootLock`], innermost
49//! in the lock order `.lock`, then `cursors/<tag>.lock`, then `dirsync.lock`), so an
50//! earlier successful sync never clears the marker of a later change whose sync failed.
51//!
52//! **After a reboot.** `journal.idx` and the id indexes are derived from the journal. A
53//! process crash keeps the page cache, so they stay exact; a power loss can lose unsynced
54//! writes to them in any order. `<root>/boot` records the kernel boot id of the last writer
55//! that verified them; the first writer (or reader, through [`Board::recover`]) of a new boot
56//! rebuilds all of them from the journal before anything else
57//! ([`Recovery::rebuilt_after_boot`]). The old table is kept until the new one is written,
58//! and what it proves committed is never cut as a torn tail.
59
60use super::frame::{
61 self, corrupt, key_hash, Entry, ENTRY_BYTES, FRAME_HEADER, H_IDEM, H_THREAD, H_TOPIC, ID_BYTES,
62 MAX_FRAME_BYTES,
63};
64use super::{io_err, Board, BoardError, BoardId, Event, Me, Post, BOARD_ID_FILE, BOARD_ID_FORMAT};
65use crate::record::{refusal_for, RecordRefusal};
66use std::fs::{self, File, OpenOptions};
67use std::io::Write;
68use std::os::unix::fs::{FileExt, OpenOptionsExt};
69use std::os::unix::io::AsRawFd;
70use std::path::{Path, PathBuf};
71use std::sync::{Mutex, MutexGuard};
72
73pub(crate) const JOURNAL: &str = "journal.log";
74pub(crate) const TABLE: &str = "journal.idx";
75/// Boot id of the last writer that verified the derived files (see "After a reboot").
76pub(crate) const BOOT: &str = "boot";
77pub(crate) const SUBDIRS: [&str; 6] = ["topics", "inbox", "agents", "subs", "cursors", "wake"];
78
79/// Unverifiable bytes after the commit point larger than this are corruption, not a torn
80/// tail (a torn tail is at most one partly written frame).
81const MAX_TORN: u64 = FRAME_HEADER + MAX_FRAME_BYTES as u64;
82
83/// Exit status of a board process killed by an injected fault.
84pub const FAULT_EXIT: i32 = 86;
85
86/// Test-only fault injection (`SYNAPSE_COORD_FAULT=<point>`, the coordination store's
87/// variable): the process dies on the spot. It exits instead of aborting so a crash test
88/// does not wait on the system core-dump handler (about 1 s per abort here); the disk state
89/// is the same, because every board write is a direct syscall with no user-space buffer.
90fn fault(point: &str) {
91 if fault_active(point) {
92 std::process::exit(FAULT_EXIT);
93 }
94}
95
96pub(crate) fn fault_active(point: &str) -> bool {
97 std::env::var("SYNAPSE_COORD_FAULT").as_deref() == Ok(point)
98}
99
100/// Test-only barrier (`SYNAPSE_COORD_FAULT=<point>` plus `SYNAPSE_COORD_PAUSE_DIR=<dir>`):
101/// the first time this process reaches `point` it creates `<dir>/ready` and waits (at most
102/// 60 s) until `<dir>/go` exists, so an interleaving test can run another process inside
103/// exactly this window. Unset in normal use.
104fn pause(point: &str) {
105 static PAUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
106 if !fault_active(point) {
107 return;
108 }
109 let Some(dir) = std::env::var_os("SYNAPSE_COORD_PAUSE_DIR").map(PathBuf::from) else {
110 return;
111 };
112 if PAUSED.swap(true, std::sync::atomic::Ordering::SeqCst) {
113 return;
114 }
115 let _ = fs::write(dir.join("ready"), b"");
116 // Test-only barrier: a failed lookup of `go` just keeps waiting (bounded), nothing else.
117 for _ in 0..6000 {
118 if fs::symlink_metadata(dir.join("go")).is_ok() {
119 return;
120 }
121 std::thread::sleep(std::time::Duration::from_millis(10));
122 }
123}
124
125/// This kernel boot (`/proc/sys/kernel/random/boot_id`). `SYNAPSE_BOARD_BOOT_ID` overrides
126/// it so tests can simulate a reboot. None where neither is available: reboots are then not
127/// detected and the derived files are trusted as they are.
128fn boot_id() -> Option<String> {
129 let raw = match std::env::var("SYNAPSE_BOARD_BOOT_ID") {
130 Ok(v) => v,
131 Err(_) => fs::read_to_string("/proc/sys/kernel/random/boot_id").ok()?,
132 };
133 let s = raw.trim();
134 let ok =
135 !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-');
136 ok.then(|| s.to_string())
137}
138
139/// The boot id stored in `<root>/boot`, or None when missing or unreadable as one.
140fn stored_boot_id(root: &Path) -> Result<Option<String>, BoardError> {
141 let p = root.join(BOOT);
142 let Some(f) = open_ro(&p)? else {
143 return Ok(None);
144 };
145 let mut b = [0u8; 65];
146 let n = f.read_at(&mut b, 0).map_err(io_err(&p))?;
147 Ok(std::str::from_utf8(&b[..n.min(64)])
148 .ok()
149 .map(|s| s.trim().to_string()))
150}
151
152/// A board with no journal yet has nothing derived to verify: record this boot so its first
153/// writer does not report a rebuild. Called by `Board::init` under the lock, also on an
154/// existing board. Only a journal that is certainly absent (`NotFound`) is fresh: any other
155/// lookup failure is returned with `boot` untouched, because recording this boot over an
156/// existing board would tell its next reader and writer that the derived indexes were
157/// already verified, so the reboot rebuild would be skipped (round 14 of the #928 review).
158pub(crate) fn mark_boot_if_fresh(root: &Path) -> Result<(), BoardError> {
159 if !present(&root.join(JOURNAL))? {
160 if let Some(b) = boot_id() {
161 crate::durable_write(root, &root.join(BOOT), format!("{b}\n").as_bytes())?;
162 }
163 }
164 Ok(())
165}
166
167/// True when this boot has not yet verified the board's derived files.
168pub(crate) fn needs_boot_rebuild(root: &Path) -> Result<bool, BoardError> {
169 Ok(match boot_id() {
170 Some(b) => stored_boot_id(root)?.as_deref() != Some(b.as_str()),
171 None => false,
172 })
173}
174
175fn refused(path: &Path, reason: RecordRefusal) -> BoardError {
176 BoardError::Refused {
177 path: path.to_path_buf(),
178 reason,
179 }
180}
181
182/// Open an existing board file read-only without following a link or blocking on a FIFO
183/// (the [`crate::record`] rules): `lstat` first, a non-regular name is never opened.
184pub(crate) fn open_ro(path: &Path) -> Result<Option<File>, BoardError> {
185 match fs::symlink_metadata(path) {
186 Ok(m) => {
187 if let Some(r) = refusal_for(&m.file_type()) {
188 return Err(refused(path, r));
189 }
190 }
191 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
192 Err(e) => return Err(io_err(path)(e)),
193 }
194 let f = match OpenOptions::new()
195 .read(true)
196 .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
197 .open(path)
198 {
199 Ok(f) => f,
200 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
201 Err(e) if e.raw_os_error() == Some(libc::ELOOP) => {
202 return Err(refused(path, RecordRefusal::Symlink))
203 }
204 Err(e) => return Err(io_err(path)(e)),
205 };
206 let m = f.metadata().map_err(io_err(path))?;
207 if let Some(r) = refusal_for(&m.file_type()) {
208 return Err(refused(path, r));
209 }
210 Ok(Some(f))
211}
212
213/// Open (creating if absent) a board file for writing, with the same refusals. Returns
214/// whether it was created (its directory then needs an fsync).
215pub(crate) fn open_rw(root: &Path, path: &Path) -> Result<(File, bool), BoardError> {
216 crate::record::check_real_parents(root, path)?;
217 let created = match fs::symlink_metadata(path) {
218 Ok(m) => {
219 if let Some(r) = refusal_for(&m.file_type()) {
220 return Err(refused(path, r));
221 }
222 false
223 }
224 Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
225 Err(e) => return Err(io_err(path)(e)),
226 };
227 let f = OpenOptions::new()
228 .read(true)
229 .write(true)
230 .create(true)
231 .truncate(false)
232 .mode(0o644)
233 .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
234 .open(path)
235 .map_err(|e| match e.raw_os_error() {
236 Some(libc::ELOOP) => refused(path, RecordRefusal::Symlink),
237 Some(libc::ENXIO) => refused(path, RecordRefusal::NotRegular("fifo")),
238 Some(libc::EISDIR) => refused(path, RecordRefusal::NotRegular("directory")),
239 _ => io_err(path)(e),
240 })?;
241 let m = f.metadata().map_err(io_err(path))?;
242 if let Some(r) = refusal_for(&m.file_type()) {
243 return Err(refused(path, r));
244 }
245 Ok((f, created))
246}
247
248/// A missing `journal.log` under a `journal.idx` that holds any bytes (every entry, even a
249/// partly written one, was written only after the frame it names was durable) is a lost
250/// journal, not a fresh board: refused here, before `open_rw` would create an empty journal,
251/// so both files stay as they are and every retry refuses the same way. Compaction replaces
252/// the journal by `rename(2)`, so no legitimate state lacks it while the table names events.
253/// An empty journal under such a table is refused by the tail scan (`Committed`).
254///
255/// Both lookups are strict (only `NotFound` is absence): a journal or table that cannot be
256/// looked up is an error here, never "present" or "empty", so a transient lookup failure
257/// cannot let `open_rw` create an empty journal under a table that names committed events.
258fn refuse_lost_journal(jp: &Path, ip: &Path) -> Result<(), BoardError> {
259 if present(jp)? {
260 // Present: `open_rw` vets it.
261 return Ok(());
262 }
263 match crate::record::lstat(ip) {
264 Ok(m) if m.file_type().is_file() && m.len() > 0 => Err(corrupt(
265 jp,
266 0,
267 format!(
268 "journal.log is missing but journal.idx ({} bytes) names committed events; refusing",
269 m.len()
270 ),
271 )),
272 // An empty table names nothing; anything but a regular file is refused by `open_rw`.
273 Ok(_) => Ok(()),
274 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
275 Err(e) => Err(io_err(ip)(e)),
276 }
277}
278
279/// Make `<root>/<name>` a real directory (a symlink or file planted there is refused), then
280/// reconcile the root (`reconcile_root`): every durable mutator reaches its subdirectory
281/// through here, so an existing directory whose creation sync failed earlier (or any other
282/// root change left in `dirsync.pending`) is flushed before the caller reports success.
283pub(crate) fn ensure_dir(root: &Path, name: &str) -> Result<PathBuf, BoardError> {
284 let d = make_dir(root, name)?;
285 reconcile_root(root)?;
286 Ok(d)
287}
288
289/// `ensure_dir` without the reconciliation, for callers that reconcile the root
290/// themselves (`Writer::open`, after it created everything it needs) or keep nothing
291/// durable there (the wake sockets).
292pub(crate) fn make_dir(root: &Path, name: &str) -> Result<PathBuf, BoardError> {
293 let d = root.join(name);
294 match fs::symlink_metadata(&d) {
295 Ok(m) if m.file_type().is_dir() => return Ok(d),
296 Ok(m) => {
297 return Err(refused(
298 &d,
299 refusal_for(&m.file_type()).unwrap_or(RecordRefusal::NotDirectory),
300 ))
301 }
302 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
303 Err(e) => return Err(io_err(&d)(e)),
304 }
305 // A new subdirectory is a root entry: marked before the change and synced after it,
306 // under the root-marker lock (`publish_root`), so a failed sync is retried by the next
307 // writer and no other operation's sync can clear the mark in between.
308 publish_root(root, || match fs::create_dir(&d) {
309 Ok(()) => Ok(()),
310 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
311 Err(e) => Err(io_err(&d)(e)),
312 })?;
313 match fs::symlink_metadata(&d) {
314 Ok(m) if m.file_type().is_dir() => Ok(d),
315 _ => Err(refused(&d, RecordRefusal::NotDirectory)),
316 }
317}
318
319/// Flush a board directory (see `crate::fsync_dir`: every failure is an error).
320pub(crate) fn fsync_dir(d: &Path) -> Result<(), BoardError> {
321 Ok(crate::fsync_dir(d)?)
322}
323
324/// `<root>/dirsync.pending`: an entry of the board root (the journal, `journal.idx`, a
325/// subdirectory, `BOARD_ID`, a compacted generation) was created or renamed but the
326/// directory sync that makes it durable has not succeeded yet. A later writer that sees it
327/// syncs the root again before it acknowledges anything (see `Writer::open`), and so does
328/// every other durable mutator (`reconcile_root`: registration, cursors, subscriptions,
329/// init, unregister), including a retry that finds its subdirectory already there; only a
330/// successful sync removes it. The marker is set before every such change and again after
331/// a failed sync; it needs no durability of its own, because what a reboot shows is already
332/// on disk, and a stale marker costs one extra directory sync.
333///
334/// Its whole lifecycle runs under [`RootLock`]: mark, change and sync of one change
335/// (`publish_root`), and check, sync and removal of a reconciliation. A removal therefore
336/// follows a sync that began after every marked change had finished, so an earlier
337/// successful sync can never clear the marker of a later change whose own sync failed.
338pub(crate) const DIRSYNC_PENDING: &str = "dirsync.pending";
339
340/// `<root>/dirsync.lock`, the lock file of [`RootLock`].
341pub(crate) const DIRSYNC_LOCK: &str = "dirsync.lock";
342
343static ROOT_MARKER: Mutex<()> = Mutex::new(());
344
345/// The root-marker lock: serialises the `dirsync.pending` lifecycle across threads and
346/// processes (see [`DIRSYNC_PENDING`]).
347///
348/// **Lock order:** [`BoardLock`] (`<root>/.lock`), then the tag lock
349/// (`cursors/<tag>.lock`), then `RootLock`. `RootLock` is a leaf: while it is held only the
350/// marker, the root entries of the one change it covers and the root fsync are touched, and
351/// no other lock is taken, so it closes no cycle with the others. It is taken with or
352/// without the outer locks (a reader's `tag_lock` reconciles before its tag lock, compaction
353/// publishes under `BoardLock`), and never held while waiting for anything but the disk.
354pub(crate) struct RootLock(#[allow(dead_code)] FileLock);
355
356impl RootLock {
357 fn acquire(root: &Path) -> Result<RootLock, BoardError> {
358 Ok(RootLock(fcntl_lock(
359 root,
360 &root.join(DIRSYNC_LOCK),
361 &ROOT_MARKER,
362 )?))
363 }
364}
365
366/// Look up a durability marker (`dirsync.pending`, `cursors/<tag>.unsynced`). Test-only
367/// fault injection: `SYNAPSE_COORD_FAULT=marker-stat-eio:<file name>` (or
368/// `stat-eio:<file name>`, see [`crate::record::lstat`]) makes the lookup of that one
369/// marker fail with `EIO` (unset in normal use).
370pub(crate) fn marker_stat(p: &Path) -> std::io::Result<()> {
371 crate::record::lstat(p).map(drop)
372}
373
374/// Whether a durability marker is set. Only `NotFound` means nothing is owed: any other
375/// lookup failure is returned, because a marker that cannot be observed may still record
376/// an unsynced publication (round 13 of the #928 review).
377pub(crate) fn marker_present(p: &Path) -> Result<bool, BoardError> {
378 present(p)
379}
380
381/// Whether anything has the name `p` (never following a link). Only `NotFound` is absence;
382/// any other lookup failure is returned as [`BoardError::Io`], never read as "absent".
383pub(crate) fn present(p: &Path) -> Result<bool, BoardError> {
384 match marker_stat(p) {
385 Ok(()) => Ok(true),
386 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
387 Err(e) => Err(BoardError::Io {
388 path: p.to_path_buf(),
389 source: e,
390 }),
391 }
392}
393
394fn root_sync_pending(root: &Path) -> Result<bool, BoardError> {
395 marker_present(&root.join(DIRSYNC_PENDING))
396}
397
398/// Flush a root change an earlier operation left unsynced (`dirsync.pending`) before this
399/// one reports success; a failure (of the sync or of the marker lookup itself) is returned
400/// and the marker kept. A stat when nothing is pending: a change that marks after that stat is not this operation's to flush (its own
401/// `publish_root` syncs it), and the marker is checked again under the lock.
402pub(crate) fn reconcile_root(root: &Path) -> Result<(), BoardError> {
403 if !root_sync_pending(root)? {
404 return Ok(());
405 }
406 let held = RootLock::acquire(root)?;
407 if root_sync_pending(root)? {
408 sync_root_locked(root, &held)?;
409 }
410 Ok(())
411}
412
413/// Make one root change durable: under [`RootLock`], set `dirsync.pending`, apply
414/// `change`, sync the root. A failed change or sync returns the error with the marker
415/// kept, so the next writer flushes the root before it acknowledges anything.
416fn publish_root<T>(
417 root: &Path,
418 change: impl FnOnce() -> Result<T, BoardError>,
419) -> Result<T, BoardError> {
420 let held = RootLock::acquire(root)?;
421 mark_root_unsynced(root)?;
422 let v = change()?;
423 sync_root_locked(root, &held)?;
424 Ok(v)
425}
426
427/// Set `dirsync.pending` (a no-op when anything already has that name).
428fn mark_root_unsynced(root: &Path) -> Result<(), BoardError> {
429 create_marker(&root.join(DIRSYNC_PENDING))
430}
431
432/// Create the empty marker file `p` unless something already has that name (never
433/// following a link). Markers need no durability of their own (see `DIRSYNC_PENDING`).
434///
435/// A lookup that fails is not read as "already set" or "absent" with any effect: it only
436/// means the no-follow create below is attempted, and that create's failure is returned.
437pub(crate) fn create_marker(p: &Path) -> Result<(), BoardError> {
438 if fs::symlink_metadata(p).is_ok() {
439 return Ok(());
440 }
441 OpenOptions::new()
442 .write(true)
443 .create(true)
444 .truncate(false)
445 .mode(0o644)
446 .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
447 .open(p)
448 .map(drop)
449 .map_err(io_err(p))
450}
451
452/// Sync the board root under [`RootLock`] (see `sync_root_locked`).
453pub(crate) fn sync_root(root: &Path) -> Result<(), BoardError> {
454 let held = RootLock::acquire(root)?;
455 sync_root_locked(root, &held)
456}
457
458/// Sync the board root; the caller holds [`RootLock`]. On success drop `dirsync.pending`:
459/// every change marked before this sync was made under the same lock, so it finished
460/// before the sync began and is now durable. On failure leave the marker (best effort: the
461/// sync error is what is returned) so the next writer retries the flush before it
462/// acknowledges.
463fn sync_root_locked(root: &Path, _held: &RootLock) -> Result<(), BoardError> {
464 match fsync_dir(root) {
465 Ok(()) => {
466 pause("pause-after-root-sync");
467 // Best effort: a leftover marker only costs the next writer one more sync.
468 let _ = fs::remove_file(root.join(DIRSYNC_PENDING));
469 Ok(())
470 }
471 Err(e) => {
472 let _ = mark_root_unsynced(root);
473 Err(e)
474 }
475 }
476}
477
478/// A process-wide mutex plus an `fcntl` write lock on one lock file, the pattern of the
479/// coordination store's transaction lock (POSIX record locks belong to the process, so
480/// threads are serialised by the mutex and processes by `fcntl`).
481pub(crate) struct FileLock {
482 _file: File,
483 _guard: MutexGuard<'static, ()>,
484}
485
486pub(crate) fn fcntl_lock(
487 root: &Path,
488 lp: &Path,
489 mutex: &'static Mutex<()>,
490) -> Result<FileLock, BoardError> {
491 let guard = mutex.lock().unwrap_or_else(|e| e.into_inner());
492 let (f, _) = open_rw(root, lp)?;
493 // SAFETY: a zeroed flock is a valid "whole file from offset 0" request.
494 let mut fl: libc::flock = unsafe { std::mem::zeroed() };
495 fl.l_type = libc::F_WRLCK as _;
496 fl.l_whence = libc::SEEK_SET as _;
497 loop {
498 // SAFETY: f is open for the duration of the call; fl is a valid flock.
499 let rc = unsafe { libc::fcntl(f.as_raw_fd(), libc::F_SETLKW, &fl) };
500 if rc == 0 {
501 break;
502 }
503 let e = std::io::Error::last_os_error();
504 if e.raw_os_error() != Some(libc::EINTR) {
505 return Err(io_err(lp)(e));
506 }
507 }
508 Ok(FileLock {
509 _file: f,
510 _guard: guard,
511 })
512}
513
514static WRITER: Mutex<()> = Mutex::new(());
515
516/// The board writer lock on `<root>/.lock`.
517pub(crate) struct BoardLock(#[allow(dead_code)] FileLock);
518impl BoardLock {
519 pub fn acquire(root: &Path) -> Result<BoardLock, BoardError> {
520 Ok(BoardLock(fcntl_lock(root, &root.join(".lock"), &WRITER)?))
521 }
522}
523
524/// A coordination store (`STORE_ID`, `dirs/`) is never a board root: the two would share
525/// a `.lock` and an operator could mistake one for the other. Each discriminator is
526/// present, certainly absent (`NotFound`) or not observable. Any one present refuses the
527/// root as [`BoardError::NotABoard`]; otherwise the first lookup error is returned, so a
528/// root that cannot be inspected is never adopted (no `BOARD_ID` is created in it; round
529/// 14 of the #928 review). Only when both are certainly absent is it a board root.
530pub(crate) fn refuse_coord_root(root: &Path) -> Result<(), BoardError> {
531 let mut unobservable = None;
532 for n in [crate::STORE_ID_FILE, "dirs"] {
533 match present(&root.join(n)) {
534 Ok(true) => {
535 return Err(BoardError::NotABoard {
536 root: root.to_path_buf(),
537 reason: format!("it has {n}, so it is a Crumb coordination store"),
538 })
539 }
540 Ok(false) => {}
541 Err(e) => {
542 unobservable.get_or_insert(e);
543 }
544 }
545 }
546 unobservable.map_or(Ok(()), Err)
547}
548
549fn encode_board_id(id: &BoardId) -> Vec<u8> {
550 format!("{BOARD_ID_FORMAT} {}\n", id.to_hex()).into_bytes()
551}
552
553fn decode_board_id(b: &[u8]) -> Result<BoardId, String> {
554 let s = std::str::from_utf8(b).map_err(|_| "not UTF-8".to_string())?;
555 let line = s
556 .strip_suffix('\n')
557 .ok_or_else(|| "no trailing newline (torn or foreign file)".to_string())?;
558 let (tag, hex) = line
559 .split_once(' ')
560 .ok_or_else(|| "expected `<format> <id>`".to_string())?;
561 if tag != BOARD_ID_FORMAT {
562 return Err(format!("unsupported format {tag:?}"));
563 }
564 BoardId::parse_hex(hex).ok_or_else(|| format!("bad id {hex:?}"))
565}
566
567/// Read `<root>/BOARD_ID` (bounded, never following a link). `Ok(None)` when absent.
568pub(crate) fn read_board_id(root: &Path) -> Result<Option<BoardId>, BoardError> {
569 let p = root.join(BOARD_ID_FILE);
570 match crate::record::read_bounded(&p, crate::MAX_MARKER_BYTES)? {
571 Some(b) => decode_board_id(&b)
572 .map(Some)
573 .map_err(|reason| BoardError::BoardIdUnreadable { path: p, reason }),
574 None => Ok(None),
575 }
576}
577
578/// Create the marker if absent (caller holds the writer lock); published with `link(2)` so
579/// it is never replaced, exactly like `STORE_ID`.
580pub(crate) fn ensure_board_id_locked(root: &Path) -> Result<BoardId, BoardError> {
581 if let Some(id) = read_board_id(root)? {
582 return Ok(id);
583 }
584 let p = root.join(BOARD_ID_FILE);
585 let tmp = root.join(format!("{BOARD_ID_FILE}.tmp{}", std::process::id()));
586 let id = BoardId::random().map_err(io_err(Path::new("/dev/urandom")))?;
587 publish_root(root, || {
588 {
589 let mut f = crate::record::create_temp(&tmp)?;
590 f.write_all(&encode_board_id(&id)).map_err(io_err(&tmp))?;
591 f.sync_all().map_err(io_err(&tmp))?;
592 }
593 let linked = fs::hard_link(&tmp, &p);
594 let _ = fs::remove_file(&tmp);
595 match linked {
596 Ok(()) => Ok(()),
597 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
598 Err(e) => Err(io_err(&p)(e)),
599 }
600 })?;
601 read_board_id(root)?.ok_or(BoardError::BoardIdMissing {
602 root: root.to_path_buf(),
603 })
604}
605
606/// Why a frame at an offset did not verify.
607enum FrameBad {
608 Short,
609 Length(u32),
610 Checksum,
611}
612
613impl FrameBad {
614 fn reason(&self) -> String {
615 match self {
616 FrameBad::Short => "frame runs past the end of the file".into(),
617 FrameBad::Length(l) => format!("frame length {l} is over {MAX_FRAME_BYTES}"),
618 FrameBad::Checksum => "frame checksum does not verify".into(),
619 }
620 }
621}
622
623/// A frame as read: `Ok((len, crc, body))` or why it does not verify.
624type FrameRead = Result<(u32, u32, Vec<u8>), FrameBad>;
625
626/// Read and verify the frame at `off` of a journal of length `flen`: `(len, crc, body)`.
627fn read_frame(f: &File, path: &Path, off: u64, flen: u64) -> Result<FrameRead, BoardError> {
628 if off + FRAME_HEADER > flen {
629 return Ok(Err(FrameBad::Short));
630 }
631 let mut h = [0u8; FRAME_HEADER as usize];
632 f.read_exact_at(&mut h, off).map_err(io_err(path))?;
633 let len = u32::from_le_bytes([h[0], h[1], h[2], h[3]]);
634 let crc = u32::from_le_bytes([h[4], h[5], h[6], h[7]]);
635 if len > MAX_FRAME_BYTES {
636 return Ok(Err(FrameBad::Length(len)));
637 }
638 if off + FRAME_HEADER + len as u64 > flen {
639 return Ok(Err(FrameBad::Short));
640 }
641 let mut body = vec![0u8; len as usize];
642 f.read_exact_at(&mut body, off + FRAME_HEADER)
643 .map_err(io_err(path))?;
644 if frame::crc32c(&body) != crc {
645 return Ok(Err(FrameBad::Checksum));
646 }
647 Ok(Ok((len, crc, body)))
648}
649
650fn entry_for(ev: &Event, offset: u64, len: u32, crc: u32) -> Entry {
651 Entry {
652 id: ev.id,
653 offset,
654 len,
655 crc,
656 topic_h: key_hash(H_TOPIC, ev.topic.as_bytes()),
657 thread_h: key_hash(H_THREAD, ev.thread.as_bytes()),
658 idem_h: ev
659 .idem
660 .as_deref()
661 .map(|k| key_hash(H_IDEM, k.as_bytes()))
662 .unwrap_or(0),
663 }
664}
665
666pub(crate) fn topic_file(root: &Path, topic: &str) -> PathBuf {
667 root.join("topics")
668 .join(format!("{:016x}.idx", key_hash(H_TOPIC, topic.as_bytes())))
669}
670
671pub(crate) fn inbox_file(root: &Path, tag: &str) -> PathBuf {
672 root.join("inbox").join(format!("{tag}.idx"))
673}
674
675/// A read-only view of the committed board, taken without the lock.
676pub(crate) struct Snapshot {
677 idx: Option<File>,
678 journal: Option<File>,
679 idx_path: PathBuf,
680 j_path: PathBuf,
681 mission: BoardId,
682 /// Oldest kept id (0 when empty).
683 pub base: u64,
684 /// Last committed id (0 when empty).
685 pub last: u64,
686 /// Offset of a partly written or unverifiable final table entry (a post in flight).
687 pub torn_entry: Option<u64>,
688 jlen: u64,
689}
690
691impl Snapshot {
692 pub fn take(board: &Board) -> Result<Snapshot, BoardError> {
693 let root = board.root();
694 let idx_path = root.join(TABLE);
695 let j_path = root.join(JOURNAL);
696 let idx = open_ro(&idx_path)?;
697 let journal = open_ro(&j_path)?;
698 let mut s = Snapshot {
699 idx: None,
700 journal: None,
701 idx_path,
702 j_path,
703 mission: board.id(),
704 base: 0,
705 last: 0,
706 torn_entry: None,
707 jlen: 0,
708 };
709 let lim = board.limits();
710 if let Some(j) = &journal {
711 s.jlen = j.metadata().map_err(io_err(&s.j_path))?.len();
712 if s.jlen > lim.max_journal_bytes + MAX_TORN {
713 return Err(refused(
714 &s.j_path,
715 RecordRefusal::TooLarge {
716 limit: lim.max_journal_bytes + MAX_TORN,
717 },
718 ));
719 }
720 }
721 let Some(idx) = idx else {
722 s.journal = journal;
723 return Ok(s);
724 };
725 let ilen = idx.metadata().map_err(io_err(&s.idx_path))?.len();
726 let cap = (lim.max_events + 1) * ENTRY_BYTES;
727 if ilen > cap {
728 return Err(refused(&s.idx_path, RecordRefusal::TooLarge { limit: cap }));
729 }
730 let mut n = ilen / ENTRY_BYTES;
731 if ilen % ENTRY_BYTES != 0 {
732 s.torn_entry = Some(n * ENTRY_BYTES);
733 }
734 if n == 0 {
735 s.journal = journal;
736 return Ok(s);
737 }
738 if journal.is_none() {
739 return Err(corrupt(
740 &s.j_path,
741 0,
742 "journal.idx names events but journal.log is missing",
743 ));
744 }
745 let read = |i: u64| -> Result<Option<Entry>, BoardError> {
746 let mut b = [0u8; ENTRY_BYTES as usize];
747 idx.read_exact_at(&mut b, i * ENTRY_BYTES)
748 .map_err(io_err(&s.idx_path))?;
749 Ok(Entry::decode(&b))
750 };
751 let mut last_e = read(n - 1)?;
752 if last_e.is_none() {
753 s.torn_entry = Some((n - 1) * ENTRY_BYTES);
754 n -= 1;
755 if n == 0 {
756 s.journal = journal;
757 return Ok(s);
758 }
759 last_e = read(n - 1)?;
760 }
761 let le =
762 last_e.ok_or_else(|| corrupt(&s.idx_path, (n - 1) * ENTRY_BYTES, "entry checksum"))?;
763 let e0 = read(0)?.ok_or_else(|| corrupt(&s.idx_path, 0, "entry checksum"))?;
764 if e0.id == 0 || le.id != e0.id + n - 1 {
765 return Err(corrupt(&s.idx_path, 0, "table ids are not contiguous"));
766 }
767 s.base = e0.id;
768 s.last = le.id;
769 s.idx = Some(idx);
770 s.journal = journal;
771 Ok(s)
772 }
773
774 pub fn entry(&self, id: u64) -> Result<Entry, BoardError> {
775 let idx = self.idx.as_ref().ok_or(BoardError::IndexMismatch { id })?;
776 if id < self.base || id > self.last {
777 return Err(BoardError::IndexMismatch { id });
778 }
779 let off = (id - self.base) * ENTRY_BYTES;
780 let mut b = [0u8; ENTRY_BYTES as usize];
781 idx.read_exact_at(&mut b, off)
782 .map_err(io_err(&self.idx_path))?;
783 let e = Entry::decode(&b).ok_or_else(|| corrupt(&self.idx_path, off, "entry checksum"))?;
784 if e.id != id {
785 return Err(corrupt(&self.idx_path, off, "entry id out of sequence"));
786 }
787 Ok(e)
788 }
789
790 /// Read and verify the event an entry names.
791 pub fn event(&self, e: &Entry) -> Result<Event, BoardError> {
792 let j = self
793 .journal
794 .as_ref()
795 .ok_or(BoardError::IndexMismatch { id: e.id })?;
796 match read_frame(j, &self.j_path, e.offset, self.jlen)? {
797 Ok((len, crc, body)) => {
798 if len != e.len || crc != e.crc {
799 return Err(BoardError::IndexMismatch { id: e.id });
800 }
801 let ev = Event::from_body(&body).map_err(|r| corrupt(&self.j_path, e.offset, r))?;
802 if ev.id != e.id {
803 return Err(BoardError::IndexMismatch { id: e.id });
804 }
805 if ev.mission != self.mission {
806 return Err(BoardError::ForeignMission {
807 id: ev.id,
808 found: ev.mission,
809 });
810 }
811 Ok(ev)
812 }
813 Err(FrameBad::Short) if e.frame_end() > self.jlen => {
814 // The table names bytes the journal does not have: a swapped-in compaction
815 // seen half-way, or a truncated journal (persisting means corruption).
816 Err(BoardError::IndexMismatch { id: e.id })
817 }
818 Err(b) => Err(corrupt(&self.j_path, e.offset, b.reason())),
819 }
820 }
821
822 pub fn get(&self, id: u64) -> Result<Event, BoardError> {
823 let e = self.entry(id)?;
824 self.event(&e)
825 }
826
827 /// Visit entries `from..=last` in order until `f` returns false.
828 pub fn scan(
829 &self,
830 from: u64,
831 mut f: impl FnMut(&Entry) -> Result<bool, BoardError>,
832 ) -> Result<(), BoardError> {
833 let Some(idx) = &self.idx else { return Ok(()) };
834 let mut id = from.max(self.base);
835 const CHUNK: u64 = 256;
836 while id <= self.last {
837 let n = CHUNK.min(self.last - id + 1);
838 let mut buf = vec![0u8; (n * ENTRY_BYTES) as usize];
839 let off = (id - self.base) * ENTRY_BYTES;
840 idx.read_exact_at(&mut buf, off)
841 .map_err(io_err(&self.idx_path))?;
842 for (k, c) in buf
843 .as_chunks::<{ ENTRY_BYTES as usize }>()
844 .0
845 .iter()
846 .enumerate()
847 {
848 let at = off + k as u64 * ENTRY_BYTES;
849 let e = Entry::decode(c)
850 .ok_or_else(|| corrupt(&self.idx_path, at, "entry checksum"))?;
851 if e.id != id + k as u64 {
852 return Err(corrupt(&self.idx_path, at, "entry id out of sequence"));
853 }
854 if !f(&e)? {
855 return Ok(());
856 }
857 }
858 id += n;
859 }
860 Ok(())
861 }
862}
863
864/// Ids in an index file `(after, last]`, at most `limit`, plus whether more were left.
865pub(crate) fn read_ids_after(
866 path: &Path,
867 after: u64,
868 last: u64,
869 limit: usize,
870 max_events: u64,
871) -> Result<(Vec<u64>, bool), BoardError> {
872 let Some(f) = open_ro(path)? else {
873 return Ok((Vec::new(), false));
874 };
875 let len = f.metadata().map_err(io_err(path))?.len();
876 let cap = (max_events + 1) * ID_BYTES * 4;
877 if len > cap {
878 return Err(refused(path, RecordRefusal::TooLarge { limit: cap }));
879 }
880 let n = len / ID_BYTES;
881 let at = |i: u64| -> Result<u64, BoardError> {
882 let mut b = [0u8; 8];
883 f.read_exact_at(&mut b, i * ID_BYTES)
884 .map_err(io_err(path))?;
885 Ok(u64::from_le_bytes(b))
886 };
887 // First position whose id is > after (ids are strictly increasing; checked below).
888 let (mut lo, mut hi) = (0u64, n);
889 while lo < hi {
890 let mid = lo + (hi - lo) / 2;
891 if at(mid)? <= after {
892 lo = mid + 1;
893 } else {
894 hi = mid;
895 }
896 }
897 let mut out = Vec::new();
898 let mut prev = if lo > 0 { at(lo - 1)? } else { 0 };
899 let mut i = lo;
900 while i < n {
901 let id = at(i)?;
902 if id <= prev {
903 return Err(corrupt(path, i * ID_BYTES, "index ids are not increasing"));
904 }
905 if id > last {
906 break;
907 }
908 if out.len() == limit {
909 return Ok((out, true));
910 }
911 out.push(id);
912 prev = id;
913 i += 1;
914 }
915 Ok((out, false))
916}
917
918/// Binary search a sorted id list of `n` entries for `id`.
919fn index_contains(path: &Path, f: &File, n: u64, id: u64) -> Result<bool, BoardError> {
920 let (mut lo, mut hi) = (0u64, n);
921 while lo < hi {
922 let mid = lo + (hi - lo) / 2;
923 let mut b = [0u8; 8];
924 f.read_exact_at(&mut b, mid * ID_BYTES)
925 .map_err(io_err(path))?;
926 match u64::from_le_bytes(b).cmp(&id) {
927 std::cmp::Ordering::Equal => return Ok(true),
928 std::cmp::Ordering::Less => lo = mid + 1,
929 std::cmp::Ordering::Greater => hi = mid,
930 }
931 }
932 Ok(false)
933}
934
935/// Append `id` to an id index unless it is already listed. A partly written final entry is
936/// dropped first.
937fn append_id(path: &Path, f: &File, id: u64) -> Result<bool, BoardError> {
938 let mut len = f.metadata().map_err(io_err(path))?.len();
939 if len % ID_BYTES != 0 {
940 len -= len % ID_BYTES;
941 f.set_len(len).map_err(io_err(path))?;
942 }
943 if len >= ID_BYTES {
944 let mut b = [0u8; 8];
945 f.read_exact_at(&mut b, len - ID_BYTES)
946 .map_err(io_err(path))?;
947 let last = u64::from_le_bytes(b);
948 if last == id {
949 return Ok(false);
950 }
951 // Rebuilding journal.idx after a cut compaction re-indexes events the id lists
952 // already hold: an id already present is not appended twice (lists are sorted).
953 if last > id && index_contains(path, f, len / ID_BYTES, id)? {
954 return Ok(false);
955 }
956 if last > id {
957 return Err(corrupt(
958 path,
959 len - ID_BYTES,
960 format!("index already lists {last} > {id}"),
961 ));
962 }
963 }
964 f.write_all_at(&id.to_le_bytes(), len)
965 .map_err(io_err(path))?;
966 Ok(true)
967}
968
969/// The id index files an event is listed in: its topic, then each distinct addressee.
970fn index_paths(root: &Path, topic: &str, to: &[String]) -> Vec<PathBuf> {
971 let mut paths = vec![topic_file(root, topic)];
972 for t in to {
973 let p = inbox_file(root, t);
974 if !paths.contains(&p) {
975 paths.push(p);
976 }
977 }
978 paths
979}
980
981/// Replace an id index with exactly `ids` (tmp + fsync + rename; the caller syncs the dir).
982fn rewrite_ids(p: &Path, ids: &[u64]) -> Result<(), BoardError> {
983 let mut data = Vec::with_capacity(ids.len() * ID_BYTES as usize);
984 for id in ids {
985 data.extend_from_slice(&id.to_le_bytes());
986 }
987 let mut tmp = p.as_os_str().to_owned();
988 tmp.push(format!(".tmp{}", std::process::id()));
989 let tmp = PathBuf::from(tmp);
990 let mut f = crate::record::create_temp(&tmp)?;
991 f.write_all(&data).map_err(io_err(&tmp))?;
992 f.sync_all().map_err(io_err(&tmp))?;
993 fs::rename(&tmp, p).map_err(io_err(p))
994}
995
996/// The `.idx` files of `<root>/<d>` (`topics` or `inbox`), sorted. The listing decides which
997/// derived files a reboot rebuild, a torn-tail cleanup or a trim reaches, so it is complete
998/// or an error: only an absent directory is empty; a directory or an entry that cannot be
999/// read is [`BoardError::Io`], never a shorter list.
1000fn index_files(root: &Path, d: &str) -> Result<Vec<PathBuf>, BoardError> {
1001 let dir = root.join(d);
1002 let rd = match crate::record::list_dir(&dir) {
1003 Ok(rd) => rd,
1004 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1005 Err(e) => return Err(io_err(&dir)(e)),
1006 };
1007 let mut out = Vec::new();
1008 for ent in rd {
1009 let p = ent.map_err(io_err(&dir))?.path();
1010 if p.extension().and_then(|x| x.to_str()) == Some("idx") {
1011 out.push(p);
1012 }
1013 }
1014 out.sort();
1015 Ok(out)
1016}
1017
1018/// `fdatasync` a group of files, in parallel threads (one journal commit can cover them).
1019fn sync_group(files: &[(&Path, &File)]) -> Result<(), BoardError> {
1020 if files.len() <= 1 {
1021 for (p, f) in files {
1022 f.sync_data().map_err(io_err(p))?;
1023 }
1024 return Ok(());
1025 }
1026 std::thread::scope(|s| {
1027 let hs: Vec<_> = files
1028 .iter()
1029 .map(|(p, f)| s.spawn(move || f.sync_data().map_err(io_err(p))))
1030 .collect();
1031 hs.into_iter()
1032 .zip(files.iter())
1033 .map(|(h, (p, _))| match h.join() {
1034 Ok(r) => r,
1035 Err(_) => Err(BoardError::Io {
1036 path: p.to_path_buf(),
1037 source: std::io::Error::other("fsync thread panicked"),
1038 }),
1039 })
1040 .collect::<Result<Vec<()>, BoardError>>()
1041 })?;
1042 Ok(())
1043}
1044
1045/// What the writer reconciled before its own append.
1046#[derive(Clone, Debug, Default, PartialEq, Eq)]
1047pub struct Recovery {
1048 /// A torn (unacknowledged, unverifiable) tail was truncated at this journal offset.
1049 pub torn_tail_at: Option<u64>,
1050 pub torn_bytes: u64,
1051 /// Complete frames after the commit point written by another writer (one in flight, or
1052 /// one that died before its commit) were committed by this one with these ids.
1053 pub adopted: Vec<u64>,
1054 /// A partly written final `journal.idx` entry was dropped.
1055 pub dropped_table_entry: bool,
1056 /// `journal.idx` disagreed with `journal.log` (a compaction cut between its renames)
1057 /// and was rebuilt from the journal.
1058 pub table_rebuilt: bool,
1059 /// First writer of this kernel boot: `journal.idx` and every id index were rebuilt from
1060 /// the journal (a power loss can lose their unsynced writes).
1061 pub rebuilt_after_boot: bool,
1062}
1063
1064impl Recovery {
1065 pub fn is_empty(&self) -> bool {
1066 *self == Recovery::default()
1067 }
1068}
1069
1070/// The receipt of a post: returned only after both fsync rounds, so it is the ACK.
1071#[derive(Clone, Debug, PartialEq, Eq)]
1072pub struct PostReceipt {
1073 pub id: u64,
1074 pub mission: BoardId,
1075 /// True when an earlier event with the same idempotency key and body was returned.
1076 pub dedup: bool,
1077 pub recovery: Recovery,
1078 /// Wake datagrams delivered (best effort).
1079 pub woke: usize,
1080}
1081
1082/// A complete, verifying frame after the commit point (see "Pending frames").
1083struct Pending {
1084 e: Entry,
1085 topic: String,
1086 to: Vec<String>,
1087}
1088
1089/// Index files written by a commit, to be synced (outside the lock) before the ACK.
1090#[derive(Default)]
1091struct Touched {
1092 files: Vec<(PathBuf, File)>,
1093 created: bool,
1094}
1095
1096struct Writer<'a> {
1097 board: &'a Board,
1098 lock: Option<BoardLock>,
1099 j: File,
1100 jp: PathBuf,
1101 idx: File,
1102 ip: PathBuf,
1103 base: u64,
1104 last: u64,
1105 end: u64,
1106 pending: Vec<Pending>,
1107 /// End of the last pending frame (`end` when there is none).
1108 tail_end: u64,
1109 /// Recovery evidence: what `journal.idx` proved committed before recovery touched it.
1110 /// The tail scan must verify every frame it names; one that does not verify, or a
1111 /// journal that ends before it, is damage to a committed event, never a torn tail.
1112 committed: Committed,
1113 rec: Recovery,
1114}
1115
1116/// What `journal.idx` proves is committed beyond the point a tail scan starts from, read
1117/// before recovery changes anything. Every table entry, even a partly written or
1118/// undecodable final one, was written only after the frame it names was durable, so this
1119/// evidence survives a power loss.
1120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1121enum Committed {
1122 /// Nothing: every frame after the scan start may be a pending frame or a torn tail.
1123 Nothing,
1124 /// Every frame starting before byte `floor` is committed, and so are the `more` frames
1125 /// that follow it (named by final table entries that are partly written or do not
1126 /// decode). The scan must reach `floor` and verify `more` frames from there.
1127 Through { floor: u64, more: u64 },
1128 /// The table names committed frames this journal cannot place (another generation, an
1129 /// unreadable first entry): nothing may be cut, and how far they reach in bytes is
1130 /// unknown, so a journal that ends on a frame boundary is accepted only when its frames
1131 /// reach event `through` (the table's last decodable entry plus one per partly written
1132 /// or undecodable slot after it, at least the slot count; see `Writer::unplaced`), and
1133 /// never with no frame at all. Every generation a compaction leaves (a cut between its
1134 /// renames, or a power loss before its root sync) holds that event: it keeps everything
1135 /// up to the last committed id, and `keep_since <= last`. Distinct from a known floor.
1136 Unplaced { through: u64 },
1137}
1138
1139impl<'a> Writer<'a> {
1140 fn open(board: &'a Board) -> Result<Writer<'a>, BoardError> {
1141 let root = board.root();
1142 let lock = BoardLock::acquire(root)?;
1143 board.check_id_locked()?;
1144 for d in SUBDIRS {
1145 // Not `ensure_dir`: the root is reconciled below, once the files exist.
1146 make_dir(root, d)?;
1147 }
1148 let jp = root.join(JOURNAL);
1149 let ip = root.join(TABLE);
1150 refuse_lost_journal(&jp, &ip)?;
1151 // The journal's directory entry must be durable before any ACK. A journal or table
1152 // this open creates is published (marked, created, root synced) under `RootLock`.
1153 // Otherwise the root is synced while the journal is still empty (so a creation whose
1154 // sync failed earlier is retried, whoever created it), or a file appeared after the
1155 // check (created by `open_rw` below), and reconciled while an earlier change left
1156 // `dirsync.pending`. A failure refuses the open: nothing is acknowledged.
1157 // A lookup error only takes the conservative path (publish under `RootLock`, root
1158 // synced); `open_rw` then vets each file and returns its own lookup's error.
1159 let creating = fs::symlink_metadata(&jp).is_err() || fs::symlink_metadata(&ip).is_err();
1160 let open = || -> Result<_, BoardError> { Ok((open_rw(root, &jp)?, open_rw(root, &ip)?)) };
1161 let ((j, jc), (idx, ic)) = if creating {
1162 publish_root(root, open)?
1163 } else {
1164 open()?
1165 };
1166 let empty = j.metadata().map_err(io_err(&jp))?.len() == 0;
1167 // When `creating`, `publish_root` synced the root, covering every earlier marked change.
1168 if !creating {
1169 if jc || ic || empty {
1170 sync_root(root)?;
1171 } else {
1172 reconcile_root(root)?;
1173 }
1174 }
1175 let mut w = Writer {
1176 board,
1177 lock: Some(lock),
1178 j,
1179 jp,
1180 idx,
1181 ip,
1182 base: 0,
1183 last: 0,
1184 end: 0,
1185 pending: Vec::new(),
1186 tail_end: 0,
1187 committed: Committed::Nothing,
1188 rec: Recovery::default(),
1189 };
1190 if needs_boot_rebuild(root)? {
1191 w.rebuild_after_boot()?;
1192 } else {
1193 w.recover()?;
1194 }
1195 Ok(w)
1196 }
1197
1198 /// Release the writer lock; the open files stay usable for syncing.
1199 fn unlock(&mut self) {
1200 self.lock = None;
1201 }
1202
1203 /// The id the next appended frame gets.
1204 fn next_id(&self) -> u64 {
1205 self.pending.last().map_or(self.last, |p| p.e.id) + 1
1206 }
1207
1208 /// Events committed or pending (the count bounded by `max_events`).
1209 fn count(&self) -> u64 {
1210 let first = if self.last == 0 {
1211 self.pending.first().map_or(0, |p| p.e.id)
1212 } else {
1213 self.base
1214 };
1215 if first == 0 {
1216 0
1217 } else {
1218 self.next_id() - first
1219 }
1220 }
1221
1222 fn jlen(&self) -> Result<u64, BoardError> {
1223 Ok(self.j.metadata().map_err(io_err(&self.jp))?.len())
1224 }
1225
1226 fn table_entry(&self, i: u64) -> Result<Option<Entry>, BoardError> {
1227 let mut b = [0u8; ENTRY_BYTES as usize];
1228 self.idx
1229 .read_exact_at(&mut b, i * ENTRY_BYTES)
1230 .map_err(io_err(&self.ip))?;
1231 Ok(Entry::decode(&b))
1232 }
1233
1234 /// True when the frame at `e.offset` is exactly the one `e` names.
1235 fn frame_matches(&self, e: &Entry, jlen: u64) -> Result<bool, BoardError> {
1236 Ok(match read_frame(&self.j, &self.jp, e.offset, jlen)? {
1237 Ok((len, crc, body)) => {
1238 len == e.len && crc == e.crc && Event::from_body(&body).map(|ev| ev.id) == Ok(e.id)
1239 }
1240 Err(_) => false,
1241 })
1242 }
1243
1244 /// Same-boot reconciliation. Nothing in `journal.idx` is changed before the tail scan
1245 /// has succeeded: a refusal leaves the table (and the journal) byte for byte as they
1246 /// were, so the evidence that made this attempt refuse (the table's claim that events
1247 /// are committed) is still there for the next one, which refuses the same way instead
1248 /// of cutting acknowledged events as a torn tail.
1249 fn recover(&mut self) -> Result<(), BoardError> {
1250 let jlen = self.jlen()?;
1251 let ilen = self.idx.metadata().map_err(io_err(&self.ip))?.len();
1252 let slots = ilen.div_ceil(ENTRY_BYTES);
1253 let mut n = ilen / ENTRY_BYTES;
1254 let mut drop_entry = ilen % ENTRY_BYTES != 0;
1255 if n > 0 && self.table_entry(n - 1)?.is_none() {
1256 n -= 1;
1257 drop_entry = true;
1258 }
1259 if n > 0 {
1260 let e0 = self.table_entry(0)?;
1261 let le = self.table_entry(n - 1)?;
1262 match (e0, le) {
1263 (Some(e0), Some(le))
1264 if e0.offset == 0
1265 && e0.id > 0
1266 && le.id == e0.id + n - 1
1267 && self.frame_matches(&e0, jlen)? =>
1268 {
1269 // Same generation. The last committed frame must be intact: acknowledged
1270 // events would be lost by any repair, so a mismatch is refused.
1271 if le.frame_end() > jlen || !self.frame_matches(&le, jlen)? {
1272 return Err(corrupt(
1273 &self.jp,
1274 le.offset,
1275 format!(
1276 "committed event {} does not verify (journal truncated or overwritten); refusing",
1277 le.id
1278 ),
1279 ));
1280 }
1281 self.base = e0.id;
1282 self.last = le.id;
1283 self.end = le.frame_end();
1284 }
1285 _ => {
1286 // The table belongs to another journal generation (a compaction cut
1287 // between its two renames) or is unreadable: rebuild it from the
1288 // journal, which is the truth. The old table claimed committed events,
1289 // so nothing may be cut while rebuilding, the journal must still reach
1290 // the last of them (see `Committed::Unplaced`), and the table is only
1291 // replaced once the whole journal verified.
1292 self.rec.table_rebuilt = true;
1293 self.committed = self.unplaced(n, slots)?;
1294 return self.scan_tail(jlen, Some(0));
1295 }
1296 }
1297 }
1298 if drop_entry {
1299 // A partly written (or undecodable) final entry was the commit of the frame at
1300 // `end`, which was durable before its entry was written: it must verify, never
1301 // be cut, and a journal that ends at `end` lost it.
1302 self.committed = Committed::Through {
1303 floor: self.end,
1304 more: slots - n,
1305 };
1306 return self.scan_tail(jlen, Some(n));
1307 }
1308 self.scan_tail(jlen, None)
1309 }
1310
1311 /// What the current `journal.idx` proves is committed, read without changing it (the
1312 /// reboot scan starts at offset 0). When the table verifiably belongs to this journal
1313 /// (its first entry is the frame at offset 0): every frame up to the end of the one its
1314 /// last decodable entry names, plus one more frame per final slot after it that is
1315 /// partly written or does not decode, exactly like the same-boot `drop_entry` case.
1316 /// A table with only such slots proves that many frames from offset 0. `Unplaced` when
1317 /// it holds decodable entries this journal cannot place, `Nothing` when it is empty.
1318 fn table_evidence(&self, jlen: u64) -> Result<Committed, BoardError> {
1319 let ilen = self.idx.metadata().map_err(io_err(&self.ip))?.len();
1320 let slots = ilen.div_ceil(ENTRY_BYTES);
1321 let mut k = ilen / ENTRY_BYTES;
1322 let le = loop {
1323 if k == 0 {
1324 return Ok(if slots == 0 {
1325 Committed::Nothing
1326 } else {
1327 Committed::Through {
1328 floor: 0,
1329 more: slots,
1330 }
1331 });
1332 }
1333 if let Some(e) = self.table_entry(k - 1)? {
1334 break e;
1335 }
1336 k -= 1;
1337 };
1338 Ok(match self.table_entry(0)? {
1339 Some(e0)
1340 if e0.offset == 0
1341 && e0.id > 0
1342 && le.id == e0.id + k - 1
1343 && self.frame_matches(&e0, jlen)? =>
1344 {
1345 Committed::Through {
1346 floor: le.frame_end(),
1347 more: slots - k,
1348 }
1349 }
1350 _ => self.unplaced(k, slots)?,
1351 })
1352 }
1353
1354 /// `Committed::Unplaced` for a table of `slots` slots this journal cannot place, whose
1355 /// first `full` slots are whole: the lowest id its last committed event can have. Slots
1356 /// hold consecutive ids, and every slot after the last decodable entry (partly written
1357 /// or not decoding) is the commit of one more frame, exactly as `Committed::Through`
1358 /// counts them, so the bound is that entry's id plus the number of slots after it. Ids
1359 /// start at 1, so it is never below `slots` (the whole bound when no entry decodes).
1360 /// This is an id, not a frame count: a valid compaction keeps the ids but removes a
1361 /// prefix of the frames. A bound past the id range cannot be established: refused.
1362 fn unplaced(&self, full: u64, slots: u64) -> Result<Committed, BoardError> {
1363 let mut k = full;
1364 while k > 0 {
1365 if let Some(e) = self.table_entry(k - 1)? {
1366 let Some(through) = e.id.checked_add(slots - k) else {
1367 return Err(corrupt(
1368 &self.ip,
1369 (k - 1) * ENTRY_BYTES,
1370 format!(
1371 "entry for id {} with {} slots after it names an id past the id range; refusing",
1372 e.id,
1373 slots - k
1374 ),
1375 ));
1376 };
1377 return Ok(Committed::Unplaced {
1378 through: through.max(slots),
1379 });
1380 }
1381 k -= 1;
1382 }
1383 Ok(Committed::Unplaced { through: slots })
1384 }
1385
1386 /// Reconcile bytes after the commit point (see the torn-tail rule above). With
1387 /// `table_len`, `journal.idx` is cut to that many entries, but only after the scan
1388 /// succeeded (a refusal changes nothing).
1389 fn scan_tail(&mut self, jlen: u64, table_len: Option<u64>) -> Result<(), BoardError> {
1390 self.pending.clear();
1391 let mut pos = self.end;
1392 let mut expect = if self.last == 0 {
1393 None
1394 } else {
1395 Some(self.last + 1)
1396 };
1397 // Frames verified at or after the evidence floor (see `Committed::Through`).
1398 let (floor, more) = match self.committed {
1399 Committed::Through { floor, more } => (floor, more),
1400 Committed::Nothing | Committed::Unplaced { .. } => (0, 0),
1401 };
1402 let mut beyond = 0u64;
1403 while pos < jlen {
1404 let bad = match read_frame(&self.j, &self.jp, pos, jlen)? {
1405 Ok((len, crc, body)) => match Event::from_body(&body) {
1406 Ok(ev) if expect.is_none_or(|x| x == ev.id) => {
1407 if ev.mission != self.board.id() {
1408 return Err(BoardError::ForeignMission {
1409 id: ev.id,
1410 found: ev.mission,
1411 });
1412 }
1413 let e = entry_for(&ev, pos, len, crc);
1414 expect = Some(ev.id + 1);
1415 if pos >= floor {
1416 beyond += 1;
1417 }
1418 pos = e.frame_end();
1419 self.pending.push(Pending {
1420 e,
1421 topic: ev.topic,
1422 to: ev.to,
1423 });
1424 None
1425 }
1426 Ok(ev) => Some(format!("frame id {} out of sequence", ev.id)),
1427 Err(r) => Some(r),
1428 },
1429 Err(b) => Some(b.reason()),
1430 };
1431 if let Some(reason) = bad {
1432 let torn = jlen - pos;
1433 if torn > MAX_TORN {
1434 return Err(corrupt(
1435 &self.jp,
1436 pos,
1437 format!("{reason}, with {torn} bytes after it (more than one frame): not a torn tail; refusing"),
1438 ));
1439 }
1440 if self.rec.table_rebuilt || matches!(self.committed, Committed::Unplaced { .. }) {
1441 // The old table claimed committed events it cannot place; never cut
1442 // anything while rebuilding it.
1443 return Err(corrupt(
1444 &self.jp,
1445 pos,
1446 format!("{reason} while rebuilding journal.idx; refusing"),
1447 ));
1448 }
1449 if pos < floor || beyond < more {
1450 // journal.idx names a committed frame here: damage, not a torn tail.
1451 return Err(corrupt(
1452 &self.jp,
1453 pos,
1454 format!(
1455 "{reason}, but journal.idx names a committed event at or after this offset; refusing"
1456 ),
1457 ));
1458 }
1459 // Indexes first (see `clean_index_tails`): a failure keeps the torn tail, so
1460 // the retry finds it and cleans again before any id is reused.
1461 self.clean_index_tails()?;
1462 self.j.set_len(pos).map_err(io_err(&self.jp))?;
1463 self.j.sync_data().map_err(io_err(&self.jp))?;
1464 self.rec.torn_tail_at = Some(pos);
1465 self.rec.torn_bytes = torn;
1466 break;
1467 }
1468 }
1469 if pos < floor || beyond < more {
1470 // The journal ends on a frame boundary before a frame journal.idx names as
1471 // committed (it was durable before its entry was written): the event is lost.
1472 // Refused before anything is changed, so a retry refuses the same way.
1473 return Err(corrupt(
1474 &self.jp,
1475 pos,
1476 format!(
1477 "journal ends at {pos}, before the committed events journal.idx names (through offset {floor}, {more} more); refusing"
1478 ),
1479 ));
1480 }
1481 if let Committed::Unplaced { through } = self.committed {
1482 // The table proves committed events this journal cannot place. An empty journal
1483 // (or one whose frames stop short of the table's last committed id) lost them:
1484 // accepting it would truncate the table and hand those ids out again. Refused
1485 // before anything is changed, so a retry refuses the same way.
1486 let reached = self.pending.last().map_or(self.last, |p| p.e.id);
1487 if reached == 0 || reached < through {
1488 return Err(corrupt(
1489 &self.jp,
1490 pos,
1491 format!(
1492 "journal ends at {pos} with its last event at id {reached}, but journal.idx names committed events through id {through}; refusing"
1493 ),
1494 ));
1495 }
1496 }
1497 self.tail_end = pos;
1498 if let Some(k) = table_len {
1499 self.idx
1500 .set_len(k * ENTRY_BYTES)
1501 .map_err(io_err(&self.ip))?;
1502 if !self.rec.table_rebuilt {
1503 self.rec.dropped_table_entry = true;
1504 }
1505 }
1506 if self.rec.table_rebuilt {
1507 self.commit_all()?;
1508 }
1509 Ok(())
1510 }
1511
1512 fn write_entry(&mut self, e: &Entry) -> Result<(), BoardError> {
1513 let off = (e.id - if self.last == 0 { e.id } else { self.base }) * ENTRY_BYTES;
1514 self.idx
1515 .write_all_at(&e.encode(), off)
1516 .map_err(io_err(&self.ip))
1517 }
1518
1519 /// Commit the pending frames with ids up to `upto`, in id order: index ids first, then
1520 /// the table entry. The caller made them durable first (its journal fdatasync covered
1521 /// every frame appended before its own). Nothing is synced here; the caller syncs the
1522 /// returned files and `journal.idx` before it acknowledges.
1523 fn commit_through(&mut self, upto: u64, own: Option<u64>) -> Result<Touched, BoardError> {
1524 let n = self.pending.iter().take_while(|p| p.e.id <= upto).count();
1525 let batch: Vec<Pending> = self.pending.drain(..n).collect();
1526 let mut t = Touched::default();
1527 for p in &batch {
1528 for (path, f, c) in self.open_indexes(&p.topic, &p.to)? {
1529 append_id(&path, &f, p.e.id)?;
1530 t.created |= c;
1531 if !t.files.iter().any(|(q, _)| *q == path) {
1532 t.files.push((path, f));
1533 }
1534 }
1535 fault("before-table-entry");
1536 if self.last == 0 {
1537 self.base = p.e.id;
1538 }
1539 self.write_entry(&p.e)?;
1540 self.last = p.e.id;
1541 self.end = p.e.frame_end();
1542 if Some(p.e.id) != own {
1543 self.rec.adopted.push(p.e.id);
1544 }
1545 }
1546 Ok(t)
1547 }
1548
1549 /// `fdatasync` `journal.idx` and the index files of a commit (one parallel group).
1550 fn sync_touched(&self, t: &Touched) -> Result<(), BoardError> {
1551 let mut group: Vec<(&Path, &File)> = vec![(self.ip.as_path(), &self.idx)];
1552 group.extend(t.files.iter().map(|(p, f)| (p.as_path(), f)));
1553 sync_group(&group)?;
1554 if t.created {
1555 // A new index file's entry is not needed for durability (the id indexes are
1556 // rebuilt from the journal after a reboot), but a failed sync is still a
1557 // failure: no ACK is given over an error.
1558 fsync_dir(&self.board.root().join("topics"))?;
1559 fsync_dir(&self.board.root().join("inbox"))?;
1560 }
1561 Ok(())
1562 }
1563
1564 /// Commit every pending frame now, durably (under the lock: recovery and compaction).
1565 fn commit_all(&mut self) -> Result<(), BoardError> {
1566 let Some(upto) = self.pending.last().map(|p| p.e.id) else {
1567 return Ok(());
1568 };
1569 self.j.sync_data().map_err(io_err(&self.jp))?;
1570 let t = self.commit_through(upto, None)?;
1571 self.sync_touched(&t)
1572 }
1573
1574 /// First writer of a new kernel boot: the page cache is gone, so only what was synced
1575 /// is known to be on disk. Every acknowledged frame was synced; `journal.idx` and the id
1576 /// indexes may have lost writes in any order. Rebuild them all from the journal (the
1577 /// usual tail rule applies to bytes after the last verifying frame), then record the
1578 /// boot id.
1579 fn rebuild_after_boot(&mut self) -> Result<(), BoardError> {
1580 let root = self.board.root().to_path_buf();
1581 let jlen = self.jlen()?;
1582 // The old table stays as it is until the new one is complete: what it proves is
1583 // committed (a durable frame) is never cut as a torn tail, here or on a retry.
1584 self.committed = self.table_evidence(jlen)?;
1585 self.base = 0;
1586 self.last = 0;
1587 self.end = 0;
1588 self.scan_tail(jlen, None)?;
1589 self.j.sync_data().map_err(io_err(&self.jp))?;
1590 let mut want: std::collections::BTreeMap<PathBuf, Vec<u64>> = Default::default();
1591 // Every existing index is rewritten (one that no event names becomes empty), so the
1592 // listing must be complete: a listing error refuses the rebuild with `boot` still
1593 // the old one, and the next operation of this boot rebuilds again.
1594 for d in ["topics", "inbox"] {
1595 for p in index_files(&root, d)? {
1596 want.entry(p).or_default();
1597 }
1598 }
1599 for p in &self.pending {
1600 for path in index_paths(&root, &p.topic, &p.to) {
1601 want.entry(path).or_default().push(p.e.id);
1602 }
1603 }
1604 for (p, ids) in &want {
1605 // Vet the existing file first: a planted link or FIFO is refused, not replaced.
1606 open_rw(&root, p)?;
1607 rewrite_ids(p, ids)?;
1608 }
1609 fsync_dir(&root.join("topics"))?;
1610 fsync_dir(&root.join("inbox"))?;
1611 let mut table = Vec::with_capacity(self.pending.len() * ENTRY_BYTES as usize);
1612 for p in &self.pending {
1613 table.extend_from_slice(&p.e.encode());
1614 }
1615 self.idx.write_all_at(&table, 0).map_err(io_err(&self.ip))?;
1616 self.idx
1617 .set_len(table.len() as u64)
1618 .map_err(io_err(&self.ip))?;
1619 self.idx.sync_data().map_err(io_err(&self.ip))?;
1620 if let (Some(f), Some(l)) = (self.pending.first(), self.pending.last()) {
1621 self.base = f.e.id;
1622 self.last = l.e.id;
1623 self.end = l.e.frame_end();
1624 }
1625 self.pending.clear();
1626 self.tail_end = self.end;
1627 self.rec.rebuilt_after_boot = true;
1628 if let Some(b) = boot_id() {
1629 crate::durable_write(&root, &root.join(BOOT), format!("{b}\n").as_bytes())?;
1630 }
1631 Ok(())
1632 }
1633
1634 fn open_indexes(
1635 &self,
1636 topic: &str,
1637 to: &[String],
1638 ) -> Result<Vec<(PathBuf, File, bool)>, BoardError> {
1639 let root = self.board.root();
1640 index_paths(root, topic, to)
1641 .into_iter()
1642 .map(|p| open_rw(root, &p).map(|(f, c)| (p, f, c)))
1643 .collect()
1644 }
1645
1646 /// Before a torn tail is cut, drop index entries naming ids past the commit point (a
1647 /// crash between the index group and the table entry can leave them; the ids would be
1648 /// handed out again, and a stale entry would deliver a later event to the wrong
1649 /// reader). Every index must be reached, so a listing error is returned. This runs
1650 /// before the cut, so a failure leaves the torn tail in place and the next writer
1651 /// cleans again; the dropped ids are past the commit point, invisible to every reader.
1652 fn clean_index_tails(&self) -> Result<(), BoardError> {
1653 let root = self.board.root();
1654 for d in ["topics", "inbox"] {
1655 for p in index_files(root, d)? {
1656 let (f, _) = open_rw(root, &p)?;
1657 let mut len = f.metadata().map_err(io_err(&p))?.len();
1658 len -= len % ID_BYTES;
1659 let before = len;
1660 while len >= ID_BYTES {
1661 let mut b = [0u8; 8];
1662 f.read_exact_at(&mut b, len - ID_BYTES)
1663 .map_err(io_err(&p))?;
1664 if u64::from_le_bytes(b) <= self.last {
1665 break;
1666 }
1667 len -= ID_BYTES;
1668 }
1669 if len != before || f.metadata().map_err(io_err(&p))?.len() != len {
1670 f.set_len(len).map_err(io_err(&p))?;
1671 f.sync_data().map_err(io_err(&p))?;
1672 }
1673 }
1674 }
1675 Ok(())
1676 }
1677
1678 fn snapshot(&self) -> Result<Snapshot, BoardError> {
1679 Snapshot::take(self.board)
1680 }
1681
1682 /// The event with idempotency key `k`, committed or pending: `Ok(id)` when its content
1683 /// equals `p`, `Err(id)` when it differs.
1684 fn find_idem(&self, k: &str, p: &Post) -> Result<Option<Result<u64, u64>>, BoardError> {
1685 let h = key_hash(H_IDEM, k.as_bytes());
1686 let judge = |ev: &Event| {
1687 if same_content(ev, p) {
1688 Ok(ev.id)
1689 } else {
1690 Err(ev.id)
1691 }
1692 };
1693 let snap = self.snapshot()?;
1694 let mut hit = None;
1695 snap.scan(snap.base, |e| {
1696 if e.idem_h == h {
1697 let ev = snap.event(e)?;
1698 if ev.idem.as_deref() == Some(k) {
1699 hit = Some(judge(&ev));
1700 return Ok(false);
1701 }
1702 }
1703 Ok(true)
1704 })?;
1705 if hit.is_some() {
1706 return Ok(hit);
1707 }
1708 let jlen = self.jlen()?;
1709 for pe in &self.pending {
1710 if pe.e.idem_h != h {
1711 continue;
1712 }
1713 let ev = match read_frame(&self.j, &self.jp, pe.e.offset, jlen)? {
1714 Ok((_, _, body)) => {
1715 Event::from_body(&body).map_err(|r| corrupt(&self.jp, pe.e.offset, r))?
1716 }
1717 Err(b) => return Err(corrupt(&self.jp, pe.e.offset, b.reason())),
1718 };
1719 if ev.idem.as_deref() == Some(k) {
1720 return Ok(Some(judge(&ev)));
1721 }
1722 }
1723 Ok(None)
1724 }
1725}
1726
1727fn same_content(ev: &Event, p: &Post) -> bool {
1728 ev.thread == p.thread
1729 && ev.topic == p.topic
1730 && ev.to == p.to
1731 && ev.kind == p.kind
1732 && ev.parent == p.parent
1733 && ev.text == p.text
1734 && ev.refs == p.refs
1735}
1736
1737impl Board {
1738 /// Append one event (group commit, see the module docs). Returns only after both fsync
1739 /// rounds (the ACK). With an idempotency
1740 /// key already used for the same body, returns that event's id (`dedup`); with a
1741 /// different body, refuses with [`BoardError::IdempotencyConflict`]. The body comparison
1742 /// covers thread, topic, to, kind, parent, text and refs, not the sender: two agents
1743 /// racing to post the same keyed message produce one event.
1744 pub fn post(&self, p: &Post) -> Result<PostReceipt, BoardError> {
1745 super::validate_post(p)?;
1746 let me = &Me {
1747 tag: p.from_tag.clone(),
1748 session: p.from.clone(),
1749 };
1750 // Step 1, under the lock: reconcile, check, append.
1751 let w = Writer::open(self)?;
1752 let binding = self.check_binding(me)?;
1753 self.touch_locked(me, &binding)?;
1754 let newest = w.next_id() - 1;
1755 if let Some(parent) = p.parent {
1756 if parent > newest {
1757 return Err(BoardError::BadParent {
1758 parent,
1759 last: newest,
1760 });
1761 }
1762 }
1763 if let Some(k) = &p.idem {
1764 match w.find_idem(k, p)? {
1765 Some(Ok(id)) => {
1766 // The first event may still be pending: make it durable and committed
1767 // before answering, exactly as its own writer does.
1768 let recovery = self.finish_commit(w, id, None)?;
1769 return Ok(PostReceipt {
1770 id,
1771 mission: self.id(),
1772 dedup: true,
1773 recovery,
1774 woke: 0,
1775 });
1776 }
1777 Some(Err(existing)) => {
1778 return Err(BoardError::IdempotencyConflict {
1779 idem: k.clone(),
1780 existing,
1781 })
1782 }
1783 None => {}
1784 }
1785 }
1786 let lim = self.limits();
1787 if w.count() >= lim.max_events {
1788 return Err(BoardError::BoardFull {
1789 what: "events",
1790 limit: lim.max_events,
1791 });
1792 }
1793 let ev = Event {
1794 id: w.next_id(),
1795 from_tag: me.tag.clone(),
1796 from: me.session.clone(),
1797 mission: self.id(),
1798 thread: p.thread.clone(),
1799 topic: p.topic.clone(),
1800 to: p.to.clone(),
1801 kind: p.kind,
1802 parent: p.parent,
1803 ts: self.now(),
1804 text: p.text.clone(),
1805 refs: p.refs.clone(),
1806 idem: p.idem.clone(),
1807 };
1808 let body = ev.body();
1809 if body.len() > MAX_FRAME_BYTES as usize {
1810 return Err(BoardError::TooLarge {
1811 field: "record",
1812 len: body.len(),
1813 limit: MAX_FRAME_BYTES as usize,
1814 });
1815 }
1816 let frame_bytes = frame::encode_frame(&body);
1817 if w.tail_end + frame_bytes.len() as u64 > lim.max_journal_bytes {
1818 return Err(BoardError::BoardFull {
1819 what: "journal bytes",
1820 limit: lim.max_journal_bytes,
1821 });
1822 }
1823 // Open (and so vet) every index file before the journal is touched: a FIFO or link
1824 // planted under topics/ or inbox/ refuses the post with nothing written.
1825 w.open_indexes(&ev.topic, &ev.to)?;
1826 if fault_active("torn-journal-write") {
1827 let half = frame_bytes.len() / 2;
1828 let _ = w.j.write_all_at(&frame_bytes[..half], w.tail_end);
1829 std::process::exit(FAULT_EXIT);
1830 }
1831 w.j.write_all_at(&frame_bytes, w.tail_end)
1832 .map_err(io_err(&w.jp))?;
1833 let recovery = self.finish_commit(w, ev.id, Some(frame::crc32c(&body)))?;
1834 fault("before-ack");
1835 let woke = if fault_active("drop-wake") {
1836 0
1837 } else {
1838 super::notify::wake_all(self.root(), ev.id)
1839 };
1840 Ok(PostReceipt {
1841 id: ev.id,
1842 mission: self.id(),
1843 dedup: false,
1844 recovery,
1845 woke,
1846 })
1847 }
1848
1849 /// Steps 2 to 4 of a post for event `id`, appended or pending in `w` (which holds the
1850 /// lock): unlock, `fdatasync` the journal, commit every pending frame up to `id` under
1851 /// the lock, unlock, then sync `journal.idx` and the event's index files. With `crc`,
1852 /// the committed entry must be that frame. Returns both steps' recovery, merged.
1853 fn finish_commit(
1854 &self,
1855 mut w: Writer<'_>,
1856 id: u64,
1857 crc: Option<u32>,
1858 ) -> Result<Recovery, BoardError> {
1859 let mut rec = std::mem::take(&mut w.rec);
1860 w.unlock();
1861 fault("before-journal-fsync");
1862 w.j.sync_data().map_err(io_err(&w.jp))?;
1863 fault("after-journal-before-index");
1864 drop(w);
1865 let mut w = Writer::open(self)?;
1866 let mut t = if id > w.last {
1867 w.commit_through(id, Some(id))?
1868 } else {
1869 Touched::default()
1870 };
1871 if id > w.last {
1872 return Err(BoardError::Io {
1873 path: w.jp.clone(),
1874 source: std::io::Error::other(format!(
1875 "event {id} vanished from the journal before its commit"
1876 )),
1877 });
1878 }
1879 if id >= w.base {
1880 // Sync the event's own index files too when another writer committed it.
1881 let snap = w.snapshot()?;
1882 let e = snap.entry(id)?;
1883 if crc.is_some_and(|c| c != e.crc) {
1884 return Err(corrupt(
1885 &w.jp,
1886 e.offset,
1887 format!("event {id} committed with another frame than this post wrote"),
1888 ));
1889 }
1890 let ev = snap.event(&e)?;
1891 for (path, f, c) in w.open_indexes(&ev.topic, &ev.to)? {
1892 t.created |= c;
1893 if !t.files.iter().any(|(q, _)| *q == path) {
1894 t.files.push((path, f));
1895 }
1896 }
1897 }
1898 w.unlock();
1899 w.sync_touched(&t)?;
1900 let r = std::mem::take(&mut w.rec);
1901 if rec.torn_tail_at.is_none() {
1902 rec.torn_tail_at = r.torn_tail_at;
1903 }
1904 rec.torn_bytes += r.torn_bytes;
1905 rec.adopted.extend(r.adopted);
1906 rec.dropped_table_entry |= r.dropped_table_entry;
1907 rec.table_rebuilt |= r.table_rebuilt;
1908 rec.rebuilt_after_boot |= r.rebuilt_after_boot;
1909 Ok(rec)
1910 }
1911
1912 /// Run writer recovery now and report it: reconcile the tail, rebuild after a reboot,
1913 /// and commit (durably) every pending frame.
1914 pub fn recover(&self) -> Result<Recovery, BoardError> {
1915 let mut w = Writer::open(self)?;
1916 w.commit_all()?;
1917 Ok(w.rec)
1918 }
1919
1920 /// Last committed id (0 when empty) and the oldest kept id (0 when empty).
1921 pub fn bounds(&self) -> Result<(u64, u64), BoardError> {
1922 let s = Snapshot::take(self)?;
1923 Ok((s.base, s.last))
1924 }
1925
1926 /// Explicit compaction: keep events `keep_since..=last`. Refuses while a cursor still
1927 /// needs older events unless `expire_cursors`, which marks those cursors expired first
1928 /// (their owners get [`BoardError::CursorExpired`], never a silent gap).
1929 pub fn compact(
1930 &self,
1931 keep_since: u64,
1932 expire_cursors: bool,
1933 ) -> Result<CompactReport, BoardError> {
1934 let mut w = Writer::open(self)?;
1935 // Pending frames would be lost by the rewrite: commit them first.
1936 w.commit_all()?;
1937 if w.last == 0 || keep_since <= w.base || keep_since > w.last {
1938 return Err(BoardError::BadKeepSince {
1939 keep_since,
1940 base: w.base,
1941 last: w.last,
1942 });
1943 }
1944 let lagging: Vec<String> = self
1945 .all_cursors()?
1946 .into_iter()
1947 .filter(|(_, c)| !c.expired && c.acked + 1 < keep_since)
1948 .map(|(t, _)| t)
1949 .collect();
1950 if !lagging.is_empty() && !expire_cursors {
1951 return Err(BoardError::CompactRefused {
1952 keep_since,
1953 tags: lagging,
1954 });
1955 }
1956 let snap = w.snapshot()?;
1957 let first = snap.entry(keep_since)?;
1958 let delta = first.offset;
1959 let bytes_before = w.end;
1960 let root = self.root();
1961 let jt = root.join(format!("{JOURNAL}.compact.tmp{}", std::process::id()));
1962 let it = root.join(format!("{TABLE}.compact.tmp{}", std::process::id()));
1963 {
1964 let mut nj = crate::record::create_temp(&jt)?;
1965 let mut buf = vec![0u8; 1 << 20];
1966 let mut off = delta;
1967 while off < w.end {
1968 let n = ((w.end - off) as usize).min(buf.len());
1969 w.j.read_exact_at(&mut buf[..n], off)
1970 .map_err(io_err(&w.jp))?;
1971 nj.write_all(&buf[..n]).map_err(io_err(&jt))?;
1972 off += n as u64;
1973 }
1974 nj.sync_all().map_err(io_err(&jt))?;
1975 let mut ni = crate::record::create_temp(&it)?;
1976 let mut out = Vec::with_capacity(((w.last - keep_since + 1) * ENTRY_BYTES) as usize);
1977 snap.scan(keep_since, |e| {
1978 let mut e = *e;
1979 e.offset -= delta;
1980 out.extend_from_slice(&e.encode());
1981 Ok(true)
1982 })?;
1983 ni.write_all(&out).map_err(io_err(&it))?;
1984 ni.sync_all().map_err(io_err(&it))?;
1985 }
1986 // Expire, then flush `cursors/` before anything is published: the decision above
1987 // read cursor state (acks, expirations, first reads) that an earlier operation may
1988 // have renamed into place without a successful directory sync, and a retry finds
1989 // an expiration already applied (the `lagging` filter skips it) without writing it
1990 // again. Publishing over a cursor a power loss could still undo would drop events
1991 // its reader never acknowledged. A failure refuses here, the journal untouched.
1992 let ready = (|| {
1993 if expire_cursors {
1994 self.expire_cursors(&lagging)?;
1995 }
1996 self.sync_cursor_dir()
1997 })();
1998 if let Err(e) = ready {
1999 let _ = fs::remove_file(&jt);
2000 let _ = fs::remove_file(&it);
2001 return Err(e);
2002 }
2003 let expired = if expire_cursors { lagging } else { Vec::new() };
2004 // The renames publish the new generation: marked before them and synced after, all
2005 // under `RootLock` (`publish_root`), so a failed sync refuses the compaction, the
2006 // marker survives every other operation's sync, and the next writer flushes the
2007 // root again before it acknowledges a post into the new journal.
2008 publish_root(root, || {
2009 fs::rename(&jt, &w.jp).map_err(io_err(&w.jp))?;
2010 fault("compact-between-renames");
2011 fs::rename(&it, &w.ip).map_err(io_err(&w.ip))?;
2012 if fault_active("compact-root-sync-eio") {
2013 // Test-only: the publication's root sync fails; the marker set above stays.
2014 return Err(io_err(root)(std::io::Error::from_raw_os_error(libc::EIO)));
2015 }
2016 Ok(())
2017 })?;
2018 self.trim_indexes(keep_since)?;
2019 Ok(CompactReport {
2020 base: keep_since,
2021 last: w.last,
2022 dropped_events: keep_since - w.base,
2023 bytes_before,
2024 bytes_after: w.end - delta,
2025 expired,
2026 })
2027 }
2028
2029 /// Drop ids below `base` from every topic and inbox index (tmp + rename each; readers
2030 /// skip ids below the base anyway, so either version of one file is correct). An index
2031 /// that cannot be reached is not skipped: the listing error is returned, so the
2032 /// compaction (already published and durable at this point) does not report success
2033 /// while an index may keep growing toward its read cap; a later compaction trims it.
2034 fn trim_indexes(&self, base: u64) -> Result<(), BoardError> {
2035 let root = self.root();
2036 for d in ["topics", "inbox"] {
2037 let dir = root.join(d);
2038 let files = index_files(root, d)?;
2039 if files.is_empty() {
2040 // Absent or without indexes: nothing renamed, nothing to flush.
2041 continue;
2042 }
2043 for p in files {
2044 let (ids, _) =
2045 read_ids_after(&p, base - 1, u64::MAX, usize::MAX, self.limits().max_events)?;
2046 rewrite_ids(&p, &ids)?;
2047 }
2048 fsync_dir(&dir)?;
2049 }
2050 Ok(())
2051 }
2052
2053 /// Read-only verification that `journal.idx`, every topic index and every inbox index
2054 /// agree with `journal.log`. Takes the writer lock for a stable view, repairs nothing.
2055 pub fn check(&self) -> Result<CheckReport, BoardError> {
2056 let _lock = BoardLock::acquire(self.root())?;
2057 self.check_id_locked()?;
2058 let snap = Snapshot::take(self)?;
2059 let mut problems = Vec::new();
2060 let mut expect_topic: std::collections::BTreeMap<PathBuf, Vec<u64>> = Default::default();
2061 let mut expect_inbox: std::collections::BTreeMap<PathBuf, Vec<u64>> = Default::default();
2062 let jp = self.root().join(JOURNAL);
2063 let jlen = snap.jlen;
2064 let mut events = 0u64;
2065 let mut pos = 0u64;
2066 let mut committed_end = 0u64;
2067 if let Some(j) = &snap.journal {
2068 let mut want = snap.base;
2069 while pos < jlen {
2070 match read_frame(j, &jp, pos, jlen)? {
2071 Ok((len, crc, body)) => {
2072 let ev = match Event::from_body(&body) {
2073 Ok(ev) => ev,
2074 Err(r) => {
2075 problems.push(format!("frame at {pos}: {r}"));
2076 break;
2077 }
2078 };
2079 if ev.mission != self.id() {
2080 problems.push(format!(
2081 "event {} at {pos} belongs to mission {}",
2082 ev.id, ev.mission
2083 ));
2084 }
2085 if ev.id > snap.last || snap.last == 0 {
2086 problems.push(format!(
2087 "event {} at {pos} is after the commit point (unacknowledged; the next post reconciles it)",
2088 ev.id
2089 ));
2090 break;
2091 }
2092 if ev.id != want {
2093 problems.push(format!("event {} at {pos}, expected {want}", ev.id));
2094 break;
2095 }
2096 let e = entry_for(&ev, pos, len, crc);
2097 match snap.entry(ev.id) {
2098 Ok(t) if t == e => {}
2099 Ok(t) => problems.push(format!(
2100 "journal.idx entry {} is {t:?}, journal says {e:?}",
2101 ev.id
2102 )),
2103 Err(err) => {
2104 problems.push(format!("journal.idx entry {}: {err}", ev.id))
2105 }
2106 }
2107 expect_topic
2108 .entry(topic_file(self.root(), &ev.topic))
2109 .or_default()
2110 .push(ev.id);
2111 let mut seen = Vec::new();
2112 for t in &ev.to {
2113 if !seen.contains(t) {
2114 expect_inbox
2115 .entry(inbox_file(self.root(), t))
2116 .or_default()
2117 .push(ev.id);
2118 seen.push(t.clone());
2119 }
2120 }
2121 events += 1;
2122 want += 1;
2123 pos = e.frame_end();
2124 committed_end = pos;
2125 }
2126 Err(b) => {
2127 problems.push(format!(
2128 "{} bytes after offset {pos} do not verify ({}): torn tail, cut by the next post",
2129 jlen - pos,
2130 b.reason()
2131 ));
2132 break;
2133 }
2134 }
2135 }
2136 }
2137 if events
2138 != if snap.last == 0 {
2139 0
2140 } else {
2141 snap.last - snap.base + 1
2142 }
2143 {
2144 problems.push(format!(
2145 "journal holds {events} committed events, journal.idx names {}..={}",
2146 snap.base, snap.last
2147 ));
2148 }
2149 for (d, expect) in [("topics", &expect_topic), ("inbox", &expect_inbox)] {
2150 let dir = self.root().join(d);
2151 let mut found: Vec<PathBuf> = Vec::new();
2152 // A verification that cannot list a directory does not pass: the listing error
2153 // (of the directory or of one entry) is a problem. Only an absent directory is
2154 // empty; "missing" is reported only from a complete listing.
2155 let mut complete = true;
2156 match crate::record::list_dir(&dir) {
2157 Ok(rd) => {
2158 for ent in rd {
2159 match ent {
2160 Ok(ent) => found.push(ent.path()),
2161 Err(e) => {
2162 complete = false;
2163 problems.push(format!("{}: cannot list: {e}", dir.display()));
2164 }
2165 }
2166 }
2167 }
2168 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2169 Err(e) => {
2170 complete = false;
2171 problems.push(format!("{}: cannot list: {e}", dir.display()));
2172 }
2173 }
2174 found.sort();
2175 for p in &found {
2176 let want = expect.get(p).cloned().unwrap_or_default();
2177 match read_ids_after(
2178 p,
2179 snap.base.saturating_sub(1),
2180 snap.last,
2181 usize::MAX,
2182 self.limits().max_events,
2183 ) {
2184 Ok((ids, _)) if ids == want => {}
2185 Ok((ids, _)) => problems.push(format!(
2186 "{} lists {} ids, journal says {} ({:?} vs {:?})",
2187 p.display(),
2188 ids.len(),
2189 want.len(),
2190 &ids[..ids.len().min(8)],
2191 &want[..want.len().min(8)]
2192 )),
2193 Err(e) => problems.push(format!("{}: {e}", p.display())),
2194 }
2195 }
2196 for (p, ids) in expect {
2197 if complete && !found.contains(p) {
2198 problems.push(format!(
2199 "{} is missing ({} ids expected)",
2200 p.display(),
2201 ids.len()
2202 ));
2203 }
2204 }
2205 }
2206 Ok(CheckReport {
2207 base: snap.base,
2208 last: snap.last,
2209 events,
2210 journal_bytes: jlen,
2211 committed_bytes: committed_end,
2212 problems,
2213 })
2214 }
2215}
2216
2217/// Result of [`Board::compact`].
2218#[derive(Clone, Debug, PartialEq, Eq)]
2219pub struct CompactReport {
2220 pub base: u64,
2221 pub last: u64,
2222 pub dropped_events: u64,
2223 pub bytes_before: u64,
2224 pub bytes_after: u64,
2225 /// Tags whose cursors were expired.
2226 pub expired: Vec<String>,
2227}
2228
2229/// Result of [`Board::check`]: `problems` is empty when every index agrees with the journal.
2230#[derive(Clone, Debug, PartialEq, Eq)]
2231pub struct CheckReport {
2232 pub base: u64,
2233 pub last: u64,
2234 pub events: u64,
2235 pub journal_bytes: u64,
2236 pub committed_bytes: u64,
2237 pub problems: Vec<String>,
2238}
2239
2240impl CheckReport {
2241 pub fn ok(&self) -> bool {
2242 self.problems.is_empty()
2243 }
2244}