diff --git a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs index 8f76cbae..f916a13b 100644 --- a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs +++ b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs @@ -710,17 +710,23 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore // Only a writer creates the records folder and the lock, so opening the store creates nothing. A reader opens an // existing lock and returns null when there is none; that does not mean no writer committed (a store may be copied // without its lock, and a first writer may create it mid-load), so an unleased load checks that it settled. + // A writer's lease is also where a link at the manifest path is refused (a commit would replace the link with a file): before + // the records folder or the lock is made, and again once the lease is held, because a link can be put there while it waited. private FileStream? AcquireCommitLease(bool wait, bool create) { if (create) + { + CultStoreLinks.Refuse(_manifestFile.FullName); Directory.CreateDirectory(_recordDirectory.FullName); + } var lockPath = Path.Combine(_recordDirectory.FullName, ".commit.lock"); var started = Stopwatch.StartNew(); while (true) { + FileStream held; try { - return new FileStream( + held = new FileStream( lockPath, create ? FileMode.OpenOrCreate : FileMode.Open, FileAccess.ReadWrite, @@ -743,7 +749,23 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore catch (IOException) when (started.Elapsed < TimeSpan.FromSeconds(30)) { Thread.Sleep(10); + continue; } + + if (create) + { + try + { + CultStoreLinks.Refuse(_manifestFile.FullName); + } + catch + { + held.Dispose(); + throw; + } + } + + return held; } } diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 8934aec9..c461bc67 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -5154,24 +5154,15 @@ namespace GameCult.Caching } // Something is at the path even when the path cannot be opened: a link keeps the reparse-point attribute whether or not its - // target is there. A path with nothing at it reports no attributes at all (-1). - private bool PathIsALink() - { - FileInfo.Refresh(); - var attributes = FileInfo.Attributes; - return (int)attributes != -1 && (attributes & FileAttributes.ReparsePoint) != 0; - } + // target is there. + private bool PathIsALink() => CultStoreLinks.IsLink(FileInfo.FullName); - // A write never goes through a link at the store path: replacing it would silently detach the store from its link. Every - // write takes the lock first, so this is the one place a link is refused, before the lock file or anything else is made. - private void RefuseLinkedStore() - { - if (PathIsALink()) - throw new CultStoreLinkedException( - $"The store path {FileInfo.FullName} is a link; a write is refused so it does not replace the link. Configure the link's target as the store path to write to it."); - } + // A write never goes through a link at the store path: replacing it would silently detach the store from its link. + private void RefuseLinkedStore() => CultStoreLinks.Refuse(FileInfo.FullName); // The lock is a sidecar opened exclusively, which excludes other handles in this process and in others alike. + // Every write takes the lock first, so the link is refused here twice: before the lock file or anything else is made, and + // again once the lock is held, because a link can be put at the path while this writer waited on another's lock. private FileStream? AcquireLock(bool wait) { RefuseLinkedStore(); @@ -5180,9 +5171,10 @@ namespace GameCult.Caching var started = Stopwatch.StartNew(); while (true) { + FileStream held; try { - return new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, bufferSize: 1); + held = new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, bufferSize: 1); } catch (IOException) when (!wait) { @@ -5191,7 +5183,20 @@ namespace GameCult.Caching catch (IOException) when (started.Elapsed < TimeSpan.FromSeconds(30)) { Thread.Sleep(10); + continue; } + + try + { + RefuseLinkedStore(); + } + catch + { + held.Dispose(); + throw; + } + + return held; } } diff --git a/src/GameCult.Caching/CultStoreLinkedException.cs b/src/GameCult.Caching/CultStoreLinkedException.cs index 2c3c0ca2..79e6c545 100644 --- a/src/GameCult.Caching/CultStoreLinkedException.cs +++ b/src/GameCult.Caching/CultStoreLinkedException.cs @@ -3,15 +3,20 @@ using System.IO; namespace GameCult.Caching { /// - /// A write was attempted at a single-file store path that is a link (a symbolic link to a file or a directory, a Windows - /// junction or any other reparse-point link). The write is refused before the lock, the staging file or the replace, so the - /// link and what it points at are untouched. Configure the link's target as the store path to write to it; reads through a - /// live link are unchanged. names the path. + /// A write was attempted at a store path that is a link (a symbolic link to a file or a directory, a Windows junction or any + /// other reparse-point link). The write is refused before the lock, the staging file or the replace, and again once the lock + /// is held, so the link and what it points at are untouched. Configure the link's target as the store path to write to it; + /// reads through a live link are unchanged. /// public sealed class CultStoreLinkedException : IOException { - public CultStoreLinkedException(string message) : base(message) + public CultStoreLinkedException(string path) + : base($"CultCache store {path} is a link, and a write at it would replace the link; configure the link's target as the store path.") { + Path = path; } + + /// The store path that is a link. + public string Path { get; } } } diff --git a/src/GameCult.Caching/CultStoreLinks.cs b/src/GameCult.Caching/CultStoreLinks.cs new file mode 100644 index 00000000..cc9ec2b0 --- /dev/null +++ b/src/GameCult.Caching/CultStoreLinks.cs @@ -0,0 +1,22 @@ +using System.IO; + +namespace GameCult.Caching +{ + // The one decision on whether a store-owned file is a link, shared by every store kind that replaces files. + internal static class CultStoreLinks + { + // A path with nothing at it reports no attributes at all (-1). Any reparse point counts as a link, whether or not its + // target is there. + internal static bool IsLink(string path) + { + var attributes = new FileInfo(path).Attributes; + return (int)attributes != -1 && (attributes & FileAttributes.ReparsePoint) != 0; + } + + internal static void Refuse(string path) + { + if (IsLink(path)) + throw new CultStoreLinkedException(path); + } + } +} diff --git a/tests/GameCult.Caching.Tests/StoreLinkRefusalTests.cs b/tests/GameCult.Caching.Tests/StoreLinkRefusalTests.cs new file mode 100644 index 00000000..1de99237 --- /dev/null +++ b/tests/GameCult.Caching.Tests/StoreLinkRefusalTests.cs @@ -0,0 +1,315 @@ +#nullable enable +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching.MessagePack; +using NUnit.Framework; +using static GameCult.Caching.Tests.ElementIdTests; +using static GameCult.Caching.Tests.StoreReadabilityTests; + +namespace GameCult.Caching.Tests +{ + // A write never replaces a link at a store-owned path. The refusal holds for every way a write reaches a store (waiting or + // not, as a judge of another store's commit), for a link put there while the write waited on the store's lock, and for the + // directory store's manifest. + public class StoreLinkRefusalTests + { + private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(IdDeck), typeof(VectorItem) }); + private string _directory = ""; + + [SetUp] + public void SetUp() + { + _directory = Path.Combine(Path.GetTempPath(), "cultlib-link-refusal-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + } + + [TearDown] + public void TearDown() + { + if (!Directory.Exists(_directory)) + return; + foreach (var entry in Directory.EnumerateFileSystemEntries(_directory).Where(IsALink)) + File.Delete(entry); + Directory.Delete(_directory, true); + } + + private string PathOf(string name) => Path.Combine(_directory, name); + + private static bool IsALink(string path) + { + var attributes = new FileInfo(path).Attributes; + return (int)attributes != -1 && (attributes & FileAttributes.ReparsePoint) != 0; + } + + private static void Link(string path, string target) + { + try + { + File.CreateSymbolicLink(path, target); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Assert.Ignore("A file symlink needs a privilege this account lacks: " + ex.Message); + } + } + + private static void SeedSingle(string path) + { + using var seed = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = Registry }); + seed.Commit(batch => batch.Upsert(typeof(IdDeck), new IdDeck { Name = "seed" }, new CultRecordKey("seed"))); + } + + private static void SeedItem(string path) + { + using var seed = new CultCache(Registry); + seed.AddBackingStore(new SingleFileMessagePackBackingStore(path), typeof(VectorItem)); + seed.Commit(batch => batch.Upsert(typeof(VectorItem), new VectorItem(), new CultRecordKey("item"))); + } + + // Runs `write` while another holder has `lockPath`; `swap` runs while it waits, then the lock is released. + private static Exception? WriteWhileWaiting(string lockPath, Action write, Action swap) + { + using var held = new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + var task = Task.Run(write); + Assert.That(task.Wait(TimeSpan.FromMilliseconds(600)), Is.False, "the lock is held, so the write must wait"); + swap(); + held.Dispose(); + try + { + Assert.That(task.Wait(TimeSpan.FromSeconds(10)), Is.True); + return null; + } + catch (AggregateException ex) + { + return ex.GetBaseException(); + } + } + + private static void ReplaceWithLink(string path, string target) + { + File.Delete(path); + Link(path, target); + } + + // ---- a link put at the store path while the write waited on the lock ---- + + [Test] + public void ACommitRefusesALinkPutAtTheStoreWhileItWaitedOnTheLock() + { + var path = PathOf("store.cc"); + var target = PathOf("shared.cc"); + SeedSingle(path); + SeedSingle(target); + var before = File.ReadAllBytes(target); + using var cache = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = Registry, FlushOnDispose = false, StoreFlushOnDispose = false }); + + var error = WriteWhileWaiting(path + ".lock", + () => cache.Commit(batch => batch.Upsert(typeof(IdDeck), new IdDeck { Name = "late" }, new CultRecordKey("late"))), + () => ReplaceWithLink(path, target)); + + Assert.That(error, Is.InstanceOf(), error?.ToString()); + Assert.That(((CultStoreLinkedException)error!).Path, Is.EqualTo(path)); + Assert.That(IsALink(path), "the link was replaced"); + Assert.That(File.ReadAllBytes(target), Is.EqualTo(before)); + } + + [Test] + public void AFlushRefusesALinkPutAtTheStoreWhileItWaitedOnTheLock() + { + var path = PathOf("store.cc"); + var target = PathOf("shared.cc"); + SeedSingle(path); + SeedSingle(target); + var before = File.ReadAllBytes(target); + using var cache = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = Registry, FlushOnDispose = false, StoreFlushOnDispose = false }); + cache.UpsertAsync(typeof(IdDeck), new IdDeck { Name = "late" }, new CultRecordKey("late")).GetAwaiter().GetResult(); + + var error = WriteWhileWaiting(path + ".lock", () => cache.FlushAllBackingStores(), () => ReplaceWithLink(path, target)); + + Assert.That(error, Is.InstanceOf(), error?.ToString()); + Assert.That(IsALink(path), "the link was replaced"); + Assert.That(File.ReadAllBytes(target), Is.EqualTo(before)); + } + + // ---- the non-waiting and judging write paths ---- + + [Test] + public void ATryCommitAtALiveLinkIsRefusedNotContendedOrReplaced() + { + var path = PathOf("store.cc"); + var link = PathOf("link.cc"); + SeedSingle(path); + Link(link, path); + var before = File.ReadAllBytes(path); + using var cache = CultCacheMessagePack.Create(link, new CultCacheOpenOptions { Registry = Registry, FlushOnDispose = false, StoreFlushOnDispose = false }); + + var refusal = Assert.Throws(() => + cache.TryCommit(batch => batch.Upsert(typeof(IdDeck), new IdDeck { Name = "t" }, new CultRecordKey("t"))))!; + + Assert.That(refusal.Path, Is.EqualTo(link)); + Assert.That(refusal.Message, Does.Contain(link)); + Assert.That(IsALink(link), "the link was replaced"); + Assert.That(File.ReadAllBytes(path), Is.EqualTo(before)); + Assert.That(File.Exists(link + ".lock"), Is.False, "the refused write took the lock"); + } + + [Test] + public void ATryCommitAtALiveLinkWhoseLockIsHeldIsStillRefused() + { + var path = PathOf("store.cc"); + var link = PathOf("link.cc"); + SeedSingle(path); + Link(link, path); + using var cache = CultCacheMessagePack.Create(link, new CultCacheOpenOptions { Registry = Registry, FlushOnDispose = false, StoreFlushOnDispose = false }); + using var held = new FileStream(link + ".lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + + Assert.Throws(() => + cache.TryCommit(batch => batch.Upsert(typeof(IdDeck), new IdDeck { Name = "t" }, new CultRecordKey("t")))); + Assert.That(IsALink(link), "the link was replaced"); + } + + // A batch that upserts into one store and removes a key the cache does not hold has the other store judge that removal + // under its own lock (JudgeChecks). + private CultCache OpenTwoStores(string homePath, string otherPath) + { + var cache = new CultCache(Registry); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(homePath), typeof(IdDeck)); + cache.AddBackingStore(new SingleFileMessagePackBackingStore(otherPath), typeof(VectorItem)); + return cache; + } + + [Test] + public void AnotherStoreAtALiveLinkRefusesTheChecksItIsAskedToJudge() + { + var other = PathOf("other.cc"); + var link = PathOf("other-link.cc"); + SeedItem(other); + Link(link, other); + var before = File.ReadAllBytes(other); + using var cache = OpenTwoStores(PathOf("home.cc"), link); + + var refusal = Assert.Throws(() => cache.Commit(batch => + { + batch.Upsert(typeof(IdDeck), new IdDeck { Name = "home" }, new CultRecordKey("home")); + batch.Remove(new CultRecordKey("ghost")); + }))!; + + Assert.That(refusal.Path, Is.EqualTo(link)); + Assert.That(IsALink(link), "the link was replaced"); + Assert.That(File.ReadAllBytes(other), Is.EqualTo(before)); + Assert.That(File.Exists(PathOf("home.cc")), Is.False, "the home store was written though a judge refused"); + } + + [Test] + public void AJudgeReadsTheFileItHoldsUnderTheLockNotTheFileBeforeItWaited() + { + var other = PathOf("other.cc"); + SeedItem(other); + using var cache = OpenTwoStores(PathOf("home.cc"), other); + + var error = WriteWhileWaiting(other + ".lock", + () => cache.Commit(batch => + { + batch.Upsert(typeof(IdDeck), new IdDeck { Name = "home" }, new CultRecordKey("home")); + batch.Remove(new CultRecordKey("ghost")); + }), + () => File.WriteAllBytes(other, Array.Empty())); + + Assert.That(error, Is.InstanceOf(), error?.ToString()); + } + + // ---- the directory store's manifest ---- + + private DirectoryMessagePackBackingStore SeedDirectory(string manifest) + { + using (var seed = new CultCache(Registry)) + { + seed.AddBackingStore(new DirectoryMessagePackBackingStore(manifest), typeof(IdDeck)); + seed.Commit(batch => batch.Upsert(typeof(IdDeck), new IdDeck { Name = "seed" }, new CultRecordKey("seed"))); + } + + return new DirectoryMessagePackBackingStore(manifest); + } + + private CultCache OpenDirectory(DirectoryMessagePackBackingStore store) + { + var cache = new CultCache(Registry); + cache.AddBackingStore(store, typeof(IdDeck)); + return cache; + } + + [Test] + public void ADirectoryStoreCommitAtALiveManifestLinkIsRefusedAndNothingChanges() + { + var manifest = PathOf("real.cc"); + var link = PathOf("link.cc"); + SeedDirectory(manifest); + Link(link, manifest); + Directory.Move(manifest + ".records", link + ".records"); + var before = File.ReadAllBytes(manifest); + var pages = Directory.GetFileSystemEntries(link + ".records").OrderBy(entry => entry).ToArray(); + using var cache = OpenDirectory(new DirectoryMessagePackBackingStore(link)); + + var refusal = Assert.Throws(() => + cache.Commit(batch => batch.Upsert(typeof(IdDeck), new IdDeck { Name = "b" }, new CultRecordKey("b"))))!; + + Assert.That(refusal.Path, Is.EqualTo(link)); + Assert.That(IsALink(link), "the link was replaced"); + Assert.That(File.ReadAllBytes(manifest), Is.EqualTo(before)); + Assert.That(Directory.GetFileSystemEntries(link + ".records").OrderBy(entry => entry), Is.EqualTo(pages), "the refused write left files beside the manifest"); + } + + [Test] + public void ADirectoryStoreFlushAtALiveManifestLinkIsRefused() + { + var manifest = PathOf("real.cc"); + var link = PathOf("link.cc"); + SeedDirectory(manifest); + Link(link, manifest); + Directory.Move(manifest + ".records", link + ".records"); + var before = File.ReadAllBytes(manifest); + using var cache = OpenDirectory(new DirectoryMessagePackBackingStore(link)); + cache.UpsertAsync(typeof(IdDeck), new IdDeck { Name = "f" }, new CultRecordKey("f")).GetAwaiter().GetResult(); + + Assert.Throws(() => cache.FlushAllBackingStores()); + + Assert.That(IsALink(link), "the link was replaced"); + Assert.That(File.ReadAllBytes(manifest), Is.EqualTo(before)); + } + + [Test] + public void ADirectoryStoreCommitRefusesAManifestLinkPutThereWhileItWaitedOnTheLease() + { + var manifest = PathOf("store.cc"); + var target = PathOf("shared.cc"); + SeedDirectory(manifest); + SeedDirectory(target); + var before = File.ReadAllBytes(target); + using var cache = OpenDirectory(new DirectoryMessagePackBackingStore(manifest)); + + var error = WriteWhileWaiting(Path.Combine(manifest + ".records", ".commit.lock"), + () => cache.Commit(batch => batch.Upsert(typeof(IdDeck), new IdDeck { Name = "late" }, new CultRecordKey("late"))), + () => ReplaceWithLink(manifest, target)); + + Assert.That(error, Is.InstanceOf(), error?.ToString()); + Assert.That(IsALink(manifest), "the link was replaced"); + Assert.That(File.ReadAllBytes(target), Is.EqualTo(before)); + } + + [Test] + public void ADirectoryStoreReadsThroughALiveManifestLink() + { + var manifest = PathOf("real.cc"); + var link = PathOf("link.cc"); + SeedDirectory(manifest); + Link(link, manifest); + Directory.Move(manifest + ".records", link + ".records"); + + using var cache = OpenDirectory(new DirectoryMessagePackBackingStore(link)); + + Assert.That(cache.Get(new CultRecordKey("seed"))?.Name, Is.EqualTo("seed")); + } + } +}