vault import: unique temp name, poisoned entries replaced, load copies instead of opening the store
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a5ddfb9d76
commit
48f24f94df
1 changed files with 222 additions and 24 deletions
|
|
@ -182,6 +182,11 @@ impl VaultSnapshot {
|
|||
/// directory entry that is itself a reparse point is refused outright
|
||||
/// rather than descended into, because canonicalizing its *contents* would
|
||||
/// still resolve through it before the containment check ever ran.
|
||||
///
|
||||
/// Known limit: a hard link inside the root to a file outside it is an
|
||||
/// ordinary file with its own name and is admitted. A link count above one
|
||||
/// does not say where the other names live, so no cheap check exists; the
|
||||
/// vaults are operator-owned copies and a profile's root must be trusted.
|
||||
pub fn build(profile: &VaultProfile) -> Result<Self, VaultError> {
|
||||
let root = profile.root.canonicalize().map_err(|_| VaultError::Root)?;
|
||||
if !root.is_dir() {
|
||||
|
|
@ -256,46 +261,83 @@ impl VaultSnapshot {
|
|||
})
|
||||
}
|
||||
|
||||
/// Writes this snapshot as `<id>.cc` under `directory`, unless that file is
|
||||
/// already there, in which case nothing is touched. The file appears whole
|
||||
/// or not at all.
|
||||
/// Writes this snapshot as `<id>.cc` under `directory`. A directory entry
|
||||
/// that already loads as this snapshot is left untouched; one that does not
|
||||
/// (zero bytes, foreign, torn) is replaced. The file appears whole or not at
|
||||
/// all: it is written under a name no other importer shares and renamed into
|
||||
/// place, and a rename that loses to a concurrent importer of the same id is
|
||||
/// success, because the winner holds the same bytes. The store's lock
|
||||
/// sidecar is removed, so an import leaves exactly one file.
|
||||
pub fn import_into(&self, directory: &Path) -> Result<ImportOutcome, VaultError> {
|
||||
let path = directory.join(format!("{}.cc", self.id));
|
||||
if path.exists() {
|
||||
let already = || Self::load(directory, &self.id).is_ok_and(|held| held == *self);
|
||||
if already() {
|
||||
return Ok(ImportOutcome::AlreadyImported(self.id.clone()));
|
||||
}
|
||||
std::fs::create_dir_all(directory).map_err(|_| VaultError::Store)?;
|
||||
let partial = directory.join(format!("{}.cc.partial", self.id));
|
||||
let _ = std::fs::remove_file(&partial);
|
||||
{
|
||||
let mut store =
|
||||
OwnedRedbMessagePackBackingStore::new(&partial).map_err(|_| VaultError::Store)?;
|
||||
store
|
||||
.push(&CultCacheEnvelope {
|
||||
key: self.id.to_string(),
|
||||
r#type: VAULT_SNAPSHOT_SCHEMA.into(),
|
||||
payload: self.to_bytes(),
|
||||
stored_at: SNAPSHOT_STORED_AT.into(),
|
||||
schema_id: Some(VAULT_SNAPSHOT_SCHEMA.into()),
|
||||
let path = directory.join(format!("{}.cc", self.id));
|
||||
let partial = directory.join(format!("{}.cc.{}.partial", self.id, unique_suffix()));
|
||||
let written = self.write_store(&partial);
|
||||
let _ = std::fs::remove_file(sidecar(&partial));
|
||||
let published = written.and_then(|()| {
|
||||
// Unix replaces a held file atomically. Windows refuses to, so a
|
||||
// corrupt predecessor is removed and the rename tried once more.
|
||||
std::fs::rename(&partial, &path)
|
||||
.or_else(|_| {
|
||||
if already() {
|
||||
return Ok(());
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
std::fs::rename(&partial, &path)
|
||||
})
|
||||
.map_err(|_| VaultError::Store)?;
|
||||
.map_err(|_| VaultError::Store)
|
||||
});
|
||||
let _ = std::fs::remove_file(&partial);
|
||||
match published {
|
||||
Ok(()) => Ok(ImportOutcome::Imported(self.id.clone())),
|
||||
Err(_) if already() => Ok(ImportOutcome::AlreadyImported(self.id.clone())),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
std::fs::rename(&partial, &path).map_err(|_| VaultError::Store)?;
|
||||
// The store leaves its lock sidecar beside the file it created.
|
||||
let _ = std::fs::remove_file(directory.join(format!("{}.cc.partial.lock", self.id)));
|
||||
Ok(ImportOutcome::Imported(self.id.clone()))
|
||||
}
|
||||
|
||||
fn write_store(&self, partial: &Path) -> Result<(), VaultError> {
|
||||
let mut store = OwnedRedbMessagePackBackingStore::new(partial).map_err(|_| VaultError::Store)?;
|
||||
store
|
||||
.push(&CultCacheEnvelope {
|
||||
key: self.id.to_string(),
|
||||
r#type: VAULT_SNAPSHOT_SCHEMA.into(),
|
||||
payload: self.to_bytes(),
|
||||
stored_at: SNAPSHOT_STORED_AT.into(),
|
||||
schema_id: Some(VAULT_SNAPSHOT_SCHEMA.into()),
|
||||
})
|
||||
.map_err(|_| VaultError::Store)
|
||||
}
|
||||
|
||||
/// Reads the stored snapshot of `id`. The id is the stored row's own key and
|
||||
/// field, read back and compared, never re-derived: the note bytes it was
|
||||
/// derived from are not kept.
|
||||
///
|
||||
/// The store opens a file read-write, creates a lock sidecar beside it and
|
||||
/// writes a table on open, so the stored file is never opened: a private
|
||||
/// copy in the system temp directory is, and removed after. Loading leaves
|
||||
/// the store directory as it was, works on a read-only one, and takes no
|
||||
/// lock that a concurrent loader or importer could collide with.
|
||||
pub fn load(directory: &Path, id: &SnapshotId) -> Result<Self, VaultError> {
|
||||
let path = directory.join(format!("{id}.cc"));
|
||||
if !path.is_file() {
|
||||
return Err(VaultError::NotImported);
|
||||
}
|
||||
let store = OwnedRedbMessagePackBackingStore::new(&path).map_err(|_| VaultError::Store)?;
|
||||
let rows = store.pull_all().map_err(|_| VaultError::Store)?;
|
||||
let scratch = std::env::temp_dir().join(format!("ghostlight-vault-load-{}", unique_suffix()));
|
||||
let copied = std::fs::create_dir_all(&scratch)
|
||||
.and_then(|()| std::fs::copy(&path, scratch.join("snapshot.cc")))
|
||||
.map_err(|_| VaultError::Store);
|
||||
let read = copied.and_then(|_| Self::read_row(&scratch.join("snapshot.cc"), id));
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
read
|
||||
}
|
||||
|
||||
fn read_row(copy: &Path, id: &SnapshotId) -> Result<Self, VaultError> {
|
||||
let store = OwnedRedbMessagePackBackingStore::new(copy).map_err(|_| VaultError::Corrupt)?;
|
||||
let rows = store.pull_all().map_err(|_| VaultError::Corrupt)?;
|
||||
let [row] = rows.as_slice() else {
|
||||
return Err(VaultError::Corrupt);
|
||||
};
|
||||
|
|
@ -313,6 +355,20 @@ impl VaultSnapshot {
|
|||
}
|
||||
}
|
||||
|
||||
/// Unique across processes and threads: no two importers or loaders share a
|
||||
/// temporary name.
|
||||
fn unique_suffix() -> String {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
format!("{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// The lock file the store leaves beside the file it opened.
|
||||
fn sidecar(path: &Path) -> PathBuf {
|
||||
let mut name = path.as_os_str().to_owned();
|
||||
name.push(".lock");
|
||||
PathBuf::from(name)
|
||||
}
|
||||
|
||||
/// Length-prefixed fields, so no two profiles or note lists share an encoding.
|
||||
fn snapshot_id(profile: &VaultProfile, notes: &[SnapshotNote]) -> SnapshotId {
|
||||
fn field(digest: &mut Sha256, text: &str) {
|
||||
|
|
@ -1299,6 +1355,148 @@ mod tests {
|
|||
assert!(VaultSnapshot::build(&VaultProfile { exclude: vec!["/abs".into()], ..profile(vault.path()) }).is_err());
|
||||
}
|
||||
|
||||
fn listing(directory: &Path) -> Vec<String> {
|
||||
let mut names: Vec<String> = std::fs::read_dir(directory)
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
/// Stores `rows` as the file a snapshot of `id` would be, however wrong.
|
||||
fn plant(directory: &Path, id: &SnapshotId, rows: &[CultCacheEnvelope]) {
|
||||
let path = directory.join(format!("{id}.cc"));
|
||||
{
|
||||
let mut store = OwnedRedbMessagePackBackingStore::new(&path).unwrap();
|
||||
for row in rows {
|
||||
store.push(row).unwrap();
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(sidecar(&path));
|
||||
}
|
||||
|
||||
fn row(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
|
||||
CultCacheEnvelope {
|
||||
key: key.into(),
|
||||
r#type: VAULT_SNAPSHOT_SCHEMA.into(),
|
||||
payload,
|
||||
stored_at: SNAPSHOT_STORED_AT.into(),
|
||||
schema_id: Some(VAULT_SNAPSHOT_SCHEMA.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every way a stored file can fail to be the snapshot of its name is
|
||||
/// Corrupt, one condition at a time; the honest file loads.
|
||||
#[test]
|
||||
fn load_refuses_a_row_that_is_wrong_in_any_one_way() {
|
||||
let vault = fixture();
|
||||
let built = snapshot(vault.path());
|
||||
let id = built.id();
|
||||
write(vault.path(), "Public/extra.md", "extra\n");
|
||||
let other = snapshot(vault.path());
|
||||
let honest = row(id.as_str(), built.to_bytes());
|
||||
let non_canonical = rmp_serde::to_vec(&built).unwrap();
|
||||
assert_ne!(non_canonical, built.to_bytes());
|
||||
assert_eq!(rmp_serde::from_slice::<VaultSnapshot>(&non_canonical).unwrap(), built);
|
||||
|
||||
let cases: Vec<(&str, Vec<CultCacheEnvelope>)> = vec![
|
||||
("no rows", vec![]),
|
||||
("two rows", vec![honest.clone(), row("second", built.to_bytes())]),
|
||||
("foreign type", vec![CultCacheEnvelope { r#type: "other.v1".into(), ..honest.clone() }]),
|
||||
("no schema id", vec![CultCacheEnvelope { schema_id: None, ..honest.clone() }]),
|
||||
(
|
||||
"foreign schema id",
|
||||
vec![CultCacheEnvelope { schema_id: Some("other.v1".into()), ..honest.clone() }],
|
||||
),
|
||||
("foreign key", vec![row(other.id().as_str(), built.to_bytes())]),
|
||||
("another snapshot's bytes", vec![row(id.as_str(), other.to_bytes())]),
|
||||
("a non-canonical encoding", vec![row(id.as_str(), non_canonical)]),
|
||||
("garbage payload", vec![row(id.as_str(), b"not msgpack".to_vec())]),
|
||||
];
|
||||
for (label, rows) in cases {
|
||||
let store = tempfile::tempdir().unwrap();
|
||||
plant(store.path(), id, &rows);
|
||||
assert!(
|
||||
matches!(VaultSnapshot::load(store.path(), id), Err(VaultError::Corrupt)),
|
||||
"{label} loaded"
|
||||
);
|
||||
}
|
||||
let store = tempfile::tempdir().unwrap();
|
||||
plant(store.path(), id, &[honest]);
|
||||
assert_eq!(&VaultSnapshot::load(store.path(), id).unwrap(), &built);
|
||||
}
|
||||
|
||||
/// A stored file that is not a snapshot of its name is replaced by an
|
||||
/// import, never reported as already imported.
|
||||
#[test]
|
||||
fn a_poisoned_store_entry_is_replaced_not_reported_as_imported() {
|
||||
let vault = fixture();
|
||||
let built = snapshot(vault.path());
|
||||
for poison in [Vec::new(), b"definitely not a store".to_vec()] {
|
||||
let store = tempfile::tempdir().unwrap();
|
||||
let path = store.path().join(format!("{}.cc", built.id()));
|
||||
std::fs::write(&path, &poison).unwrap();
|
||||
assert!(matches!(VaultSnapshot::load(store.path(), built.id()), Err(VaultError::Corrupt)));
|
||||
assert_eq!(
|
||||
built.import_into(store.path()).unwrap(),
|
||||
ImportOutcome::Imported(built.id().clone())
|
||||
);
|
||||
assert_eq!(VaultSnapshot::load(store.path(), built.id()).unwrap(), built);
|
||||
assert_eq!(listing(store.path()), [format!("{}.cc", built.id())]);
|
||||
}
|
||||
// A well-formed store holding another snapshot's row is replaced too.
|
||||
let store = tempfile::tempdir().unwrap();
|
||||
plant(store.path(), built.id(), &[row(built.id().as_str(), b"x".to_vec())]);
|
||||
assert!(built.import_into(store.path()).unwrap() == ImportOutcome::Imported(built.id().clone()));
|
||||
assert_eq!(VaultSnapshot::load(store.path(), built.id()).unwrap(), built);
|
||||
}
|
||||
|
||||
/// Importers racing on one snapshot all succeed and leave one loadable file.
|
||||
#[test]
|
||||
fn concurrent_imports_of_one_snapshot_leave_one_loadable_file() {
|
||||
let vault = fixture();
|
||||
let built = std::sync::Arc::new(snapshot(vault.path()));
|
||||
for _ in 0..8 {
|
||||
let store = tempfile::tempdir().unwrap();
|
||||
let directory = std::sync::Arc::new(store.path().to_path_buf());
|
||||
let workers: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let (built, directory) = (built.clone(), directory.clone());
|
||||
std::thread::spawn(move || {
|
||||
let imported = built.import_into(&directory).unwrap();
|
||||
let loaded = VaultSnapshot::load(&directory, built.id()).unwrap();
|
||||
(imported, loaded)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for worker in workers {
|
||||
let (_, loaded) = worker.join().unwrap();
|
||||
assert_eq!(&loaded, &*built);
|
||||
}
|
||||
assert_eq!(listing(store.path()), [format!("{}.cc", built.id())]);
|
||||
assert_eq!(
|
||||
built.import_into(store.path()).unwrap(),
|
||||
ImportOutcome::AlreadyImported(built.id().clone())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_leaves_the_store_directory_as_it_found_it() {
|
||||
let vault = fixture();
|
||||
let built = snapshot(vault.path());
|
||||
let store = tempfile::tempdir().unwrap();
|
||||
built.import_into(store.path()).unwrap();
|
||||
let file = store.path().join(format!("{}.cc", built.id()));
|
||||
let before = std::fs::read(&file).unwrap();
|
||||
for _ in 0..2 {
|
||||
VaultSnapshot::load(store.path(), built.id()).unwrap();
|
||||
}
|
||||
assert_eq!(listing(store.path()), [format!("{}.cc", built.id())]);
|
||||
assert_eq!(before, std::fs::read(&file).unwrap());
|
||||
}
|
||||
|
||||
fn references(snapshot: &VaultSnapshot) -> Vec<&str> {
|
||||
snapshot.notes.iter().map(|note| note.reference.as_str()).collect()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue