diff --git a/packages/cultcache-py/tests/test_store_lock.py b/packages/cultcache-py/tests/test_store_lock.py index 0122f094..50b95436 100644 --- a/packages/cultcache-py/tests/test_store_lock.py +++ b/packages/cultcache-py/tests/test_store_lock.py @@ -85,8 +85,9 @@ class StoreLockTests(unittest.TestCase): "push_all": lambda store: store.push_all([envelope("b")]), "delete": lambda store: store.delete("t", "a"), } - for name, write in writes.items(): - with self.subTest(name): + missing = self.dir / "volume" / "missing.cc" + for (name, write), link_to in [(item, to) for item in writes.items() for to in (target, missing)]: + with self.subTest(name, dangling=link_to == missing): if os.path.lexists(self.path): os.unlink(self.path) holder = start_holder([sys.executable, "-c", PY_HOLDER, str(self.path), str(HOLD_SECONDS)]) @@ -104,14 +105,16 @@ class StoreLockTests(unittest.TestCase): writer = threading.Thread(target=run) writer.start() time.sleep(0.3) - os.symlink(target, self.path) # after the writer's pre-lock look, while it waits + os.symlink(link_to, self.path) # after the writer's pre-lock look, while it waits writer.join() holder.wait() self.assertEqual(1, len(outcome)) self.assertIsInstance(outcome[0], StoreLinkedError) self.assertTrue(os.path.islink(self.path), "the link was replaced") self.assertEqual(before, target.read_bytes()) - with store_write_lock(target, timeout=0.2): # the lock is free + self.assertFalse(missing.exists(), "the dangling target was created") + os.unlink(self.path) # a link is refused before the lock, so remove it to probe the writer's own lock file + with store_write_lock(self.path, timeout=0.2): # the lock is free pass def test_the_lock_is_released_after_each_write(self) -> None: diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index 9bd88fb5..9ba800e9 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -1752,8 +1752,7 @@ impl SingleFileMessagePackBackingStore { let lock = self.open_lock_file()?; fs2::FileExt::lock_exclusive(&lock) .with_context(|| format!("failed to lock {}", self.lock_path().display()))?; - // A link may have been put at the path while the lock was awaited; the refusal above only saw the path before. - release_lock(lock, refuse_linked(&self.path).and_then(|()| action())) + self.run_locked(lock, action) } /// Replaces the named entries only if each still matches its expectation. @@ -1871,7 +1870,13 @@ impl SingleFileMessagePackBackingStore { .with_context(|| format!("failed to lock {}", self.lock_path().display())); } } - release_lock(lock, refuse_linked(&self.path).and_then(|()| action())).map(Some) + self.run_locked(lock, action).map(Some) + } + + /// The one tail of both exclusive entries: with the lock held, look for a link again (one may have been put at the + /// path while the lock was awaited; the look before the lock saw the path earlier), run the action, release. + fn run_locked(&self, lock: File, action: impl FnOnce() -> Result) -> Result { + release_lock(lock, refuse_linked(&self.path).and_then(|()| action())) } fn open_lock_file(&self) -> Result { @@ -8200,8 +8205,6 @@ mod tests { Ok(()) } - // A write at a store path that is a link is refused: a replace there would swap the link for a regular file and - // detach the store from its target. Reads through a live link keep working. // A link put at the store path while a writer waits on the lock is refused once the lock is taken, as C# does, and the // lock is free afterwards. #[cfg(unix)] @@ -8213,6 +8216,7 @@ mod tests { let target = volume.join("store.cc"); SingleFileMessagePackBackingStore::new(&target).push(&snapshot_envelope("a", b"1"))?; let before = fs::read(&target)?; + let dangling = volume.join("missing.cc"); let path = temp.path().join("late.cc"); let writers: [(&str, fn(&mut SingleFileMessagePackBackingStore) -> Result<()>); 4] = [ ("push", |s| s.push(&snapshot_envelope("b", b"2"))), @@ -8220,7 +8224,7 @@ mod tests { ("delete", |s| s.delete(&snapshot_envelope("a", b"1"))), ("compare_exchange_snapshot", |s| s.compare_exchange_snapshot(&[], &[snapshot_envelope("b", b"2")]).map(|_| ())), ]; - for (name, write) in writers { + for (name, write, link_to) in writers.into_iter().flat_map(|(n, w)| [(n, w, &target), (n, w, &dangling)]) { let _ = fs::remove_file(&path); let store = SingleFileMessagePackBackingStore::new(&path); let holder = store.open_lock_file()?; @@ -8228,18 +8232,21 @@ mod tests { let mut waiting = SingleFileMessagePackBackingStore::new(&path); let handle = std::thread::spawn(move || write(&mut waiting)); std::thread::sleep(std::time::Duration::from_millis(300)); - std::os::unix::fs::symlink(&target, &path)?; + std::os::unix::fs::symlink(link_to, &path)?; fs2::FileExt::unlock(&holder)?; let error = handle.join().expect("writer thread").expect_err("the late link must be refused"); assert!(error.downcast_ref::().is_some(), "{name}: {error:#}"); assert!(fs::symlink_metadata(&path)?.file_type().is_symlink(), "{name}: the link was replaced"); assert_eq!(fs::read(&target)?, before, "{name}: the target changed"); + assert!(!dangling.exists(), "{name}: the dangling target was created"); let probe = store.open_lock_file()?; fs2::FileExt::try_lock_exclusive(&probe).map_err(|e| anyhow!("{name}: lock still held: {e}"))?; } Ok(()) } + // A write at a store path that is a link is refused: a replace there would swap the link for a regular file and + // detach the store from its target. Reads through a live link keep working. #[cfg(unix)] #[test] fn a_write_at_a_live_link_is_refused_and_nothing_changes_while_a_read_through_it_works() -> Result<()> { diff --git a/packages/cultcache-ts/test/store-file.test.ts b/packages/cultcache-ts/test/store-file.test.ts index 13e1956a..7ddf7fe3 100644 --- a/packages/cultcache-ts/test/store-file.test.ts +++ b/packages/cultcache-ts/test/store-file.test.ts @@ -428,18 +428,20 @@ test("a link put while a writer waits on the store lock is refused once it holds ["pushAll", (store) => store.pushAll([noteEnvelope("b")])], ["delete", (store) => store.delete(noteEnvelope("a"))], ]; - for (const [name, write] of writes) { - const link = join(directory, `${name}.cc`); + const missing = join(directory, "missing.cc"); + for (const [name, write, linkTo] of writes.flatMap(([n, w]) => [[n, w, target], [`${n} (dangling)`, w, missing]] as const)) { + const link = join(directory, `${name.replace(/\W+/g, "-")}.cc`); let writer: Promise | undefined; await withStoreWriteLock(link, async () => { writer = write(new SingleFileMessagePackBackingStore(link)); writer.catch(() => undefined); await sleepFor(150); - await fsp.symlink(target, link); // after the writer's pre-lock look, while it waits + await fsp.symlink(linkTo, link); // after the writer's pre-lock look, while it waits }); await assert.rejects(writer!, (error: unknown) => error instanceof PackageStoreLinkedError, name); assert.ok((await fsp.lstat(link)).isSymbolicLink(), `${name}: the link was replaced`); assert.deepEqual(await readFile(target), before, `${name}: the target changed`); + await assert.rejects(fsp.lstat(missing), { code: "ENOENT" }, `${name}: the dangling target was created`); await rm(link); // the link is refused before the lock, so remove it to probe the lock assert.equal(await withStoreWriteLock(link, async () => "free", { timeoutMs: 200 }), "free", `${name}: the lock is held`); }