diff --git a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs index 6e0ce6cd..aecbb6f6 100644 --- a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs +++ b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs @@ -64,7 +64,8 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore var reports = new List(); var loaded = new Dictionary(StringComparer.Ordinal); var foreign = new List(); - LoadManifestPages(null, loaded, reports, foreign, Trace); + var versions = new Dictionary(StringComparer.Ordinal); + LoadManifestPages(null, loaded, reports, foreign, Trace, versions); bool Staged(string key) => _dirtyKeys.ContainsKey(key) || _deletedKeys.ContainsKey(key); var arrived = loaded @@ -88,6 +89,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore Entries[stored.Key.Value] = stored; foreach (var key in loaded.Keys) _hydratedKeys.Add(key); + ReadAllVersions(versions); SetLastSchemaMigrationReports(reports); SetForeignRecords(foreign); @@ -96,19 +98,22 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore } // The one load of manifest pages, for the whole store (key null) or one record: under the lease, with the moved-manifest retry. - // It reads only; adopting what it loaded is the caller's. + // It reads only; adopting what it loaded is the caller's. A whole-store load (key null) also fills versions with every manifest + // record's version, claimed and foreign: what the store held when it was read. private void LoadManifestPages( string? key, Dictionary loaded, List reports, List foreign, - Action trace) + Action trace, + Dictionary? versions = null) { for (var attempt = 1; ; attempt++) { loaded.Clear(); reports.Clear(); foreign.Clear(); + versions?.Clear(); // Only pages named by the manifest read under the lease are loaded; orphaned pages are never loaded. With no // lock to lease (none created yet, or a store copied without it) a writer may commit mid-load, so an unleased // load stands only if its manifest is still current; if the manifest moved it reloads, under the lease the @@ -117,6 +122,12 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore var manifestBytes = ReadManifestBytes(); var (manifest, _) = ParseManifest(manifestBytes); trace($"manifest records={manifest.Records.Length}"); + if (key == null) + { + foreach (var record in manifest.Records) + versions?.TryAdd(record.Key, VersionOf(record.Payload)); + } + try { if (lease == null) @@ -221,6 +232,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore return CultCommitOutcome.Committed; } + RefuseWriteIntoMovedManifest( + manifest, + request.Upserts, + StagedKeys.Concat(request.Upserts.Select(entry => entry.Key.Value)).Concat(request.Deletes.Select(entry => entry.Key.Value))); + var previousEntries = Entries.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal); var previousDirtyKeys = _dirtyKeys.Keys.ToArray(); var previousDeletedKeys = _deletedKeys.Keys.ToArray(); @@ -278,7 +294,10 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore return; RefuseUndeclaredOnDisk(manifest, StagedKeys, Array.Empty(), Array.Empty(), Array.Empty()); if (IsDirty) + { + RefuseWriteIntoMovedManifest(manifest, Array.Empty(), StagedKeys); WriteGeneration(manifest, catalogBytes); + } else MarkFlushSucceeded(); }); @@ -337,18 +356,51 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore HeldAt, WrittenAt, deletes.Select(entry => entry.Key.Value).Concat(checks), - key => HeldAt(key) is { } held && Foreign(held, currentManifest.SchemaCatalog, VersionOf(held.Payload)) == null - ? LoadPage(held, currentManifest.SchemaCatalog, out _, out _) - : null, - key => HeldAt(key) is { } held ? ForeignAt(held, currentManifest.SchemaCatalog) : null, + key => DurableAt(currentManifest, key), + key => ForeignAt(currentManifest, key), key => { - _dirtyKeys.TryRemove(key, out _); - _deletedKeys.TryRemove(key, out _); - IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty; + Unstage(key); + if (HeldAt(key) is { } held) + Wrote(key, VersionOf(held.Payload)); + else + Forgot(key); }); } + // The record at a key as the manifest holds it, decoded as a load would; null when none, or when no registered type claims it. + private CultStoredDocument? DurableAt(CultPersistedStoreSnapshot manifest, string key) => + manifest.Records.FirstOrDefault(record => string.Equals(record.Key, key, StringComparison.Ordinal)) is { } held && + Foreign(held, manifest.SchemaCatalog, VersionOf(held.Payload)) == null + ? LoadPage(held, manifest.SchemaCatalog, out _, out _) + : null; + + private CultForeignRecord? ForeignAt(CultPersistedStoreSnapshot manifest, string key) => + manifest.Records.FirstOrDefault(record => string.Equals(record.Key, key, StringComparison.Ordinal)) is { } held + ? ForeignAt(held, manifest.SchemaCatalog) + : null; + + private void Unstage(string key) + { + _dirtyKeys.TryRemove(key, out _); + _deletedKeys.TryRemove(key, out _); + IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty; + } + + // A write that lands a record of a type with a unique index, in the batch or already staged, lands only while the manifest it + // read under the commit lease is the one this store last read or wrote, whichever record moved (the one rule every store + // shares, CacheBackingStore.RefuseWriteIntoMovedStore). Variants are refused earlier, so only the unique-index arm applies. + private void RefuseWriteIntoMovedManifest(CultPersistedStoreSnapshot manifest, IEnumerable upserts, IEnumerable writeKeys) => + RefuseWriteIntoMovedStore( + () => manifest.Records.ToDictionary(record => record.Key, record => VersionOf(record.Payload), StringComparer.Ordinal), + gated: WritesUniqueIndex( + upserts.Select(entry => entry.Descriptor.SchemaId) + .Concat(_dirtyKeys.Keys.Select(key => Entries.TryGetValue(key, out var staged) ? staged.Descriptor.SchemaId : null).OfType())), + writeKeys, + key => DurableAt(manifest, key), + key => ForeignAt(manifest, key), + Unstage); + // Runs under the commit lease: pages first, then the manifest that names them. private void WriteGeneration(CultPersistedStoreSnapshot currentManifest, IReadOnlyDictionary catalogBytes) { @@ -416,6 +468,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore DeleteUnreferencedRecordPages(currentIndex.Values); + // The manifest names what this store wrote now: that is what it last read of those keys. + foreach (var key in _deletedKeys.Keys) + Forgot(key); + foreach (var key in written) + Wrote(key, Entries[key].StoredVersion); _dirtyKeys.Clear(); _deletedKeys.Clear(); MarkFlushSucceeded(); diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index 303d3737..cae722a5 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -4563,6 +4563,97 @@ namespace GameCult.Caching throw refusal(null); } + // The version of every record the store held when this store last read it, as this store last wrote it for keys it wrote. A write + // that lands a variant or a record with a unique index lands only while the durable versions still equal these + // (RefuseWriteIntoMovedStore). Bookkeeping derived from reads and writes: it judges no value. + private readonly Dictionary _lastRead = new(StringComparer.Ordinal); + + // A whole-store read: the versions of every record the store held, replacing what was last read. + protected void ReadAllVersions(IEnumerable> versions) + { + _lastRead.Clear(); + foreach (var (key, version) in versions) + _lastRead[key] = version; + } + + // This store wrote the record at a key, at this version. + protected void Wrote(string key, string version) => _lastRead[key] = version; + + // This store removed the record at a key, or found the store holds none. + protected void Forgot(string key) => _lastRead.Remove(key); + + // Whether any of the schema ids is a type that holds a unique index. + protected bool WritesUniqueIndex(IEnumerable schemaIds) => + AttachedRegistry is { } registry && schemaIds.Any(registry.HoldsUniqueIndex); + + /// + /// The one refusal of a write into a store that moved since this store last read it, for every store kind, called under the + /// store's lock. A write that is (it lands a variant or a record of a type with a unique index, which + /// resolve against other records and which a write cannot judge against records it did not read) lands only while every + /// record the store holds is at the version this store last read or wrote, whichever record it names; otherwise nothing is + /// written, what moved is reloaded through , and a is thrown for + /// the cache's judge to retry against. Versions only: a write hashes other records' bytes, never decodes them. + /// + /// The version of every record the store holds, read under the lock; evaluated only when gated. + /// Whether the write lands a record this rule guards. + /// Every key the write would write or remove, staged ones included. + /// See . + /// See . + /// See ; the store's last-read version of the key is set from the durable one after it. + protected void RefuseWriteIntoMovedStore( + Func> durableVersions, + bool gated, + IEnumerable writeKeys, + Func durableAt, + Func foreignAt, + Action unstage) + { + if (!gated) + return; + var versions = durableVersions(); + var changed = new HashSet(StringComparer.Ordinal); + foreach (var (key, version) in versions) + { + if (!_lastRead.TryGetValue(key, out var read) || !SameStoredIdentity(read, version)) + changed.Add(key); + } + + foreach (var key in _lastRead.Keys) + { + if (!versions.ContainsKey(key)) + changed.Add(key); + } + + if (changed.Count == 0) + return; + var recordKeys = writeKeys.Distinct(StringComparer.Ordinal).OrderBy(key => key, StringComparer.Ordinal).ToArray(); + var changedKeys = changed.OrderBy(key => key, StringComparer.Ordinal).ToArray(); + Refuse( + recordKeys.Concat(changedKeys), + key => Cache == null ? null : durableAt(key), + foreignAt, + key => + { + unstage(key); + if (versions.TryGetValue(key, out var version)) + _lastRead[key] = version; + else + _lastRead.Remove(key); + }, + inner => new CultWriteConflictException( + Cache == null + ? $"{this} holds a variant or a unique index and was written by a writer with no CultCache, which cannot resolve variants; nothing was written. " + + $"Records it would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that differ from what the writer has read: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}." + : $"{this} changed since this cache last read it, and it holds a variant or a record with a unique index, which resolve against other records; nothing was written. " + + $"Records this write would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that changed: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}. " + + (inner == null + ? "The cache reloaded them; retry the write against what the store holds now." + : "Reloading them failed, so the cache is unchanged."), + recordKeys, + changedKeys, + inner)); + } + // Two stored records are the same stored bytes when their versions are equal. The one place a pull's reload filter, the // staleness check and a refusal's reload decide it. protected static bool SameStoredIdentity(string? version, string? otherVersion) => @@ -4638,10 +4729,6 @@ namespace GameCult.Caching // A key is staged exactly while the store is dirty with it, and a pull runs only on a clean store. private readonly HashSet _staged = new(StringComparer.Ordinal); - // The version of every record the store held when this store last read it, as this store last wrote it for keys it wrote. - // A write into a store holding a variant lands only while the durable versions still equal these. - private readonly Dictionary _lastRead = new(StringComparer.Ordinal); - /// /// A store file from its parts, each already encoded: a catalog entry or record this store carries forward is the bytes its /// file held, one it writes is or of the object. @@ -4735,7 +4822,7 @@ namespace GameCult.Caching var durable = ReadSnapshot(); if (durable == null) { - _lastRead.Clear(); + ReadAllVersions(Array.Empty>()); SetLastSchemaMigrationReports(Array.Empty()); SetForeignRecords(Array.Empty()); return; @@ -4772,9 +4859,7 @@ namespace GameCult.Caching Entries.TryRemove(stored.Key.Value, out _); foreach (var stored in loaded) Entries[stored.Key.Value] = stored; - _lastRead.Clear(); - foreach (var (key, version) in versions) - _lastRead[key] = version; + ReadAllVersions(versions); SetLastSchemaMigrationReports(reports); SetForeignRecords(foreign); } @@ -5008,7 +5093,7 @@ namespace GameCult.Caching RefuseUndeclaredOnDisk(durable, upserts, removals, checks); if (upserts.Count == 0 && removals.Count == 0 && (checks.Any() || StagedChecks.Count > 0)) return Array.Empty<(CultStagedRecord, string)>(); - RefuseWriteIntoMovedStore(durable, upserts, removals); + RefuseWriteIntoMovedFile(durable, upserts, removals); var durableRecords = durable?.Snapshot.Records ?? Array.Empty(); // A record written over one the store holds is stored at a storedAt later than the one it replaces, whoever wrote that. var replaced = durableRecords.ToDictionary(record => record.Key, record => record.StoredAt, StringComparer.Ordinal); @@ -5050,9 +5135,9 @@ namespace GameCult.Caching Directory.CreateDirectory(FileInfo.DirectoryName!); WriteSnapshotAtomically(FileInfo.FullName, SerializeStore(format, catalog, fileRecords)); foreach (var key in removed) - _lastRead.Remove(key); + Forgot(key); foreach (var (staged, version) in versions) - _lastRead[staged.Record.Key] = version; + Wrote(staged.Record.Key, version); return versions; } @@ -5093,58 +5178,21 @@ namespace GameCult.Caching return false; } - private void RefuseWriteIntoMovedStore(Durable? durable, IReadOnlyCollection upserts, IReadOnlyCollection removals) - { - var records = durable?.Snapshot.Records ?? Array.Empty(); - if (records.All(record => record.Variant == null) && upserts.All(staged => staged.Record.Variant == null) && - !upserts.Any(staged => AttachedRegistry?.HoldsUniqueIndex(staged.Entry.SchemaId) == true)) - return; - var changed = new HashSet(StringComparer.Ordinal); - var versions = records.ToDictionary(record => record.Key, record => durable!.Version(record.Key), StringComparer.Ordinal); - foreach (var (key, version) in versions) - { - if (!_lastRead.TryGetValue(key, out var read) || !SameStoredIdentity(read, version)) - changed.Add(key); - } - - var durableKeys = records.Select(record => record.Key).ToHashSet(StringComparer.Ordinal); - foreach (var key in _lastRead.Keys) - { - if (!durableKeys.Contains(key)) - changed.Add(key); - } - - if (changed.Count == 0) - return; - var recordKeys = _staged.Concat(upserts.Select(staged => staged.Record.Key)).Concat(removals) - .Distinct(StringComparer.Ordinal).OrderBy(key => key, StringComparer.Ordinal).ToArray(); - var changedKeys = changed.OrderBy(key => key, StringComparer.Ordinal).ToArray(); - Refuse( - recordKeys.Concat(changedKeys), - key => Cache == null ? null : DurableAt(durable, key), + private void RefuseWriteIntoMovedFile(Durable? durable, IReadOnlyCollection upserts, IReadOnlyCollection removals) => + RefuseWriteIntoMovedStore( + () => (durable?.Snapshot.Records ?? Array.Empty()) + .ToDictionary(record => record.Key, record => durable!.Version(record.Key), StringComparer.Ordinal), + gated: (durable?.Snapshot.Records ?? Array.Empty()).Any(record => record.Variant != null) || + upserts.Any(staged => staged.Record.Variant != null) || + WritesUniqueIndex(upserts.Select(staged => staged.Entry.SchemaId)), + _staged.Concat(upserts.Select(staged => staged.Record.Key)).Concat(removals), + key => DurableAt(durable, key), key => ForeignAt(durable, key), key => { _staged.Remove(key); IsDirty = _staged.Count > 0; - if (versions.TryGetValue(key, out var version)) - _lastRead[key] = version; - else - _lastRead.Remove(key); - }, - inner => new CultWriteConflictException( - Cache == null - ? $"{this} holds a variant or a unique index and was written by a writer with no CultCache, which cannot resolve variants; nothing was written. " + - $"Records it would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that differ from what the writer has read: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}." - : $"{this} changed since this cache last read it, and it holds a variant or a record with a unique index, which resolve against other records; nothing was written. " + - $"Records this write would have written or removed: {string.Join(", ", recordKeys.Select(key => $"'{key}'"))}; records that changed: {string.Join(", ", changedKeys.Select(key => $"'{key}'"))}. " + - (inner == null - ? "The cache reloaded them; retry the write against what the store holds now." - : "Reloading them failed, so the cache is unchanged."), - recordKeys, - changedKeys, - inner)); - } + }); // A writable store judges a removal of a key its cache does not hold at its next flush or commit, under the lock (StageChecks); // a read-only store has neither, so it answers from its view and never creates the lock file. @@ -5204,7 +5252,7 @@ namespace GameCult.Caching { _staged.Remove(key); IsDirty = _staged.Count > 0; - _lastRead[key] = durable!.Version(key); + Wrote(key, durable!.Version(key)); }, cacheless: Cache == null); } diff --git a/src/GameCult.Caching/README.md b/src/GameCult.Caching/README.md index dffce80a..8afb83cc 100644 --- a/src/GameCult.Caching/README.md +++ b/src/GameCult.Caching/README.md @@ -37,7 +37,7 @@ Available cache attributes: - `CultDocument(schemaName, schemaVersion)` - `CultName` -- `CultIndex(alias?)`: a unique lookup. Within one document type, a non-blank value names one record; a commit that would leave two records holding one is refused, and a store holding such a pair refuses to load. Uniqueness is judged by a `CultCache` over the single-file store; a cacheless `WriteDocument`/`WriteRecord` of such a type is refused (also when the catalog declares an index alias the call cannot classify), and concurrent writers on a directory store are not covered (`unique-index-directory-store`). A value is culture-invariant, and a number is its canonical decimal (`1.0m` and `1.00m`, `0.0` and `-0.0` are one value). +- `CultIndex(alias?)`: a unique lookup. Within one document type, a non-blank value names one record; a commit that would leave two records holding one is refused, and a store holding such a pair refuses to load. Uniqueness is judged by a `CultCache` over the single-file store; a cacheless `WriteDocument`/`WriteRecord` of such a type is refused (also when the catalog declares an index alias the call cannot classify). A cache whose single-file or directory store another writer changed since it last read it gets `CultWriteConflictException` for a write of an indexed type, nothing written and the changed records reloaded; retry against them (`Update` retries on its own). A value is culture-invariant, and a number is its canonical decimal (`1.0m` and `1.00m`, `0.0` and `-0.0` are one value). - `CultRole(alias?)`: a selection and reference role. Many records may share a value; it is never a lookup. - `CultGlobal` - `CultReference(targetType?, many: false)` diff --git a/tests/GameCult.Caching.Tests/UniqueIndexTests.cs b/tests/GameCult.Caching.Tests/UniqueIndexTests.cs index 45817296..c43671bb 100644 --- a/tests/GameCult.Caching.Tests/UniqueIndexTests.cs +++ b/tests/GameCult.Caching.Tests/UniqueIndexTests.cs @@ -51,8 +51,20 @@ namespace GameCult.Caching.Tests private string PathOf(string name) => Path.Combine(_directory, name); - private static CultCache Open(string path, CultDocumentRegistry? registry = null) => - CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry ?? Registry }); + private static CultCache Open(string path, CultDocumentRegistry? registry = null) => Open(path, StoreKind.SingleFile, registry); + + // The same cache over either store kind at one path: the rule under test is the base store's, so both kinds answer to it. + public enum StoreKind { SingleFile, Directory } + + private static CultCache Open(string path, StoreKind kind, CultDocumentRegistry? registry = null) + { + registry ??= Registry; + if (kind == StoreKind.SingleFile) + return CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry }); + var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry)); + cache.AddBackingStore(new DirectoryMessagePackBackingStore(path)); + return cache; + } private static CultRecordKey Key(string name) => new(name); @@ -239,13 +251,13 @@ namespace GameCult.Caching.Tests } [Test] - public void AWriteOntoAMovedFileIsAConflictAndTheRetryIsRefused() + public void AWriteOntoAMovedStoreIsAConflictAndTheRetryIsRefused([Values] StoreKind kind) { var path = PathOf("items.cc"); - using var seed = Open(path); + using var seed = Open(path, kind); seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a"))); - using var second = Open(path); - using (var first = Open(path)) + using var second = Open(path, kind); + using (var first = Open(path, kind)) first.Commit(batch => batch.Upsert(typeof(UqItem), Item(Canary), Key("b"))); var conflict = Assert.Throws( @@ -256,11 +268,141 @@ namespace GameCult.Caching.Tests var retry = Refused(() => second.Commit(batch => batch.Upsert(typeof(UqItem), Item(Canary), Key("c")))); Assert.That(retry.Message, Does.Contain("b").And.Contain("c").And.Not.Contain(Canary)); - using var reopened = Open(path); - Assert.That(reopened.Get(Key("c")), Is.Null, "the file never holds the pair"); + using var reopened = Open(path, kind); + Assert.That(reopened.Get(Key("c")), Is.Null, "the store never holds the pair"); Assert.That(reopened.Get(Key("b")), Is.Not.Null); } + // The flush path: a staged upsert is judged when it flushes, under the store's lock, against the store as it is then. + [Test] + public void AFlushOntoAMovedDirectoryStoreIsAConflict() + { + var path = PathOf("items.cc"); + using var seed = Open(path, StoreKind.Directory); + seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a"))); + using var second = Open(path, StoreKind.Directory); + using (var first = Open(path, StoreKind.Directory)) + first.Commit(batch => batch.Upsert(typeof(UqItem), Item(Canary), Key("b"))); + + second.AddAsync(Item(Canary), new CultRecordHandle(Key("c"))).GetAwaiter().GetResult(); + Assert.Throws(() => second.FlushAllBackingStores()); + + using var reopened = Open(path, StoreKind.Directory); + Assert.That(reopened.Get(Key("c")), Is.Null, "the store never holds the pair"); + Assert.That(reopened.Get(Key("b")), Is.Not.Null); + } + + // Whole-store rule, as in the single-file store and the Rust one: another writer's change to a record of any type refuses an + // indexed write, because the write cannot know which of the records it did not read bear on its value. + [Test] + public void AnUnrelatedRecordMovedByAnotherWriterStillRefusesAnIndexedWrite([Values] StoreKind kind) + { + var path = PathOf("items.cc"); + using var seed = Open(path, kind); + seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a"))); + using var second = Open(path, kind); + using (var first = Open(path, kind)) + first.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "k" }, Key("tag"))); + + Assert.Throws( + () => second.Commit(batch => batch.Upsert(typeof(UqItem), Item("fresh"), Key("c")))); + Assert.That(second.Get(Key("tag")), Is.Not.Null, "the moved record is loaded"); + Assert.That(second.Commit(batch => batch.Upsert(typeof(UqItem), Item("fresh"), Key("c"))), Is.True, "the retry against what the store holds lands"); + } + + // A type without an index is never gated, and the writes it lands are recorded as this cache's own: its next indexed write + // is refused only for what another writer moved, never for what it wrote itself. + [Test] + public void AWriteOfATypeWithoutAnIndexOntoAMovedDirectoryStoreMerges() + { + var path = PathOf("items.cc"); + using var seed = Open(path, StoreKind.Directory); + seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a"))); + using var second = Open(path, StoreKind.Directory); + using (var first = Open(path, StoreKind.Directory)) + first.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "one" }, Key("t1"))); + + Assert.That(second.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "two" }, Key("t2"))), Is.True); + using (var reopened = Open(path, StoreKind.Directory)) + { + Assert.That(reopened.Get(Key("t1")), Is.Not.Null); + Assert.That(reopened.Get(Key("t2")), Is.Not.Null); + } + + Assert.Throws( + () => second.Commit(batch => batch.Upsert(typeof(UqItem), Item("x"), Key("c"))), "t1 was never read by this cache"); + Assert.That(second.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "three" }, Key("t3"))), Is.True); + Assert.That(second.Commit(batch => batch.Upsert(typeof(UqItem), Item("x"), Key("c"))), Is.True, "only this cache wrote since it last read"); + } + + // A record this cache removed is gone from what it last read: its next indexed write is judged against the store after the + // removal, not refused for a record it deleted itself. + [Test] + public void ADeleteIsRecordedSoTheNextIndexedWriteIsJudgedAgainstTheStoreAfterIt([Values] StoreKind kind) + { + var path = PathOf("items.cc"); + using var seed = Open(path, kind); + seed.Commit(batch => + { + batch.Upsert(typeof(UqItem), Item("one"), Key("a")); + batch.Upsert(typeof(UqItem), Item("two"), Key("b")); + }); + using var cache = Open(path, kind); + Assert.That(cache.Commit(batch => batch.Remove(Key("b"))), Is.True); + + Assert.That(cache.Commit(batch => batch.Upsert(typeof(UqItem), Item("three"), Key("c"))), Is.True, + "nothing but this cache's own delete moved the store"); + using var reopened = Open(path, kind); + Assert.That(reopened.Get(Key("b")), Is.Null); + Assert.That(reopened.Get(Key("c")), Is.Not.Null); + } + + // A record of a type this cache does not define is part of the store it last read: unchanged, it never refuses an indexed + // write; changed by another writer, it does. + [Test] + public void AForeignTypedRecordIsReadWithTheStoreAndRefusesAnIndexedWriteOnlyWhenItMoves([Values] StoreKind kind) + { + var path = PathOf("items.cc"); + using var seed = Open(path, kind); + seed.Commit(batch => + { + batch.Upsert(typeof(UqItem), Item("one"), Key("a")); + batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "x" }, Key("tag")); + }); + using var narrow = Open(path, kind, CultDocumentRegistry.ForTypes(new[] { typeof(UqItem) })); + Assert.That(narrow.Commit(batch => batch.Upsert(typeof(UqItem), Item("two"), Key("b"))), Is.True, + "the foreign record has not moved since this cache read the store"); + + seed.Commit(batch => batch.Upsert(typeof(UqTagged), new UqTagged { Kind = "y" }, Key("tag"))); + Assert.Throws( + () => narrow.Commit(batch => batch.Upsert(typeof(UqItem), Item("three"), Key("c")))); + } + + // A conflict costs Update an attempt, not an error: it applies again to what the store holds and lands. + [Test] + public void AnUpdateOnAMovedDirectoryStoreRetriesAndLands() + { + var path = PathOf("items.cc"); + using var seed = Open(path, StoreKind.Directory); + seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a"))); + using var cache = Open(path, StoreKind.Directory); + using var rival = Open(path, StoreKind.Directory); + var calls = 0; + + var result = cache.Update(Key("c"), item => + { + if (++calls == 1) + rival.Commit(batch => batch.Upsert(typeof(UqItem), Item("rival"), Key("b"))); + return Item("mine"); + }); + + Assert.That(result.Outcome, Is.EqualTo(CultUpdateOutcome.Updated)); + Assert.That(calls, Is.EqualTo(2)); + using var reopened = Open(path, StoreKind.Directory); + Assert.That(reopened.Get(Key("c"))!.Sku, Is.EqualTo("mine")); + Assert.That(reopened.Get(Key("b"))!.Sku, Is.EqualTo("rival")); + } + [Test] public void CachelessWritesOfAUniqueIndexedTypeAreRefused() { @@ -357,13 +499,13 @@ namespace GameCult.Caching.Tests } [Test] - public void AMixedBatchOntoAMovedFileIsAConflictWhateverItsOrder() + public void AMixedBatchOntoAMovedStoreIsAConflictWhateverItsOrder([Values] StoreKind kind) { var path = PathOf("items.cc"); - using var seed = Open(path); + using var seed = Open(path, kind); seed.Commit(batch => batch.Upsert(typeof(UqItem), Item("base"), Key("a"))); - using var second = Open(path); - using (var first = Open(path)) + using var second = Open(path, kind); + using (var first = Open(path, kind)) first.Commit(batch => batch.Upsert(typeof(UqItem), Item("moved"), Key("b"))); Assert.Throws(() => second.Commit(batch =>