diff --git a/Cargo.lock b/Cargo.lock index 2eddcbfaeba..e2fa8404a1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9273,6 +9273,7 @@ dependencies = [ "spacetimedb-primitives", "spacetimedb-sats", "spacetimedb-schema", + "tempfile", "thiserror 1.0.69", ] diff --git a/crates/datastore/src/db_metrics/mod.rs b/crates/datastore/src/db_metrics/mod.rs index 2c3f5381986..4b241b7de01 100644 --- a/crates/datastore/src/db_metrics/mod.rs +++ b/crates/datastore/src/db_metrics/mod.rs @@ -322,7 +322,7 @@ Each HTTP request performed by a database will be counted either here, in `space pub page_cache_evicted_bytes: IntCounterVec, #[name = spacetime_page_cache_disk_io_duration_seconds] - #[help = "Local-cache read and write durations, including failed operations."] + #[help = "Local-cache read, write, and hardlink durations, including failed operations."] #[labels(database_identity: Identity, replica_id: u64, operation: str)] #[buckets(0.00001, 0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 30.0)] pub page_cache_disk_time: HistogramVec, diff --git a/crates/datastore/src/db_metrics/page_cache.rs b/crates/datastore/src/db_metrics/page_cache.rs index bd4771002d2..65ef75d0985 100644 --- a/crates/datastore/src/db_metrics/page_cache.rs +++ b/crates/datastore/src/db_metrics/page_cache.rs @@ -61,11 +61,13 @@ struct TierMetrics { struct DiskIoMetrics { read: OnceLock, write: OnceLock, + hardlink: OnceLock, read_bytes: OnceLock, write_bytes: OnceLock, read_operations: DiskOperationCounters, write_operations: DiskOperationCounters, delete_operations: DiskOperationCounters, + hardlink_operations: DiskOperationCounters, } #[derive(Debug, Default)] @@ -342,8 +344,9 @@ impl FaultMetrics { impl DiskIoMetrics { fn record(&self, stats: &StorageMetrics, operation: DiskOperation, nanos: u64, bytes: u64) { let (duration, transferred_bytes) = match operation { - DiskOperation::Read => (&self.read, &self.read_bytes), - DiskOperation::Write => (&self.write, &self.write_bytes), + DiskOperation::Read => (&self.read, Some(&self.read_bytes)), + DiskOperation::Write => (&self.write, Some(&self.write_bytes)), + DiskOperation::Hardlink => (&self.hardlink, None), DiskOperation::Delete => return, }; let (db, replica) = (&stats.database, &stats.replica); @@ -354,7 +357,9 @@ impl DiskIoMetrics { .with_label_values(db, replica, operation.as_str()) }) .observe(nanos as f64 / 1e9); - if bytes > 0 { + if bytes > 0 + && let Some(transferred_bytes) = transferred_bytes + { transferred_bytes .get_or_init(|| { DB_METRICS @@ -370,6 +375,7 @@ impl DiskIoMetrics { DiskOperation::Read => &self.read_operations, DiskOperation::Write => &self.write_operations, DiskOperation::Delete => &self.delete_operations, + DiskOperation::Hardlink => &self.hardlink_operations, }; let (db, replica) = (&stats.database, &stats.replica); counters @@ -472,7 +478,12 @@ fn remove_series(stats: &StorageMetrics) { .page_cache_reclamation_time .remove_label_values(db, replica, outcome); } - for operation in [DiskOperation::Read, DiskOperation::Write, DiskOperation::Delete] { + for operation in [ + DiskOperation::Read, + DiskOperation::Write, + DiskOperation::Delete, + DiskOperation::Hardlink, + ] { let _ = DB_METRICS .page_cache_disk_operations .remove_label_values(db, replica, operation.as_str()); diff --git a/crates/datastore/src/locking_tx_datastore/committed_state.rs b/crates/datastore/src/locking_tx_datastore/committed_state.rs index 20b1b7073c0..4891379d209 100644 --- a/crates/datastore/src/locking_tx_datastore/committed_state.rs +++ b/crates/datastore/src/locking_tx_datastore/committed_state.rs @@ -1147,16 +1147,12 @@ impl CommittedState { (table, self.storage.blobs()) } - /// Returns an iterator over all persistent tables (i.e., non-ephemeral tables) #[cfg(feature = "durability")] - pub(super) fn persistent_tables_and_blob_store(&mut self) -> (impl Iterator, &BlobSet) { - ( - self.tables - .iter_mut() - .filter(|(table_id, _)| !self.ephemeral_tables.contains(*table_id)) - .map(|(_, table)| table), - self.storage.blobs(), - ) + pub(super) fn tables_for_snapshot(&mut self) -> impl Iterator { + self.tables + .iter_mut() + .filter(|(table_id, _)| !self.ephemeral_tables.contains(*table_id)) + .map(|(_, table)| table) } #[cfg(feature = "metrics")] diff --git a/crates/datastore/src/locking_tx_datastore/datastore.rs b/crates/datastore/src/locking_tx_datastore/datastore.rs index d3d102b7456..cbe960f11bb 100644 --- a/crates/datastore/src/locking_tx_datastore/datastore.rs +++ b/crates/datastore/src/locking_tx_datastore/datastore.rs @@ -326,8 +326,9 @@ impl Locking { tx_offset, ); - let (mut tables, blob_store) = committed_state.persistent_tables_and_blob_store(); - let unflushed_snapshot = repo.create_snapshot(&mut tables, blob_store.scan(), tx_offset)?; + let storage = committed_state.storage.clone(); + let mut tables = committed_state.tables_for_snapshot(); + let unflushed_snapshot = repo.create_snapshot(tx_offset, &storage, &mut tables)?; Ok(Some((tx_offset, unflushed_snapshot))) } diff --git a/crates/engine/src/relational_db.rs b/crates/engine/src/relational_db.rs index e502acb0858..7d22eb01ed5 100644 --- a/crates/engine/src/relational_db.rs +++ b/crates/engine/src/relational_db.rs @@ -704,6 +704,7 @@ impl RelationalDB { SnapshotError::Page(inner) => inner.is_transient(), SnapshotError::Blob(inner) => inner.is_transient(), SnapshotError::ObjectStore(inner) => inner.is_transient(), + SnapshotError::Tiered(inner) => inner.is_transient(), } } diff --git a/crates/paths/src/server.rs b/crates/paths/src/server.rs index c1e60238d27..c492d29536b 100644 --- a/crates/paths/src/server.rs +++ b/crates/paths/src/server.rs @@ -243,6 +243,15 @@ impl SnapshotDirPath { .file_stem() .and_then(|s| s.to_str()?.split('.').next()?.parse::().ok()) } + + pub fn snapshots(&self) -> SnapshotsPath { + SnapshotsPath( + self.0 + .parent() + .expect("SnapshotDirPath should have a parent") + .to_path_buf(), + ) + } } path_type! { diff --git a/crates/snapshot/src/common.rs b/crates/snapshot/src/common.rs index ab9fe81a95d..8778f4fef4a 100644 --- a/crates/snapshot/src/common.rs +++ b/crates/snapshot/src/common.rs @@ -1,29 +1,29 @@ use std::{ collections::BTreeMap, + ffi::OsStr, fs, io::{BufWriter, Read as _, Write as _}, num::NonZeroUsize, time::Instant, }; +use spacetimedb_durability::TxOffset; use spacetimedb_fs_utils::{ compression::{CompressReader, CompressType}, - dir_trie::{o_excl, o_rdonly, CountCreated, DirTrie}, + dir_trie::{o_excl, o_rdonly, DirTrie}, + lockfile::Lockfile, }; use spacetimedb_lib::bsatn; -use spacetimedb_paths::server::SnapshotFilePath; -use spacetimedb_primitives::TableId; -use spacetimedb_table::{ - blob_store::BlobHash, - page::Page, - page_pool::PagePool, - table::Table, - tiered::{BlobMap, ObjectStoreError, ScannedBlob}, +use spacetimedb_paths::{ + server::{SnapshotDirPath, SnapshotFilePath, SnapshotsPath}, + FromPathUnchecked as _, }; +use spacetimedb_primitives::TableId; +use spacetimedb_table::{blob_store::BlobHash, page::Page, page_pool::PagePool, tiered::BlobMap}; use crate::{ - v0, v1, BlobEntry, FileOrDirPath, ObjectType, Snapshot, SnapshotError, SnapshotReadKindMetrics, TableEntry, - TablePages, MAGIC, ZERO_HASH_DENOTING_ABSENT_PAGE, + v0, v1, BlobEntry, FileOrDirPath, ObjectType, ParentRepo, Snapshot, SnapshotError, SnapshotReadKindMetrics, + TableEntry, TablePages, MAGIC, SNAPSHOT_DIR_EXT, ZERO_HASH_DENOTING_ABSENT_PAGE, }; pub(crate) fn read_from_file(path: &SnapshotFilePath) -> Result<(Snapshot, CompressType), SnapshotError> { @@ -250,72 +250,6 @@ fn reconstruct_one_table_pages( .collect() } -pub(crate) fn write_blobs<'a>( - repo: &DirTrie, - parent: Option<&DirTrie>, - mut on_write: impl FnMut(BlobEntry), - counter: &mut CountCreated, - blobs: impl Iterator, ObjectStoreError>>, -) -> Result<(), SnapshotError> { - let io_error = |hash, cause| SnapshotError::WriteObject { - ty: ObjectType::Blob(hash), - dest_repo: repo.root().to_path_buf(), - source_repo: parent.map(|src| src.root().to_path_buf()), - cause, - }; - for blob in blobs { - let blob = blob?; - repo.hardlink_or_write(parent, &blob.hash.data, || blob.data, counter) - .map_err(|e| io_error(blob.hash, e))?; - on_write(BlobEntry { - hash: blob.hash, - uses: blob.uses.get() as u32, - }); - } - - Ok(()) -} - -pub(crate) fn write_tables<'a>( - repo: &DirTrie, - parent: Option<&DirTrie>, - mut on_write: impl FnMut(TableEntry), - counter: &mut CountCreated, - tables: impl Iterator, -) -> Result<(), SnapshotError> { - for table in tables { - let mut pages = Vec::new(); - for page in table.iter_pages_with_hashes() { - let hash = match page? { - None => ZERO_HASH_DENOTING_ABSENT_PAGE, - Some((hash, page)) => { - let page = page.read(); - debug_assert!(page.unmodified_hash().copied() == Some(hash)); - - repo.hardlink_or_write(parent, hash.as_bytes(), || bsatn::to_vec(&*page).unwrap(), counter) - .map_err(|cause| SnapshotError::WriteObject { - ty: ObjectType::Page(hash), - dest_repo: repo.root().to_path_buf(), - source_repo: parent.map(|src| src.root().to_path_buf()), - cause, - })?; - - hash - } - }; - - pages.push(hash); - } - - on_write(TableEntry { - table_id: table.schema.table_id, - pages, - }); - } - - Ok(()) -} - pub(crate) fn write_snapshot_file(path: SnapshotFilePath, snapshot_bsatn: &[u8]) -> Result<(), SnapshotError> { let hash = blake3::hash(snapshot_bsatn); @@ -335,3 +269,50 @@ pub(crate) fn write_snapshot_file(path: SnapshotFilePath, snapshot_bsatn: &[u8]) Ok(()) } + +pub(crate) fn latest_snapshot_older_than( + root: &SnapshotsPath, + upper_bound: TxOffset, +) -> Result, SnapshotError> { + all_snapshots(root).map(|iter| iter.filter(|&tx_offset| tx_offset <= upper_bound).max()) +} + +pub(crate) fn all_snapshots(root: &SnapshotsPath) -> Result + use<>, SnapshotError> { + Ok(root + // Item = Result + .read_dir()? + // Item = DirEntry + .filter_map(Result::ok) + // Item = PathBuf + .map(|dirent| dirent.path()) + // Ignore entries not shaped like snapshot directories. + .filter(|path| path.extension() == Some(OsStr::new(SNAPSHOT_DIR_EXT))) + // Ignore entries whose lockfile still exists. + .filter(|path| !Lockfile::lock_path(path).exists()) + // Parse each entry's TxOffset from the file name; ignore unparsable. + // Also ignore if the snapshot file doesn't exists. + // This can happen on incomplete transfers, or if something went + // wrong during creation. + // Item = TxOffset + .filter_map(|path| { + let offset = TxOffset::from_str_radix(path.file_stem()?.to_str()?, 10).ok()?; + let snapshot_file = SnapshotDirPath::from_path_unchecked(path).snapshot_file(offset); + if !snapshot_file.0.exists() { + None + } else { + Some(offset) + } + })) +} + +pub(crate) fn parent_repo(root: &SnapshotsPath, before: TxOffset) -> Result, SnapshotError> { + let Some(offset) = latest_snapshot_older_than(root, before)? else { + return Ok(None); + }; + + let parent_dir = root.snapshot_dir(offset); + let (parent_snapshot, _) = Snapshot::read_from_file(&parent_dir.snapshot_file(offset))?; + let parent_repo = parent_snapshot.into_parent_repo(&parent_dir)?; + + Ok(Some(parent_repo)) +} diff --git a/crates/snapshot/src/lib.rs b/crates/snapshot/src/lib.rs index f5f8b0f9f22..38b37603498 100644 --- a/crates/snapshot/src/lib.rs +++ b/crates/snapshot/src/lib.rs @@ -30,7 +30,7 @@ use spacetimedb_fs_utils::compression::{ compress_with_zstd, CompressCount, CompressReader, CompressType, CompressionAlgorithm, }; use spacetimedb_fs_utils::{ - dir_trie::{o_excl, o_rdonly, CountCreated, DirTrie}, + dir_trie::{o_excl, o_rdonly, DirTrie}, lockfile::{Lockfile, LockfileError}, }; use spacetimedb_lib::ser::Serializer; @@ -39,10 +39,12 @@ use spacetimedb_paths::server::{ArchivedSnapshotDirPath, SnapshotDirPath, Snapsh use spacetimedb_paths::FromPathUnchecked; use spacetimedb_primitives::TableId; use spacetimedb_sats::{bsatn, de::Deserialize, ser::Serialize}; +use spacetimedb_table::table::Table; use spacetimedb_table::tiered::{ - BlobError, BlobMap, BlobScan, ObjectKey, ObjectStoreError, PageError, PageHash, ScannedBlob, + self, BlobError, BlobMap, ObjectKey, ObjectStoreError, PageError, PageHash, SnapshotObjectStorage, + TieredDatabaseStorage, }; -use spacetimedb_table::{blob_store::BlobHash, page::Page, page_pool::PagePool, table::Table}; +use spacetimedb_table::{blob_store::BlobHash, page::Page, page_pool::PagePool}; use std::fs::{self, File}; use std::io; use std::ops::{Range, RangeBounds}; @@ -189,6 +191,8 @@ pub enum SnapshotError { Blob(#[from] BlobError), #[error(transparent)] ObjectStore(#[from] ObjectStoreError), + #[error(transparent)] + Tiered(#[from] tiered::SnapshotError), } impl SnapshotError { @@ -283,6 +287,16 @@ pub struct UnflushedSnapshot { } impl UnflushedSnapshot { + fn new(snapshot_dir: SnapshotDirPath, snapshot: WritableSnapshot, lockfile: Lockfile) -> Self { + let inner = UnflushedSnapshotInner { + snapshot_dir, + repo: snapshot, + lockfile, + }; + + Self { inner: Some(inner) } + } + /// Return the transaction offset this pending snapshot will finalize at. pub fn tx_offset(&self) -> TxOffset { self.inner.as_ref().unwrap().repo.tx_offset() @@ -358,7 +372,26 @@ impl PendingSnapshot for UnflushedSnapshot { } } -pub enum WritableSnapshot { +pub struct WritableSnapshot { + parent: Option, + inner: WritableSnapshotInner, +} + +enum ParentRepo { + V0(v0::SnapshotRepo), + V1(v1::SnapshotRepo), +} + +impl ParentRepo { + fn file_path(&self, key: ObjectKey) -> PathBuf { + match self { + Self::V0(inner) => inner.file_path(key), + Self::V1(inner) => inner.file_path(key), + } + } +} + +enum WritableSnapshotInner { V0 { manifest: v0::Snapshot, repo: v0::SnapshotRepo, @@ -371,30 +404,30 @@ pub enum WritableSnapshot { impl WritableSnapshot { pub fn root(&self) -> &Path { - match self { - Self::V0 { repo, .. } => repo.root(), - Self::V1 { repo, .. } => repo.root(), + match &self.inner { + WritableSnapshotInner::V0 { repo, .. } => repo.root(), + WritableSnapshotInner::V1 { repo, .. } => repo.root(), } } pub fn file_path(&self, key: ObjectKey) -> PathBuf { - match self { - Self::V0 { repo, .. } => repo.file_path(key), - Self::V1 { repo, .. } => repo.file_path(key), + match &self.inner { + WritableSnapshotInner::V0 { repo, .. } => repo.file_path(key), + WritableSnapshotInner::V1 { repo, .. } => repo.file_path(key), } } pub fn tx_offset(&self) -> TxOffset { - match self { - Self::V0 { manifest, .. } => manifest.tx_offset, - Self::V1 { manifest, .. } => manifest.tx_offset, + match &self.inner { + WritableSnapshotInner::V0 { manifest, .. } => manifest.tx_offset, + WritableSnapshotInner::V1 { manifest, .. } => manifest.tx_offset, } } pub fn manifest(&self) -> Snapshot { - match self { - Self::V0 { manifest, .. } => Snapshot::V0(manifest.clone()), - Self::V1 { manifest, .. } => Snapshot::V1(manifest.clone()), + match &self.inner { + WritableSnapshotInner::V0 { manifest, .. } => Snapshot::V0(manifest.clone()), + WritableSnapshotInner::V1 { manifest, .. } => Snapshot::V1(manifest.clone()), } } @@ -403,27 +436,31 @@ impl WritableSnapshot { } pub fn objects(&self) -> impl Iterator { - let (v0, v1) = match self { - Self::V0 { manifest, .. } => (Some(manifest.objects()), None), - Self::V1 { manifest, .. } => (None, Some(manifest.objects())), + let (v0, v1) = match &self.inner { + WritableSnapshotInner::V0 { manifest, .. } => (Some(manifest.objects()), None), + WritableSnapshotInner::V1 { manifest, .. } => (None, Some(manifest.objects())), }; v0.into_iter().flatten().chain(v1.into_iter().flatten()) } fn object_keys_and_file_paths(&self) -> impl Iterator { - let (v0, v1) = match self { - Self::V0 { manifest, repo } => (Some(manifest.objects().map(|key| (key, repo.file_path(key)))), None), - Self::V1 { manifest, repo } => (None, Some(manifest.objects().map(|key| (key, repo.file_path(key))))), + let (v0, v1) = match &self.inner { + WritableSnapshotInner::V0 { manifest, repo } => { + (Some(manifest.objects().map(|key| (key, repo.file_path(key)))), None) + } + WritableSnapshotInner::V1 { manifest, repo } => { + (None, Some(manifest.objects().map(|key| (key, repo.file_path(key))))) + } }; v0.into_iter().flatten().chain(v1.into_iter().flatten()) } fn commit(self) -> Result<(), SnapshotError> { - match self { - WritableSnapshot::V0 { manifest, repo } => manifest.write_snapshot_file(&repo), - WritableSnapshot::V1 { manifest, repo } => manifest.write_snapshot_file(&repo), + match self.inner { + WritableSnapshotInner::V0 { manifest, repo } => manifest.write_snapshot_file(&repo), + WritableSnapshotInner::V1 { manifest, repo } => manifest.write_snapshot_file(&repo), } } @@ -432,8 +469,8 @@ impl WritableSnapshot { page_pool: &PagePool, metrics: &mut SnapshotReadMetrics, ) -> Result<(BlobMap, BTreeMap), SnapshotError> { - match self { - Self::V0 { manifest, repo } => { + match &self.inner { + WritableSnapshotInner::V0 { manifest, repo } => { let blob_start = Instant::now(); let blob_store = repo.reconstruct_blobs(manifest, &mut metrics.blob)?; metrics.blob.read_time = blob_start.elapsed(); @@ -444,7 +481,7 @@ impl WritableSnapshot { Ok((blob_store, tables)) } - Self::V1 { manifest, repo } => { + WritableSnapshotInner::V1 { manifest, repo } => { let blob_start = Instant::now(); let blob_store = repo.reconstruct_blobs(manifest, &mut metrics.blob)?; metrics.blob.read_time = blob_start.elapsed(); @@ -458,19 +495,6 @@ impl WritableSnapshot { } } - fn write_objects<'db, 'a>( - &mut self, - parent: Option<&SnapshotDirPath>, - tables: impl Iterator, - blobs: impl Iterator, ObjectStoreError>>, - counter: &mut CountCreated, - ) -> Result<(), SnapshotError> { - match self { - Self::V0 { manifest, repo } => manifest.write_objects(repo, parent, tables, blobs, counter), - Self::V1 { manifest, repo } => manifest.write_objects(repo, parent, tables, blobs, counter), - } - } - fn try_hardlink_from(&self, parent: &Self, key: ObjectKey) -> io::Result { let src = parent.file_path(key); if src.is_file() { @@ -483,19 +507,55 @@ impl WritableSnapshot { Ok(false) } } + + fn set_blobs(&mut self, blobs: impl Iterator) { + match &mut self.inner { + WritableSnapshotInner::V0 { manifest, .. } => manifest.blobs.extend(blobs), + WritableSnapshotInner::V1 { manifest, .. } => manifest.blobs_mut().extend(blobs), + } + } + + fn set_tables(&mut self, tables: impl Iterator) { + match &mut self.inner { + WritableSnapshotInner::V0 { manifest, .. } => manifest.tables.extend(tables), + WritableSnapshotInner::V1 { manifest, .. } => manifest.tables_mut().extend(tables), + } + } } impl ObjectProvider for WritableSnapshot { type Reader = ::Reader; async fn object_reader(&self, key: ObjectKey) -> io::Result { - match self { - Self::V0 { repo, .. } => repo.object_reader(key).await, - Self::V1 { repo, .. } => repo.object_reader(key).await, + match &self.inner { + WritableSnapshotInner::V0 { repo, .. } => repo.object_reader(key).await, + WritableSnapshotInner::V1 { repo, .. } => repo.object_reader(key).await, } } } +impl SnapshotObjectStorage for WritableSnapshot { + fn write(&self, object: tiered::SnapshotObject<'_>) -> io::Result<()> { + let path = match &self.inner { + WritableSnapshotInner::V0 { repo, .. } => repo.file_path(object.key()), + WritableSnapshotInner::V1 { repo, .. } => repo.file_path(object.key()), + }; + fs::create_dir_all(path.parent().expect("dir trie file paths have a parent"))?; + + // Avoid writing resident objects on each snapshot. + if let Some((parent_repo, resident_object)) = self.parent.as_ref().zip(object.as_resident()) { + let parent_path = parent_repo.file_path(resident_object.key()); + if parent_path.is_file() { + fs::hard_link(&parent_path, &path)?; + + return Ok(()); + } + } + + object.write(path, tiered::Fsync::Defer) + } +} + #[derive(Clone)] pub enum Snapshot { V0(v0::Snapshot), @@ -592,18 +652,33 @@ impl Snapshot { } } - pub fn into_writable(self, dir: &SnapshotDirPath) -> io::Result { + pub fn into_writable(self, dir: &SnapshotDirPath) -> Result { match self { Self::V0(inner) => { let repo = inner.repo(dir)?; - Ok(WritableSnapshot::V0 { manifest: inner, repo }) + let parent = repo.parent()?; + Ok(WritableSnapshot { + parent, + inner: WritableSnapshotInner::V0 { manifest: inner, repo }, + }) } Self::V1(inner) => { let repo = inner.repo(dir)?; - Ok(WritableSnapshot::V1 { manifest: inner, repo }) + let parent = repo.parent()?; + Ok(WritableSnapshot { + parent, + inner: WritableSnapshotInner::V1 { manifest: inner, repo }, + }) } } } + + pub(crate) fn into_parent_repo(self, dir: &SnapshotDirPath) -> io::Result { + match self { + Self::V0(inner) => inner.repo(dir).map(ParentRepo::V0), + Self::V1(inner) => inner.repo(dir).map(ParentRepo::V1), + } + } } impl Serialize for Snapshot { @@ -773,76 +848,50 @@ impl SnapshotRepository { /// Also note that the snapshot remains locked for as long as [UnflushedSnapshot] /// is alive. It will not appear in [Self::all_snapshots] nor can it be /// modified by methods in [SnapshotRepository]. - pub fn create_snapshot<'db, 'b>( + pub fn create_snapshot<'db>( &self, + offset: TxOffset, + storage: &TieredDatabaseStorage, tables: impl Iterator, - blobs: BlobScan<'b>, - tx_offset: TxOffset, ) -> Result { - // Invalidate equal to or newer than `tx_offset`. - // - // This is because snapshots don't currently track the epoch in which - // they were created: - // - // Say, for example, a snapshot was created at offset 10, then a leader - // failover causes the commitlog to be reset to offset 9. The next - // transaction (also offset 10) will trigger snapshot creation, but we'd - // mistake the existing snapshot (now invalid) as the previous snapshot. - self.invalidate_newer_snapshots(tx_offset.saturating_sub(1))?; - - let snapshot_dir = self.snapshot_dir_path(tx_offset); - - // Before performing any observable operations, - // acquire a lockfile on the snapshot you want to create. - // Because we could be compressing the snapshot. + self.invalidate_newer_snapshots(offset.saturating_sub(1))?; + let snapshot_dir = self.snapshot_dir_path(offset); let lockfile = Lockfile::for_file(&snapshot_dir)?; - - // Create the snapshot directory. snapshot_dir.create()?; - // Build the in-memory `Snapshot` object. - let manifest = self.empty_manifest(tx_offset); - - let mut counter = CountCreated::default(); - - let mut object_repo = manifest.into_writable(&snapshot_dir)?; - let parent = self.latest_snapshot()?.map(|offset| self.snapshot_dir_path(offset)); - object_repo.write_objects(parent.as_ref(), tables, blobs.iter(), &mut counter)?; - - log::info!( - "[{}] SNAPSHOT {:0>20}: Hardlinked {} objects and wrote {} objects", - self.database_identity, - tx_offset, - counter.objects_hardlinked, - counter.objects_written, - ); - - Ok(UnflushedSnapshot { - inner: Some(UnflushedSnapshotInner { - snapshot_dir, - repo: object_repo, - lockfile, - }), - }) - } - - fn empty_manifest(&self, tx_offset: TxOffset) -> Snapshot { let manifest = v0::Snapshot { magic: MAGIC, version: CURRENT_SNAPSHOT_VERSION, database_identity: self.database_identity, replica_id: self.replica_id, module_abi_version: CURRENT_MODULE_ABI_VERSION, - tx_offset, + tx_offset: offset, blobs: vec![], tables: vec![], }; - match CURRENT_SNAPSHOT_VERSION { + let manifest = match CURRENT_SNAPSHOT_VERSION { v0::SNAPSHOT_VERSION => Snapshot::V0(manifest), v1::SNAPSHOT_VERSION => Snapshot::V1(v1::Snapshot::new(manifest)), v => unreachable!("invalid CURRENT_SNAPSHOT_VERSION: {v}"), - } + }; + let mut snapshot = manifest.into_writable(&snapshot_dir)?; + let (blobs, tables) = storage.create_snapshot(&snapshot, tables)?.into_parts(); + snapshot.set_blobs(blobs.into_iter().map(|(hash, uses)| BlobEntry { + hash, + uses: uses.get() as u32, + })); + snapshot.set_tables(tables.into_iter().map(|(table_id, pages)| { + TableEntry { + table_id, + pages: pages + .into_iter() + .map(|page| page.map(Into::into).unwrap_or(ZERO_HASH_DENOTING_ABSENT_PAGE)) + .collect(), + } + })); + + Ok(UnflushedSnapshot::new(snapshot_dir, snapshot, lockfile)) } /// Get the path to the directory which would contain the snapshot of transaction `tx_offset`. @@ -1034,41 +1083,11 @@ impl SnapshotRepository { /// Does not verify that the snapshot of the returned `TxOffset` is valid and uncorrupted, /// so a subsequent [`Self::read_snapshot`] may fail. pub fn latest_snapshot_older_than(&self, upper_bound: TxOffset) -> Result, SnapshotError> { - Ok(self - .all_snapshots()? - // Ignore `tx_offset`s greater than the current upper bound. - .filter(|tx_offset| *tx_offset <= upper_bound) - // Select the largest TxOffset. - .max()) + common::latest_snapshot_older_than(&self.root, upper_bound) } pub fn all_snapshots(&self) -> Result + use<>, SnapshotError> { - Ok(self - .root - // Item = Result - .read_dir()? - // Item = DirEntry - .filter_map(Result::ok) - // Item = PathBuf - .map(|dirent| dirent.path()) - // Ignore entries not shaped like snapshot directories. - .filter(|path| path.extension() == Some(OsStr::new(SNAPSHOT_DIR_EXT))) - // Ignore entries whose lockfile still exists. - .filter(|path| !Lockfile::lock_path(path).exists()) - // Parse each entry's TxOffset from the file name; ignore unparsable. - // Also ignore if the snapshot file doesn't exists. - // This can happen on incomplete transfers, or if something went - // wrong during creation. - // Item = TxOffset - .filter_map(|path| { - let offset = TxOffset::from_str_radix(path.file_stem()?.to_str()?, 10).ok()?; - let snapshot_file = SnapshotDirPath::from_path_unchecked(path).snapshot_file(offset); - if !snapshot_file.0.exists() { - None - } else { - Some(offset) - } - })) + common::all_snapshots(&self.root) } /// Return an interator of [`ArchivedSnapshotDirPath`] for all the archived snapshot directories on disk @@ -1329,11 +1348,11 @@ pub trait SnapshotRepo: Send + Sync { fn database_identity(&self) -> Identity; /// Start creating a snapshot at `tx_offset` from the provided tables and blob store. - fn create_snapshot<'a, 'b>( + fn create_snapshot( &self, - tables: &mut dyn Iterator, - blobs: BlobScan<'b>, tx_offset: TxOffset, + storage: &TieredDatabaseStorage, + tables: &mut dyn Iterator, ) -> Result; /// Reconstruct the snapshot at `tx_offset` using the supplied page pool. @@ -1370,14 +1389,14 @@ impl SnapshotRepo for SnapshotRepository { SnapshotRepository::database_identity(self) } - fn create_snapshot<'a, 'b>( + fn create_snapshot( &self, - tables: &mut dyn Iterator, - blobs: BlobScan<'b>, tx_offset: TxOffset, + storage: &TieredDatabaseStorage, + tables: &mut dyn Iterator, ) -> Result { Ok(Box::new(SnapshotRepository::create_snapshot( - self, tables, blobs, tx_offset, + self, tx_offset, storage, tables, )?)) } diff --git a/crates/snapshot/src/tests.rs b/crates/snapshot/src/tests.rs index 6f466bed463..1f233432828 100644 --- a/crates/snapshot/src/tests.rs +++ b/crates/snapshot/src/tests.rs @@ -4,6 +4,7 @@ use spacetimedb_sats::{product, AlgebraicType}; use spacetimedb_schema::schema::TableSchema; use spacetimedb_table::{ indexes::SquashedOffset, + table::Table, tiered::{ metrics::CacheTier, ByteBudget, ByteBudgetConfig, EvictionPolicy, TieredDatabaseStorage, TieredStorageConfig, }, @@ -43,8 +44,7 @@ fn snapshot_evicts_other_tables_to_load_pages() -> anyhow::Result<()> { let tmp = tempdir()?; let repo = SnapshotRepository::open(SnapshotsPath::from_path_unchecked(tmp.path()), Identity::ZERO, 42)?; - repo.create_snapshot(tables.iter_mut(), storage.blobs().scan(), 0)? - .sync_all()?; + repo.create_snapshot(0, &storage, &mut tables.iter_mut())?.sync_all()?; let mut snapshot = repo.read_snapshot(0, &pool)?; assert_eq!(snapshot.tables.len(), 2); for (table, expected) in tables.iter().zip([11_u64, 22_u64]) { diff --git a/crates/snapshot/src/tests/versions.rs b/crates/snapshot/src/tests/versions.rs index d4e98aaa6fc..6080f91cd88 100644 --- a/crates/snapshot/src/tests/versions.rs +++ b/crates/snapshot/src/tests/versions.rs @@ -1,11 +1,12 @@ -use std::{collections::BTreeSet, io::Cursor, num::NonZeroUsize, sync::Arc}; +use std::{collections::BTreeSet, io::Cursor, sync::Arc}; use proptest::{collection::vec, prelude::*}; use spacetimedb_sats::{product, AlgebraicType}; use spacetimedb_schema::schema::TableSchema; use spacetimedb_table::{ indexes::SquashedOffset, - tiered::{EvictionPolicy, ScannedBlobData, TieredDatabaseStorage, TieredStorageConfig}, + table::Table, + tiered::{EvictionPolicy, TieredDatabaseStorage, TieredStorageConfig}, }; use tempfile::tempdir; @@ -74,29 +75,32 @@ fn capture( }; let mut writable = manifest.into_writable(&dir)?; - // Capture actual table pages and a blob through the version-specific writer. let storage = TieredDatabaseStorage::empty(TieredStorageConfig::new_for_test()); let mut tables = [new_table(TABLE, &storage), new_table(EMPTY_TABLE, &storage)]; tables[0].insert(storage.blobs(), &product![row])?; - let blob = ScannedBlob { - hash: BlobHash::hash_from_bytes(bytes), - uses: NonZeroUsize::new(BLOB_USES.try_into().unwrap()).unwrap(), - data: ScannedBlobData::Resident(bytes), - }; - let mut counter = CountCreated::default(); - writable.write_objects(None, tables.iter_mut(), std::iter::once(Ok(blob)), &mut counter)?; - assert_eq!(counter.objects_written, 2); - assert_eq!(counter.objects_hardlinked, 0); - - // Sparse tables retain absent page slots, which must never become object files. - match &mut writable { - WritableSnapshot::V0 { manifest, .. } => { - manifest.tables[0].pages.push(ZERO_HASH_DENOTING_ABSENT_PAGE); - } - WritableSnapshot::V1 { manifest, .. } => { - manifest.get_mut().tables[0].pages.push(ZERO_HASH_DENOTING_ABSENT_PAGE); - } + + for _ in 0..BLOB_USES { + storage.blobs().insert(EvictionPolicy::Memory, bytes)?; } + + let (blobs, tables) = storage.create_snapshot(&writable, tables.iter_mut())?.into_parts(); + writable.set_blobs(blobs.into_iter().map(|(hash, uses)| BlobEntry { + hash, + uses: uses.get() as _, + })); + writable.set_tables(tables.into_iter().map(|(table_id, pages)| { + let mut pages = pages + .into_iter() + .map(|maybe_hash| maybe_hash.map(Into::into).unwrap_or(ZERO_HASH_DENOTING_ABSENT_PAGE)) + .collect::>(); + + if table_id == TABLE { + pages.push(ZERO_HASH_DENOTING_ABSENT_PAGE); + } + + TableEntry { table_id, pages } + })); + let manifest = writable.manifest(); let pending = UnflushedSnapshot { inner: Some(UnflushedSnapshotInner { diff --git a/crates/snapshot/src/v0.rs b/crates/snapshot/src/v0.rs index 98988444358..b0277596855 100644 --- a/crates/snapshot/src/v0.rs +++ b/crates/snapshot/src/v0.rs @@ -5,20 +5,19 @@ use std::{ }; use spacetimedb_durability::TxOffset; -use spacetimedb_fs_utils::dir_trie::{CountCreated, DirTrie}; +use spacetimedb_fs_utils::dir_trie::DirTrie; use spacetimedb_lib::{bsatn, Identity}; use spacetimedb_paths::server::SnapshotDirPath; use spacetimedb_primitives::TableId; use spacetimedb_sats::{Deserialize, Serialize}; use spacetimedb_table::{ page_pool::PagePool, - table::Table, - tiered::{BlobMap, ObjectKey, ObjectStoreError, ScannedBlob}, + tiered::{BlobMap, ObjectKey}, }; use crate::{ - common, remote::ObjectProvider, BlobEntry, ObjectType, SnapshotError, SnapshotReadKindMetrics, TableEntry, - TablePages, + common, remote::ObjectProvider, BlobEntry, ObjectType, ParentRepo, SnapshotError, SnapshotReadKindMetrics, + TableEntry, TablePages, }; pub const SNAPSHOT_VERSION: u8 = 0; @@ -68,37 +67,6 @@ impl Snapshot { self.objects().map(|key| (key.into(), repo.file_path(key))) } - pub fn write_objects<'db, 'a>( - &mut self, - repo: &SnapshotRepo, - parent: Option<&SnapshotDirPath>, - tables: impl Iterator, - blobs: impl Iterator, ObjectStoreError>>, - counter: &mut CountCreated, - ) -> Result<(), SnapshotError> { - let parent = parent.map(SnapshotRepo::open).transpose()?; - - let on_blob_write = |entry| self.blobs.push(entry); - let on_table_write = |entry| self.tables.push(entry); - - common::write_blobs( - &repo.inner, - parent.as_ref().map(|repo| &repo.inner), - on_blob_write, - counter, - blobs, - )?; - common::write_tables( - &repo.inner, - parent.as_ref().map(|repo| &repo.inner), - on_table_write, - counter, - tables, - )?; - - Ok(()) - } - pub fn write_snapshot_file(self, repo: &SnapshotRepo) -> Result<(), SnapshotError> { let path = repo.root.snapshot_file(self.tx_offset); // Serialize and hash the in-memory `Snapshot` object. @@ -161,6 +129,12 @@ impl SnapshotRepo { pub fn file_path(&self, key: ObjectKey) -> PathBuf { self.inner.file_path(key.as_bytes()) } + + pub(crate) fn parent(&self) -> Result, SnapshotError> { + let snapshots_dir = self.root.snapshots(); + let offset = self.root.tx_offset().map(|offset| offset - 1).unwrap_or(TxOffset::MAX); + common::parent_repo(&snapshots_dir, offset) + } } impl ObjectProvider for SnapshotRepo { diff --git a/crates/snapshot/src/v1.rs b/crates/snapshot/src/v1.rs index 27b3ac98abc..99d960a4c41 100644 --- a/crates/snapshot/src/v1.rs +++ b/crates/snapshot/src/v1.rs @@ -6,7 +6,7 @@ use std::{ }; use spacetimedb_durability::TxOffset; -use spacetimedb_fs_utils::dir_trie::{CountCreated, DirTrie}; +use spacetimedb_fs_utils::dir_trie::DirTrie; use spacetimedb_lib::{ bsatn, de::{self, Deserializer}, @@ -17,11 +17,13 @@ use spacetimedb_primitives::TableId; use spacetimedb_sats::{Deserialize, Serialize}; use spacetimedb_table::{ page_pool::PagePool, - table::Table, - tiered::{BlobMap, ObjectKey, ObjectStoreError, ScannedBlob}, + tiered::{BlobMap, ObjectKey}, }; -use crate::{common, remote::ObjectProvider, v0, ObjectType, SnapshotError, SnapshotReadKindMetrics, TablePages}; +use crate::{ + common, remote::ObjectProvider, v0, BlobEntry, ObjectType, ParentRepo, SnapshotError, SnapshotReadKindMetrics, + TableEntry, TablePages, +}; pub const SNAPSHOT_VERSION: u8 = 1; @@ -47,34 +49,6 @@ impl Snapshot { self.objects().map(|key| (key.into(), repo.file_path(key))) } - pub fn write_objects<'db, 'a>( - &mut self, - repo: &SnapshotRepo, - parent: Option<&SnapshotDirPath>, - tables: impl Iterator, - blobs: impl Iterator, ObjectStoreError>>, - counter: &mut CountCreated, - ) -> Result<(), SnapshotError> { - let parent = parent.map(SnapshotRepo::open).transpose()?; - - common::write_blobs( - &repo.blobs, - parent.as_ref().map(|repo| &repo.blobs), - |entry| self.0.blobs.push(entry), - counter, - blobs, - )?; - common::write_tables( - &repo.pages, - parent.as_ref().map(|repo| &repo.pages), - |entry| self.0.tables.push(entry), - counter, - tables, - )?; - - Ok(()) - } - pub fn write_snapshot_file(self, repo: &SnapshotRepo) -> Result<(), SnapshotError> { let path = repo.root.snapshot_file(self.tx_offset); // Serialize and hash the in-memory `Snapshot` object. @@ -88,6 +62,14 @@ impl Snapshot { pub(super) fn repo(&self, dir: &SnapshotDirPath) -> io::Result { SnapshotRepo::open(dir) } + + pub(super) fn blobs_mut(&mut self) -> &mut Vec { + &mut self.0.blobs + } + + pub(super) fn tables_mut(&mut self) -> &mut Vec { + &mut self.0.tables + } } impl Deref for Snapshot { @@ -165,6 +147,12 @@ impl SnapshotRepo { ObjectKey::Page(hash) => self.pages.file_path(hash.as_bytes()), } } + + pub(crate) fn parent(&self) -> Result, SnapshotError> { + let snapshots_dir = self.root.snapshots(); + let offset = self.root.tx_offset().map(|offset| offset - 1).unwrap_or(TxOffset::MAX); + common::parent_repo(&snapshots_dir, offset) + } } impl ObjectProvider for SnapshotRepo { diff --git a/crates/table/Cargo.toml b/crates/table/Cargo.toml index 982459c8aaf..cc36cce3a90 100644 --- a/crates/table/Cargo.toml +++ b/crates/table/Cargo.toml @@ -49,6 +49,7 @@ hashbrown.workspace = true itertools.workspace = true parking_lot.workspace = true smallvec.workspace = true +tempfile.workspace = true thiserror.workspace = true # For the 'proptest' feature. diff --git a/crates/table/src/table.rs b/crates/table/src/table.rs index ffaaf6176e2..544dd054f99 100644 --- a/crates/table/src/table.rs +++ b/crates/table/src/table.rs @@ -4,7 +4,7 @@ use crate::{ page, tiered::{ BlobError, BlobHandle, BlobReadSet, BlobSet, DiskPinnedBlobHandle, DiskPinnedPageHandle, EvictionError, - EvictionPolicy, ObjectStoreError, PageBorrow, PageError, PageHandle, PageManager, PageRef, PageSet, + EvictionPolicy, ObjectStoreError, PageBorrow, PageError, PageHandle, PageHash, PageManager, PageRef, PageSet, PreparedCommit, ReservedPage, }, var_len::VarLenMembers as _, @@ -3417,19 +3417,12 @@ impl Table { } /// Returns the pages storing the physical rows of this table. - fn pages(&self) -> &PageSet { + pub fn pages(&self) -> &PageSet { &self.inner.pages } - /// Iterates over each [`Page`] in this table, ensuring that its hash is computed before yielding it. - /// - /// Used when capturing a snapshot. - // - // TODO(disk-tables): Avoid faulting in pages that are already on disk. - pub fn iter_pages_with_hashes( - &mut self, - ) -> impl Iterator)>, PageError>> { - self.inner.pages.iter_pages_with_hashes() + pub(crate) fn pages_mut(&mut self) -> &mut PageSet { + &mut self.inner.pages } /// Returns the number of pages storing the physical rows of this table. @@ -3454,6 +3447,15 @@ impl Table { .map(|row_ref| row_ref.map(|row_ref| (row_ref.row_hash(), row_ref.pointer()))) .collect() } + + /// Iterate over all pages in this table, faulting them in as needed. + /// + /// This is exposed for testing only! + pub fn iter_pages_with_hashes( + &mut self, + ) -> impl Iterator)>, PageError>> { + self.inner.pages.iter_pages_with_hashes() + } } /// An insert planned during [Table::prepare_commit]. diff --git a/crates/table/src/tiered/blob_set.rs b/crates/table/src/tiered/blob_set.rs index c5b59b0712f..c7075845680 100644 --- a/crates/table/src/tiered/blob_set.rs +++ b/crates/table/src/tiered/blob_set.rs @@ -19,7 +19,7 @@ use crate::{ map::{BlobHashWrapper, ObjectKey}, mem::{self, BlobEvictionCandidate, BlobFrame, EvictionSource, ReservedBlob}, storage::{DiskObject, DiskRetention, Object}, - ByteBudget, ByteBudgetUsage, EvictionPolicy, ObjectBytes, TieredStorage, + ByteBudget, ByteBudgetUsage, EvictionPolicy, TieredStorage, }, var_len::VarLenMembers, }; @@ -539,7 +539,6 @@ impl BlobSet { pub fn scan(&self) -> BlobScan<'_> { BlobScan { entries: self.entries.read(), - storage: &self.storage, } } @@ -926,49 +925,67 @@ impl BlobSetInner { } } -pub struct ScannedBlob<'a> { - pub hash: BlobHash, - pub uses: NonZeroUsize, - pub data: ScannedBlobData<'a>, +pub struct BlobScan<'a> { + entries: RwLockReadGuard<'a, IntMap>, } -pub enum ScannedBlobData<'a> { - Resident(&'a [u8]), - Stored(ObjectBytes), +impl<'a> BlobScan<'a> { + pub fn iter(&'a self) -> IterBlobScan<'a> { + self.into_iter() + } } -impl AsRef<[u8]> for ScannedBlobData<'_> { - fn as_ref(&self) -> &[u8] { - match self { - Self::Resident(bytes) => bytes, - Self::Stored(bytes) => bytes.as_ref(), +impl<'a> IntoIterator for &'a BlobScan<'_> { + type IntoIter = IterBlobScan<'a>; + type Item = ::Item; + + fn into_iter(self) -> Self::IntoIter { + IterBlobScan { + iter: self.entries.iter(), } } } -pub struct BlobScan<'a> { - entries: RwLockReadGuard<'a, IntMap>, - storage: &'a TieredStorage, +pub struct ScannedBlob<'a> { + pub hash: BlobHash, + pub uses: NonZeroUsize, + pub(crate) data: BlobData<'a>, } -impl<'a> BlobScan<'a> { - pub fn iter(&'a self) -> impl Iterator, ObjectStoreError>> + 'a { - self.entries.iter().filter_map(move |(&hash, entry)| { - let uses = NonZeroUsize::new(entry.uses())?; - let get_or_read = || { - let data = match entry { - BlobEntry::Resident { blob, .. } => ScannedBlobData::Resident(blob), - BlobEntry::NonResident { .. } => self.storage.read(hash.into()).map(ScannedBlobData::Stored)?, - }; +pub(crate) enum BlobData<'a> { + Resident { + bytes: &'a BlobHandle, + backing: Option, + }, + Stored { + backing: DiskObject, + }, +} - Ok(ScannedBlob { - hash: hash.into(), - uses, - data, - }) - }; +pub struct IterBlobScan<'a> { + iter: hash_map::Iter<'a, BlobHashWrapper, BlobEntry>, +} + +impl<'a> Iterator for IterBlobScan<'a> { + type Item = ScannedBlob<'a>; + + fn next(&mut self) -> Option { + let (&hash, entry) = self.iter.by_ref().next()?; + let uses = NonZeroUsize::new(entry.uses())?; + let data = match entry { + BlobEntry::Resident { blob, backing, .. } => BlobData::Resident { + bytes: blob, + backing: backing.clone(), + }, + BlobEntry::NonResident { backing, .. } => BlobData::Stored { + backing: backing.clone(), + }, + }; - Some(get_or_read()) + Some(ScannedBlob { + hash: hash.into(), + uses, + data, }) } } diff --git a/crates/table/src/tiered/error.rs b/crates/table/src/tiered/error.rs index d202508cc86..b79b2550f55 100644 --- a/crates/table/src/tiered/error.rs +++ b/crates/table/src/tiered/error.rs @@ -179,3 +179,20 @@ impl EvictionError { } } } + +#[derive(Debug, thiserror::Error)] +pub enum SnapshotError { + #[error(transparent)] + Storage(#[from] ObjectStoreError), + #[error(transparent)] + Io(#[from] io::Error), +} + +impl SnapshotError { + pub fn is_transient(&self) -> bool { + match self { + Self::Storage(e) => e.is_transient(), + Self::Io(_) => true, + } + } +} diff --git a/crates/table/src/tiered/metrics/labels.rs b/crates/table/src/tiered/metrics/labels.rs index b8801e47c9c..2449f283d30 100644 --- a/crates/table/src/tiered/metrics/labels.rs +++ b/crates/table/src/tiered/metrics/labels.rs @@ -63,6 +63,7 @@ pub enum DiskOperation { Read, Write, Delete, + Hardlink, } impl DiskOperation { @@ -71,6 +72,7 @@ impl DiskOperation { Self::Read => "read", Self::Write => "write", Self::Delete => "delete", + Self::Hardlink => "hardlink", } } } diff --git a/crates/table/src/tiered/mod.rs b/crates/table/src/tiered/mod.rs index 9a5c101be27..8998d009ce9 100644 --- a/crates/table/src/tiered/mod.rs +++ b/crates/table/src/tiered/mod.rs @@ -2,7 +2,7 @@ use std::{io, sync::Arc}; use spacetimedb_memory_usage::MemoryUsage; -use crate::page_pool::PagePool; +use crate::{page_pool::PagePool, table::Table}; mod blob_set; mod budget; @@ -13,21 +13,23 @@ pub mod metrics; mod page_manager; mod page_ref; mod page_set; +mod snapshot; mod storage; pub(crate) use self::{blob_set::DiskPinnedBlobHandle, page_set::DiskPinnedPageHandle}; pub use self::{ - blob_set::{BlobHandle, BlobMap, BlobReadSet, BlobScan, BlobSet, ScannedBlob, ScannedBlobData}, + blob_set::{BlobHandle, BlobMap, BlobReadSet, BlobSet}, budget::{BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetConfig, ByteBudgetUsage}, - error::{BlobError, EvictionError, ObjectStoreError, PageError, TrimError}, + error::{BlobError, EvictionError, ObjectStoreError, PageError, SnapshotError, TrimError}, map::{ObjectKey, PageHash}, mem::ResidentObjects, page_manager::{PageHandle, PageManager, ReservedPage}, page_ref::{PageBorrow, PageRead, PageRef}, page_set::{PageSet, PreparedCommit}, + snapshot::{Snapshot, SnapshotObject, SnapshotObjectStorage}, storage::{ - BackingStore, LocalBackingStore, LocalStorage, MemoryObjectStore, Object, ObjectBytes, ObjectMetadata, - ObjectStore, RemoteBackingStore, RemoteStorage, RemoveObject, TieredStorage, + BackingStore, Fsync, HardlinkObject, LocalBackingStore, LocalStorage, MemoryObjectStore, Object, ObjectBytes, + ObjectMetadata, ObjectStore, RemoteBackingStore, RemoteStorage, RemoveObject, TieredStorage, }, }; @@ -137,6 +139,20 @@ impl TieredDatabaseStorage { } } + pub fn create_snapshot<'a>( + &self, + storage: &impl SnapshotObjectStorage, + tables: impl IntoIterator, + ) -> Result { + Snapshot::create( + self, + storage, + tables + .into_iter() + .map(|table| (table.schema.table_id, table.pages_mut())), + ) + } + /// Attempt to free space by reclaiming orphaned objects and evicting from /// memory resident sets and local storage. /// diff --git a/crates/table/src/tiered/page_manager.rs b/crates/table/src/tiered/page_manager.rs index ded59b72eea..6f69fd7563e 100644 --- a/crates/table/src/tiered/page_manager.rs +++ b/crates/table/src/tiered/page_manager.rs @@ -461,17 +461,10 @@ pub struct PageManager { pool: PagePool, resident_cache: Pool, resident: Arc, - pub(crate) storage: Arc, + pub(super) storage: Arc, eviction: Arc, } -#[derive(Debug)] -pub(super) struct PageEviction { - resident: Arc, - storage: Arc, - candidates: Mutex>, -} - impl PageManager { /// Wrap a memory table's page in a tiered slot, keeping its allocation and /// memory charge. An empty slot must stay empty to preserve page indices. @@ -820,6 +813,13 @@ impl PageManager { } } +#[derive(Debug)] +pub(super) struct PageEviction { + resident: Arc, + storage: Arc, + candidates: Mutex>, +} + impl PageEviction { pub(super) fn evict(&self, target_usage: u64) -> Result { let mut bytes_freed = 0; diff --git a/crates/table/src/tiered/page_set.rs b/crates/table/src/tiered/page_set.rs index b0b92852051..1330de25008 100644 --- a/crates/table/src/tiered/page_set.rs +++ b/crates/table/src/tiered/page_set.rs @@ -1,4 +1,3 @@ -use super::metrics::{CacheTier, ObjectType}; use std::{ collections::{btree_map, BTreeMap, BTreeSet}, convert::Infallible, @@ -9,6 +8,7 @@ use spacetimedb_lib::ProductValue; use spacetimedb_memory_usage::MemoryUsage; use spacetimedb_sats::layout::Size; +use super::metrics::{CacheTier, ObjectType}; use crate::{ indexes::{PageIndex, RowPointer}, page::{Page, PageCapacity}, @@ -16,9 +16,10 @@ use crate::{ table::{BlobNumBytes, PreparedInsert, Table, TableError}, tiered::{ blob_set::BlobHandle, + map::PageHash, page_manager::{PageFrameWriteGuard, PageHandle, PageManager, PageSlot, PageSlotHandle, ReservedPage}, storage::DiskObject, - BlobSet, BudgetPermit, EvictionError, EvictionPolicy, ObjectStoreError, PageError, PageRead, PageRef, + BlobSet, BudgetPermit, EvictionError, EvictionPolicy, Object, ObjectStoreError, PageError, PageRead, PageRef, }, var_len::VarLenMembers, }; @@ -232,39 +233,44 @@ pub enum PageInfo<'a> { } impl PageInfo<'_> { - #[cfg(test)] - fn is_full(&self, size: Size) -> Option { - match self { - Self::Resident(p) => Some(p.is_full(size)), - Self::Tiered(p) => p.is_full(size), - } - } fn available_var_len_granules(&self) -> Option { match self { Self::Resident(p) => Some(p.available_var_len_granules()), Self::Tiered(p) => p.available_var_len_granules(), } } + fn has_space_for_row(&self, size: Size, granules: usize) -> Option { match self { Self::Resident(p) => Some(p.has_space_for_row(size, granules)), Self::Tiered(p) => p.has_space_for_row(size, granules), } } + pub fn bytes_used_by_rows(&self, size: Size) -> usize { match self { Self::Resident(p) => p.bytes_used_by_rows(size), Self::Tiered(p) => p.bytes_used_by_rows(), } } - #[cfg(test)] +} + +#[cfg(test)] +impl PageInfo<'_> { + fn is_full(&self, size: Size) -> Option { + match self { + Self::Resident(p) => Some(p.is_full(size)), + Self::Tiered(p) => p.is_full(size), + } + } + pub fn reconstruct_num_rows(&self) -> usize { match self { Self::Resident(p) => p.reconstruct_num_rows(), Self::Tiered(p) => p.reconstruct_num_rows(), } } - #[cfg(test)] + pub unsafe fn reconstruct_bytes_used_by_rows(&self, size: Size, visitor: &impl VarLenMembers) -> usize { unsafe { match self { @@ -503,37 +509,6 @@ impl PageSet { .expect("row reference points at a present page") } - /// Iterate over all pages in this page set, ensuring that the page's hash - /// is computed before yielding it. - /// - /// This will fault in each page if it is not resident. - /// - /// Used when capturing a snapshot. - pub(crate) fn iter_pages_with_hashes( - &mut self, - ) -> impl Iterator)>, PageError>> { - match &mut self.storage { - PageStorage::Resident(resident) => itertools::Either::Left(resident.pages.iter_mut().map(|page| { - Ok(page.as_deref_mut().map(|page| { - let hash = page.save_or_get_content_hash(); - (hash, PageRef::Resident(page)) - })) - })), - PageStorage::Tiered(tiered) => itertools::Either::Right(tiered.slots.iter().map(|slot| { - if slot.is_absent() { - Ok(None) - } else { - let mut page = self.manager.with_page_retry(|fault| { - self.manager - .get_mut_with_fault(slot, self.eviction_policy, self.fixed_row_size, fault) - })?; - let hash = page.save_or_get_content_hash(); - Ok(Some((hash, PageRef::Tiered(page.into_page_handle())))) - } - })), - } - } - /// Run a closure over a mutable [Page]. /// /// The page is faulted in if it is not already resident. @@ -1055,6 +1030,74 @@ impl PageSet { PageStorage::Tiered(_) => self.manager.with_eviction_retry(reserve), } } + + pub(crate) fn iter_pages_with_hashes( + &mut self, + ) -> impl Iterator)>, PageError>> { + use itertools::Either::*; + + match &mut self.storage { + PageStorage::Resident(resident) => Left(resident.pages.iter_mut().map(|page| { + Ok(page.as_deref_mut().map(|page| { + let hash = PageHash::from(&mut *page); + (hash, PageRef::Resident(page)) + })) + })), + PageStorage::Tiered(tiered) => Right(tiered.slots.iter().map(|slot| { + if slot.is_absent() { + Ok(None) + } else { + let mut page = self.manager.with_page_retry(|fault| { + self.manager + .get_mut_with_fault(slot, self.eviction_policy, self.fixed_row_size, fault) + })?; + let hash = PageHash::from(&mut *page); + Ok(Some((hash, PageRef::Tiered(page.into_page_handle())))) + } + })), + } + } + + pub(crate) fn snapshot(&mut self) -> impl Iterator> { + use itertools::Either::*; + + // TODO: Resident pages are serialized eagerly to bsatn. Instead, we + // should do that lazily as the page is being written, so as to use + // memory only for one page at a time. + // Requires some form of copy-on-write. + match &mut self.storage { + PageStorage::Resident(resident) => { + let iter = resident + .pages + .iter_mut() + .map(|page| page.as_deref_mut().map(Object::from).map(PageSnapshot::Memory)); + + Left(iter) + } + PageStorage::Tiered(tiered) => { + let iter = tiered.slots.iter().map(|handle| { + let slot = handle.lock_ref(); + match &*slot { + PageSlot::Absent => None, + PageSlot::NonResident { backing, .. } + | PageSlot::Resident { + backing: Some(backing), .. + } => Some(PageSnapshot::Stored(backing.clone())), + PageSlot::Resident { + handle, backing: None, .. + } => Some(PageSnapshot::Memory(Object::from(handle))), + } + }); + + Right(iter) + } + } + } +} + +pub(crate) enum PageSnapshot { + Memory(Object), + Stored(DiskObject), } #[cfg(test)] diff --git a/crates/table/src/tiered/snapshot.rs b/crates/table/src/tiered/snapshot.rs new file mode 100644 index 00000000000..a19e3694d2d --- /dev/null +++ b/crates/table/src/tiered/snapshot.rs @@ -0,0 +1,160 @@ +use std::{io, num::NonZeroUsize, path::Path}; + +use spacetimedb_primitives::TableId; + +use crate::{ + blob_store::BlobHash, + tiered::{ + blob_set::BlobData, + error::SnapshotError, + page_set::PageSnapshot, + storage::{write_atomically, DiskObject}, + Fsync, Object, ObjectKey, PageHash, PageSet, TieredDatabaseStorage, TieredStorage, + }, +}; + +pub type PageHashes = Vec>; + +pub struct Snapshot { + blobs: Vec<(BlobHash, NonZeroUsize)>, + tables: Vec<(TableId, PageHashes)>, +} + +impl Snapshot { + pub fn create<'a>( + database_storage: &TieredDatabaseStorage, + snapshot_storage: &impl SnapshotObjectStorage, + tables: impl IntoIterator, + ) -> Result { + let mut blobs = Vec::new(); + for blob in database_storage.blobs.scan().into_iter() { + let snapshot_object = match blob.data { + BlobData::Stored { backing } + | BlobData::Resident { + backing: Some(backing), .. + } => SnapshotObject::from_backing(backing, &database_storage.store)?, + BlobData::Resident { bytes, backing: None } => SnapshotObject::Memory(bytes.into()), + }; + + snapshot_storage.write(snapshot_object)?; + blobs.push((blob.hash, blob.uses)); + } + + let mut tables0 = Vec::new(); + for (id, page_set) in tables { + let mut pages = Vec::new(); + for page in page_set.snapshot() { + let Some(page) = page else { + pages.push(None); + continue; + }; + let snapshot_object = match page { + PageSnapshot::Memory(object) => SnapshotObject::Memory(object), + PageSnapshot::Stored(backing) => SnapshotObject::from_backing(backing, &database_storage.store)?, + }; + let hash = snapshot_object + .key() + .as_page_hash() + .copied() + .expect("object key must be a page hash"); + snapshot_storage.write(snapshot_object)?; + pages.push(Some(hash)); + } + + tables0.push((id, pages)); + } + + Ok(Self { blobs, tables: tables0 }) + } + + #[allow(clippy::type_complexity)] + pub fn into_parts(self) -> (Vec<(BlobHash, NonZeroUsize)>, Vec<(TableId, PageHashes)>) { + let Self { blobs, tables } = self; + (blobs, tables) + } +} + +pub enum SnapshotObject<'a> { + Memory(Object), + Local(LocalObject<'a>), + Remote(RemoteObject<'a>), +} + +impl<'a> SnapshotObject<'a> { + pub fn key(&self) -> ObjectKey { + match self { + Self::Memory(inner) => inner.key(), + Self::Local(inner) => inner.object.key(), + Self::Remote(inner) => inner.key, + } + } + + pub fn write(&self, dst: impl AsRef, fsync: Fsync) -> io::Result<()> { + match self { + Self::Memory(inner) => write_atomically(inner.as_bytes(), dst.as_ref(), fsync), + Self::Local(inner) => inner.hardlink_or_write(dst, fsync), + Self::Remote(inner) => inner.write(dst, fsync), + } + } + + pub fn is_remote(&self) -> bool { + matches!(self, Self::Remote(_)) + } + + pub fn as_resident(&self) -> Option<&Object> { + match self { + Self::Memory(object) => Some(object), + Self::Local(_) | Self::Remote(_) => None, + } + } + + fn from_backing(mut backing: DiskObject, store: &'a TieredStorage) -> Result { + // If we determine the object to be local, ensure it stays there until + // written. + backing.pin(); + + let this = if store.stat_local(&backing)?.is_some() { + Self::Local(LocalObject { object: backing, store }) + } else { + // If we have a backing object, but it's not present in the local + // tier, then it must be present in the remote tier as per our + // eviction contract. + // + // The [SnapshotObjectStorage] will have to verify this before + // committing the manifest. + Self::Remote(RemoteObject { + key: backing.key(), + store, + }) + }; + + Ok(this) + } +} + +pub struct LocalObject<'a> { + object: DiskObject, + store: &'a TieredStorage, +} + +impl LocalObject<'_> { + pub fn hardlink_or_write(&self, dst: impl AsRef, fsync: Fsync) -> io::Result<()> { + self.store.hardlink_or_write(&self.object, dst, fsync) + } +} + +pub struct RemoteObject<'a> { + key: ObjectKey, + store: &'a TieredStorage, +} + +impl RemoteObject<'_> { + pub fn write(&self, dst: impl AsRef, fsync: Fsync) -> io::Result<()> { + let bytes = self.store.read(self.key).map_err(io::Error::other)?; + write_atomically(&bytes, dst.as_ref(), fsync) + } +} + +pub trait SnapshotObjectStorage { + fn write(&self, object: SnapshotObject<'_>) -> io::Result<()>; +} diff --git a/crates/table/src/tiered/storage.rs b/crates/table/src/tiered/storage.rs index 2a4d71595a8..15a2b7270b3 100644 --- a/crates/table/src/tiered/storage.rs +++ b/crates/table/src/tiered/storage.rs @@ -1,7 +1,10 @@ use super::metrics::{CacheTier, EvictionDirection, FaultSource, Metrics}; use std::{ - fmt, iter, mem, + fmt, fs, + io::{self, Write}, + iter, mem, num::NonZeroU64, + path::Path, sync::{ atomic::{AtomicBool, AtomicU64, Ordering}, Arc, @@ -12,6 +15,7 @@ use bytes::Bytes; use parking_lot::{Mutex, MutexGuard, RwLock}; use spacetimedb_lib::bsatn; use spacetimedb_memory_usage::MemoryUsage; +use tempfile::NamedTempFile; use crate::{ page::Page, @@ -62,6 +66,22 @@ impl ObjectInner { ObjectInner::Blob { hash, bytes } => ((*hash).into(), bytes.clone()), } } + + #[inline] + pub fn as_bytes(&self) -> &ObjectBytes { + match self { + Self::Page { bytes, .. } => bytes, + Self::Blob { bytes, .. } => bytes, + } + } + + #[inline] + pub fn key(&self) -> ObjectKey { + match self { + Self::Page { hash, .. } => (*hash).into(), + Self::Blob { hash, .. } => (*hash).into(), + } + } } impl Object { @@ -72,6 +92,14 @@ impl Object { pub fn into_kv(self) -> (ObjectKey, ObjectBytes) { self.inner.into_kv() } + + pub fn as_bytes(&self) -> &ObjectBytes { + self.inner.as_bytes() + } + + pub fn key(&self) -> ObjectKey { + self.inner.key() + } } impl From<&BlobHandle> for Object { @@ -106,6 +134,16 @@ impl From<&Page> for Object { } } +impl From<&mut Page> for Object { + fn from(page: &mut Page) -> Self { + let hash = PageHash::from(&mut *page); + let bytes = bsatn::to_vec(page).unwrap().into(); + Self { + inner: ObjectInner::Page { hash, bytes }, + } + } +} + #[derive(Clone, Copy, Debug)] pub struct ObjectMetadata { pub size: u64, @@ -187,8 +225,23 @@ pub unsafe trait RemoveObject { unsafe fn remove(&self, key: ObjectKey) -> Result<(), ObjectStoreError>; } -pub trait LocalStorage: ObjectStore + MemoryUsage + RemoveObject {} -impl LocalStorage for T where T: ObjectStore + MemoryUsage + RemoveObject {} +#[derive(Clone, Copy, Debug)] +pub enum Fsync { + Require, + Defer, +} + +pub trait HardlinkObject { + fn hardlink_to(&self, _: ObjectKey, _: &Path, _: Fsync) -> io::Result<()> { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "hardlinking not supported by this object store", + )) + } +} + +pub trait LocalStorage: ObjectStore + MemoryUsage + RemoveObject + HardlinkObject {} +impl LocalStorage for T where T: ObjectStore + MemoryUsage + RemoveObject + HardlinkObject {} pub trait RemoteStorage: ObjectStore + MemoryUsage {} impl RemoteStorage for T where T: ObjectStore + MemoryUsage {} @@ -223,6 +276,8 @@ unsafe impl RemoveObject for MemoryObjectStore { } } +impl HardlinkObject for MemoryObjectStore {} + impl MemoryUsage for MemoryObjectStore { fn heap_usage(&self) -> usize { let objects = self.objects.read(); @@ -861,6 +916,31 @@ impl TieredStorage { .map_err(ObjectStoreError::from) }) } + + pub(crate) fn hardlink_or_write(&self, object: &DiskObject, dst: impl AsRef, fsync: Fsync) -> io::Result<()> { + let _guard = object.slot.state.lock(); + self.local + .object_store + .hardlink_to(object.key, dst.as_ref(), fsync) + .or_else(|e| { + if e.kind() == io::ErrorKind::Unsupported { + let bytes = self + .local + .object_store + .read(object.key) + .map_err(io::Error::other)? + .expect("object must exist locally"); + + write_atomically(&bytes, dst.as_ref(), fsync) + } else { + Err(e) + } + }) + } + + pub(crate) fn stat_local(&self, object: &DiskObject) -> Result, ObjectStoreError> { + self.local.object_store.stat(object.key) + } } fn object_from_trusted_bytes(key: ObjectKey, bytes: ObjectBytes) -> Object { @@ -871,6 +951,24 @@ fn object_from_trusted_bytes(key: ObjectKey, bytes: ObjectBytes) -> Object { Object { inner } } +pub(crate) fn write_atomically(data: &[u8], path: &Path, fsync: Fsync) -> io::Result<()> { + let dir = path.parent().expect("output path must have a parent"); + + let mut tmp = NamedTempFile::new_in(dir)?; + tmp.write_all(data)?; + if let Fsync::Require = fsync { + tmp.as_file().sync_data()?; + } + tmp.persist(path)?; + + if let Fsync::Require = fsync { + #[cfg(not(target_os = "windows"))] + fs::File::open(dir)?.sync_all()?; + } + + Ok(()) +} + /// Helper struct for promoting an object from remote to local storage. struct Promotion<'a> { key: ObjectKey, @@ -1001,6 +1099,8 @@ impl TieredStorage { } } + impl HardlinkObject for FailingReads {} + impl MemoryUsage for FailingReads { fn heap_usage(&self) -> usize { self.inner.heap_usage() diff --git a/crates/table/src/tiered/storage/tests.rs b/crates/table/src/tiered/storage/tests.rs index 9fe27e78183..d332ce072cd 100644 --- a/crates/table/src/tiered/storage/tests.rs +++ b/crates/table/src/tiered/storage/tests.rs @@ -82,6 +82,8 @@ unsafe impl RemoveObject for Arc { } } +impl HardlinkObject for Arc {} + impl MemoryUsage for TestStore { fn heap_usage(&self) -> usize { self.inner.heap_usage() diff --git a/crates/tiered-storage/src/lib.rs b/crates/tiered-storage/src/lib.rs index 9d0dc42dabd..888191db3f4 100644 --- a/crates/tiered-storage/src/lib.rs +++ b/crates/tiered-storage/src/lib.rs @@ -1,14 +1,18 @@ +use core::fmt; use std::{ fs, io::{self, Write as _}, - path::PathBuf, + path::{Path, PathBuf}, }; use spacetimedb_fs_utils::dir_trie::DirTrie; use spacetimedb_memory_usage::MemoryUsage; use spacetimedb_paths::server::TablesDir; use spacetimedb_snapshot::FileOrDirPath; -use spacetimedb_table::tiered::metrics::{DiskOperation, Metrics}; +use spacetimedb_table::tiered::{ + metrics::{DiskOperation, Metrics}, + Fsync, HardlinkObject, +}; use spacetimedb_table::{ blob_store::BlobHash, page_pool::PagePool, @@ -54,7 +58,7 @@ impl DiskStorage { result.map(|(value, _)| value) } - fn record_operation(&self, operation: DiskOperation, result: &Result) { + fn record_operation(&self, operation: DiskOperation, result: &Result) { self.metrics.disk_operation(operation, result.is_ok()); let Err(error) = result else { return }; let Some(stats) = self.metrics.collected() else { return }; @@ -170,6 +174,30 @@ unsafe impl RemoveObject for DiskStorage { } } +impl HardlinkObject for DiskStorage { + fn hardlink_to(&self, key: ObjectKey, dst: &Path, fsync: Fsync) -> io::Result<()> { + fn link(src: &Path, dst: &Path, _fsync: Fsync) -> io::Result<()> { + fs::hard_link(src, dst)?; + + #[cfg(not(target_os = "windows"))] + if let Fsync::Require = _fsync { + let dir = dst.parent().expect("hardlink target must have a parent"); + fs::File::open(dir)?.sync_all()?; + } + + Ok(()) + } + + let timer = self.metrics.timer(); + let path = self.file_path(&key); + let result = link(&path, dst, fsync); + self.metrics.disk_io(DiskOperation::Hardlink, timer.nanos(), 0); + self.record_operation(DiskOperation::Hardlink, &result); + + result + } +} + impl MemoryUsage for DiskStorage { fn heap_usage(&self) -> usize { // The page pool is a global resource, so don't count here.