Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 37.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The op log: refs, and the history of every operation that moved them.
5//!
6//! ```text
7//! oplog/lock exclusive while a transaction runs, shared while reading
8//! oplog/log operation records, append-only
9//! oplog/ckpt.<seq> every ref as of operation <seq>
10//! ```
11//!
12//! An operation record (`uv`, `sv` and `bytes` as in section 1 of the format
13//! spec, fixed-size integers little-endian):
14//!
15//! ```text
16//! u32 magic = 0xB7A10910 | u32 body_len | body | u32 record_len | u32 crc32c
17//!
18//! body: u8 version = 1 | uv seq | sv milliseconds since the Unix epoch
19//! bytes agent | bytes description | uv seq undone, 0 for none
20//! uv n | n × update
21//! update: bytes name | u8 which (bit 0: old present, bit 1: new present)
22//! [32] old, if present | [32] new, if present
23//! ```
24//!
25//! `record_len` is `body_len + 16`, so the log can be read backwards from its
26//! end; the CRC covers everything before it. Sequence numbers start at 1 and
27//! have no gaps. Each record keeps the old value of every ref it changed, so
28//! undoing it is a new operation that sets them back.
29//!
30//! A transaction holds the lock, reads the log to the end, checks every
31//! update against the current value (compare and swap), appends one record
32//! and flushes it. A record cut short by a crash is ignored by readers and
33//! cut off by the next writer, but only when no whole record follows it:
34//! damage in the middle of the log is an error, never a reason to drop data.
35//!
36//! A checkpoint, written through a temporary file and a rename:
37//!
38//! ```text
39//! [8] magic "braidckp" | u32 version = 1 | u32 0 | u64 seq | u64 end of record seq in the log
40//! uv n | n × (bytes name | [32] id), names strictly ascending
41//! [32] BLAKE3 hash of everything before it
42//! ```
43
44use std::cell::Cell;
45use std::collections::{BTreeMap, HashSet};
46use std::fs::{self, File, OpenOptions};
47use std::io;
48use std::ops::ControlFlow;
49use std::path::PathBuf;
50use std::sync::{Mutex, MutexGuard, PoisonError};
51use std::time::{SystemTime, UNIX_EPOCH};
52
53use braid_format::codec::{Reader, put_bytes, put_id, put_sv, put_uv};
54use braid_format::{DecodeError, ObjectId};
55
56use crate::error::{Error, TransactError, io_error};
57use crate::fsutil::{
58 flush_file, publish_file, read_range, remove_stale_temps, sync_dir, write_all_at,
59};
60use crate::record::array;
61use crate::{Durability, Options, Store};
62
63/// The first four bytes of every operation record.
64pub(crate) const MAGIC: u32 = 0xB7A1_0910;
65/// Bytes a record adds around its body.
66const OVERHEAD: u64 = 16;
67const BODY_VERSION: u8 = 1;
68/// The largest record body accepted, and so the largest operation.
69const MAX_BODY: u64 = 16 << 20;
70/// The longest agent label.
71const MAX_AGENT: usize = 1024;
72/// The longest operation description.
73const MAX_DESCRIPTION: usize = 64 << 10;
74/// The longest ref name.
75const MAX_REF_NAME: usize = 4096;
76
77const CHECKPOINT_MAGIC: &[u8; 8] = b"braidckp";
78const CHECKPOINT_VERSION: u32 = 1;
79/// Checkpoint file names are this prefix and a sequence number.
80pub(crate) const CHECKPOINT_PREFIX: &str = "ckpt.";
81/// How many checkpoints are kept. A reader falls back to an older one if the
82/// newest is damaged.
83const CHECKPOINTS_KEPT: usize = 2;
84
85/// Every ref and the object it points at, as of one operation.
86#[derive(Clone, Debug, Default, PartialEq, Eq)]
87pub struct Refs {
88 seq: u64,
89 map: BTreeMap<String, ObjectId>,
90}
91
92impl Refs {
93 /// The sequence number of the newest operation these refs include, or 0
94 /// before the first one.
95 pub fn seq(&self) -> u64 {
96 self.seq
97 }
98
99 /// The object a ref points at.
100 pub fn get(&self, name: &str) -> Option<ObjectId> {
101 self.map.get(name).copied()
102 }
103
104 /// Number of refs.
105 pub fn len(&self) -> usize {
106 self.map.len()
107 }
108
109 /// Whether there are no refs.
110 pub fn is_empty(&self) -> bool {
111 self.map.is_empty()
112 }
113
114 /// Every ref, by name in byte order.
115 pub fn iter(&self) -> impl Iterator<Item = (&str, ObjectId)> + '_ {
116 self.map.iter().map(|(name, id)| (name.as_str(), *id))
117 }
118
119 /// The refs as a map.
120 pub fn as_map(&self) -> &BTreeMap<String, ObjectId> {
121 &self.map
122 }
123
124 fn apply(&mut self, op: &Operation) {
125 for update in &op.updates {
126 match update.new {
127 Some(id) => {
128 self.map.insert(update.name.clone(), id);
129 }
130 None => {
131 self.map.remove(&update.name);
132 }
133 }
134 }
135 self.seq = op.seq;
136 }
137}
138
139/// A change to one ref, applied only if the ref still holds `old`.
140#[derive(Clone, Debug, PartialEq, Eq, Hash)]
141pub struct RefUpdate {
142 /// The ref's name: non-empty, at most 4,096 bytes, no NUL.
143 pub name: String,
144 /// The value the ref must hold, `None` for a ref that must not exist.
145 pub old: Option<ObjectId>,
146 /// The value to set, `None` to delete the ref.
147 pub new: Option<ObjectId>,
148}
149
150impl RefUpdate {
151 /// An update of `name` from `old` to `new`.
152 pub fn new(name: impl Into<String>, old: Option<ObjectId>, new: Option<ObjectId>) -> Self {
153 Self {
154 name: name.into(),
155 old,
156 new,
157 }
158 }
159}
160
161/// One recorded operation.
162#[derive(Clone, Debug, PartialEq, Eq)]
163pub struct Operation {
164 /// Its position in the log, from 1, without gaps.
165 pub seq: u64,
166 /// When it was recorded, in milliseconds since the Unix epoch, by the
167 /// clock of the process that recorded it.
168 pub time_ms: i64,
169 /// Who recorded it: an agent or session label.
170 pub agent: String,
171 /// What it did, for people.
172 pub description: String,
173 /// The operation it reverted, if it is an undo.
174 pub undoes: Option<u64>,
175 /// The refs it changed, each with its old and new value.
176 pub updates: Vec<RefUpdate>,
177}
178
179/// The op log half of a store: the `oplog/` directory.
180#[derive(Debug)]
181pub(crate) struct OpLog {
182 dir: PathBuf,
183 durability: Durability,
184 checkpoint_interval: u64,
185 /// The newest state this handle has seen, so that the next read only
186 /// parses the records after it.
187 cache: Mutex<Option<State>>,
188}
189
190/// The refs at the end of a valid prefix of the log.
191#[derive(Clone, Debug, Default)]
192struct State {
193 refs: Refs,
194 /// Where the record `refs.seq` ends.
195 end: u64,
196 /// The newest checkpoint this handle knows of.
197 checkpoint: u64,
198}
199
200thread_local! {
201 /// Set while a transaction's closure runs on this thread.
202 static IN_TRANSACTION: Cell<bool> = const { Cell::new(false) };
203}
204
205/// Marks the current thread as running a transaction's closure.
206struct InTransaction;
207
208impl InTransaction {
209 fn enter() -> Self {
210 IN_TRANSACTION.with(|flag| flag.set(true));
211 InTransaction
212 }
213}
214
215impl Drop for InTransaction {
216 fn drop(&mut self) {
217 IN_TRANSACTION.with(|flag| flag.set(false));
218 }
219}
220
221/// Fails if the current thread is running a transaction's closure.
222pub(crate) fn not_in_transaction() -> Result<(), Error> {
223 if IN_TRANSACTION.with(Cell::get) {
224 Err(Error::Reentrant)
225 } else {
226 Ok(())
227 }
228}
229
230impl Store {
231 /// Every ref, as of the newest operation. Waits while a transaction is
232 /// being recorded, so it never returns an operation before it is
233 /// durable.
234 pub fn refs(&self) -> Result<Refs, Error> {
235 not_in_transaction()?;
236 let _shared = self.oplog.lock(false)?;
237 let Some(log) = self.oplog.open_log(false)? else {
238 return Ok(Refs::default());
239 };
240 Ok(self.oplog.load(&log)?.0.refs)
241 }
242
243 /// Records one operation.
244 ///
245 /// Takes the op log lock, reads the refs as of the newest operation and
246 /// passes them to `f`, which returns the updates to make. Each update is
247 /// applied only if its ref still holds the update's `old` value; if any
248 /// does not, nothing is recorded and the error is a conflict (see
249 /// [`TransactError::is_conflict`]), so the caller can read again and
250 /// retry. Every `new` value must be an object in the store, and is made
251 /// durable before the record is appended. The record is flushed before
252 /// this returns.
253 ///
254 /// The lock is held while `f` runs, so `f` should be quick. It may read
255 /// and write objects, but must not use the op log: that fails with
256 /// [`Error::Reentrant`] instead of waiting forever.
257 pub fn transact<F, E>(
258 &self,
259 agent: &str,
260 description: &str,
261 f: F,
262 ) -> Result<Operation, TransactError<E>>
263 where
264 F: FnOnce(&Refs) -> Result<Vec<RefUpdate>, E>,
265 {
266 not_in_transaction()?;
267 check_labels(agent, description)?;
268 self.transact_with(agent, |refs| {
269 f(refs).map(|updates| (updates, description.to_owned()))
270 })
271 }
272
273 /// Records one operation whose description depends on what `f` finds:
274 /// like [`Store::transact`], except that `f` returns the description
275 /// with the updates, so that the record can say what the operation did,
276 /// such as how a landing went.
277 pub fn transact_with<F, E>(&self, agent: &str, f: F) -> Result<Operation, TransactError<E>>
278 where
279 F: FnOnce(&Refs) -> Result<(Vec<RefUpdate>, String), E>,
280 {
281 not_in_transaction()?;
282 check_labels(agent, "")?;
283 // Flush this handle's objects before taking the lock, to keep the
284 // critical section short.
285 self.segments.sync()?;
286 let lock = self.oplog.lock(true)?;
287 let log = self.oplog.open_for_write()?;
288 let mut state = self.oplog.load_for_write(&log)?;
289 let (updates, description) = {
290 let _inside = InTransaction::enter();
291 f(&state.refs).map_err(TransactError::Aborted)?
292 };
293 check_labels(agent, &description)?;
294 let op = self.commit(&log, &mut state, agent, &description, None, updates)?;
295 drop(log);
296 drop(lock);
297 self.oplog.maybe_checkpoint(&state);
298 self.merge_if_due();
299 Ok(op)
300 }
301
302 /// The newest operations, newest first, at most `limit` of them: what
303 /// `braid op log` shows.
304 pub fn log(&self, limit: usize) -> Result<Vec<Operation>, Error> {
305 not_in_transaction()?;
306 let _shared = self.oplog.lock(false)?;
307 let Some(log) = self.oplog.open_log(false)? else {
308 return Ok(Vec::new());
309 };
310 let (state, _) = self.oplog.load(&log)?;
311 let mut ops = Vec::new();
312 if limit > 0 {
313 self.oplog.walk_back(&log, state.end, |op| {
314 ops.push(op);
315 if ops.len() < limit {
316 ControlFlow::Continue(())
317 } else {
318 ControlFlow::Break(())
319 }
320 })?;
321 }
322 Ok(ops)
323 }
324
325 /// Reverts the newest operation that is neither an undo nor undone
326 /// already, as a new operation by `agent` that sets every ref it changed
327 /// back to its old value. Repeated calls step further back, one
328 /// operation at a time. Fails with [`Error::NothingToUndo`] when there is
329 /// nothing left.
330 ///
331 /// Undoes always revert the newest operation still in effect, so the
332 /// refs it changed still hold its new values; the updates are checked
333 /// with compare and swap all the same.
334 pub fn undo_last(&self, agent: &str) -> Result<Operation, Error> {
335 not_in_transaction()?;
336 check_labels(agent, "")?;
337 let lock = self.oplog.lock(true)?;
338 let log = self.oplog.open_for_write()?;
339 let mut state = self.oplog.load_for_write(&log)?;
340 let target = self
341 .oplog
342 .undo_target(&log, state.end)?
343 .ok_or(Error::NothingToUndo)?;
344 let updates = target
345 .updates
346 .iter()
347 .map(|update| RefUpdate::new(update.name.clone(), update.new, update.old))
348 .collect();
349 let description = format!("undo operation {}", target.seq);
350 let op = self.commit(
351 &log,
352 &mut state,
353 agent,
354 &description,
355 Some(target.seq),
356 updates,
357 )?;
358 drop(log);
359 drop(lock);
360 self.oplog.maybe_checkpoint(&state);
361 self.merge_if_due();
362 Ok(op)
363 }
364
365 /// Checks updates against the current refs, makes their targets durable,
366 /// and appends the operation.
367 fn commit(
368 &self,
369 log: &File,
370 state: &mut State,
371 agent: &str,
372 description: &str,
373 undoes: Option<u64>,
374 updates: Vec<RefUpdate>,
375 ) -> Result<Operation, Error> {
376 let mut names = HashSet::new();
377 let mut targets = Vec::new();
378 for update in &updates {
379 check_ref_name(&update.name)?;
380 if !names.insert(update.name.as_str()) {
381 return Err(Error::DuplicateRef {
382 name: update.name.clone(),
383 });
384 }
385 let found = state.refs.get(&update.name);
386 if found != update.old {
387 return Err(Error::Conflict {
388 name: update.name.clone(),
389 expected: update.old,
390 found,
391 });
392 }
393 if let Some(id) = update.new {
394 if !self.segments.contains(&id)? {
395 return Err(Error::MissingObject {
396 name: update.name.clone(),
397 id,
398 });
399 }
400 targets.push(id);
401 }
402 }
403 // The record must never point at an object that is not durable.
404 self.segments.make_durable(&targets)?;
405 let op = Operation {
406 seq: state.refs.seq + 1,
407 time_ms: now_ms(),
408 agent: agent.to_owned(),
409 description: description.to_owned(),
410 undoes,
411 updates,
412 };
413 self.oplog.append(log, state, &op)?;
414 Ok(op)
415 }
416}
417
418impl OpLog {
419 pub fn new(dir: PathBuf, options: &Options) -> Self {
420 Self {
421 dir,
422 durability: options.durability,
423 checkpoint_interval: options.checkpoint_interval,
424 cache: Mutex::new(None),
425 }
426 }
427
428 pub fn log_path(&self) -> PathBuf {
429 self.dir.join("log")
430 }
431
432 /// Locks `oplog/lock`, exclusively for a transaction or shared for a
433 /// read, until the returned file is dropped.
434 pub fn lock(&self, exclusive: bool) -> Result<File, Error> {
435 let path = self.dir.join("lock");
436 let file = OpenOptions::new()
437 .read(true)
438 .write(true)
439 .create(true)
440 .truncate(false)
441 .open(&path)
442 .map_err(io_error("open", &path))?;
443 if exclusive {
444 file.lock()
445 } else {
446 file.lock_shared()
447 }
448 .map_err(io_error("lock", &path))?;
449 Ok(file)
450 }
451
452 /// Opens the log for reading, or `None` if it does not exist yet.
453 fn open_log(&self, write: bool) -> Result<Option<File>, Error> {
454 let path = self.log_path();
455 match OpenOptions::new().read(true).write(write).open(&path) {
456 Ok(file) => Ok(Some(file)),
457 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
458 Err(err) => Err(io_error("open", &path)(err)),
459 }
460 }
461
462 /// Opens the log for a transaction, creating it if needed.
463 fn open_for_write(&self) -> Result<File, Error> {
464 if let Some(file) = self.open_log(true)? {
465 return Ok(file);
466 }
467 let path = self.log_path();
468 let file = OpenOptions::new()
469 .read(true)
470 .write(true)
471 .create(true)
472 .truncate(false)
473 .open(&path)
474 .map_err(io_error("create", &path))?;
475 sync_dir(&self.dir, self.durability)?;
476 Ok(file)
477 }
478
479 /// The state at the end of the valid records of `log`, and the log's
480 /// length. Fails if the log is damaged anywhere but at its very end.
481 fn load(&self, log: &File) -> Result<(State, u64), Error> {
482 let path = self.log_path();
483 let len = log.metadata().map_err(io_error("read", &path))?.len();
484 let mut state = self.start(log, len)?;
485 self.read_forward(log, len, &mut state)?;
486 if state.end < len {
487 self.check_torn_tail(log, &state, len)?;
488 }
489 self.remember(&state);
490 Ok((state, len))
491 }
492
493 /// Loads the state for a transaction, under the exclusive lock, and cuts
494 /// off the end of a record that a writer which died left behind.
495 fn load_for_write(&self, log: &File) -> Result<State, Error> {
496 let (state, len) = self.load(log)?;
497 if state.end < len {
498 let path = self.log_path();
499 log.set_len(state.end)
500 .map_err(io_error("truncate", &path))?;
501 flush_file(&path, log, self.durability)?;
502 }
503 Ok(state)
504 }
505
506 /// Where reading starts: this handle's cached state, else the newest
507 /// valid checkpoint, else the beginning.
508 fn start(&self, log: &File, len: u64) -> Result<State, Error> {
509 let cached = self.lock_cache().clone();
510 if let Some(state) = cached
511 && self.ends_at(log, len, state.end, state.refs.seq)?
512 {
513 return Ok(state);
514 }
515 for (seq, path) in self.checkpoints()?.into_iter().rev() {
516 let Ok(bytes) = fs::read(&path) else {
517 continue;
518 };
519 let Ok(checkpoint) = decode_checkpoint(&bytes) else {
520 continue;
521 };
522 if checkpoint.refs.seq == seq && self.ends_at(log, len, checkpoint.end, seq)? {
523 return Ok(State {
524 refs: checkpoint.refs,
525 end: checkpoint.end,
526 checkpoint: seq,
527 });
528 }
529 }
530 Ok(State::default())
531 }
532
533 /// Whether a valid record with sequence number `seq` ends at `end`.
534 fn ends_at(&self, log: &File, len: u64, end: u64, seq: u64) -> Result<bool, Error> {
535 if seq == 0 {
536 return Ok(end == 0);
537 }
538 if end > len {
539 return Ok(false);
540 }
541 let before = record_before(log, end).map_err(io_error("read", &self.log_path()))?;
542 Ok(before.is_some_and(|(op, _)| op.seq == seq))
543 }
544
545 /// Applies the records after `state.end`, up to the first that is not
546 /// whole.
547 fn read_forward(&self, log: &File, len: u64, state: &mut State) -> Result<(), Error> {
548 if state.end >= len {
549 return Ok(());
550 }
551 let path = self.log_path();
552 let bytes = read_range(log, state.end, len - state.end).map_err(io_error("read", &path))?;
553 let mut at = 0usize;
554 while at < bytes.len() {
555 match parse_record(&bytes[at..]) {
556 Ok((op, len)) => {
557 if op.seq != state.refs.seq + 1 {
558 return Err(Error::corrupt(
559 &path,
560 state.end,
561 format!("operation {} follows operation {}", op.seq, state.refs.seq),
562 ));
563 }
564 state.refs.apply(&op);
565 state.end += len;
566 at += len as usize;
567 }
568 Err(Bad::Torn) => break,
569 Err(Bad::Damaged(detail, _)) => {
570 return Err(Error::corrupt(&path, state.end, detail));
571 }
572 }
573 }
574 Ok(())
575 }
576
577 /// Fails unless the bytes after the last valid record can only be the
578 /// remains of one append cut short by a crash.
579 fn check_torn_tail(&self, log: &File, state: &State, len: u64) -> Result<(), Error> {
580 let path = self.log_path();
581 let tail = read_range(log, state.end, len - state.end).map_err(io_error("read", &path))?;
582 if next_record(&tail, 1, state.refs.seq).is_some() {
583 return Err(Error::corrupt(
584 &path,
585 state.end,
586 "a damaged operation record is followed by valid ones",
587 ));
588 }
589 Ok(())
590 }
591
592 /// Appends an operation and flushes it.
593 fn append(&self, log: &File, state: &mut State, op: &Operation) -> Result<(), Error> {
594 let bytes = encode_record(op);
595 if bytes.len() as u64 > MAX_BODY + OVERHEAD {
596 return Err(Error::TooLong {
597 what: "operation record",
598 len: bytes.len(),
599 max: (MAX_BODY + OVERHEAD) as usize,
600 });
601 }
602 let path = self.log_path();
603 let written = write_all_at(log, &bytes, state.end)
604 .map_err(io_error("append to", &path))
605 .and_then(|()| flush_file(&path, log, self.durability));
606 if let Err(err) = written {
607 // Take the record back where possible, so that the failed
608 // operation is not left half recorded for the next reader.
609 if log.set_len(state.end).is_ok() {
610 let _ = flush_file(&path, log, self.durability);
611 }
612 return Err(err);
613 }
614 state.refs.apply(op);
615 state.end += bytes.len() as u64;
616 self.remember(state);
617 Ok(())
618 }
619
620 /// The newest operation that is neither an undo nor undone already.
621 fn undo_target(&self, log: &File, end: u64) -> Result<Option<Operation>, Error> {
622 let mut undone = HashSet::new();
623 let mut target = None;
624 self.walk_back(log, end, |op| {
625 if let Some(seq) = op.undoes {
626 undone.insert(seq);
627 ControlFlow::Continue(())
628 } else if undone.contains(&op.seq) {
629 ControlFlow::Continue(())
630 } else {
631 target = Some(op);
632 ControlFlow::Break(())
633 }
634 })?;
635 Ok(target)
636 }
637
638 /// Visits the records that end at or before `end`, newest first.
639 fn walk_back(
640 &self,
641 log: &File,
642 mut end: u64,
643 mut visit: impl FnMut(Operation) -> ControlFlow<()>,
644 ) -> Result<(), Error> {
645 let path = self.log_path();
646 while end > 0 {
647 let Some((op, start)) = record_before(log, end).map_err(io_error("read", &path))?
648 else {
649 return Err(Error::corrupt(
650 &path,
651 end,
652 "no valid operation record ends here",
653 ));
654 };
655 if visit(op).is_break() {
656 break;
657 }
658 end = start;
659 }
660 Ok(())
661 }
662
663 /// Writes a checkpoint if enough operations have passed since the newest
664 /// one. Best effort: the operation is already recorded, and a missing
665 /// checkpoint only makes the next cold start read more of the log.
666 fn maybe_checkpoint(&self, state: &State) {
667 let interval = self.checkpoint_interval;
668 if interval == 0 || state.refs.seq < state.checkpoint.saturating_add(interval) {
669 return;
670 }
671 // Another process may have written one since this handle last looked.
672 let newest = self
673 .checkpoints()
674 .ok()
675 .and_then(|all| all.last().map(|(seq, _)| *seq))
676 .unwrap_or(0);
677 if newest.saturating_add(interval) > state.refs.seq {
678 self.note_checkpoint(newest);
679 return;
680 }
681 remove_stale_temps(&self.dir);
682 let name = format!("{CHECKPOINT_PREFIX}{}", state.refs.seq);
683 if publish_file(
684 &self.dir,
685 &name,
686 &encode_checkpoint(state),
687 self.durability,
688 &[],
689 )
690 .is_err()
691 {
692 return;
693 }
694 self.note_checkpoint(state.refs.seq);
695 if let Ok(all) = self.checkpoints() {
696 for (_, path) in all.iter().rev().skip(CHECKPOINTS_KEPT) {
697 let _ = fs::remove_file(path);
698 }
699 }
700 }
701
702 fn note_checkpoint(&self, seq: u64) {
703 if let Some(state) = self.lock_cache().as_mut() {
704 state.checkpoint = state.checkpoint.max(seq);
705 }
706 }
707
708 /// The checkpoints in the directory, oldest first.
709 pub fn checkpoints(&self) -> Result<Vec<(u64, PathBuf)>, Error> {
710 let mut out = Vec::new();
711 for entry in fs::read_dir(&self.dir).map_err(io_error("list", &self.dir))? {
712 let entry = entry.map_err(io_error("list", &self.dir))?;
713 let name = entry.file_name();
714 let Some(seq) = name
715 .to_str()
716 .and_then(|name| name.strip_prefix(CHECKPOINT_PREFIX))
717 .filter(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
718 .and_then(|digits| digits.parse::<u64>().ok())
719 else {
720 continue;
721 };
722 out.push((seq, entry.path()));
723 }
724 out.sort();
725 Ok(out)
726 }
727
728 fn remember(&self, state: &State) {
729 let mut cache = self.lock_cache();
730 let checkpoint = cache.as_ref().map_or(0, |cached| cached.checkpoint);
731 if cache
732 .as_ref()
733 .is_none_or(|cached| cached.refs.seq <= state.refs.seq)
734 {
735 let mut state = state.clone();
736 state.checkpoint = state.checkpoint.max(checkpoint);
737 *cache = Some(state);
738 }
739 }
740
741 fn lock_cache(&self) -> MutexGuard<'_, Option<State>> {
742 self.cache.lock().unwrap_or_else(PoisonError::into_inner)
743 }
744}
745
746fn now_ms() -> i64 {
747 match SystemTime::now().duration_since(UNIX_EPOCH) {
748 Ok(after) => i64::try_from(after.as_millis()).unwrap_or(i64::MAX),
749 Err(before) => i64::try_from(before.duration().as_millis()).map_or(i64::MIN, |ms| -ms),
750 }
751}
752
753fn check_labels(agent: &str, description: &str) -> Result<(), Error> {
754 if agent.len() > MAX_AGENT {
755 return Err(Error::TooLong {
756 what: "agent label",
757 len: agent.len(),
758 max: MAX_AGENT,
759 });
760 }
761 if description.len() > MAX_DESCRIPTION {
762 return Err(Error::TooLong {
763 what: "operation description",
764 len: description.len(),
765 max: MAX_DESCRIPTION,
766 });
767 }
768 Ok(())
769}
770
771/// Checks a ref name against the op log's rules: not empty, at most 4,096
772/// bytes, no NUL. [`Store::transact`] refuses any other name with
773/// [`Error::InvalidRefName`]; this lets a caller, such as a server checking
774/// a request, refuse it before.
775pub fn check_ref_name(name: &str) -> Result<(), Error> {
776 let reason = if name.is_empty() {
777 "empty"
778 } else if name.len() > MAX_REF_NAME {
779 "longer than 4096 bytes"
780 } else if name.contains('\0') {
781 "contains NUL"
782 } else {
783 return Ok(());
784 };
785 Err(Error::InvalidRefName {
786 name: name.to_owned(),
787 reason,
788 })
789}
790
791/// Why bytes are not an operation record.
792#[derive(Debug, PartialEq, Eq)]
793pub(crate) enum Bad {
794 /// Not a whole record: what a crash leaves at the end of the log.
795 Torn,
796 /// A whole record by its checksum, of this many bytes, whose contents no
797 /// writer produces.
798 Damaged(&'static str, u64),
799}
800
801pub(crate) fn encode_record(op: &Operation) -> Vec<u8> {
802 let mut body = vec![BODY_VERSION];
803 put_uv(&mut body, op.seq);
804 put_sv(&mut body, op.time_ms);
805 put_bytes(&mut body, op.agent.as_bytes());
806 put_bytes(&mut body, op.description.as_bytes());
807 put_uv(&mut body, op.undoes.unwrap_or(0));
808 put_uv(&mut body, op.updates.len() as u64);
809 for update in &op.updates {
810 put_bytes(&mut body, update.name.as_bytes());
811 body.push(u8::from(update.old.is_some()) | (u8::from(update.new.is_some()) << 1));
812 if let Some(old) = &update.old {
813 put_id(&mut body, old);
814 }
815 if let Some(new) = &update.new {
816 put_id(&mut body, new);
817 }
818 }
819 let total = body.len() as u64 + OVERHEAD;
820 let mut out = Vec::with_capacity(total as usize);
821 out.extend_from_slice(&MAGIC.to_le_bytes());
822 out.extend_from_slice(&(body.len() as u32).to_le_bytes());
823 out.extend_from_slice(&body);
824 out.extend_from_slice(&(total as u32).to_le_bytes());
825 let crc = crc32c::crc32c(&out);
826 out.extend_from_slice(&crc.to_le_bytes());
827 out
828}
829
830/// Parses the record at the start of `bytes`, and returns it with its length.
831pub(crate) fn parse_record(bytes: &[u8]) -> Result<(Operation, u64), Bad> {
832 if bytes.len() < OVERHEAD as usize || u32::from_le_bytes(array(&bytes[0..4])) != MAGIC {
833 return Err(Bad::Torn);
834 }
835 let body_len = u64::from(u32::from_le_bytes(array(&bytes[4..8])));
836 if body_len > MAX_BODY {
837 return Err(Bad::Torn);
838 }
839 let total = body_len + OVERHEAD;
840 if (bytes.len() as u64) < total {
841 return Err(Bad::Torn);
842 }
843 let body_end = 8 + body_len as usize;
844 let stored_total = u64::from(u32::from_le_bytes(array(&bytes[body_end..body_end + 4])));
845 let crc = u32::from_le_bytes(array(&bytes[body_end + 4..body_end + 8]));
846 if stored_total != total || crc32c::crc32c(&bytes[..body_end + 4]) != crc {
847 return Err(Bad::Torn);
848 }
849 let op = decode_body(&bytes[8..body_end]).map_err(|detail| Bad::Damaged(detail, total))?;
850 Ok((op, total))
851}
852
853/// The first offset at or after `from` where a whole record of an operation
854/// after `seq` starts.
855pub(crate) fn next_record(bytes: &[u8], from: usize, seq: u64) -> Option<usize> {
856 let magic = MAGIC.to_le_bytes();
857 (from..bytes.len()).find(|&at| {
858 bytes[at..].starts_with(&magic)
859 && matches!(parse_record(&bytes[at..]), Ok((op, _)) if op.seq > seq)
860 })
861}
862
863/// The record that ends at `end`, and where it starts, if a whole one does.
864fn record_before(log: &File, end: u64) -> io::Result<Option<(Operation, u64)>> {
865 if end < OVERHEAD {
866 return Ok(None);
867 }
868 let trailer = read_range(log, end - 8, 8)?;
869 let total = u64::from(u32::from_le_bytes(array(&trailer[0..4])));
870 if !(OVERHEAD..=MAX_BODY + OVERHEAD).contains(&total) || total > end {
871 return Ok(None);
872 }
873 let bytes = read_range(log, end - total, total)?;
874 Ok(match parse_record(&bytes) {
875 Ok((op, len)) if len == total => Some((op, end - total)),
876 _ => None,
877 })
878}
879
880fn malformed(_: DecodeError) -> &'static str {
881 "malformed operation record"
882}
883
884fn decode_body(body: &[u8]) -> Result<Operation, &'static str> {
885 let mut reader = Reader::new(body);
886 if reader.u8().map_err(malformed)? != BODY_VERSION {
887 return Err("unknown operation record version");
888 }
889 let seq = reader.uv().map_err(malformed)?;
890 if seq == 0 {
891 return Err("operation with sequence number 0");
892 }
893 let time_ms = reader.sv().map_err(malformed)?;
894 let agent = text(reader.bytes().map_err(malformed)?)?;
895 let description = text(reader.bytes().map_err(malformed)?)?;
896 let undoes = match reader.uv().map_err(malformed)? {
897 0 => None,
898 undone if undone < seq => Some(undone),
899 _ => return Err("operation undoes one that comes after it"),
900 };
901 // Every update takes at least a name length and the presence byte.
902 let count = reader.count(2).map_err(malformed)?;
903 let mut updates = Vec::with_capacity(count);
904 for _ in 0..count {
905 let name = text(reader.bytes().map_err(malformed)?)?;
906 if name.is_empty() {
907 return Err("update of a ref with an empty name");
908 }
909 let which = reader.u8().map_err(malformed)?;
910 if which > 3 {
911 return Err("unknown update flags");
912 }
913 let old = if which & 1 != 0 {
914 Some(reader.id().map_err(malformed)?)
915 } else {
916 None
917 };
918 let new = if which & 2 != 0 {
919 Some(reader.id().map_err(malformed)?)
920 } else {
921 None
922 };
923 updates.push(RefUpdate { name, old, new });
924 }
925 reader.finish().map_err(malformed)?;
926 Ok(Operation {
927 seq,
928 time_ms,
929 agent,
930 description,
931 undoes,
932 updates,
933 })
934}
935
936fn text(bytes: &[u8]) -> Result<String, &'static str> {
937 String::from_utf8(bytes.to_vec()).map_err(|_| "text that is not UTF-8")
938}
939
940/// A decoded checkpoint.
941#[derive(Debug)]
942pub(crate) struct Checkpoint {
943 /// The refs, with the sequence number they are as of.
944 pub refs: Refs,
945 /// Where that operation's record ends in the log.
946 pub end: u64,
947}
948
949fn encode_checkpoint(state: &State) -> Vec<u8> {
950 let mut out = Vec::new();
951 out.extend_from_slice(CHECKPOINT_MAGIC);
952 out.extend_from_slice(&CHECKPOINT_VERSION.to_le_bytes());
953 out.extend_from_slice(&0u32.to_le_bytes());
954 out.extend_from_slice(&state.refs.seq.to_le_bytes());
955 out.extend_from_slice(&state.end.to_le_bytes());
956 put_uv(&mut out, state.refs.map.len() as u64);
957 for (name, id) in &state.refs.map {
958 put_bytes(&mut out, name.as_bytes());
959 put_id(&mut out, id);
960 }
961 let hash = blake3::hash(&out);
962 out.extend_from_slice(hash.as_bytes());
963 out
964}
965
966pub(crate) fn decode_checkpoint(bytes: &[u8]) -> Result<Checkpoint, &'static str> {
967 if bytes.len() < 32 + 1 + 32 {
968 return Err("checkpoint cut short");
969 }
970 let (body, footer) = bytes.split_at(bytes.len() - 32);
971 if blake3::hash(body).as_bytes() != footer {
972 return Err("checkpoint checksum mismatch");
973 }
974 if &body[0..8] != CHECKPOINT_MAGIC {
975 return Err("not a checkpoint");
976 }
977 if u32::from_le_bytes(array(&body[8..12])) != CHECKPOINT_VERSION
978 || u32::from_le_bytes(array(&body[12..16])) != 0
979 {
980 return Err("unknown checkpoint version");
981 }
982 let seq = u64::from_le_bytes(array(&body[16..24]));
983 let end = u64::from_le_bytes(array(&body[24..32]));
984 let bad = |_: DecodeError| "malformed checkpoint";
985 let mut reader = Reader::new(&body[32..]);
986 let count = reader.count(1 + 32).map_err(bad)?;
987 let mut map = BTreeMap::new();
988 let mut last: Option<String> = None;
989 for _ in 0..count {
990 let name = text(reader.bytes().map_err(bad)?)?;
991 let id = reader.id().map_err(bad)?;
992 if name.is_empty() || last.as_ref().is_some_and(|last| *last >= name) {
993 return Err("checkpoint names are not strictly ascending");
994 }
995 map.insert(name.clone(), id);
996 last = Some(name);
997 }
998 reader.finish().map_err(bad)?;
999 Ok(Checkpoint {
1000 refs: Refs { seq, map },
1001 end,
1002 })
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007 use braid_format::Kind;
1008
1009 use super::*;
1010
1011 fn id(n: u8) -> ObjectId {
1012 ObjectId::hash(Kind::Blob, &[n])
1013 }
1014
1015 fn op(seq: u64) -> Operation {
1016 Operation {
1017 seq,
1018 time_ms: 1_700_000_000_000 + seq as i64,
1019 agent: format!("agent-{seq}"),
1020 description: "move main".to_owned(),
1021 undoes: (seq > 2).then(|| seq - 2),
1022 updates: vec![
1023 RefUpdate::new("main", Some(id(1)), Some(id(2))),
1024 RefUpdate::new("feature/x", None, Some(id(3))),
1025 RefUpdate::new("old", Some(id(4)), None),
1026 ],
1027 }
1028 }
1029
1030 #[test]
1031 fn records_round_trip() {
1032 for seq in 1..5 {
1033 let op = op(seq);
1034 let bytes = encode_record(&op);
1035 assert_eq!(parse_record(&bytes), Ok((op.clone(), bytes.len() as u64)));
1036 // Trailing bytes belong to the next record.
1037 let mut longer = bytes.clone();
1038 longer.extend_from_slice(b"next");
1039 assert_eq!(parse_record(&longer), Ok((op, bytes.len() as u64)));
1040 }
1041 }
1042
1043 #[test]
1044 fn every_flipped_byte_is_caught() {
1045 let bytes = encode_record(&op(3));
1046 for i in 0..bytes.len() {
1047 let mut damaged = bytes.clone();
1048 damaged[i] ^= 0x04;
1049 assert!(parse_record(&damaged).is_err(), "byte {i}");
1050 }
1051 for len in 0..bytes.len() {
1052 assert_eq!(parse_record(&bytes[..len]), Err(Bad::Torn), "cut at {len}");
1053 }
1054 }
1055
1056 #[test]
1057 fn bad_contents_under_a_valid_checksum_are_damage() {
1058 let reseal = |mut body: Vec<u8>| {
1059 let mut out = MAGIC.to_le_bytes().to_vec();
1060 out.extend_from_slice(&(body.len() as u32).to_le_bytes());
1061 out.append(&mut body);
1062 out.extend_from_slice(&((out.len() + 8) as u32).to_le_bytes());
1063 let crc = crc32c::crc32c(&out);
1064 out.extend_from_slice(&crc.to_le_bytes());
1065 out
1066 };
1067 let good = encode_record(&op(1));
1068 let body = good[8..good.len() - 8].to_vec();
1069 let mut version = body.clone();
1070 version[0] = 9;
1071 assert!(matches!(
1072 parse_record(&reseal(version)),
1073 Err(Bad::Damaged(..))
1074 ));
1075 let mut trailing = body.clone();
1076 trailing.push(0);
1077 assert!(matches!(
1078 parse_record(&reseal(trailing)),
1079 Err(Bad::Damaged(..))
1080 ));
1081 }
1082
1083 #[test]
1084 fn checkpoints_round_trip_and_catch_damage() {
1085 let mut refs = Refs::default();
1086 refs.apply(&op(1));
1087 let state = State {
1088 refs,
1089 end: 1234,
1090 checkpoint: 0,
1091 };
1092 let bytes = encode_checkpoint(&state);
1093 let checkpoint = decode_checkpoint(&bytes).unwrap();
1094 assert_eq!(checkpoint.refs, state.refs);
1095 assert_eq!(checkpoint.end, 1234);
1096 for i in 0..bytes.len() {
1097 let mut damaged = bytes.clone();
1098 damaged[i] ^= 0x80;
1099 assert!(decode_checkpoint(&damaged).is_err(), "byte {i}");
1100 }
1101 }
1102
1103 #[test]
1104 fn ref_names_are_checked() {
1105 assert!(check_ref_name("main").is_ok());
1106 assert!(check_ref_name("").is_err());
1107 assert!(check_ref_name("a\0b").is_err());
1108 assert!(check_ref_name(&"x".repeat(MAX_REF_NAME)).is_ok());
1109 assert!(check_ref_name(&"x".repeat(MAX_REF_NAME + 1)).is_err());
1110 }
1111}