Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/datastore/src/db_metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ Each HTTP request performed by a database will be counted either here, in `space
pub page_cache_evicted_bytes: IntCounterVec,

#[name = spacetime_page_cache_disk_io_duration_seconds]
#[help = "Local-cache read and write durations, including failed operations."]
#[help = "Local-cache read, write, and hardlink durations, including failed operations."]
#[labels(database_identity: Identity, replica_id: u64, operation: str)]
#[buckets(0.00001, 0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 30.0)]
pub page_cache_disk_time: HistogramVec,
Expand Down
19 changes: 15 additions & 4 deletions crates/datastore/src/db_metrics/page_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,13 @@ struct TierMetrics {
struct DiskIoMetrics {
read: OnceLock<Histogram>,
write: OnceLock<Histogram>,
hardlink: OnceLock<Histogram>,
read_bytes: OnceLock<IntCounter>,
write_bytes: OnceLock<IntCounter>,
read_operations: DiskOperationCounters,
write_operations: DiskOperationCounters,
delete_operations: DiskOperationCounters,
hardlink_operations: DiskOperationCounters,
}

#[derive(Debug, Default)]
Expand Down Expand Up @@ -342,8 +344,9 @@ impl FaultMetrics {
impl DiskIoMetrics {
fn record(&self, stats: &StorageMetrics, operation: DiskOperation, nanos: u64, bytes: u64) {
let (duration, transferred_bytes) = match operation {
DiskOperation::Read => (&self.read, &self.read_bytes),
DiskOperation::Write => (&self.write, &self.write_bytes),
DiskOperation::Read => (&self.read, Some(&self.read_bytes)),
DiskOperation::Write => (&self.write, Some(&self.write_bytes)),
DiskOperation::Hardlink => (&self.hardlink, None),
DiskOperation::Delete => return,
};
let (db, replica) = (&stats.database, &stats.replica);
Expand All @@ -354,7 +357,9 @@ impl DiskIoMetrics {
.with_label_values(db, replica, operation.as_str())
})
.observe(nanos as f64 / 1e9);
if bytes > 0 {
if bytes > 0
&& let Some(transferred_bytes) = transferred_bytes
{
transferred_bytes
.get_or_init(|| {
DB_METRICS
Expand All @@ -370,6 +375,7 @@ impl DiskIoMetrics {
DiskOperation::Read => &self.read_operations,
DiskOperation::Write => &self.write_operations,
DiskOperation::Delete => &self.delete_operations,
DiskOperation::Hardlink => &self.hardlink_operations,
};
let (db, replica) = (&stats.database, &stats.replica);
counters
Expand Down Expand Up @@ -472,7 +478,12 @@ fn remove_series(stats: &StorageMetrics) {
.page_cache_reclamation_time
.remove_label_values(db, replica, outcome);
}
for operation in [DiskOperation::Read, DiskOperation::Write, DiskOperation::Delete] {
for operation in [
DiskOperation::Read,
DiskOperation::Write,
DiskOperation::Delete,
DiskOperation::Hardlink,
] {
let _ = DB_METRICS
.page_cache_disk_operations
.remove_label_values(db, replica, operation.as_str());
Expand Down
14 changes: 5 additions & 9 deletions crates/datastore/src/locking_tx_datastore/committed_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1147,16 +1147,12 @@ impl CommittedState {
(table, self.storage.blobs())
}

/// Returns an iterator over all persistent tables (i.e., non-ephemeral tables)
#[cfg(feature = "durability")]
pub(super) fn persistent_tables_and_blob_store(&mut self) -> (impl Iterator<Item = &mut Table>, &BlobSet) {
(
self.tables
.iter_mut()
.filter(|(table_id, _)| !self.ephemeral_tables.contains(*table_id))
.map(|(_, table)| table),
self.storage.blobs(),
)
pub(super) fn tables_for_snapshot(&mut self) -> impl Iterator<Item = &mut Table> {
self.tables
.iter_mut()
.filter(|(table_id, _)| !self.ephemeral_tables.contains(*table_id))
.map(|(_, table)| table)
}

#[cfg(feature = "metrics")]
Expand Down
5 changes: 3 additions & 2 deletions crates/datastore/src/locking_tx_datastore/datastore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,9 @@ impl Locking {
tx_offset,
);

let (mut tables, blob_store) = committed_state.persistent_tables_and_blob_store();
let unflushed_snapshot = repo.create_snapshot(&mut tables, blob_store.scan(), tx_offset)?;
let storage = committed_state.storage.clone();
let mut tables = committed_state.tables_for_snapshot();
let unflushed_snapshot = repo.create_snapshot(tx_offset, &storage, &mut tables)?;

Ok(Some((tx_offset, unflushed_snapshot)))
}
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/relational_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,7 @@ impl RelationalDB {
SnapshotError::Page(inner) => inner.is_transient(),
SnapshotError::Blob(inner) => inner.is_transient(),
SnapshotError::ObjectStore(inner) => inner.is_transient(),
SnapshotError::Tiered(inner) => inner.is_transient(),
}
}

Expand Down
9 changes: 9 additions & 0 deletions crates/paths/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,15 @@ impl SnapshotDirPath {
.file_stem()
.and_then(|s| s.to_str()?.split('.').next()?.parse::<u64>().ok())
}

pub fn snapshots(&self) -> SnapshotsPath {
SnapshotsPath(
self.0
.parent()
.expect("SnapshotDirPath should have a parent")
.to_path_buf(),
)
}
}

path_type! {
Expand Down
135 changes: 58 additions & 77 deletions crates/snapshot/src/common.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
use std::{
collections::BTreeMap,
ffi::OsStr,
fs,
io::{BufWriter, Read as _, Write as _},
num::NonZeroUsize,
time::Instant,
};

use spacetimedb_durability::TxOffset;
use spacetimedb_fs_utils::{
compression::{CompressReader, CompressType},
dir_trie::{o_excl, o_rdonly, CountCreated, DirTrie},
dir_trie::{o_excl, o_rdonly, DirTrie},
lockfile::Lockfile,
};
use spacetimedb_lib::bsatn;
use spacetimedb_paths::server::SnapshotFilePath;
use spacetimedb_primitives::TableId;
use spacetimedb_table::{
blob_store::BlobHash,
page::Page,
page_pool::PagePool,
table::Table,
tiered::{BlobMap, ObjectStoreError, ScannedBlob},
use spacetimedb_paths::{
server::{SnapshotDirPath, SnapshotFilePath, SnapshotsPath},
FromPathUnchecked as _,
};
use spacetimedb_primitives::TableId;
use spacetimedb_table::{blob_store::BlobHash, page::Page, page_pool::PagePool, tiered::BlobMap};

use crate::{
v0, v1, BlobEntry, FileOrDirPath, ObjectType, Snapshot, SnapshotError, SnapshotReadKindMetrics, TableEntry,
TablePages, MAGIC, ZERO_HASH_DENOTING_ABSENT_PAGE,
v0, v1, BlobEntry, FileOrDirPath, ObjectType, ParentRepo, Snapshot, SnapshotError, SnapshotReadKindMetrics,
TableEntry, TablePages, MAGIC, SNAPSHOT_DIR_EXT, ZERO_HASH_DENOTING_ABSENT_PAGE,
};

pub(crate) fn read_from_file(path: &SnapshotFilePath) -> Result<(Snapshot, CompressType), SnapshotError> {
Expand Down Expand Up @@ -250,72 +250,6 @@ fn reconstruct_one_table_pages(
.collect()
}

pub(crate) fn write_blobs<'a>(
repo: &DirTrie,
parent: Option<&DirTrie>,
mut on_write: impl FnMut(BlobEntry),
counter: &mut CountCreated,
blobs: impl Iterator<Item = Result<ScannedBlob<'a>, 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<Item = &'a mut Table>,
) -> 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);

Expand All @@ -335,3 +269,50 @@ pub(crate) fn write_snapshot_file(path: SnapshotFilePath, snapshot_bsatn: &[u8])

Ok(())
}

pub(crate) fn latest_snapshot_older_than(
root: &SnapshotsPath,
upper_bound: TxOffset,
) -> Result<Option<TxOffset>, SnapshotError> {
all_snapshots(root).map(|iter| iter.filter(|&tx_offset| tx_offset <= upper_bound).max())
}

pub(crate) fn all_snapshots(root: &SnapshotsPath) -> Result<impl Iterator<Item = TxOffset> + use<>, SnapshotError> {
Ok(root
// Item = Result<DirEntry>
.read_dir()?
// Item = DirEntry
.filter_map(Result::ok)
// Item = PathBuf
.map(|dirent| dirent.path())
// Ignore entries not shaped like snapshot directories.
.filter(|path| path.extension() == Some(OsStr::new(SNAPSHOT_DIR_EXT)))
// Ignore entries whose lockfile still exists.
.filter(|path| !Lockfile::lock_path(path).exists())
// Parse each entry's TxOffset from the file name; ignore unparsable.
// Also ignore if the snapshot file doesn't exists.
// This can happen on incomplete transfers, or if something went
// wrong during creation.
// Item = TxOffset
.filter_map(|path| {
let offset = TxOffset::from_str_radix(path.file_stem()?.to_str()?, 10).ok()?;
let snapshot_file = SnapshotDirPath::from_path_unchecked(path).snapshot_file(offset);
if !snapshot_file.0.exists() {
None
} else {
Some(offset)
}
}))
}

pub(crate) fn parent_repo(root: &SnapshotsPath, before: TxOffset) -> Result<Option<ParentRepo>, SnapshotError> {
let Some(offset) = latest_snapshot_older_than(root, before)? else {
return Ok(None);
};

let parent_dir = root.snapshot_dir(offset);
let (parent_snapshot, _) = Snapshot::read_from_file(&parent_dir.snapshot_file(offset))?;
let parent_repo = parent_snapshot.into_parent_repo(&parent_dir)?;

Ok(Some(parent_repo))
}
Loading
Loading