2424//! Committing a batch also indexes its new records, see
2525//! [`index`](crate::index).
2626
27+ use std:: collections:: BTreeSet ;
2728use std:: fs;
2829use std:: io;
2930use std:: num:: NonZero ;
3031use std:: panic;
3132use std:: path:: { Path , PathBuf } ;
3233use std:: sync:: { Arc , Mutex , PoisonError } ;
3334use 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 } ;
3738use origin_shared:: object:: { DecodeError , IdMismatch } ;
3839use 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
403491impl < 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