Skip to content
Merged
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
94 changes: 76 additions & 18 deletions src/context_sync_replica.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ extern "C" {

/// Use an isolated APFS copy-on-write clone for the large database file.
/// The caller compares source signatures before and after the clone and
/// sidecar copies. Filesystems without `clonefile` support use a byte copy.
/// WAL copy. Filesystems without `clonefile` support use a byte copy.
fn clone_main_database(source: &Path, destination: &Path) -> io::Result<()> {
#[cfg(target_os = "macos")]
{
Expand Down Expand Up @@ -66,12 +66,12 @@ fn sidecar_path(db_path: &Path, suffix: &str) -> Result<PathBuf> {
Ok(db_path.with_file_name(format!("{name}{suffix}")))
}

fn source_paths(db_path: &Path) -> Result<[PathBuf; 3]> {
Ok([
db_path.to_path_buf(),
sidecar_path(db_path, "-wal")?,
sidecar_path(db_path, "-shm")?,
])
/// The source `-shm` is left out. It is SQLite's transient WAL index, and the
/// first connection to open a database rebuilds it from the DB and WAL, so it
/// changes while the data does not. The read-only replica rebuilds its own
/// `-shm` in the private directory.
fn source_paths(db_path: &Path) -> Result<[PathBuf; 2]> {
Ok([db_path.to_path_buf(), sidecar_path(db_path, "-wal")?])
}

fn file_signature(path: PathBuf, required: bool) -> Result<FileSignature> {
Expand Down Expand Up @@ -125,16 +125,12 @@ fn file_signature(path: PathBuf, required: bool) -> Result<FileSignature> {
})
}

fn snapshot_signature(db_path: &Path) -> Result<[FileSignature; 3]> {
let [db, wal, shm] = source_paths(db_path)?;
Ok([
file_signature(db, true)?,
file_signature(wal, false)?,
file_signature(shm, false)?,
])
fn snapshot_signature(db_path: &Path) -> Result<[FileSignature; 2]> {
let [db, wal] = source_paths(db_path)?;
Ok([file_signature(db, true)?, file_signature(wal, false)?])
}

fn remove_previous_attempt(tmpdir: &Path, source: &[FileSignature; 3]) -> Result<()> {
fn remove_previous_attempt(tmpdir: &Path, source: &[FileSignature; 2]) -> Result<()> {
for item in source {
let name = item
.path
Expand All @@ -153,7 +149,7 @@ fn remove_previous_attempt(tmpdir: &Path, source: &[FileSignature; 3]) -> Result
Ok(())
}

fn copy_signature_set(tmpdir: &Path, source: &[FileSignature; 3]) -> Result<PathBuf> {
fn copy_signature_set(tmpdir: &Path, source: &[FileSignature; 2]) -> Result<PathBuf> {
remove_previous_attempt(tmpdir, source)?;
for (index, item) in source.iter().enumerate().filter(|(_, item)| item.exists) {
let name = item
Expand Down Expand Up @@ -340,13 +336,26 @@ mod tests {
}

#[test]
fn context_sync_local_replica_copies_wal_and_shm_sidecars() -> Result<()> {
fn context_sync_local_replica_copies_wal_and_rebuilds_shm_privately() -> Result<()> {
let (_tempdir, db_path, _source_connection) = wal_fixture()?;
assert!(sidecar_path(&db_path, "-wal")?.exists());
assert!(sidecar_path(&db_path, "-shm")?.exists());
let source_shm = sidecar_path(&db_path, "-shm")?;
let source_shm_bytes = fs::read(&source_shm)?;
let replica = IsolatedSqliteReplica::create(&db_path)?;
assert!(sidecar_path(&replica.db_path, "-wal")?.exists());
assert!(!sidecar_path(&replica.db_path, "-shm")?.exists());
let connection = Connection::open_with_flags(
&replica.db_path,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
connection.execute_batch("PRAGMA query_only=ON")?;
assert_eq!(
connection.query_row("SELECT COUNT(*) FROM messages", [], |row| row
.get::<_, i64>(0))?,
1
);
assert!(sidecar_path(&replica.db_path, "-shm")?.exists());
assert_eq!(fs::read(&source_shm)?, source_shm_bytes);
Ok(())
}

Expand All @@ -373,6 +382,55 @@ mod tests {
Ok(())
}

fn read_message_count(db_path: &Path) -> Result<i64> {
let connection = Connection::open_with_flags(
db_path,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
Ok(connection.query_row("SELECT COUNT(*) FROM messages", [], |row| row.get(0))?)
}

#[test]
fn context_sync_local_replica_ignores_shm_rebuilt_by_another_reader() -> Result<()> {
let (fixture_dir, fixture_db, writer) = wal_fixture()?;
let source_dir = tempfile::tempdir()?;
let db_path = source_dir.path().join("source.sqlite3");
fs::copy(&fixture_db, &db_path)?;
fs::copy(
sidecar_path(&fixture_db, "-wal")?,
sidecar_path(&db_path, "-wal")?,
)?;
drop(writer);
drop(fixture_dir);
assert_eq!(read_message_count(&db_path)?, 1);
let signatures = || -> Result<[FileSignature; 3]> {
Ok([
file_signature(db_path.clone(), true)?,
file_signature(sidecar_path(&db_path, "-wal")?, false)?,
file_signature(sidecar_path(&db_path, "-shm")?, false)?,
])
};
let tempdir = tempfile::tempdir()?;
let mut attempts = Vec::new();
let replica_db = copy_consistent_sqlite_replica_with_hook(
&db_path,
tempdir.path(),
|attempt, source| {
attempts.push(attempt);
let [db_before, wal_before, shm_before] = signatures()?;
assert_eq!(read_message_count(source)?, 1);
let [db_after, wal_after, shm_after] = signatures()?;
assert_eq!(db_after, db_before, "reader left the main DB unchanged");
assert_eq!(wal_after, wal_before, "reader left the WAL unchanged");
assert_ne!(shm_after, shm_before, "reader rebuilt the SHM");
Ok(())
},
)?;
assert_eq!(attempts, vec![1]);
assert_eq!(read_message_count(&replica_db)?, 1);
Ok(())
}

#[test]
fn context_sync_local_replica_can_copy_while_source_holds_exclusive_transaction() -> Result<()>
{
Expand Down
Loading