From 61e8d1b95d57bed588d4591e50cefb3737a45d00 Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 23 Nov 2026 13:57:30 +0100 Subject: [PATCH] feat(store): delete objects and remember when they were stored Nothing could delete an object, and nothing knew how long one had been stored. `Store::remove` deletes objects durably, loose and packed: each pack holding one is rewritten into a single new pack without them (`Store::remove_packed`, which shares `replace_packs` with compaction). `Store::stored_at` says when this node stored an object: its loose file's modification time, which pack indexes now record for each object so packing never resets it. Deleting must never race a writer that found an object already stored and skipped writing it. Such writers hold the store's objects (`Store::hold_objects`, a shared lock) from finding the object to writing what refers to it, as issuing a statement and snapshotting the working copy do. A collector takes the lock exclusively (`Store::lock_for_collection`), and a batch rereads the pack manifest before it trusts a pack to hold an object (`Batch::packed`), since a collection may have rewritten that pack without it. `Store::reach` finds every object some trees refer to, which a collector keeps. --- apps/origin-src/src/annotations/mod.rs | 7 +- apps/origin-src/src/annotations/promotion.rs | 5 +- apps/origin-src/src/queue/session.rs | 5 +- apps/origin-src/src/store/mod.rs | 128 +++++++++- apps/origin-src/src/store/packs.rs | 236 ++++++++++++++----- apps/origin-src/src/tree.rs | 43 +++- apps/origin-src/src/workspace/mod.rs | 7 +- 7 files changed, 355 insertions(+), 76 deletions(-) diff --git a/apps/origin-src/src/annotations/mod.rs b/apps/origin-src/src/annotations/mod.rs index 2d38a539..fc94dd39 100644 --- a/apps/origin-src/src/annotations/mod.rs +++ b/apps/origin-src/src/annotations/mod.rs @@ -141,13 +141,16 @@ impl<'a, P: Platform> Annotations<'a, P> { Ok((id, statement)) } - /// Writes a statement after its payload, which is durable before - /// anything refers to it. + /// Writes `payload`, then `statement`, and returns the statement's id. The + /// payload is durable before anything refers to it. It holds objects while + /// writing, so garbage collection cannot delete the payload before the + /// statement refers to it. fn write( &self, statement: &Statement, payload: Option, ) -> Result { + let _held = self.store.hold_objects()?; if let Some(payload) = payload { self.store.write_all(&[payload])?; } diff --git a/apps/origin-src/src/annotations/promotion.rs b/apps/origin-src/src/annotations/promotion.rs index b9bf1620..251d881a 100644 --- a/apps/origin-src/src/annotations/promotion.rs +++ b/apps/origin-src/src/annotations/promotion.rs @@ -206,7 +206,9 @@ impl Annotations<'_, P> { } /// Issues the [`promotions`](Self::promotions) to `subject` as `issuer` and - /// returns them. + /// returns them. A promotion refers to its original's payload without + /// writing it, so this [holds the objects](Store::hold_objects) from + /// finding the originals until the promotions are written. /// /// # Errors /// @@ -217,6 +219,7 @@ impl Annotations<'_, P> { subject: RecordId, issuer: &Principal, ) -> Result, StoreError> { + let _held = self.store.hold_objects()?; let promotions = self.promotions(subject, issuer)?; let encoded: Vec<_> = promotions.iter().map(Statement::encode).collect(); self.store.write_all(&encoded)?; diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index 72894294..24f3b3c8 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -190,9 +190,12 @@ impl Session<'_, '_, P> { /// Checks the policy for `candidate`, and lands it if its evidence is there /// or else keeps it waiting. Writes the records in layers, each durable /// before the next refers to it: the trees, then the rebased revision, then - /// the promoted statements and the acceptance. + /// the promoted statements and the acceptance. It [holds the + /// objects](Store::hold_objects) throughout, because the promotions refer + /// to their originals' payloads without writing them. pub(super) fn submit(&mut self, candidate: Candidate) -> Result { let store = self.queue.store; + let _held = store.hold_objects()?; if !candidate.trees.is_empty() { store.write_all(&candidate.trees)?; } diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 1318e04e..2a0a56cf 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -19,6 +19,7 @@ //! Committing a batch also indexes its new records (see //! [`index`](crate::index)). +use std::collections::BTreeSet; use std::fs; use std::io; use std::num::NonZero; @@ -26,9 +27,9 @@ use std::panic; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, PoisonError}; use std::thread; -use std::time::Duration; +use std::time::{Duration, SystemTime}; -use origin_platform::{DurableWrite, Native, Platform, WritableError}; +use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform, WritableError}; use origin_shared::object::{DecodeError, IdMismatch}; use origin_shared::{EncodedObject, ObjectId, TargetName, TypedId}; @@ -199,6 +200,7 @@ impl Store

{ store: self, write: self.durable_write(), entries: Mutex::default(), + manifest_read: Mutex::default(), } } @@ -297,6 +299,90 @@ impl Store

{ Ok(self.path(id).exists() || self.find_packed(id)?.is_some()) } + /// Returns when this node stored the object: when its loose file was + /// written. Packing keeps that time. + /// + /// # Errors + /// + /// Fails if the store doesn't have the object or its file cannot be + /// inspected. + pub fn stored_at(&self, id: ObjectId) -> Result { + let path = self.path(id); + match fs::metadata(&path).and_then(|metadata| metadata.modified()) { + // Compaction may have moved it into a pack. + Err(error) if error.kind() == io::ErrorKind::NotFound => { + let (_, location) = self.find_packed(id)?.ok_or(StoreError::NotFound(id))?; + Ok(location.stored()) + } + result => result.map_err(|source| StoreError::io(&path, source)), + } + } + + /// The lock file that keeps garbage collection and writers apart. + const COLLECTION_LOCK: &str = "objects/collection"; + + /// Takes a shared lock that stops garbage collection from deleting objects + /// while it is held. Any number of writers can hold it at once. A writer + /// that may skip writing an object because it is already stored must hold + /// it until the records referring to that object are written. + /// + /// # Errors + /// + /// Fails if the lock file cannot be opened. + pub fn hold_objects(&self) -> Result { + let path = self.root.join(Self::COLLECTION_LOCK); + Ok(LockedFile::open(&self.platform, &path, LockMode::Shared)?) + } + + /// Takes the exclusive lock for garbage collection: waits for the writers + /// holding [`Store::hold_objects`], and blocks new ones while held. Garbage + /// collection holds it while it finds unreferenced objects and deletes + /// them. + /// + /// # Errors + /// + /// Fails if the lock file cannot be opened. + pub fn lock_for_collection(&self) -> Result { + let path = self.root.join(Self::COLLECTION_LOCK); + Ok(LockedFile::open( + &self.platform, + &path, + LockMode::Exclusive, + )?) + } + + /// Deletes objects durably, loose and packed, and returns how many bytes + /// that freed. Only garbage collection calls it, for objects nothing refers + /// to, while holding [`Store::lock_for_collection`]. + /// + /// # Errors + /// + /// Fails if an object cannot be removed, its directory synced, or its pack + /// rewritten. + pub fn remove(&self, ids: &[ObjectId]) -> Result { + let mut freed = self.remove_packed(&ids.iter().copied().collect())?; + let mut dirs = BTreeSet::new(); + for &id in ids { + let path = self.path(id); + let removed = fs::symlink_metadata(&path).and_then(|metadata| { + fs::remove_file(&path)?; + Ok(metadata.len()) + }); + match removed { + Ok(len) => freed += len, + Err(error) if error.kind() == io::ErrorKind::NotFound => continue, + Err(source) => return Err(StoreError::io(&path, source)), + } + let mut shard = path; + shard.pop(); + dirs.insert(shard); + } + for dir in dirs { + self.sync_dir(&dir)?; + } + Ok(freed) + } + /// Reads an object, or `None` if the store does not have it. /// /// # Errors @@ -393,18 +479,21 @@ pub struct Batch<'a, P> { write: DurableWrite<'a, P>, /// What the index keeps of each new record staged. entries: Mutex>, + /// Whether the batch has read the pack manifest. It reads it before it + /// first trusts a pack to hold an object (see [`Batch::packed`]). + manifest_read: Mutex, } impl Batch<'_, P> { - /// Stages an object, unless the store already has it, returning whether - /// it was new. Either way, it is durable once the batch commits. Packs - /// are only checked as last loaded: an object packed since is staged - /// again, and the next compaction removes the copy. + /// Stages an object unless the store already has it, and returns whether it + /// was new. Either way, the object is durable once the batch commits. An + /// object packed since the packs were last loaded is staged again; the next + /// compaction removes the extra copy. /// /// # Errors /// - /// Fails if the object is a record that doesn't decode, or if it cannot - /// be compressed or written. + /// Fails if the object is a record that doesn't decode, or if it cannot be + /// compressed or written. pub fn write(&self, object: &EncodedObject) -> Result { let id = object.id(); let path = self.store.path(id); @@ -416,7 +505,7 @@ impl Batch<'_, P> { self.write.sync_dir_with(shard); return Ok(false); } - if self.store.packs.find(id).is_some() { + if self.packed(id)? { // The manifest naming its pack may not be durable yet. self.write.sync_dir_with(self.store.packs_dir()); return Ok(false); @@ -434,6 +523,26 @@ impl Batch<'_, P> { Ok(true) } + /// Whether a pack holds `id`, according to a manifest read since the batch + /// started. It reloads the manifest the first time, since garbage + /// collection may have rewritten a pack without the object, and a writer + /// must never skip an object that is gone. + fn packed(&self, id: ObjectId) -> Result { + // A miss only stages the object again, so it needs no fresh read. + if self.store.packs.find(id).is_none() { + return Ok(false); + } + let mut read = self + .manifest_read + .lock() + .unwrap_or_else(PoisonError::into_inner); + if !*read { + self.store.reload_packs()?; + *read = true; + } + Ok(self.store.packs.find(id).is_some()) + } + /// Stages each of `objects` in turn, returning how many were new. fn write_all(&self, objects: &[EncodedObject]) -> Result { objects.iter().try_fold(0, |written, object| { @@ -537,7 +646,6 @@ pub(crate) mod tests { use std::fs::File; use std::slice; use std::sync::Mutex; - use std::time::SystemTime; use origin_platform::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, ReadAt}; diff --git a/apps/origin-src/src/store/packs.rs b/apps/origin-src/src/store/packs.rs index fad279af..10fa08e2 100644 --- a/apps/origin-src/src/store/packs.rs +++ b/apps/origin-src/src/store/packs.rs @@ -1,47 +1,48 @@ -//! Pack files: small objects gathered into a few large files, so a store of -//! a million statements holds a handful of files rather than a million. +//! Pack files: many small objects stored together in a few large files, so +//! a store of a million statements holds a handful of files instead of a +//! million. //! //! `objects/packs/` holds: //! //! - `.pack`: [`Pack::MAGIC`], then each object as the `u32` length of -//! its compressed encoding and the encoding, compressed as in a loose -//! file. A pack can be read on its own, start to end. -//! - `.idx`: [`Pack::INDEX_MAGIC`], the ids of the pack's objects in -//! ascending order, then where each one's compressed encoding is in the -//! pack: a `u64` offset and a `u32` length. The pack's id is the hash of -//! its object ids, which opening the pack verifies. -//! - `manifest`: the ids of the packs in use, one per line in hex, largest -//! pack first. Replacing it publishes and retires packs at once. -//! - `lock`: held by the compactor, so only one ever runs. +//! its compressed encoding followed by the encoding, compressed as in a +//! loose file. A pack can be read on its own, from start to end. +//! - `.idx`: [`Pack::INDEX_MAGIC`], the pack's object ids in ascending +//! order, then for each object a `u64` offset and a `u32` length of its +//! compressed encoding in the pack, and a `u64` time in seconds since the +//! Unix epoch: when this node stored the object (the modification time of +//! its loose file). The pack's id is the hash of its object ids; opening +//! the pack checks it. +//! - `manifest`: the ids of the packs in use, one hex id per line, largest +//! first. Replacing this file adds and retires packs in one step. +//! - `lock`: held by the compactor, so only one runs at a time. //! //! Integers are little endian. //! //! [`Store::compact`] gathers the small loose objects into a new pack, and -//! merges into it every pack smaller than twice what it holds so far, so a -//! store keeps a logarithmic number of packs and an object is rewritten a -//! logarithmic number of times. It writes the pack and its index durably, -//! then the manifest, and only then removes the loose files and the packs -//! it merged. A crash loses nothing: until the manifest is published, every -//! object is still where it was, and the next compaction removes the files -//! the manifest doesn't name. +//! merges into it every pack smaller than twice what the new pack holds so +//! far. A store thus keeps a logarithmic number of packs, and each object is +//! rewritten a logarithmic number of times. Compaction writes the pack and +//! its index durably, then the manifest, and only then removes the loose +//! files and the merged packs. A crash loses nothing: the next compaction +//! removes the files the manifest does not name. //! -//! [`Store::compact_if_due`] compacts once enough loose objects pile up, -//! for a long-running process to call as it writes. +//! [`Store::compact_if_due`] compacts once enough loose objects pile up. A +//! long-running process calls it as it writes. //! //! Readers look in the packs they loaded last, and reload the manifest when -//! an object isn't there. An object in neither the loose objects nor the -//! current manifest's packs is not in the store, since a pack is published -//! before what it replaces is removed. A pack stays readable once opened, -//! even after it's retired, because an open file outlives its name, so -//! readers also reload the manifest every few seconds, to let go of the -//! packs it no longer names. +//! an object is not there. An object that is neither loose nor in the +//! current manifest's packs is not in the store. An open pack stays readable +//! after it is retired, so readers also reload the manifest every few +//! seconds to close the packs it no longer names. +use std::collections::HashSet; use std::fmt; use std::fs::{self, File}; -use std::io; +use std::io::{self, Read}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, PoisonError, RwLock}; -use std::time::{Duration, Instant}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use origin_platform::{LockMode, LockedFile, Platform, ReadAt}; use origin_shared::{Digest, ObjectId}; @@ -107,29 +108,41 @@ pub(super) struct Pack { index: Vec, } -/// Where a compressed encoding is in a pack. +/// Where an object's compressed encoding is in a pack, and when this node +/// stored the object. Packing keeps that time so retention counts from the +/// first write. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Location { offset: u64, len: u32, + /// Seconds since the Unix epoch. + stored: u64, } impl Location { /// The length of an encoded location. - const LEN: usize = 8 + 4; + const LEN: usize = 8 + 4 + 8; fn encode(self, out: &mut Vec) { out.extend_from_slice(&self.offset.to_le_bytes()); out.extend_from_slice(&self.len.to_le_bytes()); + out.extend_from_slice(&self.stored.to_le_bytes()); } fn decode(bytes: &[u8; Self::LEN]) -> Self { - let (offset, len) = bytes.split_at(8); + let (offset, rest) = bytes.split_at(8); + let (len, stored) = rest.split_at(4); Self { offset: u64::from_le_bytes(offset.try_into().expect("8 bytes")), len: u32::from_le_bytes(len.try_into().expect("4 bytes")), + stored: u64::from_le_bytes(stored.try_into().expect("8 bytes")), } } + + /// Returns when this node stored the object. + pub(super) fn stored(self) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(self.stored) + } } impl Pack { @@ -324,7 +337,7 @@ impl Store

{ } /// Loads the manifest's packs, unless they're already loaded. - fn reload_packs(&self) -> Result<(), StoreError> { + pub(super) fn reload_packs(&self) -> Result<(), StoreError> { let dir = self.packs_dir(); let path = dir.join(Self::MANIFEST); let mut missing_from = None; @@ -489,32 +502,85 @@ impl Store

{ } sources.sort_unstable_by_key(|&(id, _)| id); sources.dedup_by_key(|&mut (id, _)| id); - let id = self.write_pack(&dir, &sources, merged)?; + self.replace_packs(&dir, kept, merged, &sources)?; + + // Everything below is published in the new pack. A crash before + // these files are gone leaves duplicates for the next compaction. + Self::on_every_core(&loose, |ids| { + ids.iter() + .try_for_each(|&id| Self::remove_file(&self.path(id))) + }) + .into_iter() + .collect::>()?; + compaction.packed = loose.len(); + compaction.merged = merged.len(); + Ok(Some(compaction)) + } + /// Removes `ids` from the packs: every pack that holds one is rewritten, + /// without them, into a single new pack. Returns the bytes of compressed + /// encodings that freed. Waits for any running compaction. + /// + /// # Errors + /// + /// Fails like [`Store::compact`]. + pub(super) fn remove_packed(&self, ids: &HashSet) -> Result { + let dir = self.packs_dir(); + let _lock = LockedFile::open(&self.platform, &dir.join(Self::LOCK), LockMode::Exclusive)?; + self.reload_packs()?; + let (rewritten, kept): (Vec<_>, Vec<_>) = self + .packs + .loaded() + .into_iter() + .partition(|pack| pack.entries().any(|(id, _)| ids.contains(&id))); + if rewritten.is_empty() { + return Ok(0); + } + let mut freed = 0; + let mut sources = Vec::new(); + for (position, pack) in rewritten.iter().enumerate() { + for (id, location) in pack.entries() { + if ids.contains(&id) { + freed += u64::from(location.len); + } else { + sources.push((id, Source::Packed(position, location))); + } + } + } + sources.sort_unstable_by_key(|&(id, _)| id); + sources.dedup_by_key(|&mut (id, _)| id); + self.replace_packs(&dir, &kept, &rewritten, &sources)?; + Ok(freed) + } + + /// Publishes a manifest naming `kept` and a new pack of `sources` sorted by + /// id (if there are any), then removes the files of `retired`. The caller + /// must hold the compactor's lock. + fn replace_packs( + &self, + dir: &Path, + kept: &[Arc], + retired: &[Arc], + sources: &[(ObjectId, Source)], + ) -> Result<(), StoreError> { let mut manifest: Vec<_> = kept.iter().map(|pack| (pack.len(), pack.id)).collect(); - manifest.push((sources.len(), id)); + if !sources.is_empty() { + manifest.push((sources.len(), self.write_pack(dir, sources, retired)?)); + } manifest.sort_by_key(|&(len, _)| std::cmp::Reverse(len)); let manifest: String = manifest.iter().map(|(_, id)| id.to_hex() + "\n").collect(); let write = self.durable_write(); write.stage(dir.join(Self::MANIFEST), manifest.as_bytes())?; write.commit()?; self.reload_packs()?; - - // Everything below is published in the new pack. A crash before - // these files are gone leaves duplicates for the next compaction. - for pack in merged { + // A crash before these files are gone leaves them for the next + // compaction. + for pack in retired { for extension in ["idx", "pack"] { - Self::remove(&Pack::file_path(&dir, pack.id, extension))?; + Self::remove_file(&Pack::file_path(dir, pack.id, extension))?; } } - Self::on_every_core(&loose, |ids| { - ids.iter().try_for_each(|&id| Self::remove(&self.path(id))) - }) - .into_iter() - .collect::>()?; - compaction.packed = loose.len(); - compaction.merged = merged.len(); - Ok(Some(compaction)) + Ok(()) } /// Writes a pack of `sources`, sorted by id, and its index, durably, @@ -544,11 +610,16 @@ impl Store

{ .collect::, _>>() }); for read in read { - for (len, bytes) in read? { + for (len, stored, bytes) in read? { file.write_all(&len.to_le_bytes())?; file.write_all(&bytes)?; offset += 4; - Location { offset, len }.encode(&mut index); + Location { + offset, + len, + stored, + } + .encode(&mut index); offset += u64::from(len); } } @@ -560,24 +631,36 @@ impl Store

{ Ok(id) } - /// Reads the compressed encoding of `id` from `source`, and its length. + /// Reads the compressed encoding of `id` from `source`. Returns it with its + /// length and when this node stored it, in seconds since the Unix epoch. fn read_source( &self, id: ObjectId, source: Source, merged: &[Arc], - ) -> Result<(u32, Vec), StoreError> { + ) -> Result<(u32, u64, Vec), StoreError> { match source { Source::Loose => { let path = self.path(id); - let bytes = fs::read(&path).map_err(|source| StoreError::io(&path, source))?; + let io_error = |source| StoreError::io(&path, source); + let mut file = File::open(&path).map_err(io_error)?; + let modified = file.metadata().and_then(|metadata| metadata.modified()); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).map_err(io_error)?; let len = u32::try_from(bytes.len()) - .map_err(|_| StoreError::io(&path, io::ErrorKind::FileTooLarge.into()))?; - Ok((len, bytes)) - } - Source::Packed(pack, location) => { - Ok((location.len, merged[pack].read(&self.platform, location)?)) + .map_err(|_| io_error(io::ErrorKind::FileTooLarge.into()))?; + // A time before the epoch counts as the epoch. + let stored = modified + .map_err(io_error)? + .duration_since(UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + Ok((len, stored, bytes)) } + Source::Packed(pack, location) => Ok(( + location.len, + location.stored, + merged[pack].read(&self.platform, location)?, + )), } } @@ -593,7 +676,7 @@ impl Store

{ for entry in fs::read_dir(dir).map_err(|source| StoreError::io(dir, source))? { let entry = entry.map_err(|source| StoreError::io(dir, source))?; if !keep.iter().any(|name| entry.file_name() == name.as_str()) { - Self::remove(&entry.path())?; + Self::remove_file(&entry.path())?; } } Ok(()) @@ -623,7 +706,7 @@ impl Store

{ continue; }; if packs.iter().any(|pack| pack.find(id).is_some()) { - Self::remove(&entry.path())?; + Self::remove_file(&entry.path())?; duplicates += 1; } else if entry.metadata().map_err(io_error)?.len() <= Self::PACKED_MAX { small.push(id); @@ -642,7 +725,7 @@ impl Store

{ } /// Removes a file, unless it's already gone. - fn remove(path: &Path) -> Result<(), StoreError> { + fn remove_file(path: &Path) -> Result<(), StoreError> { match fs::remove_file(path) { Err(error) if error.kind() != io::ErrorKind::NotFound => { Err(StoreError::io(path, error)) @@ -826,6 +909,39 @@ mod tests { ); } + #[test] + fn removes_packed_objects_and_keeps_when_each_was_stored() { + let (_dir, store) = store(); + let first = objects(0, 10); + store.write_all(&first).unwrap(); + let secs = |id| { + store + .stored_at(id) + .unwrap() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() + }; + let stored = secs(first[0].id()); + store.compact().unwrap(); + store.write_all(&objects(10, 10)).unwrap(); + assert_eq!(store.compact().unwrap().unwrap().merged, 1); + assert_eq!(secs(first[0].id()), stored, "packing keeps it, merging too"); + + let loose = EncodedObject::blob(b"loose"); + store.write_all(slice::from_ref(&loose)).unwrap(); + let doomed = [first[0].id(), first[1].id(), loose.id()]; + assert!(store.remove(&doomed).unwrap() > 0); + let fresh = Store::new(&store.root, Native::default()); + for id in doomed { + assert!(!fresh.contains(id).unwrap(), "{id}"); + } + assert_readable(&fresh, &first[2..]); + assert_readable(&fresh, &objects(10, 10)); + assert_eq!(pack_files(&store).len(), 4, "the old pack is removed"); + assert_eq!(store.remove(&doomed).unwrap(), 0, "already gone"); + } + #[test] fn unreadable_objects_fail_the_compaction() { let (_dir, store) = store(); diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index cc59b90d..7aecc8b6 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -1,7 +1,7 @@ //! Comparing trees, merging them, and looking up what they hold. -use std::collections::HashMap; use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; use origin_platform::Platform; use origin_shared::{ @@ -397,6 +397,42 @@ impl<'a, P: Platform> Snapshots<'a, P> { } } +impl Store

{ + /// Adds to `reached` every object the trees `roots` reach: the trees + /// themselves, their subtrees and their files. Trees already in `reached` + /// are not read again, and trees the store doesn't have (as after a lazy + /// clone) are skipped. + /// + /// # Errors + /// + /// Fails if a tree cannot be read. + pub fn reach( + &self, + roots: impl IntoIterator, + reached: &mut HashSet, + ) -> Result<(), StoreError> { + let mut pending: Vec = roots.into_iter().collect(); + while let Some(id) = pending.pop() { + if !reached.insert(id.into()) { + continue; + } + let tree: Tree = match self.get(id) { + Err(StoreError::NotFound(_)) => continue, + tree => tree?, + }; + for (_, entry) in &tree { + match entry.subtree() { + Some(subtree) => pending.push(subtree), + None => { + reached.insert(entry.id); + } + } + } + } + Ok(()) + } +} + #[cfg(test)] pub(crate) mod tests { use std::collections::BTreeMap; @@ -655,5 +691,10 @@ pub(crate) mod tests { for missing in ["nope", "src/nope", "README/inside"] { assert_eq!(at(missing), None, "{missing}"); } + + let mut reached = HashSet::new(); + store.reach([root], &mut reached).unwrap(); + assert_eq!(reached.len(), 4, "two trees and two files"); + assert!(reached.contains(&file("lib").id)); } } diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 798f744b..099a61d0 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -27,7 +27,7 @@ use std::fs; use std::io; use std::path::{self, Path, PathBuf}; -use origin_platform::Native; +use origin_platform::{LockedFile, Native}; use origin_shared::{ AcceptanceId, Base, BlobId, ChangeId, EncodedObject, Kind, NodePublicKey, Principal, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetId, TargetName, @@ -67,6 +67,9 @@ struct WorkingCopy { unsaved: Option, /// The revision's unresolved conflicts that the files still have. conflicts: Conflicts, + /// Keeps garbage collection from removing the objects the snapshot found, until + /// the command that saves the snapshot is done. + _held: LockedFile, } impl WorkingCopy { @@ -202,6 +205,7 @@ impl Workspace { /// Snapshots the working copy into a draft, recording nothing, for the /// commands that only read it. fn snapshot(&self) -> Result { + let held = self.store.hold_objects()?; let revision: Revision = self.store.get(self.revision)?; let path = self.meta("state"); let (files, cache) = @@ -220,6 +224,7 @@ impl Workspace { files, unsaved: None, conflicts, + _held: held, }) }