diff --git a/Cargo.lock b/Cargo.lock index 6fd6f4051fb..2eddcbfaeba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9165,6 +9165,7 @@ dependencies = [ "futures", "log", "pretty_assertions", + "proptest", "rand 0.9.5", "scopeguard", "spacetimedb-core", diff --git a/crates/datastore/src/locking_tx_datastore/datastore.rs b/crates/datastore/src/locking_tx_datastore/datastore.rs index aa1719eccbe..d3d102b7456 100644 --- a/crates/datastore/src/locking_tx_datastore/datastore.rs +++ b/crates/datastore/src/locking_tx_datastore/datastore.rs @@ -327,7 +327,7 @@ impl Locking { ); let (mut tables, blob_store) = committed_state.persistent_tables_and_blob_store(); - let unflushed_snapshot = repo.create_snapshot(&mut tables, blob_store, tx_offset)?; + let unflushed_snapshot = repo.create_snapshot(&mut tables, blob_store.scan(), tx_offset)?; Ok(Some((tx_offset, unflushed_snapshot))) } diff --git a/crates/engine/src/relational_db.rs b/crates/engine/src/relational_db.rs index d1fa4e96fca..e502acb0858 100644 --- a/crates/engine/src/relational_db.rs +++ b/crates/engine/src/relational_db.rs @@ -4285,10 +4285,10 @@ mod tests { let mut hard_linked_on = 0; let mut hard_linked_off = 0; - let (snapshot, compress) = Snapshot::read_from_file(&snapshot_dir.snapshot_file(last_compress))?; + let (manifest, compress) = Snapshot::read_from_file(&snapshot_dir.snapshot_file(last_compress))?; assert!(compress.is_compressed()); - let repo = SnapshotRepository::object_repo(&snapshot_dir)?; - for (_, path) in snapshot.files(&repo) { + let snapshot = manifest.into_writable(&snapshot_dir)?; + for path in snapshot.file_paths() { match path.metadata()?.nlink() { 0 => hard_linked_off += 1, _ => hard_linked_on += 1, diff --git a/crates/paths/src/server.rs b/crates/paths/src/server.rs index 0131b7e3529..c1e60238d27 100644 --- a/crates/paths/src/server.rs +++ b/crates/paths/src/server.rs @@ -250,12 +250,45 @@ path_type! { /// `{data-dir}/replica/$replica_id/snapshots/$tx_offset.snapshot_dir/$tx_offset.snapshot_bsatn` SnapshotFilePath: file } + +impl SnapshotFilePath { + pub fn snapshot_dir(&self) -> SnapshotDirPath { + SnapshotDirPath( + self.0 + .parent() + .map(ToOwned::to_owned) + .expect("snapshot file must be in a directory"), + ) + } +} + path_type! { /// The objects directory for a snapshot. /// `{data-dir}/replica/$replica_id/snapshots/$tx_offset.snapshot_dir/objects` SnapshotObjectsPath: dir } +impl SnapshotObjectsPath { + pub fn pages(&self) -> SnapshotPagesPath { + SnapshotPagesPath(self.0.join("pages")) + } + + pub fn blobs(&self) -> SnapshotBlobsPath { + SnapshotBlobsPath(self.0.join("blobs")) + } +} +path_type! { + /// The pages directory within a [SnapshotObjectsPath] + /// `{data-dir}/replica/$replica_id/snapshots/$tx_offset.snapshot_dir/objects/pages` + SnapshotPagesPath: dir +} + +path_type! { + /// The blobs directory within a [SnapshotObjectsPath] + /// `{data-dir}/replica/$replica_id/snapshots/$tx_offset.snapshot_dir/objects/blobs` + SnapshotBlobsPath: dir +} + path_type! { /// The commit log directory. `{data-dir}/replica/$replica_id/clog` CommitLogDir: dir diff --git a/crates/snapshot/Cargo.toml b/crates/snapshot/Cargo.toml index 5a4c71708e9..e6d40dba658 100644 --- a/crates/snapshot/Cargo.toml +++ b/crates/snapshot/Cargo.toml @@ -39,6 +39,7 @@ spacetimedb-runtime = { path = "../runtime" } anyhow.workspace = true env_logger.workspace = true pretty_assertions = { workspace = true, features = ["unstable"] } +proptest.workspace = true rand.workspace = true [lints] diff --git a/crates/snapshot/proptest-regressions/tests/versions.txt b/crates/snapshot/proptest-regressions/tests/versions.txt new file mode 100644 index 00000000000..51364365424 --- /dev/null +++ b/crates/snapshot/proptest-regressions/tests/versions.txt @@ -0,0 +1,8 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc ed8aa5846ab7c2b3c3af2abef92c67fe65f84f971ccee9c1cabe667d554e6fd4 # shrinks to source_version = 2, offset = 0, hash = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], uses = 0 +cc fd5da47bbaeaa778260719ea5d1115675ead43444848be5b82cf80c44d53f283 # shrinks to bytes = [], row = 0, offset = 0, compressed = false diff --git a/crates/snapshot/src/common.rs b/crates/snapshot/src/common.rs new file mode 100644 index 00000000000..ab9fe81a95d --- /dev/null +++ b/crates/snapshot/src/common.rs @@ -0,0 +1,337 @@ +use std::{ + collections::BTreeMap, + fs, + io::{BufWriter, Read as _, Write as _}, + num::NonZeroUsize, + time::Instant, +}; + +use spacetimedb_fs_utils::{ + compression::{CompressReader, CompressType}, + dir_trie::{o_excl, o_rdonly, CountCreated, DirTrie}, +}; +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 crate::{ + v0, v1, BlobEntry, FileOrDirPath, ObjectType, Snapshot, SnapshotError, SnapshotReadKindMetrics, TableEntry, + TablePages, MAGIC, ZERO_HASH_DENOTING_ABSENT_PAGE, +}; + +pub(crate) fn read_from_file(path: &SnapshotFilePath) -> Result<(Snapshot, CompressType), SnapshotError> { + read_from_file_with_metrics(path).map(|(snapshot, compress_type, _metrics)| (snapshot, compress_type)) +} + +pub(crate) fn read_from_file_with_metrics( + path: &SnapshotFilePath, +) -> Result<(Snapshot, CompressType, SnapshotReadKindMetrics), SnapshotError> { + let read_start = Instant::now(); + let mut read_metrics = SnapshotReadKindMetrics { + files: 1, + ..Default::default() + }; + let err_read_object = |cause| SnapshotError::ReadObject { + ty: ObjectType::Snapshot, + source_repo: path.0.clone(), + cause, + }; + let snapshot_file = path.open_file(&o_rdonly()).map_err(err_read_object)?; + read_metrics.disk_bytes = snapshot_file.metadata().map_err(err_read_object)?.len(); + let mut snapshot_file = CompressReader::new(snapshot_file)?; + + // The snapshot file is prefixed with the hash of the `Snapshot`'s BSATN. + // Read that hash. + let mut hash = [0; blake3::OUT_LEN]; + snapshot_file.read_exact(&mut hash).map_err(err_read_object)?; + let hash = blake3::Hash::from_bytes(hash); + + // Figure out the version. + // A snapshot file doesn't have a header per-se, but let's pretend the magic + // and the version numbers are the header. Since `MAGIC` is an array, bsatn + // prefixes it with a length (u32 le). The version number is a single byte. + // + // TODO: The magic is validated in [Snapshot::read_snapshot], but we could + // do it here already and avoid I/O. + const HEADER_LEN: usize = 4 + MAGIC.len() + 1; + let mut magic_and_version = [8; HEADER_LEN]; + snapshot_file + .read_exact(&mut magic_and_version) + .map_err(err_read_object)?; + let version = magic_and_version[HEADER_LEN - 1]; + + // Read the `Snapshot`'s BSATN and compute its hash. + let mut snapshot_bsatn = magic_and_version.to_vec(); + snapshot_file + .read_to_end(&mut snapshot_bsatn) + .map_err(err_read_object)?; + let hash_start = Instant::now(); + let computed_hash = blake3::hash(&snapshot_bsatn); + read_metrics.hash_time += hash_start.elapsed(); + + // Compare the saved and computed hashes, and fail if they do not match. + if hash != computed_hash { + return Err(SnapshotError::HashMismatch { + ty: ObjectType::Snapshot, + expected: *hash.as_bytes(), + computed: *computed_hash.as_bytes(), + source_repo: path.0.clone(), + }); + } + + let deserialize_err = |cause| SnapshotError::Deserialize { + ty: ObjectType::Snapshot, + source_repo: path.0.clone(), + cause, + }; + + let snapshot = match version { + v0::SNAPSHOT_VERSION => { + let manifest: v0::Snapshot = bsatn::from_slice(&snapshot_bsatn).map_err(deserialize_err)?; + assert_eq!(manifest.version, v0::SNAPSHOT_VERSION); + Ok(Snapshot::V0(manifest)) + } + v1::SNAPSHOT_VERSION => bsatn::from_slice(&snapshot_bsatn) + .map_err(deserialize_err) + .map(Snapshot::V1), + v => Err(SnapshotError::BadVersion { + tx_offset: path.snapshot_dir().tx_offset().expect("invalid snapshot directory"), + version: v, + }), + }?; + + read_metrics.read_time += read_start.elapsed(); + + Ok((snapshot, snapshot_file.compress_type(), read_metrics)) +} + +pub(crate) fn reconstruct_blob_store( + blobs: &[BlobEntry], + repo: &DirTrie, + metrics: &mut SnapshotReadKindMetrics, +) -> Result { + let mut blob_store = BlobMap::default(); + + for BlobEntry { hash, uses } in blobs { + // Read the bytes of the blob object. + let (buf, disk_bytes) = read_object_with_disk_bytes(repo, &hash.data, ObjectType::Blob(*hash))?; + metrics.disk_bytes += disk_bytes; + + // Compute the blob's hash. + let hash_start = Instant::now(); + let computed_hash = BlobHash::hash_from_bytes(&buf); + metrics.hash_time += hash_start.elapsed(); + + // Compare the computed hash to the one recorded in the `Snapshot`, + // and fail if they do not match. + if *hash != computed_hash { + return Err(SnapshotError::HashMismatch { + ty: ObjectType::Blob(*hash), + expected: hash.data, + computed: computed_hash.data, + source_repo: repo.root().to_path_buf(), + }); + } + + if let Some(uses) = NonZeroUsize::new(*uses as usize) { + blob_store.insert_with_uses(hash, uses, buf.into()); + } + } + + Ok(blob_store) +} + +fn read_object_with_disk_bytes( + repo: &DirTrie, + file_id: &[u8; blake3::OUT_LEN], + ty: ObjectType, +) -> Result<(Vec, u64), SnapshotError> { + let source_repo = || repo.root().to_path_buf(); + let disk_bytes = fs::metadata(repo.file_path(file_id)) + .map_err(|cause| SnapshotError::ReadObject { + ty, + source_repo: source_repo(), + cause, + })? + .len(); + let buf = repo.read_entry(file_id).map_err(|cause| SnapshotError::ReadObject { + ty, + source_repo: source_repo(), + cause, + })?; + Ok((buf, disk_bytes)) +} + +/// Reconstruct all the table data from `self`, +/// reading pages from files in the `object_repo`. +/// +/// This method cannot construct [`Table`] objects +/// because doing so requires knowledge of the system tables' schemas +/// to compute the schemas of the user-defined tables +/// +/// Fails if any object file referenced in `self` (as a page or large blob) +/// is missing or corrupted, +/// as detected by comparing the hash of its bytes to the hash recorded in `self`. +pub(crate) fn reconstruct_tables( + tables: &[TableEntry], + repo: &DirTrie, + page_pool: &PagePool, + metrics: &mut SnapshotReadKindMetrics, +) -> Result, SnapshotError> { + tables + .iter() + .map(|tbl| reconstruct_one_table(repo, tbl, page_pool, metrics)) + .collect() +} + +fn reconstruct_one_table( + repo: &DirTrie, + TableEntry { table_id, pages }: &TableEntry, + page_pool: &PagePool, + metrics: &mut SnapshotReadKindMetrics, +) -> Result<(TableId, TablePages), SnapshotError> { + Ok((*table_id, reconstruct_one_table_pages(repo, pages, page_pool, metrics)?)) +} + +/// Read all the pages referenced by `pages` from the `object_repo`. +/// +/// Fails if any of the pages files is missing or corrupted, +/// as detected by comparing the hash of its bytes to the hash listed in `pages`. +fn reconstruct_one_table_pages( + repo: &DirTrie, + pages: &[blake3::Hash], + page_pool: &PagePool, + metrics: &mut SnapshotReadKindMetrics, +) -> Result { + pages + .iter() + .map(|hash| { + if *hash == ZERO_HASH_DENOTING_ABSENT_PAGE { + Ok(None) + } else { + // Read the BSATN bytes of the on-disk page object. + let (buf, disk_bytes) = read_object_with_disk_bytes(repo, hash.as_bytes(), ObjectType::Page(*hash))?; + metrics.disk_bytes += disk_bytes; + + // Deserialize the bytes into a `Page`. + let page = page_pool.take_deserialize_from(&buf); + let page = page.map_err(|cause| SnapshotError::Deserialize { + ty: ObjectType::Page(*hash), + source_repo: repo.root().to_path_buf(), + cause, + })?; + + // Compute the hash of the page. + let hash_start = Instant::now(); + let computed_hash = page.content_hash(); + metrics.hash_time += hash_start.elapsed(); + + // Compare the computed hash to the one recorded in the `Snapshot`, + // and fail if they do not match. + if *hash != computed_hash { + return Err(SnapshotError::HashMismatch { + ty: ObjectType::Page(*hash), + expected: *hash.as_bytes(), + computed: *computed_hash.as_bytes(), + source_repo: repo.root().to_path_buf(), + }); + } + + Ok::>, SnapshotError>(Some(page)) + } + }) + .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); + + // Create the snapshot file, containing first the hash, then the `Snapshot`. + { + let mut snapshot_file = BufWriter::new(path.open_file(&o_excl())?); + snapshot_file.write_all(hash.as_bytes())?; + snapshot_file.write_all(snapshot_bsatn)?; + snapshot_file.flush()?; + // fsync file + enclosing directory. + snapshot_file + .into_inner() + .expect("buffered writer just flushed") + .sync_all()?; + FileOrDirPath::Dir(&path.snapshot_dir().0).sync_all()?; + } + + Ok(()) +} diff --git a/crates/snapshot/src/lib.rs b/crates/snapshot/src/lib.rs index 9226e8c5650..4f5fc219424 100644 --- a/crates/snapshot/src/lib.rs +++ b/crates/snapshot/src/lib.rs @@ -33,16 +33,18 @@ use spacetimedb_fs_utils::{ dir_trie::{o_excl, o_rdonly, CountCreated, DirTrie}, lockfile::{Lockfile, LockfileError}, }; +use spacetimedb_lib::ser::Serializer; use spacetimedb_lib::Identity; use spacetimedb_paths::server::{ArchivedSnapshotDirPath, SnapshotDirPath, SnapshotFilePath, SnapshotsPath}; use spacetimedb_paths::FromPathUnchecked; use spacetimedb_primitives::TableId; use spacetimedb_sats::{bsatn, de::Deserialize, ser::Serialize}; -use spacetimedb_table::tiered::{BlobError, BlobMap, BlobSet, ObjectStoreError, PageError}; +use spacetimedb_table::tiered::{ + BlobError, BlobMap, BlobScan, ObjectKey, ObjectStoreError, PageError, PageHash, ScannedBlob, +}; use spacetimedb_table::{blob_store::BlobHash, page::Page, page_pool::PagePool, table::Table}; use std::fs::{self, File}; use std::io; -use std::num::NonZeroUsize; use std::ops::{Range, RangeBounds}; use std::path::Path; use std::time::{Duration, Instant}; @@ -50,14 +52,22 @@ use std::{ collections::BTreeMap, ffi::OsStr, fmt, - io::{BufWriter, Read, Write}, + io::BufWriter, ops::{Add, AddAssign}, path::PathBuf, }; use tokio::task::spawn_blocking; +mod common; pub mod remote; -use remote::verify_snapshot; +mod v0; +mod v1; + +use crate::remote::ObjectProvider; +use crate::{ + common::{read_from_file, read_from_file_with_metrics}, + remote::verify_snapshot, +}; #[derive(Debug, Copy, Clone)] /// An object which may be associated with an error during snapshotting. @@ -77,6 +87,21 @@ impl std::fmt::Display for ObjectType { } } +impl From for ObjectType { + fn from(key: ObjectKey) -> Self { + match key { + ObjectKey::Page(hash) => Self::Page(hash.into()), + ObjectKey::Blob(hash) => Self::Blob(hash.into()), + } + } +} + +impl From for ObjectType { + fn from(hash: PageHash) -> Self { + Self::Page(hash.into()) + } +} + #[derive(Debug, Copy, Clone, Default)] pub struct SnapshotReadKindMetrics { /// Time spent reading, decoding, and verifying objects of this kind. @@ -102,17 +127,6 @@ pub struct SnapshotReadMetrics { pub type TablePages = Vec>>; -fn table_present_pages(pages: &[blake3::Hash]) -> impl Iterator { - pages - .iter() - .copied() - .filter(|hash| *hash != ZERO_HASH_DENOTING_ABSENT_PAGE) -} - -fn table_num_present_pages(pages: &[blake3::Hash]) -> u64 { - table_present_pages(pages).count() as u64 -} - impl SnapshotReadMetrics { pub fn iter(&self) -> impl Iterator + '_ { [("metadata", &self.metadata), ("page", &self.page), ("blob", &self.blob)].into_iter() @@ -223,6 +237,22 @@ struct TableEntry { pages: Vec, } +impl TableEntry { + /// Iterate over all pages in the table. + /// + /// Includes absent pages, use [Self::present_pages] to exclude them. + pub fn pages(&self) -> impl Iterator { + self.pages.iter().map(|hash| + // SAFETY: A snapshot manifest table entry describes pages. + unsafe { PageHash::from_blake3(*hash) }) + } + + pub fn present_pages(&self) -> impl Iterator { + self.pages() + .filter(|hash| blake3::Hash::from(*hash) != ZERO_HASH_DENOTING_ABSENT_PAGE) + } +} + /// A non-durable snapshot created via [SnapshotRepository::create_snapshot]. /// /// When [SnapshotRepository::create_snapshot] returns, all objects will have @@ -255,7 +285,7 @@ pub struct UnflushedSnapshot { impl UnflushedSnapshot { /// Return the transaction offset this pending snapshot will finalize at. pub fn tx_offset(&self) -> TxOffset { - self.inner.as_ref().unwrap().snapshot.tx_offset + self.inner.as_ref().unwrap().repo.tx_offset() } /// Sync all objects in the snapshot and write out the snapshot file. @@ -277,10 +307,8 @@ impl Drop for UnflushedSnapshot { } struct UnflushedSnapshotInner { - snapshot: Snapshot, snapshot_dir: SnapshotDirPath, - snapshot_repo: SnapshotRepository, - object_repo: DirTrie, + repo: WritableSnapshot, lockfile: Lockfile, } @@ -290,15 +318,14 @@ impl UnflushedSnapshotInner { // The paths yielded by the [Snapshot::files] iterator are constructed // by [DirTree::file_path], which creates a path with a parent. // `parent()` is thus known to succeed. - for (_, path) in self.snapshot.files(&self.object_repo) { + for path in self.repo.file_paths() { FileOrDirPath::File(&path).sync_all()?; FileOrDirPath::Dir(path.parent().unwrap()).sync_all()?; } // Sync the root directory of the object repo - FileOrDirPath::Dir(self.object_repo.root()).sync_all()?; + FileOrDirPath::Dir(self.repo.root()).sync_all()?; // Write out the snapshot file (syncs internally). - self.snapshot_repo - .write_snapshot_file(&self.snapshot_dir, self.snapshot)?; + self.repo.commit()?; // We can now drop the lockfile. drop(self.lockfile); @@ -331,157 +358,151 @@ impl PendingSnapshot for UnflushedSnapshot { } } -#[derive(Clone, Serialize, Deserialize)] -pub struct Snapshot { - /// A magic number: must be equal to [`MAGIC`]. - magic: [u8; 4], +pub enum WritableSnapshot { + V0 { + manifest: v0::Snapshot, + repo: v0::SnapshotRepo, + }, + V1 { + manifest: v1::Snapshot, + repo: v1::SnapshotRepo, + }, +} - /// The snapshot version number. Must be equal to [`CURRENT_SNAPSHOT_VERSION`]. - version: u8, +impl WritableSnapshot { + pub fn root(&self) -> &Path { + match self { + Self::V0 { repo, .. } => repo.root(), + Self::V1 { repo, .. } => repo.root(), + } + } - /// The identity of the snapshotted database. - pub database_identity: Identity, - /// The instance ID of the snapshotted database. - pub replica_id: u64, + pub fn file_path(&self, key: ObjectKey) -> PathBuf { + match self { + Self::V0 { repo, .. } => repo.file_path(key), + Self::V1 { repo, .. } => repo.file_path(key), + } + } - /// ABI version of the module from which this snapshot was created, as [MAJOR, MINOR]. - /// - /// As of this proposal, [7, 0]. - module_abi_version: [u16; 2], + pub fn tx_offset(&self) -> TxOffset { + match self { + Self::V0 { manifest, .. } => manifest.tx_offset, + Self::V1 { manifest, .. } => manifest.tx_offset, + } + } - /// The transaction offset of the state this snapshot reflects. - pub tx_offset: TxOffset, + pub fn manifest(&self) -> Snapshot { + match self { + Self::V0 { manifest, .. } => Snapshot::V0(manifest.clone()), + Self::V1 { manifest, .. } => Snapshot::V1(manifest.clone()), + } + } - /// The hashes and reference counts of all objects in the blob store. - blobs: Vec, + pub fn file_paths(&self) -> impl Iterator { + self.object_keys_and_file_paths().map(|(_, path)| path) + } - /// For each table, its table ID followed by the hashes of all resident pages. - /// - /// It's necessary to store the table ID rather than relying on order - /// because table IDs may be sparse (and will be, once we reserve a bunch of system table ids). - tables: Vec, -} + 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())), + }; -impl Snapshot { - /// Insert a single large blob from a [`BlobSet`] - /// into the in-memory snapshot `self` - /// and the on-disk object repository `object_repo`. - /// - /// If the `prev_snapshot` is supplied, this method will attempt to hardlink the blob's on-disk object - /// from that previous snapshot into `object_repo` rather than creating a fresh object. - fn write_blob( - &mut self, - object_repo: &DirTrie, - hash: &BlobHash, - uses: usize, - blob: &[u8], - prev_snapshot: Option<&DirTrie>, - counter: &mut CountCreated, - ) -> Result<(), SnapshotError> { - object_repo - .hardlink_or_write(prev_snapshot, &hash.data, || blob, counter) - .map_err(|cause| SnapshotError::WriteObject { - ty: ObjectType::Blob(*hash), - dest_repo: object_repo.root().to_path_buf(), - source_repo: prev_snapshot.map(|dest_repo| dest_repo.root().to_path_buf()), - cause, - })?; - self.blobs.push(BlobEntry { - hash: *hash, - uses: uses as u32, - }); - Ok(()) + v0.into_iter().flatten().chain(v1.into_iter().flatten()) } - /// Populate the in-memory snapshot `self`, - /// and the on-disk object repository `object_repo`, - /// with all large blobs from `blobs`. - fn write_all_blobs( - &mut self, - object_repo: &DirTrie, - blobs: &BlobSet, - prev_snapshot: Option<&DirTrie>, - counter: &mut CountCreated, - ) -> Result<(), SnapshotError> { - blobs.try_for_each(|hash, uses, blob| { - self.write_blob(object_repo, &hash, uses.get(), blob, prev_snapshot, counter) - })?; + 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))))), + }; - Ok(()) + v0.into_iter().flatten().chain(v1.into_iter().flatten()) } - /// Write a single `page` into the on-disk object repository `object_repo`. - /// - /// `hash` must be the content hash of `page`, and must be stored in `page.unmodified_hash()`. - /// - /// Returns the `hash` for convenient use with [`Iter::map`] in [`Self::write_table`]. - /// - /// If the `prev_snapshot` is supplied, this function will attempt to hardlink the page's on-disk object - /// from that previous snapshot into `object_repo` rather than creating a fresh object. - fn write_page( - object_repo: &DirTrie, - page: &Page, - hash: blake3::Hash, - prev_snapshot: Option<&DirTrie>, - counter: &mut CountCreated, - ) -> Result { - debug_assert!(page.unmodified_hash().copied() == Some(hash)); - - object_repo - .hardlink_or_write(prev_snapshot, hash.as_bytes(), || bsatn::to_vec(page).unwrap(), counter) - .map_err(|cause| SnapshotError::WriteObject { - ty: ObjectType::Page(hash), - dest_repo: object_repo.root().to_path_buf(), - source_repo: prev_snapshot.map(|source_repo| source_repo.root().to_path_buf()), - cause, - })?; + 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), + } + } - Ok(hash) + fn reconstruct( + &self, + page_pool: &PagePool, + metrics: &mut SnapshotReadMetrics, + ) -> Result<(BlobMap, BTreeMap), SnapshotError> { + match self { + Self::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(); + + let page_start = Instant::now(); + let tables = repo.reconstruct_tables(manifest, page_pool, &mut metrics.page)?; + metrics.page.read_time = page_start.elapsed(); + + Ok((blob_store, tables)) + } + Self::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(); + + let page_start = Instant::now(); + let tables = repo.reconstruct_tables(manifest, page_pool, &mut metrics.page)?; + metrics.page.read_time = page_start.elapsed(); + + Ok((blob_store, tables)) + } + } } - /// Populate the in-memory snapshot `self`, - /// and the on-disk object repository `object_repo`, - /// with all pages from `table`. - fn write_table( + fn write_objects<'db, 'a>( &mut self, - object_repo: &DirTrie, - table: &mut Table, - prev_snapshot: Option<&DirTrie>, + parent: Option<&SnapshotDirPath>, + tables: impl Iterator, + blobs: impl Iterator, ObjectStoreError>>, counter: &mut CountCreated, ) -> Result<(), SnapshotError> { - 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)) => Self::write_page(object_repo, &page.read(), hash, prev_snapshot, counter)?, - }; - - pages.push(hash); + 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), } + } - self.tables.push(TableEntry { - table_id: table.schema.table_id, - pages, - }); - Ok(()) + fn try_hardlink_from(&self, parent: &Self, key: ObjectKey) -> io::Result { + let src = parent.file_path(key); + if src.is_file() { + let dst = self.file_path(key); + fs::create_dir_all(dst.parent().expect("dir trie paths have a parent"))?; + fs::hard_link(src, dst)?; + + Ok(true) + } else { + Ok(false) + } } +} - /// Populate the in-memory snapshot `self`, - /// and the on-disk object repository `object_repo`, - /// with all pages from all tables in `tables`. - fn write_all_tables<'db>( - &mut self, - object_repo: &DirTrie, - tables: impl Iterator, - prev_snapshot: Option<&DirTrie>, - counter: &mut CountCreated, - ) -> Result<(), SnapshotError> { - for table in tables { - self.write_table(object_repo, table, prev_snapshot, counter)?; +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, } - Ok(()) } +} + +#[derive(Clone)] +pub enum Snapshot { + V0(v0::Snapshot), + V1(v1::Snapshot), +} +impl Snapshot { /// Read a [`Snapshot`] from the file at `path`, verify its hash, and return it. /// /// **NOTE**: It detects if the file was compressed or not. @@ -492,237 +513,105 @@ impl Snapshot { /// - The file at `path` is corrupted, /// as detected by comparing the hash of its bytes to a hash recorded in the file. pub fn read_from_file(path: &SnapshotFilePath) -> Result<(Self, CompressType), SnapshotError> { - Self::read_from_file_with_metrics(path).map(|(snapshot, compress_type, _metrics)| (snapshot, compress_type)) + read_from_file(path) } - fn read_from_file_with_metrics( - path: &SnapshotFilePath, - ) -> Result<(Self, CompressType, SnapshotReadKindMetrics), SnapshotError> { - let read_start = Instant::now(); - let mut read_metrics = SnapshotReadKindMetrics { - files: 1, - ..Default::default() - }; - let err_read_object = |cause| SnapshotError::ReadObject { - ty: ObjectType::Snapshot, - source_repo: path.0.clone(), - cause, - }; - let snapshot_file = path.open_file(&o_rdonly()).map_err(err_read_object)?; - read_metrics.disk_bytes = snapshot_file.metadata().map_err(err_read_object)?.len(); - let mut snapshot_file = CompressReader::new(snapshot_file)?; - - // The snapshot file is prefixed with the hash of the `Snapshot`'s BSATN. - // Read that hash. - let mut hash = [0; blake3::OUT_LEN]; - snapshot_file.read_exact(&mut hash).map_err(err_read_object)?; - let hash = blake3::Hash::from_bytes(hash); - - // Read the `Snapshot`'s BSATN and compute its hash. - let mut snapshot_bsatn = vec![]; - snapshot_file - .read_to_end(&mut snapshot_bsatn) - .map_err(err_read_object)?; - let hash_start = Instant::now(); - let computed_hash = blake3::hash(&snapshot_bsatn); - read_metrics.hash_time += hash_start.elapsed(); - - // Compare the saved and computed hashes, and fail if they do not match. - if hash != computed_hash { - return Err(SnapshotError::HashMismatch { - ty: ObjectType::Snapshot, - expected: *hash.as_bytes(), - computed: *computed_hash.as_bytes(), - source_repo: path.0.clone(), - }); + /// The transaction offset at which this snapshot was taken. + pub fn tx_offset(&self) -> TxOffset { + match self { + Self::V0(inner) => inner.tx_offset, + Self::V1(inner) => inner.tx_offset, } + } - let snapshot = bsatn::from_slice::(&snapshot_bsatn).map_err(|cause| SnapshotError::Deserialize { - ty: ObjectType::Snapshot, - source_repo: path.0.clone(), - cause, - })?; - - read_metrics.read_time += read_start.elapsed(); - - Ok((snapshot, snapshot_file.compress_type(), read_metrics)) + /// The transaction offset at which this snapshot was taken, as a mutable borrow. + /// + /// NOTE: This is exposed for integration tests. + pub fn tx_offset_mut(&mut self) -> &mut TxOffset { + match self { + Self::V0(inner) => &mut inner.tx_offset, + Self::V1(inner) => inner.tx_offset_mut(), + } } - fn read_object_with_disk_bytes( - object_repo: &DirTrie, - file_id: &[u8; blake3::OUT_LEN], - ty: ObjectType, - ) -> Result<(Vec, u64), SnapshotError> { - let source_repo = || object_repo.root().to_path_buf(); - let disk_bytes = fs::metadata(object_repo.file_path(file_id)) - .map_err(|cause| SnapshotError::ReadObject { - ty, - source_repo: source_repo(), - cause, - })? - .len(); - let buf = object_repo - .read_entry(file_id) - .map_err(|cause| SnapshotError::ReadObject { - ty, - source_repo: source_repo(), - cause, - })?; - Ok((buf, disk_bytes)) + /// The total number of objects this snapshot references. + pub fn total_objects(&self) -> usize { + match self { + Self::V0(inner) => inner.total_objects(), + Self::V1(inner) => inner.total_objects(), + } } - /// Construct a [`BlobMap`] containing all the blobs referenced in `self`, - /// reading their data from files in the `object_repo`. - /// - /// Fails if any of the object files is missing or corrupted, - /// as detected by comparing the hash of its bytes to the hash recorded in `self`. - fn reconstruct_blob_store( - &self, - object_repo: &DirTrie, - metrics: &mut SnapshotReadKindMetrics, - ) -> Result { - let mut blob_store = BlobMap::default(); - - for BlobEntry { hash, uses } in &self.blobs { - // Read the bytes of the blob object. - let (buf, disk_bytes) = - Self::read_object_with_disk_bytes(object_repo, &hash.data, ObjectType::Blob(*hash))?; - metrics.disk_bytes += disk_bytes; - - // Compute the blob's hash. - let hash_start = Instant::now(); - let computed_hash = BlobHash::hash_from_bytes(&buf); - metrics.hash_time += hash_start.elapsed(); - - // Compare the computed hash to the one recorded in the `Snapshot`, - // and fail if they do not match. - if *hash != computed_hash { - return Err(SnapshotError::HashMismatch { - ty: ObjectType::Blob(*hash), - expected: hash.data, - computed: computed_hash.data, - source_repo: object_repo.root().to_path_buf(), - }); - } + fn magic(&self) -> [u8; 4] { + match self { + Self::V0(inner) => inner.magic, + Self::V1(inner) => inner.magic, + } + } - if let Some(uses) = NonZeroUsize::new(*uses as usize) { - blob_store.insert_with_uses(hash, uses, buf.into()); - } + #[cfg(test)] + fn version(&self) -> u8 { + match self { + Self::V0(inner) => inner.version, + Self::V1(inner) => inner.version, } + } - Ok(blob_store) + fn database_identity(&self) -> Identity { + match self { + Self::V0(inner) => inner.database_identity, + Self::V1(inner) => inner.database_identity, + } } - /// Read all the pages referenced by `pages` from the `object_repo`. - /// - /// Fails if any of the pages files is missing or corrupted, - /// as detected by comparing the hash of its bytes to the hash listed in `pages`. - fn reconstruct_one_table_pages( - object_repo: &DirTrie, - pages: &[blake3::Hash], - page_pool: &PagePool, - metrics: &mut SnapshotReadKindMetrics, - ) -> Result { - pages - .iter() - .map(|hash| { - if *hash == ZERO_HASH_DENOTING_ABSENT_PAGE { - Ok(None) - } else { - // Read the BSATN bytes of the on-disk page object. - let (buf, disk_bytes) = - Self::read_object_with_disk_bytes(object_repo, hash.as_bytes(), ObjectType::Page(*hash))?; - metrics.disk_bytes += disk_bytes; - - // Deserialize the bytes into a `Page`. - let page = page_pool.take_deserialize_from(&buf); - let page = page.map_err(|cause| SnapshotError::Deserialize { - ty: ObjectType::Page(*hash), - source_repo: object_repo.root().to_path_buf(), - cause, - })?; - - // Compute the hash of the page. - let hash_start = Instant::now(); - let computed_hash = page.content_hash(); - metrics.hash_time += hash_start.elapsed(); - - // Compare the computed hash to the one recorded in the `Snapshot`, - // and fail if they do not match. - if *hash != computed_hash { - return Err(SnapshotError::HashMismatch { - ty: ObjectType::Page(*hash), - expected: *hash.as_bytes(), - computed: *computed_hash.as_bytes(), - source_repo: object_repo.root().to_path_buf(), - }); - } + fn replica_id(&self) -> u64 { + match self { + Self::V0(inner) => inner.replica_id, + Self::V1(inner) => inner.replica_id, + } + } - Ok::>, SnapshotError>(Some(page)) - } - }) - .collect() + fn module_abi_version(&self) -> [u16; 2] { + match self { + Self::V0(inner) => inner.module_abi_version, + Self::V1(inner) => inner.module_abi_version, + } } - fn reconstruct_one_table( - object_repo: &DirTrie, - TableEntry { table_id, pages }: &TableEntry, - page_pool: &PagePool, - metrics: &mut SnapshotReadKindMetrics, - ) -> Result<(TableId, TablePages), SnapshotError> { - Ok(( - *table_id, - Self::reconstruct_one_table_pages(object_repo, pages, page_pool, metrics)?, - )) + fn blobs(&self) -> &Vec { + match self { + Self::V0(inner) => &inner.blobs, + Self::V1(inner) => &inner.blobs, + } } - /// Reconstruct all the table data from `self`, - /// reading pages from files in the `object_repo`. - /// - /// This method cannot construct [`Table`] objects - /// because doing so requires knowledge of the system tables' schemas - /// to compute the schemas of the user-defined tables - /// - /// Fails if any object file referenced in `self` (as a page or large blob) - /// is missing or corrupted, - /// as detected by comparing the hash of its bytes to the hash recorded in `self`. - fn reconstruct_tables( - &self, - object_repo: &DirTrie, - page_pool: &PagePool, - metrics: &mut SnapshotReadKindMetrics, - ) -> Result, SnapshotError> { - self.tables - .iter() - .map(|tbl| Self::reconstruct_one_table(object_repo, tbl, page_pool, metrics)) - .collect() + fn tables(&self) -> &Vec { + match self { + Self::V0(inner) => &inner.tables, + Self::V1(inner) => &inner.tables, + } } - /// The number of objects in this snapshot, both blobs and pages. - pub fn total_objects(&self) -> usize { - self.blobs.len() - + self - .tables - .iter() - .map(|table| table_num_present_pages(&table.pages) as usize) - .sum::() - } - - /// Obtain an iterator over the [`blake3::Hash`]es of all objects - /// this snapshot is referring to. - pub fn objects(&self) -> impl Iterator + '_ { - self.blobs - .iter() - .map(|b| blake3::Hash::from_bytes(b.hash.data)) - .chain(self.tables.iter().flat_map(|t| table_present_pages(&t.pages))) + pub fn into_writable(self, dir: &SnapshotDirPath) -> io::Result { + match self { + Self::V0(inner) => { + let repo = inner.repo(dir)?; + Ok(WritableSnapshot::V0 { manifest: inner, repo }) + } + Self::V1(inner) => { + let repo = inner.repo(dir)?; + Ok(WritableSnapshot::V1 { manifest: inner, repo }) + } + } } +} - /// Obtain an iterator over the [`PathBuf`]s of all objects - pub fn files<'a>(&'a self, src_repo: &'a DirTrie) -> impl Iterator + 'a { - self.objects().map(move |hash| { - let path = src_repo.file_path(hash.as_bytes()); - (hash, path) - }) +impl Serialize for Snapshot { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::V0(v0) => v0.serialize(serializer), + Self::V1(v1) => v1.serialize(serializer), + } } } @@ -884,10 +773,10 @@ 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>( + pub fn create_snapshot<'db, 'b>( &self, tables: impl Iterator, - blobs: &BlobSet, + blobs: BlobScan<'b>, tx_offset: TxOffset, ) -> Result { // Invalidate equal to or newer than `tx_offset`. @@ -901,23 +790,6 @@ impl SnapshotRepository { // mistake the existing snapshot (now invalid) as the previous snapshot. self.invalidate_newer_snapshots(tx_offset.saturating_sub(1))?; - // If a previous snapshot exists in this snapshot repo, - // get a handle on its object repo in order to hardlink shared objects into the new snapshot. - let prev_snapshot = self.latest_snapshot()?.map(|offset| self.snapshot_dir_path(offset)); - - let prev_snapshot = if let Some(prev_snapshot) = prev_snapshot { - assert!( - prev_snapshot.0.is_dir(), - "prev_snapshot {prev_snapshot:?} is not a directory" - ); - let object_repo = Self::object_repo(&prev_snapshot)?; - Some(object_repo) - } else { - None - }; - - let mut counter = CountCreated::default(); - let snapshot_dir = self.snapshot_dir_path(tx_offset); // Before performing any observable operations, @@ -928,16 +800,14 @@ impl SnapshotRepository { // Create the snapshot directory. snapshot_dir.create()?; - // Create a new `DirTrie` to hold all the content-addressed objects in the snapshot. - let object_repo = Self::object_repo(&snapshot_dir)?; - // Build the in-memory `Snapshot` object. - let mut snapshot = self.empty_snapshot(tx_offset); + let manifest = self.empty_manifest(tx_offset); - // Populate both the in-memory `Snapshot` object and the on-disk object repository - // with all the blobs and pages. - snapshot.write_all_blobs(&object_repo, blobs, prev_snapshot.as_ref(), &mut counter)?; - snapshot.write_all_tables(&object_repo, tables, prev_snapshot.as_ref(), &mut counter)?; + 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", @@ -949,49 +819,15 @@ impl SnapshotRepository { Ok(UnflushedSnapshot { inner: Some(UnflushedSnapshotInner { - snapshot, snapshot_dir, - snapshot_repo: self.clone(), - object_repo, + repo: object_repo, lockfile, }), }) } - /// Write the on-disk snapshot file containing the BSATN-encoded `snapshot` - /// into `snapshot_dir`. - /// - /// It is not recommanded to call this method directly; prefer using `create_snapshot`. - /// It is exposed publicly to be used in very specific scenarios, like modifying an existing - /// snapshot. - pub fn write_snapshot_file(&self, snapshot_dir: &SnapshotDirPath, snapshot: Snapshot) -> Result<(), SnapshotError> { - // Serialize and hash the in-memory `Snapshot` object. - let snapshot_bsatn = bsatn::to_vec(&snapshot).map_err(|cause| SnapshotError::Serialize { - ty: ObjectType::Snapshot, - cause, - })?; - let hash = blake3::hash(&snapshot_bsatn); - - // Create the snapshot file, containing first the hash, then the `Snapshot`. - { - let mut snapshot_file = - BufWriter::new(snapshot_dir.snapshot_file(snapshot.tx_offset).open_file(&o_excl())?); - snapshot_file.write_all(hash.as_bytes())?; - snapshot_file.write_all(&snapshot_bsatn)?; - snapshot_file.flush()?; - // fsync file + enclosing directory. - snapshot_file - .into_inner() - .expect("buffered writer just flushed") - .sync_all()?; - FileOrDirPath::Dir(&snapshot_dir.0).sync_all()?; - } - - Ok(()) - } - - fn empty_snapshot(&self, tx_offset: TxOffset) -> Snapshot { - Snapshot { + fn empty_manifest(&self, tx_offset: TxOffset) -> Snapshot { + let manifest = v0::Snapshot { magic: MAGIC, version: CURRENT_SNAPSHOT_VERSION, database_identity: self.database_identity, @@ -1000,6 +836,12 @@ impl SnapshotRepository { tx_offset, blobs: vec![], tables: vec![], + }; + + 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}"), } } @@ -1023,20 +865,6 @@ impl SnapshotRepository { self.root.snapshot_dir(tx_offset) } - /// Given `snapshot_dir` as the result of [`SnapshotRepository::snapshot_dir_path`], - /// get the [`DirTrie`] which contains serialized objects (pages and large blobs) - /// referenced by the [`Snapshot`] contained in the [`SnapshotDirPath`]. - /// - /// Consequences are unspecified if this method is called from outside this crate - /// on a non-existent, locked or incomplete `snapshot_dir`. - /// - /// Any mutations to the returned [`DirTrie`] or its contents - /// will likely render the snapshot corrupted, - /// causing future attempts to reconstruct it to fail. - pub fn object_repo(snapshot_dir: &SnapshotDirPath) -> Result { - DirTrie::open(snapshot_dir.objects().0) - } - /// Read a snapshot contained in self referring to `tx_offset`, /// verify its hashes, /// and parse it into an in-memory structure [`ReconstructedSnapshot`] @@ -1053,7 +881,7 @@ impl SnapshotRepository { /// is missing or corrupted, /// as detected by comparing the hash of its bytes to the hash recorded in the snapshot file. /// - The snapshot file's magic number does not match [`MAGIC`]. - /// - The snapshot file's version does not match [`CURRENT_SNAPSHOT_VERSION`]. + /// - The snapshot file's version is unsupported. /// /// The following conditions are not detected or considered as errors: /// - The snapshot file's database identity or instance ID do not match those in `self`. @@ -1074,19 +902,20 @@ impl SnapshotRepository { } let snapshot_file_path = snapshot_dir.snapshot_file(tx_offset); - let (snapshot, compress_type, metadata_metrics) = Snapshot::read_from_file_with_metrics(&snapshot_file_path)?; + let (snapshot, compress_type, metadata_metrics) = read_from_file_with_metrics(&snapshot_file_path)?; + let mut read_metrics = SnapshotReadMetrics { metadata: metadata_metrics, ..Default::default() }; - read_metrics.blob.files = snapshot.blobs.len() as u64; + read_metrics.blob.files = snapshot.blobs().len() as u64; read_metrics.page.files = snapshot - .tables + .tables() .iter() - .map(|table| table_num_present_pages(&table.pages)) + .map(|table| table.present_pages().count() as u64) .sum(); read_metrics.absent_pages = snapshot - .tables + .tables() .iter() .map(|table| { table @@ -1097,36 +926,28 @@ impl SnapshotRepository { }) .sum(); - if snapshot.magic != MAGIC { + if snapshot.magic() != MAGIC { return Err(SnapshotError::BadMagic { tx_offset, - magic: snapshot.magic, - }); - } - - if snapshot.version != CURRENT_SNAPSHOT_VERSION { - return Err(SnapshotError::BadVersion { - tx_offset, - version: snapshot.version, + magic: snapshot.magic(), }); } let snapshot_dir = self.snapshot_dir_path(tx_offset); - let object_repo = Self::object_repo(&snapshot_dir)?; - let blob_start = Instant::now(); - let blob_store = snapshot.reconstruct_blob_store(&object_repo, &mut read_metrics.blob)?; - read_metrics.blob.read_time = blob_start.elapsed(); + let database_identity = snapshot.database_identity(); + let replica_id = snapshot.replica_id(); + let tx_offset = snapshot.tx_offset(); + let module_abi_version = snapshot.module_abi_version(); - let page_start = Instant::now(); - let tables = snapshot.reconstruct_tables(&object_repo, page_pool, &mut read_metrics.page)?; - read_metrics.page.read_time = page_start.elapsed(); + let repo = snapshot.into_writable(&snapshot_dir)?; + let (blob_store, tables) = repo.reconstruct(page_pool, &mut read_metrics)?; Ok(ReconstructedSnapshot { - database_identity: snapshot.database_identity, - replica_id: snapshot.replica_id, - tx_offset: snapshot.tx_offset, - module_abi_version: snapshot.module_abi_version, + database_identity, + replica_id, + tx_offset, + module_abi_version, blob_store, tables, compress_type, @@ -1159,7 +980,7 @@ impl SnapshotRepository { /// contents match their expectations. pub async fn verify_snapshot(&self, tx_offset: TxOffset) -> Result { let snapshot_dir = self.snapshot_dir_path(tx_offset); - let snapshot = spawn_blocking({ + let manifest = spawn_blocking({ let snapshot_dir = snapshot_dir.clone(); move || { let lockfile = Lockfile::lock_path(&snapshot_dir); @@ -1168,12 +989,12 @@ impl SnapshotRepository { } let snapshot_file_path = snapshot_dir.snapshot_file(tx_offset); - let (snapshot, _compress_type) = Snapshot::read_from_file(&snapshot_file_path)?; + let (snapshot, _) = read_from_file(&snapshot_file_path)?; - if snapshot.magic != MAGIC { + if snapshot.magic() != MAGIC { return Err(SnapshotError::BadMagic { tx_offset, - magic: snapshot.magic, + magic: snapshot.magic(), }); } Ok(snapshot) @@ -1181,11 +1002,11 @@ impl SnapshotRepository { }) .await .unwrap()?; - let object_repo = Self::object_repo(&snapshot_dir)?; - verify_snapshot(object_repo, self.root.clone(), snapshot.clone()) + let snapshot = manifest.clone().into_writable(&snapshot_dir)?; + verify_snapshot(snapshot, self.root.clone(), manifest.clone()) .await .map(drop)?; - Ok(snapshot) + Ok(manifest) } /// Open a repository at `root`, failing if the `root` doesn't exist or isn't a directory. @@ -1336,23 +1157,28 @@ impl SnapshotRepository { ) -> Result { let (tx_offset, snapshot_dir) = current; let tx_offset = *tx_offset; - let snapshot_file = snapshot_dir.snapshot_file(tx_offset); - let (snapshot, compress_type) = Snapshot::read_from_file(&snapshot_file)?; + let snapshot_file_path = snapshot_dir.snapshot_file(tx_offset); + let (manifest, compress_type) = read_from_file(&snapshot_file_path)?; + let replica_id = manifest.replica_id(); let mut stats = ObjectCompressionStats::default(); if let Some(algo) = compress_type.algorithm() { log::debug!( "Snapshot {snapshot_dir:?} of replica {} is already compressed: {algo:?}", - snapshot.replica_id + manifest.replica_id() ); return Ok(stats); } let old = if let Some((tx_offset, snapshot_dir)) = parent { - let snapshot_file = snapshot_dir.snapshot_file(*tx_offset); - let (snapshot, _) = Snapshot::read_from_file(&snapshot_file)?; - let dir = SnapshotRepository::object_repo(snapshot_dir)?; - snapshot.files(&dir).collect() + let snapshot_file_path = snapshot_dir.snapshot_file(*tx_offset); + let (manifest, _) = read_from_file(&snapshot_file_path)?; + let snapshot = manifest.into_writable(snapshot_dir)?; + // TODO: Use no-hasher map with ObjectKey directly. + snapshot + .object_keys_and_file_paths() + .map(|(key, path)| (blake3::Hash::from(key), path)) + .collect() } else { HashMap::new() }; @@ -1398,32 +1224,26 @@ impl SnapshotRepository { let _lock = Lockfile::for_file(snapshot_dir)?; - log::info!( - "Compressing snapshot {snapshot_dir:?} of replica {}", - snapshot.replica_id - ); + log::info!("Compressing snapshot {snapshot_dir:?} of replica {replica_id}",); - let dir = SnapshotRepository::object_repo(snapshot_dir)?; - for (hash, path) in snapshot.files(&dir) { - compress(&old, &path, Some(hash), Some(&mut stats)).inspect_err(|err| { + let snapshot = manifest.into_writable(snapshot_dir)?; + for (hash, path) in snapshot.object_keys_and_file_paths() { + compress(&old, &path, Some(hash.into()), Some(&mut stats)).inspect_err(|err| { log::error!("Failed to compress object file {path:?}: {err}"); })?; } - File::open(dir.root())?.sync_all()?; + File::open(snapshot.root())?.sync_all()?; // Compress the snapshot file last, // which marks the whole snapshot as compressed. // // Don't update the stats for the snapshot file. - compress(&old, &snapshot_file.0, None, None).inspect_err(|err| { - log::error!("Failed to compress snapshot file {snapshot_file:?}: {err}"); + compress(&old, &snapshot_file_path.0, None, None).inspect_err(|err| { + log::error!("Failed to compress snapshot file {snapshot_file_path:?}: {err}"); })?; File::open(&snapshot_dir.0)?.sync_all()?; - log::info!( - "Compressed snapshot {snapshot_dir:?} of replica {}: {compress_type:?}", - snapshot.replica_id - ); + log::info!("Compressed snapshot {snapshot_dir:?} of replica {replica_id}: {compress_type:?}",); Ok(stats) } @@ -1477,10 +1297,10 @@ impl SnapshotRepository { let mut size = SnapshotSize::default(); let snapshot_dir = self.snapshot_dir_path(offset); - let snapshot_file = snapshot_dir.snapshot_file(offset); - let snapshot_file_size = snapshot_file.metadata()?.len(); + let snapshot_file_path = snapshot_dir.snapshot_file(offset); + let snapshot_file_size = snapshot_file_path.metadata()?.len(); - let (snapshot, compress_type) = Snapshot::read_from_file(&snapshot_file)?; + let (manifest, compress_type) = read_from_file(&snapshot_file_path)?; size.snapshot = match compress_type { CompressType::None => CompressCount { none: 1, zstd: 0 }, @@ -1489,9 +1309,9 @@ impl SnapshotRepository { size.file_size += snapshot_file_size; size.total_size += snapshot_file_size; - let repo = Self::object_repo(&snapshot_dir)?; - for (_, f) in snapshot.files(&repo) { - let file_size = f.metadata()?.len(); + let snapshot = manifest.into_writable(&snapshot_dir)?; + for path in snapshot.file_paths() { + let file_size = path.metadata()?.len(); size.object_size += file_size; size.total_size += file_size; size.object_count += 1; @@ -1509,10 +1329,10 @@ 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( + fn create_snapshot<'a, 'b>( &self, - tables: &mut dyn Iterator, - blobs: &BlobSet, + tables: &mut dyn Iterator, + blobs: BlobScan<'b>, tx_offset: TxOffset, ) -> Result; @@ -1550,10 +1370,10 @@ impl SnapshotRepo for SnapshotRepository { SnapshotRepository::database_identity(self) } - fn create_snapshot( + fn create_snapshot<'a, 'b>( &self, - tables: &mut dyn Iterator, - blobs: &BlobSet, + tables: &mut dyn Iterator, + blobs: BlobScan<'b>, tx_offset: TxOffset, ) -> Result { Ok(Box::new(SnapshotRepository::create_snapshot( @@ -1663,106 +1483,4 @@ impl FileOrDirPath<'_> { } #[cfg(test)] -mod tests { - use std::fs::OpenOptions; - - use spacetimedb_sats::{product, AlgebraicType}; - use spacetimedb_schema::schema::TableSchema; - use spacetimedb_table::{ - indexes::SquashedOffset, - tiered::{ - metrics::CacheTier, ByteBudget, ByteBudgetConfig, EvictionPolicy, TieredDatabaseStorage, - TieredStorageConfig, - }, - }; - use tempfile::tempdir; - - use super::*; - - #[test] - fn snapshot_evicts_other_tables_to_load_pages() -> anyhow::Result<()> { - let mut config = TieredStorageConfig::new_for_test(); - config.resident_budget = ByteBudget::new(ByteBudgetConfig { - tier: CacheTier::Memory, - low_water_bytes: 0, - soft_limit_bytes: size_of::() as u64, - hard_limit_bytes: size_of::() as u64, - })?; - let pool = config.page_pool.clone(); - let storage = TieredDatabaseStorage::empty(config); - let mut tables = [TableId(1), TableId(2)].map(|table_id| { - let mut schema = TableSchema::from_product_type([AlgebraicType::U64].into()); - schema.table_id = table_id; - Table::new( - schema.into(), - SquashedOffset::COMMITTED_STATE, - storage.pages().clone(), - EvictionPolicy::Memory, - ) - }); - tables[0].insert(storage.blobs(), &product![11_u64])?; - assert_eq!(tables[0].trim()?, size_of::() as u64); - // The second table occupies the whole cache. Loading the first table - // for the snapshot must evict from the second one. - tables[1].insert(storage.blobs(), &product![22_u64])?; - - let tmp = tempdir()?; - let repo = SnapshotRepository::open(SnapshotsPath::from_path_unchecked(tmp.path()), Identity::ZERO, 42)?; - repo.create_snapshot(tables.iter_mut(), storage.blobs(), 0)? - .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]) { - let pages = snapshot.tables.remove(&table.schema.table_id).unwrap(); - let mut restored = table.clone_structure(SquashedOffset::COMMITTED_STATE); - // SAFETY: These pages came from the same table and retain its schema. - unsafe { restored.set_pages(pages, storage.blobs())? }; - let mut rows = restored.scan_rows(storage.blobs()); - assert_eq!(rows.next().unwrap()?.to_product_value(), product![expected]); - assert!(rows.next().is_none()); - } - Ok(()) - } - - #[test] - fn listing_ignores_if_snapshot_file_is_missing() -> anyhow::Result<()> { - let tmp = tempdir()?; - - let root = SnapshotsPath::from_path_unchecked(tmp.path()); - let repo = SnapshotRepository::open(root, Identity::ZERO, 42)?; - for i in 0..10 { - repo.snapshot_dir_path(i).create()?; - } - repo.snapshot_dir_path(5) - .snapshot_file(5) - .open_file(OpenOptions::new().write(true).create_new(true)) - .map(drop)?; - - assert_eq!(vec![5], repo.all_snapshots()?.collect::>()); - - Ok(()) - } - - #[test] - fn listing_ignores_if_lockfile_exists() -> anyhow::Result<()> { - let tmp = tempdir()?; - - let root = SnapshotsPath::from_path_unchecked(tmp.path()); - let repo = SnapshotRepository::open(root, Identity::ZERO, 42)?; - for i in 0..10 { - let snapshot_dir = repo.snapshot_dir_path(i); - snapshot_dir.create()?; - snapshot_dir - .snapshot_file(i) - .open_file(OpenOptions::new().write(true).create_new(true)) - .map(drop)?; - } - let _lock = Lockfile::for_file(repo.snapshot_dir_path(5))?; - - let mut snapshots = repo.all_snapshots()?.collect::>(); - snapshots.sort(); - assert_eq!(vec![0, 1, 2, 3, 4, 6, 7, 8, 9], snapshots); - - Ok(()) - } -} +mod tests; diff --git a/crates/snapshot/src/remote.rs b/crates/snapshot/src/remote.rs index ff173c54a55..412c63f3a95 100644 --- a/crates/snapshot/src/remote.rs +++ b/crates/snapshot/src/remote.rs @@ -18,7 +18,12 @@ use spacetimedb_fs_utils::{compression::ZSTD_MAGIC_BYTES, dir_trie::DirTrie, loc use spacetimedb_lib::bsatn; use spacetimedb_paths::server::{SnapshotDirPath, SnapshotsPath}; use spacetimedb_sats::buffer::BufWriter as SatsWriter; -use spacetimedb_table::{blob_store::BlobHash, page::Page, page_pool::PagePool}; +use spacetimedb_table::{ + blob_store::BlobHash, + page::Page, + page_pool::PagePool, + tiered::{ObjectKey, PageHash}, +}; use tempfile::NamedTempFile; use tokio::{ fs, @@ -30,46 +35,43 @@ use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_util::io::{InspectReader, InspectWriter, StreamReader}; use zstd_framed::AsyncZstdReader; -use crate::{table_present_pages, ObjectType, Snapshot, SnapshotError, SnapshotRepository}; +use crate::{common::read_from_file, ObjectType, Snapshot, SnapshotError, SnapshotRepository, WritableSnapshot}; pub type Result = std::result::Result; /// A source of snapshot objects that can be obtained by `hash`. -pub trait BlobProvider: Send { - fn blob_reader( - &self, - hash: blake3::Hash, - ) -> impl Future> + Send; +pub trait ObjectProvider: Send { + type Reader: AsyncBufRead + Send + Unpin; + + fn object_reader(&self, key: ObjectKey) -> impl Future> + Send; } -impl BlobProvider for DirTrie { - async fn blob_reader(&self, hash: blake3::Hash) -> io::Result { - fs::File::open(self.file_path(hash.as_bytes())) - .await - .map(BufReader::new) +impl ObjectProvider for DirTrie { + type Reader = BufReader; + + async fn object_reader(&self, key: ObjectKey) -> io::Result { + fs::File::open(self.file_path(key.as_bytes())).await.map(BufReader::new) } } -impl BlobProvider for F +impl ObjectProvider for F where - F: Fn(blake3::Hash) -> Fut + Send + Sync, + F: Fn(ObjectKey) -> Fut + Send + Sync, Fut: Future> + Send, R: AsyncBufRead + Send + Unpin, { - fn blob_reader( - &self, - hash: blake3::Hash, - ) -> impl Future> + Send { - (self)(hash) + type Reader = R; + + fn object_reader(&self, key: ObjectKey) -> impl Future> + Send { + (self)(key) } } -impl BlobProvider for Arc { - fn blob_reader( - &self, - hash: blake3::Hash, - ) -> impl Future> + Send { - (**self).blob_reader(hash) +impl ObjectProvider for Arc { + type Reader = T::Reader; + + fn object_reader(&self, key: ObjectKey) -> impl Future> + Send { + (**self).object_reader(key) } } @@ -125,7 +127,7 @@ impl From for Stats { /// /// It is, however, safe to retry a failed [`synchronize_snapshot`] run. pub async fn synchronize_snapshot( - provider: impl BlobProvider + 'static, + provider: impl ObjectProvider + 'static, snapshots_dir: SnapshotsPath, snapshot: Snapshot, ) -> Result { @@ -138,7 +140,7 @@ pub async fn synchronize_snapshot( /// Like [`synchronize_snapshot`], but doesn't modify the local storage. /// Usually, a local [`BlobProvider`] like [`DirTrie`] should be provided. pub async fn verify_snapshot( - provider: impl BlobProvider + 'static, + provider: impl ObjectProvider + 'static, snapshots_dir: SnapshotsPath, snapshot: Snapshot, ) -> Result<()> { @@ -146,7 +148,7 @@ pub async fn verify_snapshot( } async fn run_fetcher( - provider: impl BlobProvider + 'static, + provider: impl ObjectProvider + 'static, snapshots_dir: SnapshotsPath, snapshot: Snapshot, dry_run: bool, @@ -223,10 +225,10 @@ pub fn default_page_pool() -> PagePool { } pub struct SnapshotFetcher

{ - snapshot: Snapshot, + manifest: Snapshot, dir: SnapshotDirPath, - object_repo: Arc, - parent_repo: Option>, + object_repo: Arc, + parent_repo: Option>, provider: P, /// Re-usable memory for deserialized pages. @@ -243,7 +245,7 @@ pub struct SnapshotFetcher

{ lock: Lockfile, } -impl SnapshotFetcher

{ +impl SnapshotFetcher

{ fn read_object_error(&self, ty: ObjectType, cause: io::Error) -> SnapshotError { SnapshotError::ReadObject { ty, @@ -255,32 +257,35 @@ impl SnapshotFetcher

{ pub fn create( provider: P, snapshots_dir: SnapshotsPath, - snapshot: Snapshot, + manifest: Snapshot, page_pool: PagePool, buf_pool: BufPool, ) -> Result { - let snapshot_repo = SnapshotRepository::open(snapshots_dir, snapshot.database_identity, snapshot.replica_id)?; - let snapshot_dir = snapshot_repo.snapshot_dir_path(snapshot.tx_offset); + let snapshot_repo = + SnapshotRepository::open(snapshots_dir, manifest.database_identity(), manifest.replica_id())?; + let snapshot_dir = snapshot_repo.snapshot_dir_path(manifest.tx_offset()); let lock = Lockfile::for_file(&snapshot_dir)?; std::fs::create_dir_all(&snapshot_dir)?; - let object_repo = SnapshotRepository::object_repo(&snapshot_dir)?; - let parent_offset = snapshot_repo.latest_snapshot_older_than(snapshot.tx_offset)?; + let snapshot_offset = manifest.tx_offset(); + let object_repo = manifest.clone().into_writable(&snapshot_dir)?; + let parent_offset = snapshot_repo.latest_snapshot_older_than(snapshot_offset)?; // The parent offset must always be smaller than `snapshot`'s offset, // because we locked `snapshot_dir`, so this snapshot is not selected. debug_assert!( - parent_offset.is_none() || parent_offset.is_some_and(|offset| offset < snapshot.tx_offset), + parent_offset.is_none() || parent_offset.is_some_and(|offset| offset < snapshot_offset), "invalid parent offset" ); let parent_repo = parent_offset .map(|offset| { - let path = snapshot_repo.snapshot_dir_path(offset); - SnapshotRepository::object_repo(&path) + let parent_dir = snapshot_repo.snapshot_dir_path(offset); + let (snapshot, _) = Snapshot::read_from_file(&parent_dir.snapshot_file(offset))?; + snapshot.into_writable(&parent_dir).map_err(SnapshotError::from) }) .transpose()?; Ok(Self { - snapshot, + manifest, dir: snapshot_dir, object_repo: Arc::new(object_repo), parent_repo: parent_repo.map(Arc::new), @@ -302,17 +307,17 @@ impl SnapshotFetcher

{ let snapshot_bsatn = { let mut buf = Vec::new(); - serialize_snapshot(&mut buf, &self.snapshot)?; + serialize_snapshot(&mut buf, &self.manifest)?; buf }; let snapshot_hash = blake3::hash(&snapshot_bsatn); - let snapshot_file_path = self.dir.snapshot_file(self.snapshot.tx_offset); + let snapshot_file_path = self.dir.snapshot_file(self.manifest.tx_offset()); // If the snapshot file already exists at the target path, // check that it is valid and that it hashes to `snapshot_hash`. if fs::try_exists(&snapshot_file_path).await? { let (existing, _) = spawn_blocking({ let snapshot_file_path = snapshot_file_path.clone(); - move || Snapshot::read_from_file(&snapshot_file_path) + move || read_from_file(&snapshot_file_path) }) .await .unwrap()?; @@ -351,13 +356,10 @@ impl SnapshotFetcher

{ async fn fetch_blobs(&self) -> Result<()> { let tasks = self - .snapshot - .blobs + .manifest + .blobs() .iter() - .map(|entry| { - let hash = blake3::Hash::from_bytes(entry.hash.data); - self.fetch_blob(hash) - }) + .map(|entry| self.fetch_blob(entry.hash)) .collect::>(); stream::iter(tasks) .map(Ok) @@ -367,11 +369,10 @@ impl SnapshotFetcher

{ async fn fetch_pages(&self) -> Result<()> { let tasks = self - .snapshot - .tables + .manifest + .tables() .iter() - .flat_map(|entry| table_present_pages(&entry.pages)) - .map(|hash| self.fetch_page(hash)) + .flat_map(|entry| entry.present_pages().map(|hash| self.fetch_page(hash))) .collect::>(); stream::iter(tasks) .map(Ok) @@ -379,23 +380,17 @@ impl SnapshotFetcher

{ .await } - async fn fetch_blob(&self, hash: blake3::Hash) -> Result<()> { - let ty = ObjectType::Blob(BlobHash { data: *hash.as_bytes() }); - let Some(dst_path) = self.object_file_path(ty).await? else { + async fn fetch_blob(&self, hash: BlobHash) -> Result<()> { + let key = ObjectKey::from(hash); + let Some(dst_path) = self.object_file_path(key).await? else { return Ok(()); }; + let err = |cause| self.read_object_error(key.into(), cause); + atomically((!self.dry_run).then_some(dst_path), |out| async move { let mut out = BufWriter::new(out); - let mut src = self - .provider - .blob_reader(hash) - .await - .map_err(|e| self.read_object_error(ty, e))?; - let compressed = src - .fill_buf() - .await - .map_err(|e| self.read_object_error(ty, e))? - .starts_with(&ZSTD_MAGIC_BYTES); + let mut src = self.provider.object_reader(key).await.map_err(err)?; + let compressed = src.fill_buf().await.map_err(err)?.starts_with(&ZSTD_MAGIC_BYTES); // Consume the blob reader, // write its contents to `out`, @@ -406,17 +401,15 @@ impl SnapshotFetcher

{ let mut writer = InspectWriter::new(&mut out, |chunk| { hasher.update(chunk); }); - tokio::io::copy_buf(&mut src, &mut writer) - .await - .map_err(|e| self.read_object_error(ty, e))?; - writer.flush().await.map_err(|e| self.read_object_error(ty, e))?; + tokio::io::copy_buf(&mut src, &mut writer).await.map_err(err)?; + writer.flush().await.map_err(err)?; hasher.hash() } else { // If the input is compressed, send a copy of all received // chunks to a separate task that decompresses the stream and // computes the hash from the decompressed bytes. - let (mut zstd, tx) = zstd_reader().map_err(|e| self.read_object_error(ty, e))?; + let (mut zstd, tx) = zstd_reader().map_err(err)?; let decompressor = tokio::spawn(async move { tokio::io::copy_buf(&mut zstd, &mut hasher).await?; Ok::<_, io::Error>(hasher.hash()) @@ -427,18 +420,16 @@ impl SnapshotFetcher

{ buf.extend_from_slice(chunk); tx.send(buf.split().freeze()).ok(); }); - tokio::io::copy(&mut src, &mut out) - .await - .map_err(|e| self.read_object_error(ty, e))?; - out.flush().await.map_err(|e| self.read_object_error(ty, e))?; + tokio::io::copy(&mut src, &mut out).await.map_err(err)?; + out.flush().await.map_err(err)?; drop(tx); - decompressor.await.unwrap().map_err(|e| self.read_object_error(ty, e))? + decompressor.await.unwrap().map_err(err)? }; - if computed_hash != hash { + if computed_hash != blake3::Hash::from(key) { return Err(SnapshotError::HashMismatch { - ty, - expected: *hash.as_bytes(), + ty: key.into(), + expected: *key.as_bytes(), computed: *computed_hash.as_bytes(), source_repo: self.dir.0.clone(), }); @@ -452,23 +443,17 @@ impl SnapshotFetcher

{ }) } - async fn fetch_page(&self, hash: blake3::Hash) -> Result<()> { - let ty = ObjectType::Page(hash); - let Some(dst_path) = self.object_file_path(ty).await? else { + async fn fetch_page(&self, hash: PageHash) -> Result<()> { + let key = ObjectKey::from(hash); + let Some(dst_path) = self.object_file_path(key).await? else { return Ok(()); }; + let err = |cause| self.read_object_error(key.into(), cause); + atomically((!self.dry_run).then_some(dst_path), |out| async { let mut out = BufWriter::new(out); - let mut src = self - .provider - .blob_reader(hash) - .await - .map_err(|e| self.read_object_error(ty, e))?; - let compressed = src - .fill_buf() - .await - .map_err(|e| self.read_object_error(ty, e))? - .starts_with(&ZSTD_MAGIC_BYTES); + let mut src = self.provider.object_reader(key).await.map_err(err)?; + let compressed = src.fill_buf().await.map_err(err)?.starts_with(&ZSTD_MAGIC_BYTES); // To compute the page hash, we need to bsatn deserialize it. // As bsatn doesn't support streaming deserialization yet, @@ -480,17 +465,15 @@ impl SnapshotFetcher

{ let mut writer = InspectWriter::new(&mut out, |chunk| { page_buf.extend_from_slice(chunk); }); - tokio::io::copy_buf(&mut src, &mut writer) - .await - .map_err(|e| self.read_object_error(ty, e))?; - writer.flush().await.map_err(|e| self.read_object_error(ty, e))?; + tokio::io::copy_buf(&mut src, &mut writer).await.map_err(err)?; + writer.flush().await.map_err(err)?; page_buf.split().freeze() } else { // If the input is compressed, send all received chunks to a // separate task that decompresses the stream and returns // the uncompressed bytes. - let (mut zstd, tx) = zstd_reader().map_err(|e| self.read_object_error(ty, e))?; + let (mut zstd, tx) = zstd_reader().map_err(err)?; let buf_pool = self.buf_pool.clone(); let decompressor = tokio::spawn(async move { let mut page_buf = buf_pool.get(); @@ -503,13 +486,11 @@ impl SnapshotFetcher

{ buf.extend_from_slice(chunk); tx.send(buf.split().freeze()).ok(); }); - tokio::io::copy_buf(&mut src, &mut writer) - .await - .map_err(|e| self.read_object_error(ty, e))?; - writer.flush().await.map_err(|e| self.read_object_error(ty, e))?; + tokio::io::copy_buf(&mut src, &mut writer).await.map_err(err)?; + writer.flush().await.map_err(err)?; drop(tx); - decompressor.await.unwrap().map_err(|e| self.read_object_error(ty, e))? + decompressor.await.unwrap().map_err(err)? }; self.verify_page(hash, &page_bytes)?; @@ -534,13 +515,8 @@ impl SnapshotFetcher

{ /// if the file exists in either the target or the parent repo, /// in order to force hash verification. /// If it does not exist, an error is returned. - async fn object_file_path(&self, ty: ObjectType) -> Result> { - let hash = match ty { - ObjectType::Blob(hash) => blake3::Hash::from_bytes(hash.data), - ObjectType::Page(hash) => hash, - ObjectType::Snapshot => unreachable!("invalid argument"), - }; - let path = self.object_repo.file_path(hash.as_bytes()); + async fn object_file_path(&self, key: ObjectKey) -> Result> { + let path = self.object_repo.file_path(key); if fs::try_exists(&path).await? { if self.dry_run { return Ok(Some(path)); @@ -550,7 +526,7 @@ impl SnapshotFetcher

{ return Ok(None); } - if self.try_hardlink(hash).await? { + if self.try_hardlink(key).await? { if self.dry_run { return Ok(Some(path)); } @@ -561,7 +537,7 @@ impl SnapshotFetcher

{ if self.dry_run { return Err(SnapshotError::ReadObject { - ty, + ty: key.into(), source_repo: self.object_repo.root().to_owned(), cause: io::Error::new(io::ErrorKind::NotFound, format!("missing object {}", path.display())), }); @@ -570,7 +546,7 @@ impl SnapshotFetcher

{ Ok(Some(path)) } - async fn try_hardlink(&self, hash: blake3::Hash) -> Result { + async fn try_hardlink(&self, key: ObjectKey) -> Result { let Some(parent) = self.parent_repo.as_ref() else { return Ok(false); }; @@ -578,30 +554,30 @@ impl SnapshotFetcher

{ let object_repo = Arc::clone(&self.object_repo); let parent_repo = Arc::clone(parent); if !self.dry_run { - spawn_blocking(move || object_repo.try_hardlink_from(&parent_repo, hash.as_bytes())) + spawn_blocking(move || object_repo.try_hardlink_from(&parent_repo, key)) .await .unwrap() .map_err(Into::into) } else { - let src_file = parent_repo.file_path(hash.as_bytes()); + let src_file = parent_repo.file_path(key); let meta = tokio::fs::metadata(src_file).await?; Ok(meta.is_file()) } } - fn verify_page(&self, expected_hash: blake3::Hash, buf: &[u8]) -> Result<()> { + fn verify_page(&self, expected_hash: PageHash, buf: &[u8]) -> Result<()> { let page = self .page_pool .take_deserialize_from(buf) .map_err(|cause| SnapshotError::Deserialize { - ty: ObjectType::Page(expected_hash), + ty: expected_hash.into(), source_repo: self.dir.0.clone(), cause, })?; let computed_hash = page.content_hash(); self.page_pool.put(page); - if computed_hash != expected_hash { + if computed_hash != blake3::Hash::from(expected_hash) { return Err(SnapshotError::HashMismatch { ty: ObjectType::Blob(BlobHash { data: *expected_hash.as_bytes(), @@ -827,24 +803,25 @@ impl AsyncWrite for AsyncBufWriter<'_> { #[cfg(test)] mod tests { - use super::{default_page_pool, BlobProvider, BufPool, SnapshotFetcher}; + use super::{default_page_pool, BufPool, ObjectProvider, SnapshotFetcher}; use crate::{ - Snapshot, SnapshotError, SnapshotRepository, TableEntry, CURRENT_MODULE_ABI_VERSION, CURRENT_SNAPSHOT_VERSION, - MAGIC, ZERO_HASH_DENOTING_ABSENT_PAGE, + v0, Snapshot, SnapshotError, SnapshotRepository, TableEntry, CURRENT_MODULE_ABI_VERSION, + CURRENT_SNAPSHOT_VERSION, MAGIC, ZERO_HASH_DENOTING_ABSENT_PAGE, }; use pretty_assertions::assert_matches; use spacetimedb_lib::Identity; use spacetimedb_paths::{server::SnapshotsPath, FromPathUnchecked}; use spacetimedb_sats::bsatn; use spacetimedb_sats::layout::{row_size_for_type, Size}; - use spacetimedb_table::tiered::EvictionPolicy; + use spacetimedb_table::blob_store::BlobHash; + use spacetimedb_table::tiered::{EvictionPolicy, PageHash}; use spacetimedb_table::{indexes::PageOffset, page::Page, tiered::BlobSet, var_len::AlignedVarLenOffsets}; use std::io::Cursor; use tempfile::tempdir; use zstd_framed::AsyncZstdWriter; const ZEROES: &[u8] = &[0; 32]; - const DUMMY_SNAPSHOT: Snapshot = Snapshot { + const DUMMY_SNAPSHOT: v0::Snapshot = v0::Snapshot { magic: MAGIC, version: CURRENT_SNAPSHOT_VERSION, database_identity: Identity::ZERO, @@ -856,12 +833,12 @@ mod tests { }; /// [`BlobProvider`] that serves only zeroes. - fn zeroes_provider() -> impl BlobProvider { + fn zeroes_provider() -> impl ObjectProvider { |_hash| async { Ok(Box::new(ZEROES)) } } /// [`BlobProvider`] that serves only the given `data`. - fn const_provider(data: Vec) -> impl BlobProvider { + fn const_provider(data: Vec) -> impl ObjectProvider { move |_hash| { let data = Cursor::new(data.clone()); async move { Ok(data) } @@ -873,18 +850,24 @@ mod tests { let tmp = tempdir().unwrap(); let dir = SnapshotsPath::from_path_unchecked(tmp.path()); - let blob_hash = blake3::hash(&[1; 32]); + let ones = BlobHash { + data: *blake3::hash(&[1, 32]).as_bytes(), + }; + let zeroes = BlobHash { + data: *blake3::hash(ZEROES).as_bytes(), + }; let sf = SnapshotFetcher::create( + // Only serve blobs made of zeroes. zeroes_provider(), dir, - DUMMY_SNAPSHOT, + Snapshot::V0(DUMMY_SNAPSHOT), default_page_pool(), BufPool::default(), ) .unwrap(); - sf.fetch_blob(blake3::hash(ZEROES)).await.unwrap(); - assert_matches!(sf.fetch_blob(blob_hash).await, Err(SnapshotError::HashMismatch { .. })); + sf.fetch_blob(zeroes).await.unwrap(); + assert_matches!(sf.fetch_blob(ones).await, Err(SnapshotError::HashMismatch { .. })); } #[tokio::test] @@ -893,14 +876,16 @@ mod tests { let dir = SnapshotsPath::from_path_unchecked(tmp.path()); let blob_data = [1; 1024]; - let blob_hash = blake3::hash(&blob_data); + let blob_hash = BlobHash { + data: *blake3::hash(&blob_data).as_bytes(), + }; let mut blob_zstd = Vec::new(); compress(&mut blob_data.as_slice(), &mut blob_zstd).await; let sf = SnapshotFetcher::create( const_provider(blob_zstd), dir, - DUMMY_SNAPSHOT, + Snapshot::V0(DUMMY_SNAPSHOT), default_page_pool(), BufPool::default(), ) @@ -908,7 +893,10 @@ mod tests { sf.fetch_blob(blob_hash).await.unwrap(); assert_matches!( - sf.fetch_blob(blake3::hash(ZEROES)).await, + sf.fetch_blob(BlobHash { + data: *blake3::hash(ZEROES).as_bytes() + }) + .await, Err(SnapshotError::HashMismatch { .. }) ); } @@ -919,9 +907,8 @@ mod tests { let snapshots = SnapshotsPath::from_path_unchecked(temp.path()); let repo = SnapshotRepository::open(snapshots, Identity::ZERO, DUMMY_SNAPSHOT.replica_id)?; - let tx_offset = DUMMY_SNAPSHOT.tx_offset + 1; - let sparse = Snapshot { - tx_offset, + let sparse = v0::Snapshot { + tx_offset: DUMMY_SNAPSHOT.tx_offset + 1, tables: vec![TableEntry { table_id: 0.into(), pages: vec![ZERO_HASH_DENOTING_ABSENT_PAGE], @@ -930,12 +917,14 @@ mod tests { }; for snapshot in [DUMMY_SNAPSHOT, sparse] { - let dir = repo.snapshot_dir_path(snapshot.tx_offset); + let offset = snapshot.tx_offset; + let dir = repo.snapshot_dir_path(offset); dir.create()?; - repo.write_snapshot_file(&dir, snapshot)?; + let writable = Snapshot::V0(snapshot).into_writable(&dir)?; + writable.commit()?; + repo.verify_snapshot(offset).await?; } - repo.verify_snapshot(tx_offset).await?; Ok(()) } @@ -948,23 +937,22 @@ mod tests { for val in 0..64 { insert_u64(&mut page, val); } - let page_hash = page_hash_save_get(&mut page); + let page_hash = PageHash::from(&mut *page); let page_blob = bsatn::to_vec(&page).unwrap(); let sf = SnapshotFetcher::create( const_provider(page_blob), dir, - DUMMY_SNAPSHOT, + Snapshot::V0(DUMMY_SNAPSHOT), default_page_pool(), BufPool::default(), ) .unwrap(); sf.fetch_page(page_hash).await.unwrap(); - assert_matches!( - sf.fetch_page(blake3::hash(ZEROES)).await, - Err(SnapshotError::HashMismatch { .. }) - ); + // SAFETY: Deliberately invalid. + let invalid = unsafe { PageHash::from_blake3(blake3::hash(ZEROES)) }; + assert_matches!(sf.fetch_page(invalid).await, Err(SnapshotError::HashMismatch { .. })); } #[tokio::test] @@ -976,7 +964,7 @@ mod tests { for val in 0..64 { insert_u64(&mut page, val); } - let page_hash = page_hash_save_get(&mut page); + let page_hash = PageHash::from(&mut *page); let page_blob = bsatn::to_vec(&page).unwrap(); let mut page_zstd = Vec::new(); compress(&mut page_blob.as_slice(), &mut page_zstd).await; @@ -984,17 +972,16 @@ mod tests { let sf = SnapshotFetcher::create( const_provider(page_zstd), dir, - DUMMY_SNAPSHOT, + Snapshot::V0(DUMMY_SNAPSHOT), default_page_pool(), BufPool::default(), ) .unwrap(); sf.fetch_page(page_hash).await.unwrap(); - pretty_assertions::assert_matches!( - sf.fetch_page(blake3::hash(ZEROES)).await, - Err(SnapshotError::HashMismatch { .. }) - ); + // SAFETY: Deliberately invalid. + let invalid = unsafe { PageHash::from_blake3(blake3::hash(ZEROES)) }; + pretty_assertions::assert_matches!(sf.fetch_page(invalid).await, Err(SnapshotError::HashMismatch { .. })); } async fn compress(input: &mut &[u8], output: &mut Vec) { @@ -1026,9 +1013,4 @@ mod tests { fn u64_var_len_visitor() -> &'static AlignedVarLenOffsets<'static> { &U64_VL_VISITOR } - - fn page_hash_save_get(page: &mut Page) -> blake3::Hash { - page.save_content_hash(); - page.content_hash() - } } diff --git a/crates/snapshot/src/tests.rs b/crates/snapshot/src/tests.rs new file mode 100644 index 00000000000..6f466bed463 --- /dev/null +++ b/crates/snapshot/src/tests.rs @@ -0,0 +1,102 @@ +use std::fs::OpenOptions; + +use spacetimedb_sats::{product, AlgebraicType}; +use spacetimedb_schema::schema::TableSchema; +use spacetimedb_table::{ + indexes::SquashedOffset, + tiered::{ + metrics::CacheTier, ByteBudget, ByteBudgetConfig, EvictionPolicy, TieredDatabaseStorage, TieredStorageConfig, + }, +}; +use tempfile::tempdir; + +use super::*; + +mod versions; + +#[test] +fn snapshot_evicts_other_tables_to_load_pages() -> anyhow::Result<()> { + let mut config = TieredStorageConfig::new_for_test(); + config.resident_budget = ByteBudget::new(ByteBudgetConfig { + tier: CacheTier::Memory, + low_water_bytes: 0, + soft_limit_bytes: size_of::() as u64, + hard_limit_bytes: size_of::() as u64, + })?; + let pool = config.page_pool.clone(); + let storage = TieredDatabaseStorage::empty(config); + let mut tables = [TableId(1), TableId(2)].map(|table_id| { + let mut schema = TableSchema::from_product_type([AlgebraicType::U64].into()); + schema.table_id = table_id; + Table::new( + schema.into(), + SquashedOffset::COMMITTED_STATE, + storage.pages().clone(), + EvictionPolicy::Memory, + ) + }); + tables[0].insert(storage.blobs(), &product![11_u64])?; + assert_eq!(tables[0].trim()?, size_of::() as u64); + // The second table occupies the whole cache. Loading the first table + // for the snapshot must evict from the second one. + tables[1].insert(storage.blobs(), &product![22_u64])?; + + 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()?; + 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]) { + let pages = snapshot.tables.remove(&table.schema.table_id).unwrap(); + let mut restored = table.clone_structure(SquashedOffset::COMMITTED_STATE); + // SAFETY: These pages came from the same table and retain its schema. + unsafe { restored.set_pages(pages, storage.blobs())? }; + let mut rows = restored.scan_rows(storage.blobs()); + assert_eq!(rows.next().unwrap()?.to_product_value(), product![expected]); + assert!(rows.next().is_none()); + } + Ok(()) +} + +#[test] +fn listing_ignores_if_snapshot_file_is_missing() -> anyhow::Result<()> { + let tmp = tempdir()?; + + let root = SnapshotsPath::from_path_unchecked(tmp.path()); + let repo = SnapshotRepository::open(root, Identity::ZERO, 42)?; + for i in 0..10 { + repo.snapshot_dir_path(i).create()?; + } + repo.snapshot_dir_path(5) + .snapshot_file(5) + .open_file(OpenOptions::new().write(true).create_new(true)) + .map(drop)?; + + assert_eq!(vec![5], repo.all_snapshots()?.collect::>()); + + Ok(()) +} + +#[test] +fn listing_ignores_if_lockfile_exists() -> anyhow::Result<()> { + let tmp = tempdir()?; + + let root = SnapshotsPath::from_path_unchecked(tmp.path()); + let repo = SnapshotRepository::open(root, Identity::ZERO, 42)?; + for i in 0..10 { + let snapshot_dir = repo.snapshot_dir_path(i); + snapshot_dir.create()?; + snapshot_dir + .snapshot_file(i) + .open_file(OpenOptions::new().write(true).create_new(true)) + .map(drop)?; + } + let _lock = Lockfile::for_file(repo.snapshot_dir_path(5))?; + + let mut snapshots = repo.all_snapshots()?.collect::>(); + snapshots.sort(); + assert_eq!(vec![0, 1, 2, 3, 4, 6, 7, 8, 9], snapshots); + + Ok(()) +} diff --git a/crates/snapshot/src/tests/versions.rs b/crates/snapshot/src/tests/versions.rs new file mode 100644 index 00000000000..d4e98aaa6fc --- /dev/null +++ b/crates/snapshot/src/tests/versions.rs @@ -0,0 +1,392 @@ +use std::{collections::BTreeSet, io::Cursor, num::NonZeroUsize, 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}, +}; +use tempfile::tempdir; + +use super::*; +use crate::remote::{synchronize_snapshot, ObjectProvider}; + +const TABLE: TableId = TableId(17); +const EMPTY_TABLE: TableId = TableId(99); +const OFFSET: TxOffset = 42; +const BLOB_USES: u32 = 3; + +#[derive(Clone, Copy, Debug)] +enum Version { + V0, + V1, +} + +const VERSIONS: [Version; 2] = [Version::V0, Version::V1]; + +impl Version { + fn number(self) -> u8 { + match self { + Self::V0 => 0, + Self::V1 => 1, + } + } +} + +fn v0_manifest(offset: TxOffset) -> v0::Snapshot { + v0::Snapshot { + magic: MAGIC, + version: v0::SNAPSHOT_VERSION, + database_identity: Identity::ZERO, + replica_id: 7, + module_abi_version: CURRENT_MODULE_ABI_VERSION, + tx_offset: offset, + blobs: vec![], + tables: vec![], + } +} + +fn new_table(id: TableId, storage: &TieredDatabaseStorage) -> Table { + let mut schema = TableSchema::from_product_type([AlgebraicType::U64].into()); + schema.table_id = id; + Table::new( + schema.into(), + SquashedOffset::COMMITTED_STATE, + storage.pages().clone(), + EvictionPolicy::Never, + ) +} + +fn capture( + root: &SnapshotsPath, + version: Version, + offset: TxOffset, + bytes: &[u8], + row: u64, +) -> anyhow::Result { + let dir = root.snapshot_dir(offset); + let lockfile = Lockfile::for_file(&dir)?; + dir.create()?; + let manifest = match version { + Version::V0 => Snapshot::V0(v0_manifest(offset)), + Version::V1 => Snapshot::V1(v1::Snapshot::new(v0_manifest(offset))), + }; + 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); + } + } + let manifest = writable.manifest(); + let pending = UnflushedSnapshot { + inner: Some(UnflushedSnapshotInner { + snapshot_dir: dir.clone(), + repo: writable, + lockfile, + }), + }; + assert_eq!(pending.tx_offset(), offset); + assert!(!dir.snapshot_file(offset).0.exists()); + assert_eq!(pending.sync_all()?.0, dir.0); + + Ok(manifest) +} + +fn at_version(manifest: &Snapshot, version: Version, offset: TxOffset) -> Snapshot { + let mut snapshot = match (version, manifest) { + (Version::V0, Snapshot::V0(_)) | (Version::V1, Snapshot::V1(_)) => manifest.clone(), + (Version::V1, Snapshot::V0(inner)) => Snapshot::V1(v1::Snapshot::new(inner.clone())), + (Version::V0, Snapshot::V1(inner)) => { + // Downgrading is only a test fixture operation: V0 and V1 share + // object encodings, so remote transfer can exercise either layout. + let mut inner = (**inner).clone(); + inner.version = v0::SNAPSHOT_VERSION; + Snapshot::V0(inner) + } + }; + *snapshot.tx_offset_mut() = offset; + snapshot +} + +fn assert_layout(root: &SnapshotsPath, manifest: &Snapshot, version: Version) -> anyhow::Result<()> { + let dir = root.snapshot_dir(manifest.tx_offset()); + let writable = manifest.clone().into_writable(&dir)?; + let mut expected = BTreeSet::new(); + for key in writable.objects() { + // Construct expected paths independently of the repository's path resolver. + let hash = key.to_string(); + let namespace = match (version, key) { + (Version::V0, _) => dir.objects().0, + (Version::V1, ObjectKey::Page(_)) => dir.objects().pages().0, + (Version::V1, ObjectKey::Blob(_)) => dir.objects().blobs().0, + }; + let path = namespace.join(&hash[..2]).join(&hash[2..]); + assert_eq!(writable.file_path(key), path); + assert!(path.is_file(), "missing object at {}", path.display()); + expected.insert(path); + } + assert_eq!(expected.len(), 2); + + // Compare the full object tree so a correct copy cannot hide extra files in + // the wrong layout or an object for the absent-page sentinel. + let mut actual = BTreeSet::new(); + let mut directories = vec![dir.objects().0]; + let mut visited = 0u32; + while let Some(directory) = directories.pop() { + visited += 1; + assert!(visited <= 8, "fixture has at most eight object directories"); + for entry in fs::read_dir(directory)? { + let entry = entry?; + if entry.file_type()?.is_dir() { + directories.push(entry.path()); + } else { + actual.insert(entry.path()); + } + } + } + assert_eq!(actual, expected); + + Ok(()) +} + +fn assert_restored(root: &SnapshotsPath, offset: TxOffset, bytes: &[u8], row: u64) -> anyhow::Result<()> { + let repo = SnapshotRepository::open(root.clone(), Identity::ZERO, 7)?; + let storage = TieredDatabaseStorage::empty(TieredStorageConfig::new_for_test()); + let pool = PagePool::new_for_test(); + let mut restored = repo.read_snapshot(offset, &pool)?; + assert_eq!(restored.database_identity, Identity::ZERO); + assert_eq!(restored.replica_id, 7); + assert_eq!(restored.module_abi_version, CURRENT_MODULE_ABI_VERSION); + assert_eq!(restored.tx_offset, offset); + assert_eq!(restored.read_metrics.blob.files, 1); + assert_eq!(restored.read_metrics.page.files, 1); + assert_eq!(restored.read_metrics.absent_pages, 1); + let blobs = restored.blob_store.iter().collect::>(); + assert_eq!(blobs.len(), 1); + assert_eq!(*blobs[0].0, BlobHash::hash_from_bytes(bytes).into()); + assert_eq!(blobs[0].1.blob.as_ref(), bytes); + assert_eq!(blobs[0].1.uses.get() as u64, u64::from(BLOB_USES)); + + // Verify reconstructed row contents as well as metadata and page hashes. + assert_eq!(restored.tables.len(), 2); + assert!(restored.tables.remove(&EMPTY_TABLE).unwrap().is_empty()); + let pages = restored.tables.remove(&TABLE).unwrap(); + assert_eq!(pages.len(), 2); + assert!(pages[0].is_some()); + assert!(pages[1].is_none()); + let mut table = new_table(TABLE, &storage); + // SAFETY: The fixture was captured from a table with this same U64 schema. + unsafe { table.set_pages(pages, storage.blobs())? }; + let mut rows = table.scan_rows(storage.blobs()); + assert_eq!(rows.next().unwrap()?.to_product_value(), product![row]); + assert!(rows.next().is_none()); + + Ok(()) +} + +#[test] +fn v1_writes_separate_page_and_blob_namespaces() -> anyhow::Result<()> { + let temp = tempdir()?; + let root = SnapshotsPath::from_path_unchecked(temp.path()); + let manifest = capture(&root, Version::V1, OFFSET, b"v1 blob", 123)?; + assert_layout(&root, &manifest, Version::V1)?; + let names = fs::read_dir(root.snapshot_dir(OFFSET).objects().0)? + .map(|entry| entry.map(|entry| entry.file_name())) + .collect::>>()?; + assert_eq!(names, ["pages".into(), "blobs".into()].into()); + + Ok(()) +} + +proptest! { + #[test] + fn v1_conversion_sets_version_one( + source_version in any::(), + offset in any::(), + hash in any::<[u8; 32]>(), + uses in any::(), + ) { + let mut source = v0_manifest(offset); + source.version = source_version; + source.blobs.push(BlobEntry { hash: BlobHash { data: hash }, uses }); + let converted = v1::Snapshot::new(source.clone()); + prop_assert_eq!(converted.version, v1::SNAPSHOT_VERSION); + + // Conversion changes only the wire version and must serialize as V1 + // without the fixture correcting the stored version field. + source.version = v1::SNAPSHOT_VERSION; + let encoded = bsatn::to_vec(&converted).unwrap(); + prop_assert_eq!(&encoded, &bsatn::to_vec(&source).unwrap()); + let decoded: v1::Snapshot = bsatn::from_slice(&encoded).unwrap(); + prop_assert_eq!(decoded.version, v1::SNAPSHOT_VERSION); + } + + #[test] + fn reads_both_versions( + bytes in vec(any::(), 0..1024), + row in any::(), + offset in any::(), + compressed in any::(), + ) { + for version in VERSIONS { + let temp = tempdir().unwrap(); + let root = SnapshotsPath::from_path_unchecked(temp.path()); + let expected = capture(&root, version, offset, &bytes, row).unwrap(); + if compressed { + SnapshotRepository::compress_snapshot(None, &(offset, root.snapshot_dir(offset))) + .unwrap(); + } + + // Both metadata decoding and the public restoring API must accept + // old snapshots, independently of the current write-version constant. + let file = root.snapshot_dir(offset).snapshot_file(offset); + let (decoded, compression) = Snapshot::read_from_file(&file).unwrap(); + prop_assert_eq!(decoded.version(), version.number()); + prop_assert_eq!(compression.is_compressed(), compressed); + prop_assert_eq!(bsatn::to_vec(&decoded).unwrap(), bsatn::to_vec(&expected).unwrap()); + assert_layout(&root, &decoded, version).unwrap(); + assert_restored(&root, offset, &bytes, row).unwrap(); + } + } +} + +#[test] +fn v1_deserialization_requires_version_one() -> anyhow::Result<()> { + // Exhaust every possible version byte, including V0 and future versions. + for version in 0..=u8::MAX { + let mut manifest = v0_manifest(OFFSET); + manifest.version = version; + let encoded = bsatn::to_vec(&manifest)?; + let decoded = bsatn::from_slice::(&encoded); + if version == v1::SNAPSHOT_VERSION { + assert_eq!(decoded?.version, v1::SNAPSHOT_VERSION); + } else { + assert!(decoded.is_err(), "V1 accepted wire version {version}"); + } + } + + Ok(()) +} + +#[test] +fn rejects_unsupported_versions() -> anyhow::Result<()> { + for version in [2, u8::MAX] { + let temp = tempdir()?; + let root = SnapshotsPath::from_path_unchecked(temp.path()); + let mut manifest = capture(&root, Version::V0, OFFSET, b"blob", 123)?; + let Snapshot::V0(inner) = &mut manifest else { + unreachable!() + }; + inner.version = version; + let file = root.snapshot_dir(OFFSET).snapshot_file(OFFSET); + fs::remove_file(&file)?; + common::write_snapshot_file(file.clone(), &bsatn::to_vec(&manifest)?)?; + + for error in [ + Snapshot::read_from_file(&file) + .err() + .expect("unsupported metadata version"), + SnapshotRepository::open(root.clone(), Identity::ZERO, 7)? + .read_snapshot(OFFSET, &PagePool::new_for_test()) + .err() + .expect("unsupported restore version"), + ] { + assert!(matches!(error, SnapshotError::BadVersion { version: actual, .. } + if actual == version)); + } + } + + Ok(()) +} + +#[tokio::test] +async fn remote_selects_layout_from_received_version() -> anyhow::Result<()> { + let bytes = b"a remotely transferred blob"; + for version in VERSIONS { + let source = tempdir()?; + let source_root = SnapshotsPath::from_path_unchecked(source.path()); + capture(&source_root, version, OFFSET, bytes, 123)?; + + // Transfer the source's persisted manifest unchanged. Its version must + // determine the receiver's layout, regardless of the current write version. + let source_dir = source_root.snapshot_dir(OFFSET); + let (received, _) = Snapshot::read_from_file(&source_dir.snapshot_file(OFFSET))?; + assert_eq!(received.version(), version.number()); + let provider = received.clone().into_writable(&source_dir)?; + let target = tempdir()?; + let root = SnapshotsPath::from_path_unchecked(target.path()); + let stats = synchronize_snapshot(provider, root.clone(), received.clone()).await?; + assert_eq!(stats.objects_written, 2); + assert_eq!(stats.objects_hardlinked, 0); + assert_layout(&root, &received, version)?; + assert_restored(&root, OFFSET, bytes, 123)?; + + // Read back the destination's manifest and verify its objects through + // the destination's provider, including version-specific object routing. + let (decoded, _) = Snapshot::read_from_file(&root.snapshot_dir(OFFSET).snapshot_file(OFFSET))?; + assert_eq!(decoded.version(), received.version()); + assert_eq!(bsatn::to_vec(&decoded)?, bsatn::to_vec(&received)?); + let destination = decoded.clone().into_writable(&root.snapshot_dir(OFFSET))?; + remote::verify_snapshot(destination, root, decoded).await?; + } + + Ok(()) +} + +fn no_fetch() -> impl ObjectProvider { + |_key| async { Err::>, _>(io::Error::other("existing objects must not be fetched")) } +} + +#[tokio::test] +async fn remote_hardlinks_across_versions_and_skips_existing_objects() -> anyhow::Result<()> { + let bytes = b"a blob shared across snapshot formats"; + let source = tempdir()?; + let source_root = SnapshotsPath::from_path_unchecked(source.path()); + let original = capture(&source_root, Version::V1, OFFSET, bytes, 123)?; + let provider = Arc::new(original.clone().into_writable(&source_root.snapshot_dir(OFFSET))?); + for parent_version in VERSIONS { + for child_version in VERSIONS { + let target = tempdir()?; + let root = SnapshotsPath::from_path_unchecked(target.path()); + let parent = at_version(&original, parent_version, OFFSET); + synchronize_snapshot(provider.clone(), root.clone(), parent).await?; + let child = at_version(&original, child_version, OFFSET + 1); + + // A provider that always fails proves both layouts can reuse a + // parent without silently fetching objects into the target layout. + let stats = synchronize_snapshot(no_fetch(), root.clone(), child.clone()).await?; + assert_eq!(stats.objects_hardlinked, 2); + assert_eq!(stats.objects_written, 0); + assert_eq!(stats.objects_skipped, 0); + assert_layout(&root, &child, child_version)?; + assert_restored(&root, OFFSET + 1, bytes, 123)?; + + let stats = synchronize_snapshot(no_fetch(), root.clone(), child).await?; + assert_eq!(stats.objects_skipped, 2); + assert_eq!(stats.objects_hardlinked, 0); + assert_eq!(stats.objects_written, 0); + } + } + + Ok(()) +} diff --git a/crates/snapshot/src/v0.rs b/crates/snapshot/src/v0.rs new file mode 100644 index 00000000000..98988444358 --- /dev/null +++ b/crates/snapshot/src/v0.rs @@ -0,0 +1,172 @@ +use std::{ + collections::BTreeMap, + io, + path::{Path, PathBuf}, +}; + +use spacetimedb_durability::TxOffset; +use spacetimedb_fs_utils::dir_trie::{CountCreated, 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}, +}; + +use crate::{ + common, remote::ObjectProvider, BlobEntry, ObjectType, SnapshotError, SnapshotReadKindMetrics, TableEntry, + TablePages, +}; + +pub const SNAPSHOT_VERSION: u8 = 0; + +#[derive(Clone, Serialize, Deserialize)] +pub struct Snapshot { + /// A magic number: must be equal to [`MAGIC`]. + pub(crate) magic: [u8; 4], + + /// The snapshot version number. Must be equal to [`SNAPSHOT_VERSION`]. + pub(crate) version: u8, + + /// The identity of the snapshotted database. + pub database_identity: Identity, + /// The instance ID of the snapshotted database. + pub replica_id: u64, + + /// ABI version of the module from which this snapshot was created, as [MAJOR, MINOR]. + /// + /// As of this proposal, [7, 0]. + pub(crate) module_abi_version: [u16; 2], + + /// The transaction offset of the state this snapshot reflects. + pub tx_offset: TxOffset, + + /// The hashes and reference counts of all objects in the blob store. + pub(crate) blobs: Vec, + + /// For each table, its table ID followed by the hashes of all resident pages. + /// + /// It's necessary to store the table ID rather than relying on order + /// because table IDs may be sparse (and will be, once we reserve a bunch of system table ids). + pub(crate) tables: Vec, +} + +impl Snapshot { + pub fn objects(&self) -> impl Iterator { + self.blobs.iter().map(|entry| ObjectKey::from(entry.hash)).chain( + self.tables + .iter() + .flat_map(|table| table.present_pages().map(Into::into)), + ) + } + + /// Obtain an iterator over the [`PathBuf`]s of all objects + pub fn files<'a>(&'a self, repo: &'a SnapshotRepo) -> impl Iterator + 'a { + 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. + let snapshot_bsatn = bsatn::to_vec(&self).map_err(|cause| SnapshotError::Serialize { + ty: ObjectType::Snapshot, + cause, + })?; + + common::write_snapshot_file(path, &snapshot_bsatn) + } + + pub fn total_objects(&self) -> usize { + self.blobs.len() + + self + .tables + .iter() + .map(|table| table.present_pages().count()) + .sum::() + } + + pub(super) fn repo(&self, dir: &SnapshotDirPath) -> io::Result { + SnapshotRepo::open(dir) + } +} + +pub struct SnapshotRepo { + root: SnapshotDirPath, + inner: DirTrie, +} + +impl SnapshotRepo { + pub fn open(dir: &SnapshotDirPath) -> io::Result { + DirTrie::open(dir.objects().0).map(|inner| Self { + root: dir.clone(), + inner, + }) + } + + pub fn root(&self) -> &Path { + self.inner.root() + } + + pub fn reconstruct_blobs( + &self, + manifest: &Snapshot, + metrics: &mut SnapshotReadKindMetrics, + ) -> Result { + common::reconstruct_blob_store(&manifest.blobs, &self.inner, metrics) + } + + pub fn reconstruct_tables( + &self, + manifest: &Snapshot, + page_pool: &PagePool, + metrics: &mut SnapshotReadKindMetrics, + ) -> Result, SnapshotError> { + common::reconstruct_tables(&manifest.tables, &self.inner, page_pool, metrics) + } + + pub fn file_path(&self, key: ObjectKey) -> PathBuf { + self.inner.file_path(key.as_bytes()) + } +} + +impl ObjectProvider for SnapshotRepo { + type Reader = ::Reader; + + fn object_reader(&self, key: ObjectKey) -> impl Future> + Send { + self.inner.object_reader(key) + } +} diff --git a/crates/snapshot/src/v1.rs b/crates/snapshot/src/v1.rs new file mode 100644 index 00000000000..27b3ac98abc --- /dev/null +++ b/crates/snapshot/src/v1.rs @@ -0,0 +1,179 @@ +use std::{ + collections::BTreeMap, + io, + ops::Deref, + path::{Path, PathBuf}, +}; + +use spacetimedb_durability::TxOffset; +use spacetimedb_fs_utils::dir_trie::{CountCreated, DirTrie}; +use spacetimedb_lib::{ + bsatn, + de::{self, Deserializer}, + ser::Serializer, +}; +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}, +}; + +use crate::{common, remote::ObjectProvider, v0, ObjectType, SnapshotError, SnapshotReadKindMetrics, TablePages}; + +pub const SNAPSHOT_VERSION: u8 = 1; + +#[derive(Clone)] +pub struct Snapshot(v0::Snapshot); + +impl Snapshot { + pub(super) fn new(mut manifest: v0::Snapshot) -> Self { + manifest.version = self::SNAPSHOT_VERSION; + Self(manifest) + } + + pub(super) fn tx_offset_mut(&mut self) -> &mut TxOffset { + &mut self.0.tx_offset + } + + #[cfg(test)] + pub fn get_mut(&mut self) -> &mut v0::Snapshot { + &mut self.0 + } + + pub fn files<'a>(&'a self, repo: &'a SnapshotRepo) -> impl Iterator { + 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. + let snapshot_bsatn = bsatn::to_vec(&self).map_err(|cause| SnapshotError::Serialize { + ty: ObjectType::Snapshot, + cause, + })?; + common::write_snapshot_file(path, &snapshot_bsatn) + } + + pub(super) fn repo(&self, dir: &SnapshotDirPath) -> io::Result { + SnapshotRepo::open(dir) + } +} + +impl Deref for Snapshot { + type Target = v0::Snapshot; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Serialize for Snapshot { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for Snapshot { + fn deserialize>(deserializer: D) -> Result { + let manifest = v0::Snapshot::deserialize(deserializer)?; + if manifest.version != self::SNAPSHOT_VERSION { + return Err(de::Error::custom(format!( + "snapshot manifest version mismatch: expected {}, encountered: {}", + self::SNAPSHOT_VERSION, + manifest.version + ))); + } + + Ok(Self(manifest)) + } +} + +pub struct SnapshotRepo { + root: SnapshotDirPath, + pages: DirTrie, + blobs: DirTrie, +} + +impl SnapshotRepo { + pub fn open(dir: &SnapshotDirPath) -> io::Result { + let objects = dir.objects(); + let pages = DirTrie::open(objects.pages().0)?; + let blobs = DirTrie::open(objects.blobs().0)?; + + Ok(Self { + root: dir.clone(), + pages, + blobs, + }) + } + + pub fn root(&self) -> &Path { + &self.root.0 + } + + pub fn reconstruct_blobs( + &self, + manifest: &Snapshot, + metrics: &mut SnapshotReadKindMetrics, + ) -> Result { + common::reconstruct_blob_store(&manifest.blobs, &self.blobs, metrics) + } + + pub fn reconstruct_tables( + &self, + manifest: &Snapshot, + page_pool: &PagePool, + metrics: &mut SnapshotReadKindMetrics, + ) -> Result, SnapshotError> { + common::reconstruct_tables(&manifest.tables, &self.pages, page_pool, metrics) + } + + pub fn file_path(&self, key: ObjectKey) -> PathBuf { + match key { + ObjectKey::Blob(hash) => self.blobs.file_path(hash.as_bytes()), + ObjectKey::Page(hash) => self.pages.file_path(hash.as_bytes()), + } + } +} + +impl ObjectProvider for SnapshotRepo { + type Reader = ::Reader; + + fn object_reader(&self, key: ObjectKey) -> impl Future> + Send { + match key { + ObjectKey::Page(_) => self.pages.object_reader(key), + ObjectKey::Blob(_) => self.blobs.object_reader(key), + } + } +} diff --git a/crates/snapshot/tests/remote.rs b/crates/snapshot/tests/remote.rs index 208234a5d48..cae70f80e61 100644 --- a/crates/snapshot/tests/remote.rs +++ b/crates/snapshot/tests/remote.rs @@ -15,7 +15,6 @@ use spacetimedb::{ use spacetimedb_datastore::execution_context::Workload; use spacetimedb_datastore::locking_tx_datastore::datastore::Locking; use spacetimedb_durability::{EmptyHistory, NoDurability, TxOffset}; -use spacetimedb_fs_utils::dir_trie::DirTrie; use spacetimedb_lib::{ bsatn, db::raw_def::v9::{RawModuleDefV9Builder, RawTableDefBuilder}, @@ -30,7 +29,7 @@ use spacetimedb_schema::{ }; use spacetimedb_snapshot::{ remote::{synchronize_snapshot, verify_snapshot}, - Snapshot, SnapshotError, SnapshotRepository, + Snapshot, SnapshotError, SnapshotRepository, WritableSnapshot, }; use spacetimedb_table::{page_pool::PagePool, tiered::TieredStorageConfig}; use tempfile::{tempdir, TempDir}; @@ -48,10 +47,10 @@ async fn can_sync_a_snapshot() -> anyhow::Result<()> { let dst_repo = SnapshotRepository::open(dst_path.clone(), Identity::ZERO, 0).map(Arc::new)?; - let mut src_snapshot = src.meta.clone(); + let mut src_snapshot = src.manifest(); let total_objects = src_snapshot.total_objects() as u64; - let blob_provider = src.objects.clone(); + let blob_provider = src.snapshot.clone(); // This is the first snapshot in `dst_repo`, so all objects should be written. let stats = synchronize_snapshot(blob_provider.clone(), dst_path.clone(), src_snapshot.clone()).await?; @@ -73,7 +72,7 @@ async fn can_sync_a_snapshot() -> anyhow::Result<()> { // Lastly, pretend the next snapshot has the same objects and // assert that they all get hardlinked. - src_snapshot.tx_offset += SNAPSHOT_FREQUENCY; + *src_snapshot.tx_offset_mut() += SNAPSHOT_FREQUENCY; let stats = synchronize_snapshot(blob_provider.clone(), dst_path.clone(), src_snapshot.clone()).await?; assert_eq!(stats.objects_hardlinked, total_objects); @@ -93,8 +92,8 @@ async fn rejects_overwrite() -> anyhow::Result<()> { let dst_path = SnapshotsPath::from_path_unchecked(tmp.path()); dst_path.create()?; - let src_snapshot = src.meta.clone(); - let blob_provider = src.objects.clone(); + let src_snapshot = src.manifest(); + let blob_provider = src.snapshot.clone(); synchronize_snapshot(blob_provider.clone(), dst_path.clone(), src_snapshot.clone()).await?; @@ -105,7 +104,7 @@ async fn rejects_overwrite() -> anyhow::Result<()> { let src_snapshot_path = src.repo.snapshot_dir_path(prev_offset); let (mut src_snapshot, _) = Snapshot::read_from_file(&src_snapshot_path.snapshot_file(prev_offset))?; // Pretend it's the current snapshot, thereby altering the preimage. - src_snapshot.tx_offset = src.offset; + *src_snapshot.tx_offset_mut() = src.offset; let res = synchronize_snapshot(blob_provider, dst_path, src_snapshot).await; assert_matches!(res, Err(SnapshotError::HashMismatch { .. })); @@ -122,19 +121,14 @@ async fn verifies_objects() -> anyhow::Result<()> { let dst_path = SnapshotsPath::from_path_unchecked(tmp.path()); dst_path.create()?; - let src_snapshot = src.meta.clone(); - - synchronize_snapshot(src.objects.clone(), dst_path.clone(), src_snapshot.clone()).await?; + let src_snapshot = src.manifest(); + synchronize_snapshot(src.snapshot.clone(), dst_path.clone(), src_snapshot.clone()).await?; // Read objects for verification from the destination repo. let blob_provider = spawn_blocking({ - let dst_path = dst_path.clone(); - let snapshot_offset = src_snapshot.tx_offset; - move || { - let repo = SnapshotRepository::open(dst_path, Identity::ZERO, 0)?; - let objects = SnapshotRepository::object_repo(&repo.snapshot_dir_path(snapshot_offset))?; - anyhow::Ok(Arc::new(objects)) - } + let dst_dir = dst_path.snapshot_dir(src_snapshot.tx_offset()); + let snapshot = src_snapshot.clone(); + move || snapshot.into_writable(&dst_dir).map(Arc::new) }) .await .unwrap()?; @@ -143,9 +137,9 @@ async fn verifies_objects() -> anyhow::Result<()> { // Pick a random object to mess with. let random_object_path = { - let all_objects = src_snapshot.objects().collect::>(); + let all_objects = src.snapshot.objects().collect::>(); let random_object = all_objects.choose(&mut rand::rng()).copied().unwrap(); - blob_provider.file_path(random_object.as_bytes()) + blob_provider.file_path(random_object) }; // Truncate the object file and assert that verification fails. @@ -184,8 +178,7 @@ async fn verifies_objects() -> anyhow::Result<()> { /// avoid creating the source snapshot repeatedly. struct SourceSnapshot { offset: TxOffset, - meta: Snapshot, - objects: Arc, + snapshot: Arc, repo: Arc, #[allow(unused)] @@ -211,23 +204,26 @@ impl SourceSnapshot { let offset = create_snapshot(repo.clone()).await?; let dir_path = repo.snapshot_dir_path(offset); - let (meta, objects) = spawn_blocking(move || { - let meta = Snapshot::read_from_file(&dir_path.snapshot_file(offset)).map(|(file, _)| file)?; - let objects = SnapshotRepository::object_repo(&dir_path).map(Arc::new)?; + let snapshot = spawn_blocking(move || { + let manifest = Snapshot::read_from_file(&dir_path.snapshot_file(offset)).map(|(file, _)| file)?; + let snapshot = manifest.into_writable(&dir_path).map(Arc::new)?; - Ok::<_, SnapshotError>((meta, objects)) + Ok::<_, SnapshotError>(snapshot) }) .await .unwrap()?; Ok(SourceSnapshot { offset, - meta, - objects, + snapshot, repo, tmp, }) } + + fn manifest(&self) -> Snapshot { + self.snapshot.manifest() + } } async fn create_snapshot(repo: Arc) -> anyhow::Result { diff --git a/crates/table/src/tiered/blob_set.rs b/crates/table/src/tiered/blob_set.rs index 6b005e500a4..c5b59b0712f 100644 --- a/crates/table/src/tiered/blob_set.rs +++ b/crates/table/src/tiered/blob_set.rs @@ -1,7 +1,7 @@ use super::metrics::{CacheTier, EvictionDirection, ObjectType}; use std::{num::NonZeroUsize, ops::Deref, sync::Arc}; -use parking_lot::{Mutex, RwLock}; +use parking_lot::{Mutex, RwLock, RwLockReadGuard}; use spacetimedb_data_structures::{ map::{hash_map, IntMap}, small_map::SmallHashMap, @@ -19,7 +19,7 @@ use crate::{ map::{BlobHashWrapper, ObjectKey}, mem::{self, BlobEvictionCandidate, BlobFrame, EvictionSource, ReservedBlob}, storage::{DiskObject, DiskRetention, Object}, - ByteBudget, ByteBudgetUsage, EvictionPolicy, TieredStorage, + ByteBudget, ByteBudgetUsage, EvictionPolicy, ObjectBytes, TieredStorage, }, var_len::VarLenMembers, }; @@ -76,11 +76,7 @@ impl BlobSet { /// This is used when restoring from a snapshot. /// /// All blobs in the map will initially be resident, bypassing the memory budget. - pub fn from_blob_map( - resident: Arc, - storage: Arc, - map: BlobMap, - ) -> Self { + pub fn from_blob_map(resident: Arc, storage: Arc, map: BlobMap) -> Self { let mut entries = IntMap::default(); for (key, BlobMapEntry { uses, blob }) in map.inner { let frame = resident.register_blob_unchecked(blob); @@ -136,95 +132,6 @@ impl BlobSet { result } - fn evict_inner(&self, target_usage: u64) -> Result { - let mut bytes_freed = 0; - - if self.resident.usage().accounted_bytes() <= target_usage { - return Ok(bytes_freed); - } - - let mut candidates = self.evictable.lock(); - self.resident.evictable_blobs(&mut candidates); - for candidate in candidates.drain(..) { - let maybe_resident = - self.entries - .read() - .get(&candidate.key) - .and_then(|entry| match entry { - BlobEntry::Resident { blob, pins, .. } => { - (pins == &0).then(|| blob.clone()) - } - BlobEntry::NonResident { .. } => None, - }); - - if let Some(blob) = maybe_resident { - let mut backing = self - .storage - .write(Object::from(&blob), DiskRetention::Required)?; - assert_eq!( - backing - .key() - .as_blob_hash() - .expect("storage key to be a blob hash"), - &candidate.key - ); - - let mut entries = self.entries.write(); - let Some(entry) = entries.get_mut(&candidate.key) else { - continue; - }; - let BlobEntry::Resident { - uses, - blob: current, - pins, - disk_pins, - .. - } = entry - else { - continue; - }; - // Skip pinned entries. - if *pins > 0 { - continue; - } - // Eviction may proceed concurrent to blob set access, in - // particular we're not holding an entries lock while writing to - // the tiered storage. Therefore, ensure that the entry is still - // the same allocation. - // - // An evictable frame must have exactly two references: one in - // `entries` + the clone of `blob` that was done above. - if !Arc::ptr_eq(&blob.frame, ¤t.frame) || Arc::strong_count(&blob.frame) != 2 - { - continue; - }; - - let size = blob.size(); - backing.set_pins(*disk_pins); - *entry = BlobEntry::NonResident { - uses: *uses, - size, - backing, - }; - self.resident.metrics().evicted( - ObjectType::Blob, - EvictionDirection::MemoryToDisk, - size, - ); - drop(blob); - self.resident.evict_blob(candidate); - drop(entries); - bytes_freed += size; - - if self.resident.usage().accounted_bytes() <= target_usage { - break; - } - } - } - - Ok(bytes_freed) - } - #[inline] pub fn resident_usage(&self) -> ByteBudgetUsage { self.resident.usage() @@ -241,7 +148,7 @@ impl BlobSet { self.resident .reserve_blob(size, hash, memory_limit_exempt, || bytes.into()) .or_else(|_| { - self.trim()?; + self.trim().map_err(Box::new)?; self.resident .reserve_blob(size, hash, memory_limit_exempt, || bytes.into()) .map_err(BlobError::from) @@ -251,11 +158,7 @@ impl BlobSet { /// Insert `bytes` into this set, making it a resident blob. /// /// Subject to the memory budget. - pub fn insert( - &self, - eviction_policy: EvictionPolicy, - bytes: &[u8], - ) -> Result { + pub fn insert(&self, eviction_policy: EvictionPolicy, bytes: &[u8]) -> Result { self.insert_with_memory_limit_exemption(eviction_policy, bytes, false) } @@ -395,11 +298,7 @@ impl BlobSet { /// entry catalog. /// /// On success returns the size in bytes of the blob. - pub fn free_ref( - &self, - hash: BlobHashWrapper, - eviction_policy: EvictionPolicy, - ) -> Result { + pub fn free_ref(&self, hash: BlobHashWrapper, eviction_policy: EvictionPolicy) -> Result { let mut entries = self.entries.write(); match entries.entry(hash) { hash_map::Entry::Vacant(_) => Err(BlobError::MissingBlob(Box::new(hash.into()))), @@ -445,9 +344,7 @@ impl BlobSet { BlobEntry::Resident { blob, .. } => Ok::<_, BlobError>(Ok(blob.clone())), BlobEntry::NonResident { .. } => { let fault_guard = fault.insert(self.resident.metrics().fault(ObjectType::Blob)); - let bytes = self - .storage - .read_with_source(hash.into(), &mut fault_guard.source)?; + let bytes = self.storage.read_with_source(hash.into(), &mut fault_guard.source)?; Ok(Err(bytes)) } } @@ -579,10 +476,7 @@ impl BlobSet { /// object is present on disk and eviction is prevented. Otherwise, the /// memory-resident blob's [BlobHandle] is retained, preventing memory /// eviction. - pub(crate) fn ensure_disk( - &self, - hash: BlobHashWrapper, - ) -> Result { + pub(crate) fn ensure_disk(&self, hash: BlobHashWrapper) -> Result { let mut entries = self.entries.write(); let Some(entry) = entries.get_mut(&hash) else { return Err(ObjectStoreError::UnknownObject(hash.into())); @@ -642,6 +536,13 @@ impl BlobSet { Ok(()) } + pub fn scan(&self) -> BlobScan<'_> { + BlobScan { + entries: self.entries.read(), + storage: &self.storage, + } + } + /// Sums size + hash bytes of each resident blob in the set. pub fn resident_bytes_used_by_blobs(&self) -> u64 { self.entries @@ -680,9 +581,7 @@ impl BlobSet { #[cfg(test)] impl BlobSet { - pub fn usage_counter( - &self, - ) -> spacetimedb_data_structures::map::HashMap { + pub fn usage_counter(&self) -> spacetimedb_data_structures::map::HashMap { self.entries .read() .iter() @@ -699,7 +598,7 @@ impl MemoryUsage for BlobSet { fn heap_usage(&self) -> usize { // Cache and backing store are counted by `TieredDatabaseStorage`. let scratch = self.evictable.lock().capacity() * size_of::(); - self.inner.heap_usage() + self.inner.heap_usage() + scratch } } @@ -784,9 +683,7 @@ impl BlobEntry { fn pin_disk(&mut self) { match self { - Self::Resident { - backing, disk_pins, .. - } => { + Self::Resident { backing, disk_pins, .. } => { *disk_pins = disk_pins.checked_add(1).expect("disk pin count overflow"); if let Some(backing) = backing { backing.pin(); @@ -798,9 +695,7 @@ impl BlobEntry { fn unpin_disk(&mut self) { match self { - Self::Resident { - backing, disk_pins, .. - } => { + Self::Resident { backing, disk_pins, .. } => { *disk_pins = disk_pins .checked_sub(1) .expect("attempt to decrement disk pin count already at zero"); @@ -879,9 +774,7 @@ impl BlobReadSet { let row_data = page.get_row_data(offset, layout.size()); let mut inner = SmallHashMap::default(); for vlr in unsafe { visitor.visit_var_len(row_data) }.filter(|vlr| vlr.is_large_blob()) { - let granule = unsafe { page.iter_var_len_object(vlr.first_granule) } - .next() - .unwrap(); + let granule = unsafe { page.iter_var_len_object(vlr.first_granule) }.next().unwrap(); let blob_hash = granule.blob_hash().into(); let blob = blobs.get(blob_hash)?; inner.insert(blob_hash, blob); @@ -922,8 +815,7 @@ impl BlobMap { /// equal to `BlobHash::hash_from_bytes(blob)`. pub fn insert_with_uses(&mut self, hash: &BlobHash, uses: NonZeroUsize, blob: Box<[u8]>) { debug_assert_eq!(hash, &BlobHash::hash_from_bytes(&blob)); - self.inner - .insert((*hash).into(), BlobMapEntry { uses, blob }); + self.inner.insert((*hash).into(), BlobMapEntry { uses, blob }); } pub fn iter(&self) -> impl Iterator { @@ -965,16 +857,10 @@ impl BlobSetInner { let mut candidates = self.evictable.lock(); self.resident.evictable_blobs(&mut candidates); for candidate in candidates.drain(..) { - let maybe_resident = - self.entries - .read() - .get(&candidate.key) - .and_then(|entry| match entry { - BlobEntry::Resident { blob, pins, .. } => { - (pins == &0).then(|| blob.clone()) - } - BlobEntry::NonResident { .. } => None, - }); + let maybe_resident = self.entries.read().get(&candidate.key).and_then(|entry| match entry { + BlobEntry::Resident { blob, pins, .. } => (pins == &0).then(|| blob.clone()), + BlobEntry::NonResident { .. } => None, + }); if let Some(blob) = maybe_resident { let mut backing = self @@ -982,10 +868,7 @@ impl BlobSetInner { .write(Object::from(&blob), DiskRetention::Required) .map_err(Box::new)?; assert_eq!( - backing - .key() - .as_blob_hash() - .expect("storage key to be a blob hash"), + backing.key().as_blob_hash().expect("storage key to be a blob hash"), &candidate.key ); @@ -1014,8 +897,7 @@ impl BlobSetInner { // // An evictable frame must have exactly two references: one in // `entries` + the clone of `blob` that was done above. - if !Arc::ptr_eq(&blob.frame, ¤t.frame) || Arc::strong_count(&blob.frame) != 2 - { + if !Arc::ptr_eq(&blob.frame, ¤t.frame) || Arc::strong_count(&blob.frame) != 2 { continue; }; @@ -1026,11 +908,9 @@ impl BlobSetInner { size, backing, }; - self.resident.metrics().evicted( - ObjectType::Blob, - EvictionDirection::MemoryToDisk, - size, - ); + self.resident + .metrics() + .evicted(ObjectType::Blob, EvictionDirection::MemoryToDisk, size); drop(blob); self.resident.evict_blob(candidate); drop(entries); @@ -1046,6 +926,53 @@ impl BlobSetInner { } } +pub struct ScannedBlob<'a> { + pub hash: BlobHash, + pub uses: NonZeroUsize, + pub data: ScannedBlobData<'a>, +} + +pub enum ScannedBlobData<'a> { + Resident(&'a [u8]), + Stored(ObjectBytes), +} + +impl AsRef<[u8]> for ScannedBlobData<'_> { + fn as_ref(&self) -> &[u8] { + match self { + Self::Resident(bytes) => bytes, + Self::Stored(bytes) => bytes.as_ref(), + } + } +} + +pub struct BlobScan<'a> { + entries: RwLockReadGuard<'a, IntMap>, + storage: &'a TieredStorage, +} + +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)?, + }; + + Ok(ScannedBlob { + hash: hash.into(), + uses, + data, + }) + }; + + Some(get_or_read()) + }) + } +} + #[cfg(test)] mod tests { use std::{collections::HashMap, num::NonZeroUsize, sync::Arc}; @@ -1055,8 +982,8 @@ mod tests { use crate::{ blob_store::BlobHash, tiered::{ - map::BlobHashWrapper, metrics::CacheTier, BlobError, BlobMap, BlobSet, ByteBudget, - ByteBudgetConfig, EvictionPolicy, ResidentObjects, TieredStorage, + map::BlobHashWrapper, metrics::CacheTier, BlobError, BlobMap, BlobSet, ByteBudget, ByteBudgetConfig, + EvictionPolicy, ResidentObjects, TieredStorage, }, }; @@ -1271,20 +1198,14 @@ mod tests { let committed = BlobSet::new(resident.clone(), storage); // Emulate transaction prepare. - transaction - .insert(EvictionPolicy::Memory, bytes) - .map(drop) - .unwrap(); + transaction.insert(EvictionPolicy::Memory, bytes).map(drop).unwrap(); let pins = transaction.fault_all().unwrap(); // Emulate transaction commit. // The shared [ResidentObjects] notices that it's the same object, so // reuses the already-held budget permit. assert!(committed.usage_counter().is_empty()); - committed - .insert(EvictionPolicy::Memory, bytes) - .map(drop) - .unwrap(); + committed.insert(EvictionPolicy::Memory, bytes).map(drop).unwrap(); assert_eq!(committed.usage_counter().get(&pins[0].hash()), Some(&1)); assert_eq!(resident.usage().accounted_bytes(), bytes.len() as u64); diff --git a/crates/table/src/tiered/map.rs b/crates/table/src/tiered/map.rs index f856dfdcf95..40d6061ffde 100644 --- a/crates/table/src/tiered/map.rs +++ b/crates/table/src/tiered/map.rs @@ -20,6 +20,16 @@ impl PageHash { pub fn as_bytes(&self) -> &[u8; Self::SIZE] { self.0.as_bytes() } + + /// Create a [PageHash] from a [blake3::Hash]. + /// + /// # Safety + /// + /// The caller promises that the provided hash is indeed a page hash, not a + /// blob hash. + pub unsafe fn from_blake3(hash: blake3::Hash) -> Self { + Self(hash) + } } impl Hash for PageHash { @@ -201,6 +211,15 @@ impl From<&mut Page> for ObjectKey { } } +impl From for blake3::Hash { + fn from(key: ObjectKey) -> Self { + match key { + ObjectKey::Page(hash) => hash.into(), + ObjectKey::Blob(hash) => hash.into(), + } + } +} + pub type ObjectMap = IntMap; #[cfg(test)] diff --git a/crates/table/src/tiered/mod.rs b/crates/table/src/tiered/mod.rs index 48c85558911..9a5c101be27 100644 --- a/crates/table/src/tiered/mod.rs +++ b/crates/table/src/tiered/mod.rs @@ -17,10 +17,10 @@ mod storage; pub(crate) use self::{blob_set::DiskPinnedBlobHandle, page_set::DiskPinnedPageHandle}; pub use self::{ - blob_set::{BlobHandle, BlobMap, BlobReadSet, BlobSet}, + blob_set::{BlobHandle, BlobMap, BlobReadSet, BlobScan, BlobSet, ScannedBlob, ScannedBlobData}, budget::{BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetConfig, ByteBudgetUsage}, error::{BlobError, EvictionError, ObjectStoreError, PageError, TrimError}, - map::ObjectKey, + map::{ObjectKey, PageHash}, mem::ResidentObjects, page_manager::{PageHandle, PageManager, ReservedPage}, page_ref::{PageBorrow, PageRead, PageRef},