diff --git a/apps/origin-src/src/oplog.rs b/apps/origin-src/src/oplog.rs index 67558010..955996f2 100644 --- a/apps/origin-src/src/oplog.rs +++ b/apps/origin-src/src/oplog.rs @@ -15,6 +15,7 @@ //! ```text //! .origin/oplog/ //! lock held exclusively while appending +//! writers/ held by each writer while it writes //! segments of entries, 16 hex digits each //! ``` //! @@ -23,10 +24,28 @@ //! oldest segments are deleted beyond a cap: the log keeps the latest 16 MiB //! of entries, and a cursor older than that has expired. //! -//! **Writing.** Each write appends its entries ([`Store::commit_logged`]) -//! just before it's committed, and they're synced with it -//! ([`DurableWrite::sync_with`]): records and waiting landings with their -//! files, and a target's head with its new acceptance. +//! **Writing.** Every entry must be durable before a reader moves past it: +//! a power loss could drop it otherwise, and the next entry would take its +//! sequence number, behind a cursor already handed out. Each write appends +//! its entries as a writer ([`Store::commit_logged`]): a lock file, +//! `writers/`, `n` being the sequence number of its first entry, which +//! every entry names, and which is created and locked before that entry is +//! appended. The entries are appended just before the write is committed, +//! and synced with it ([`DurableWrite::sync_with`]): records and waiting +//! landings with their files, and a target's head with its new acceptance. +//! Once the write is published, the writer removes its lock file. +//! +//! **Reading.** Readers read up to the entry before the first one whose +//! writer still holds its lock ([`OpLog::settled`]): every entry up to there +//! is durable, and its write as published as it will ever be. A crash can +//! leave an entry in the log whose write wasn't published, or only partly: +//! some of a batch's records were published, or none; an acceptance was +//! written but the target's head didn't move to it (the next landing on the +//! target publishes it, and logs the acceptance again); a waiting landing +//! wasn't kept. Its writer's lock file is then left behind, unlocked: +//! readers sync the segments holding its entries, which may not be durable, +//! remove the file, and take the entries' effects as what they find +//! published. So a crashed writer holds nothing back. //! //! **Partial appends.** A crash in the middle of an append leaves part of a //! frame at the end of the last segment. It never was an entry: readers @@ -86,6 +105,46 @@ impl Actor { } } +/// A writer of the op log, whose lock file readers wait on while its write +/// is in progress, as the module explains. It's done once dropped. +#[derive(Debug, Default)] +pub(crate) struct LogWriter(Option); + +/// The lock file of a writer that appended an entry. +#[derive(Debug)] +struct Held { + path: PathBuf, + /// The sequence number of its first entry, which names the lock file. + first: u64, + _lock: LockedFile, + /// The segments it appended to, which its write syncs. + segments: Vec, + /// Whether the write committed, and synced them. + synced: bool, +} + +impl Drop for Held { + /// Removes the lock file, unless the entries may not be durable: the + /// file then stays for readers to sync them, as for a writer that + /// crashed. + fn drop(&mut self) { + if self.synced { + // Best effort: readers remove a file left behind. + let _ = fs::remove_file(&self.path); + } + } +} + +/// What a writer's lock file says. +enum WriterState { + /// Its writes are in progress. + Writing, + /// It's done. + Done, + /// It crashed: its file is left, unlocked. + Crashed, +} + /// Entries read from the op log, oldest first. #[derive(Debug, Default)] pub struct Read { @@ -100,6 +159,8 @@ pub struct Entry { pub seq: u64, /// The operation it belongs to: its first entry's sequence number. pub op: u64, + /// Its writer: the sequence number of the writer's first entry. + pub writer: u64, /// The root of the workspace it came from, if any. pub workspace: Option, /// The command that appended it, such as `land 3fa2`. @@ -137,12 +198,13 @@ impl Entry { const WAITING: u8 = 2; const ADVANCED: u8 = 4; - /// Encodes the entry's frame: its sequence number, operation, workspace - /// and command, then a tag and the effect's fields. + /// Encodes the entry's frame: its sequence number, operation, writer, + /// workspace and command, then a tag and the effect's fields. fn encode(&self) -> Vec { Frames::frame(|out| { out.u64(self.seq); out.u64(self.op); + out.u64(self.writer); match &self.workspace { None => out.u8(0), Some(root) => { @@ -159,6 +221,7 @@ impl Entry { let mut reader = Reader::new(payload); let seq = reader.u64()?; let op = reader.u64()?; + let writer = reader.u64()?; let workspace = reader.option(|reader| Ok(PathBuf::from(OsStr::from_bytes(reader.prefixed()?))))?; let command = reader.prefixed_str()?.to_owned(); @@ -167,6 +230,7 @@ impl Entry { Ok(Self { seq, op, + writer, workspace, command, effect, @@ -261,6 +325,9 @@ impl<'a, P: Platform> OpLog<'a, P> { /// The lock held while appending. const APPENDING: &str = "lock"; + /// The directory of the writers' lock files. + const WRITERS: &str = "writers"; + /// The op log of `store`. pub fn new(store: &'a Store

) -> Self { Self { store } @@ -274,12 +341,12 @@ impl<'a, P: Platform> OpLog<'a, P> { self.dir().join(format!("{first:016x}")) } - /// Creates the log's directory and first segment, durably, so the first - /// entry costs no more than the next. Repositories made before the op - /// log existed get them with their first entry. + /// Creates the log's directories and first segment, durably, so the + /// first entry costs no more than the next. Repositories made before the + /// op log existed get them with their first entry. pub(crate) fn init(&self) -> Result<(), StoreError> { - let dir = self.dir(); - fs::create_dir_all(&dir).map_err(|source| StoreError::io(&dir, source))?; + let writers = self.dir().join(Self::WRITERS); + fs::create_dir_all(&writers).map_err(|source| StoreError::io(&writers, source))?; self.start_segment(1, &[])?; Ok(()) } @@ -408,6 +475,91 @@ impl<'a, P: Platform> OpLog<'a, P> { Ok(read) } + /// The sequence number of the latest entry up to which every entry is + /// settled: its writer is done, or crashed and its entries were synced, + /// so each is durable, and its write as published as it will ever be. + /// Readers never move past it. + /// + /// # Errors + /// + /// Fails if the log or a writer's lock file cannot be read, or a crashed + /// writer's entries cannot be synced. + pub fn settled(&self) -> Result { + // Read first: a writer's lock file exists, locked, before its + // first entry does. + let last = self.last_seq()?; + let dir = self.dir().join(Self::WRITERS); + let names = match fs::read_dir(&dir) { + Ok(names) => names, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(last), + Err(source) => return Err(StoreError::io(&dir, source)), + }; + let mut settled = last; + for name in names { + let name = name + .map_err(|source| StoreError::io(&dir, source))? + .file_name(); + let Some(first) = name.to_str().and_then(|name| name.parse::().ok()) else { + continue; + }; + if first > last { + continue; + } + match self.writer_state(first)? { + WriterState::Writing => settled = settled.min(first - 1), + WriterState::Done => {} + WriterState::Crashed => self.sync_crashed(first)?, + } + } + Ok(settled) + } + + /// The state of the writer whose first entry is `first`. + fn writer_state(&self, first: u64) -> Result { + let path = self.writer_path(first); + let file = match File::open(&path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(WriterState::Done), + Err(source) => return Err(StoreError::io(&path, source)), + }; + let free = self + .store + .platform + .try_lock(&file, LockMode::Exclusive) + .map_err(|source| StoreError::io(&path, source))?; + Ok(if free { + WriterState::Crashed + } else { + WriterState::Writing + }) + } + + /// Syncs the segments that may hold entries of the crashed writer whose + /// first entry is `first`, then removes its lock file. + fn sync_crashed(&self, first: u64) -> Result<(), StoreError> { + let segments = self.segments()?; + let holding = segments + .partition_point(|&start| start <= first) + .saturating_sub(1); + for &start in &segments[holding..] { + let path = self.segment(start); + File::open(&path) + .and_then(|file| self.store.platform.sync_file(&file)) + .map_err(|source| StoreError::io(&path, source))?; + } + let path = self.writer_path(first); + match fs::remove_file(&path) { + Err(error) if error.kind() != io::ErrorKind::NotFound => { + Err(StoreError::io(&path, error)) + } + _ => Ok(()), + } + } + + fn writer_path(&self, first: u64) -> PathBuf { + self.dir().join(Self::WRITERS).join(first.to_string()) + } + /// Every entry the log keeps, newest first, read a segment at a time. /// /// # Errors @@ -433,9 +585,9 @@ impl<'a, P: Platform> OpLog<'a, P> { })) } - /// Appends an entry for `effect`, as the store's actor, without syncing - /// it, returning its sequence number and the segment it's in. - fn append(&self, effect: &Effect) -> Result<(u64, PathBuf), StoreError> { + /// Appends an entry for `effect`, as the store's actor, by `writer`, + /// without syncing it, returning its sequence number. + fn append(&self, writer: &mut LogWriter, effect: &Effect) -> Result { let _lock = self.lock(Self::APPENDING, LockMode::Exclusive)?; let segments = self.segments()?; let (seq, open) = match segments.last() { @@ -446,10 +598,15 @@ impl<'a, P: Platform> OpLog<'a, P> { Some(segment) => segment, None => self.start_segment(seq, &segments)?, }; + let held = match &mut writer.0 { + Some(held) => held, + None => writer.0.insert(self.hold(seq)?), + }; let actor = &self.store.actor; let entry = Entry { seq, op: actor.op.get().copied().unwrap_or(seq), + writer: held.first, workspace: actor.workspace.clone(), command: actor.command.clone(), effect: effect.clone(), @@ -457,8 +614,40 @@ impl<'a, P: Platform> OpLog<'a, P> { Self::FRAMES .append(&self.store.platform, &segment.file, &entry.encode()) .map_err(|source| StoreError::io(&segment.path, source))?; + if !held.segments.contains(&segment.path) { + held.segments.push(segment.path); + } actor.op.get_or_init(|| seq); - Ok((seq, segment.path)) + Ok(seq) + } + + /// Appends an entry for `effect` whose write stays in progress until + /// the writer returned is dropped, which is then as if it crashed. + #[cfg(test)] + pub(crate) fn append_in_progress( + &self, + effect: &Effect, + ) -> Result<(u64, LogWriter), StoreError> { + let mut writer = LogWriter::default(); + let seq = self.append(&mut writer, effect)?; + Ok((seq, writer)) + } + + /// Creates and locks the lock file of a writer whose first entry is + /// `first`, about to be appended. A writer that crashed before + /// appending it may have left the file, unlocked. + fn hold(&self, first: u64) -> Result { + let path = self.writer_path(first); + let dir = self.dir().join(Self::WRITERS); + fs::create_dir_all(&dir).map_err(|source| StoreError::io(&dir, source))?; + let lock = LockedFile::open(&self.store.platform, &path, LockMode::Exclusive)?; + Ok(Held { + path, + first, + _lock: lock, + segments: Vec::new(), + synced: false, + }) } /// The next sequence number after the last segment, which starts at @@ -538,7 +727,8 @@ impl Store

{ } /// Commits `write`, logging `effects` as entries synced with it, at no - /// extra sync, returning the last entry's sequence number. + /// extra sync, returning the last entry's sequence number. Readers wait + /// for them until the write is published, as the module explains. /// /// # Errors /// @@ -548,19 +738,20 @@ impl Store

{ write: DurableWrite<'_, P>, effects: &[Effect], ) -> Result { + let mut writer = LogWriter::default(); let mut seq = 0; - let mut segments = Vec::new(); for effect in effects { - let (appended, segment) = self.oplog().append(effect)?; - seq = appended; - if !segments.contains(&segment) { - segments.push(segment); - } + seq = self.oplog().append(&mut writer, effect)?; } - for segment in &segments { - write.sync_with(segment); + if let Some(held) = &writer.0 { + for segment in &held.segments { + write.sync_with(segment); + } } write.commit()?; + if let Some(held) = &mut writer.0 { + held.synced = true; + } Ok(seq) } } @@ -623,6 +814,7 @@ mod tests { let entry = Entry { seq, op: 1, + writer: 1, workspace: (seq % 2 == 0).then(|| PathBuf::from("/work/ws")), command: "land 3fa2".to_owned(), effect, @@ -682,6 +874,7 @@ mod tests { let frame = Entry { seq: 2, op: 2, + writer: 2, workspace: None, command: String::new(), effect: wrote(2), @@ -693,6 +886,35 @@ mod tests { assert_eq!(oplog.after(0).unwrap().entries.len(), 2); } + #[test] + fn readers_wait_for_writers_and_sync_past_crashed_ones() { + let (_dir, store) = store(); + let oplog = store.oplog(); + log(&store, &wrote(1)); + // A write in progress: its entry is appended, not yet committed. + let (seq, writing) = oplog.append_in_progress(&wrote(2)).unwrap(); + log(&store, &wrote(3)); + assert_eq!(oplog.last_seq().unwrap(), 3); + assert_eq!(oplog.settled().unwrap(), seq - 1, "readers wait for it"); + + // It crashes: its lock is free, its file left. + drop(writing); + let left = oplog.writer_path(seq); + assert!(left.exists()); + assert_eq!(oplog.settled().unwrap(), 3, "nothing waits for it"); + assert!( + !left.exists(), + "its entries are synced, and its file removed" + ); + assert_eq!( + fs::read_dir(oplog.dir().join(OpLog::::WRITERS)) + .unwrap() + .count(), + 0, + "done writers leave nothing behind" + ); + } + #[test] fn readers_never_find_a_segment_without_its_header() { let (_dir, store) = store();