Skip to content

Commit 386905d

Browse files
committed
feat: 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.
1 parent 221b9db commit 386905d

7 files changed

Lines changed: 328 additions & 48 deletions

File tree

‎apps/origin-src/src/annotations/mod.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,13 @@ impl<'a, P: Platform> Annotations<'a, P> {
9898
}
9999

100100
/// Writes a statement after its payload, which is durable before
101-
/// anything refers to it.
101+
/// anything refers to it, and stays until then.
102102
fn write(
103103
&self,
104104
statement: &Statement,
105105
payload: Option<EncodedObject>,
106106
) -> Result<StatementId, StoreError> {
107+
let _held = self.store.hold_objects()?;
107108
if let Some(payload) = payload {
108109
self.store.write_all(&[payload])?;
109110
}

‎apps/origin-src/src/annotations/promotion.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,9 @@ impl<P: Platform> Annotations<'_, P> {
206206
}
207207

208208
/// Issues the [`promotions`](Self::promotions) to `subject` as
209-
/// `issuer`, returning them.
209+
/// `issuer`, returning them. A promotion refers to its original's
210+
/// payload without writing it, so it [holds the objects](Store::hold_objects)
211+
/// from finding the originals to writing the promotions.
210212
///
211213
/// # Errors
212214
///
@@ -217,6 +219,7 @@ impl<P: Platform> Annotations<'_, P> {
217219
subject: RecordId,
218220
issuer: &Principal,
219221
) -> Result<Vec<(StatementId, Statement)>, StoreError> {
222+
let _held = self.store.hold_objects()?;
220223
let promotions = self.promotions(subject, issuer)?;
221224
let encoded: Vec<_> = promotions.iter().map(Statement::encode).collect();
222225
self.store.write_all(&encoded)?;

‎apps/origin-src/src/queue.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -592,9 +592,12 @@ impl<P: Platform> Session<'_, '_, P> {
592592
/// Checks the policy for `candidate`, and lands it if its evidence is
593593
/// there, or keeps it waiting. Writes the records in layers, each
594594
/// durable before the next refers to it: the trees, then the rebased
595-
/// revision, then the promoted statements and the acceptance.
595+
/// revision, then the promoted statements and the acceptance. The
596+
/// promotions refer to their originals' payloads without writing them,
597+
/// so it [holds the objects](Store::hold_objects) throughout.
596598
fn submit(&mut self, candidate: Candidate) -> Result<Landing, LandError> {
597599
let store = self.queue.store;
600+
let _held = store.hold_objects()?;
598601
if !candidate.trees.is_empty() {
599602
store.write_all(&candidate.trees)?;
600603
}

‎apps/origin-src/src/store/mod.rs‎

Lines changed: 116 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,17 @@
2424
//! Committing a batch also indexes its new records, see
2525
//! [`index`](crate::index).
2626
27+
use std::collections::BTreeSet;
2728
use std::fs;
2829
use std::io;
2930
use std::num::NonZero;
3031
use std::panic;
3132
use std::path::{Path, PathBuf};
3233
use std::sync::{Arc, Mutex, PoisonError};
3334
use std::thread;
34-
use std::time::Duration;
35+
use std::time::{Duration, SystemTime};
3536

36-
use origin_platform::{DurableWrite, Native, Platform, WritableError};
37+
use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform, WritableError};
3738
use origin_shared::object::{DecodeError, IdMismatch};
3839
use origin_shared::{EncodedObject, ObjectId, TargetName, TypedId};
3940

@@ -204,6 +205,7 @@ impl<P: Platform> Store<P> {
204205
store: self,
205206
write: self.durable_write(),
206207
entries: Mutex::default(),
208+
manifest_read: Mutex::default(),
207209
}
208210
}
209211

@@ -302,6 +304,89 @@ impl<P: Platform> Store<P> {
302304
Ok(self.path(id).exists() || self.find_packed(id)?.is_some())
303305
}
304306

307+
/// When this node stored the object: when its loose file was written,
308+
/// which packing it keeps.
309+
///
310+
/// # Errors
311+
///
312+
/// Fails if the store doesn't have it or its file cannot be inspected.
313+
pub fn stored_at(&self, id: ObjectId) -> Result<SystemTime, StoreError> {
314+
let path = self.path(id);
315+
match fs::metadata(&path).and_then(|metadata| metadata.modified()) {
316+
// Compaction may have moved it into a pack.
317+
Err(error) if error.kind() == io::ErrorKind::NotFound => {
318+
let (_, location) = self.find_packed(id)?.ok_or(StoreError::NotFound(id))?;
319+
Ok(location.stored())
320+
}
321+
result => result.map_err(|source| StoreError::io(&path, source)),
322+
}
323+
}
324+
325+
/// The file whose lock keeps garbage collection and writers apart.
326+
const COLLECTION_LOCK: &str = "objects/collection";
327+
328+
/// Keeps garbage collection from deleting objects while it's held, by
329+
/// any number of writers at once. A writer that may find an object
330+
/// already stored, and skip writing it, holds it until the records
331+
/// referring to that object are written, or collection could delete
332+
/// the object in between.
333+
///
334+
/// # Errors
335+
///
336+
/// Fails if the lock file cannot be opened.
337+
pub fn hold_objects(&self) -> Result<LockedFile, StoreError> {
338+
let path = self.root.join(Self::COLLECTION_LOCK);
339+
Ok(LockedFile::open(&self.platform, &path, LockMode::Shared)?)
340+
}
341+
342+
/// Waits for the writers holding objects, and keeps new ones waiting
343+
/// while it's held: garbage collection holds it while it finds what
344+
/// nothing refers to, and deletes it.
345+
///
346+
/// # Errors
347+
///
348+
/// Fails if the lock file cannot be opened.
349+
pub fn lock_for_collection(&self) -> Result<LockedFile, StoreError> {
350+
let path = self.root.join(Self::COLLECTION_LOCK);
351+
Ok(LockedFile::open(
352+
&self.platform,
353+
&path,
354+
LockMode::Exclusive,
355+
)?)
356+
}
357+
358+
/// Deletes objects durably, loose and packed, returning how many bytes
359+
/// that freed. Only garbage collection calls it, for objects nothing
360+
/// refers to any more, holding [`Store::lock_for_collection`].
361+
///
362+
/// # Errors
363+
///
364+
/// Fails if an object cannot be removed, its directory synced, or its
365+
/// pack rewritten.
366+
pub fn remove(&self, ids: &[ObjectId]) -> Result<u64, StoreError> {
367+
let mut freed = self.remove_packed(&ids.iter().copied().collect())?;
368+
let mut dirs = BTreeSet::new();
369+
for &id in ids {
370+
let path = self.path(id);
371+
let removed = fs::symlink_metadata(&path).and_then(|metadata| {
372+
fs::remove_file(&path)?;
373+
Ok(metadata.len())
374+
});
375+
match removed {
376+
Ok(len) => freed += len,
377+
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
378+
Err(source) => return Err(StoreError::io(&path, source)),
379+
}
380+
let mut shard = path;
381+
shard.pop();
382+
dirs.insert(shard);
383+
}
384+
for dir in dirs {
385+
self.sync_dir(&dir)?;
386+
}
387+
Ok(freed)
388+
}
389+
305390
/// Reads an object, or `None` if the store does not have it.
306391
///
307392
/// # Errors
@@ -398,13 +483,16 @@ pub struct Batch<'a, P> {
398483
write: DurableWrite<'a, P>,
399484
/// What the index keeps of each new record staged.
400485
entries: Mutex<Vec<Entry>>,
486+
/// Whether the batch read the pack manifest, which it does before it
487+
/// first trusts a pack to hold an object: see [`Batch::packed`].
488+
manifest_read: Mutex<bool>,
401489
}
402490

403491
impl<P: Platform> Batch<'_, P> {
404492
/// Stages an object, unless the store already has it, returning whether
405-
/// it was new. Either way, it is durable once the batch commits. Packs
406-
/// are only checked as last loaded: an object packed since is staged
407-
/// again, and the next compaction removes the copy.
493+
/// it was new. Either way, it is durable once the batch commits. An
494+
/// object packed since the packs were last loaded is staged again, and
495+
/// the next compaction removes the copy.
408496
///
409497
/// # Errors
410498
///
@@ -421,7 +509,7 @@ impl<P: Platform> Batch<'_, P> {
421509
self.write.sync_dir_with(shard);
422510
return Ok(false);
423511
}
424-
if self.store.packs.find(id).is_some() {
512+
if self.packed(id)? {
425513
// The manifest naming its pack may not be durable yet.
426514
self.write.sync_dir_with(self.store.packs_dir());
427515
return Ok(false);
@@ -439,6 +527,28 @@ impl<P: Platform> Batch<'_, P> {
439527
Ok(true)
440528
}
441529

530+
/// Whether a pack holds `id`, as of a manifest read since the batch
531+
/// started. Packs loaded before may include one that garbage
532+
/// collection rewrote without the object since, and nothing may skip
533+
/// writing an object that's gone. Once the batch read the manifest,
534+
/// holding [`Store::hold_objects`] as writers that skip objects do,
535+
/// only compactions replace it, and they keep every object.
536+
fn packed(&self, id: ObjectId) -> Result<bool, StoreError> {
537+
// A miss only stages the object again, so it needs no fresh read.
538+
if self.store.packs.find(id).is_none() {
539+
return Ok(false);
540+
}
541+
let mut read = self
542+
.manifest_read
543+
.lock()
544+
.unwrap_or_else(PoisonError::into_inner);
545+
if !*read {
546+
self.store.reload_packs()?;
547+
*read = true;
548+
}
549+
Ok(self.store.packs.find(id).is_some())
550+
}
551+
442552
/// Stages each of `objects` in turn, returning how many were new.
443553
fn write_all(&self, objects: &[EncodedObject]) -> Result<usize, StoreError> {
444554
objects.iter().try_fold(0, |written, object| {
@@ -542,7 +652,6 @@ pub(crate) mod tests {
542652
use std::fs::File;
543653
use std::slice;
544654
use std::sync::Mutex;
545-
use std::time::SystemTime;
546655

547656
use origin_platform::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, ReadAt};
548657

0 commit comments

Comments
 (0)